1 //===-- TargetLowering.cpp - Implement the TargetLowering class -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the TargetLowering class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/TargetLowering.h"
14 #include "llvm/ADT/BitVector.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/CodeGen/CallingConvLower.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineJumpTableInfo.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/CodeGen/TargetRegisterInfo.h"
23 #include "llvm/CodeGen/TargetSubtargetInfo.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/KnownBits.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Target/TargetLoweringObjectFile.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include <cctype>
36 using namespace llvm;
37 
38 /// NOTE: The TargetMachine owns TLOF.
39 TargetLowering::TargetLowering(const TargetMachine &tm)
40   : TargetLoweringBase(tm) {}
41 
42 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
43   return nullptr;
44 }
45 
46 bool TargetLowering::isPositionIndependent() const {
47   return getTargetMachine().isPositionIndependent();
48 }
49 
50 /// Check whether a given call node is in tail position within its function. If
51 /// so, it sets Chain to the input chain of the tail call.
52 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
53                                           SDValue &Chain) const {
54   const Function &F = DAG.getMachineFunction().getFunction();
55 
56   // Conservatively require the attributes of the call to match those of
57   // the return. Ignore NoAlias and NonNull because they don't affect the
58   // call sequence.
59   AttributeList CallerAttrs = F.getAttributes();
60   if (AttrBuilder(CallerAttrs, AttributeList::ReturnIndex)
61           .removeAttribute(Attribute::NoAlias)
62           .removeAttribute(Attribute::NonNull)
63           .hasAttributes())
64     return false;
65 
66   // It's not safe to eliminate the sign / zero extension of the return value.
67   if (CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt) ||
68       CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
69     return false;
70 
71   // Check if the only use is a function return node.
72   return isUsedByReturnOnly(Node, Chain);
73 }
74 
75 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
76     const uint32_t *CallerPreservedMask,
77     const SmallVectorImpl<CCValAssign> &ArgLocs,
78     const SmallVectorImpl<SDValue> &OutVals) const {
79   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
80     const CCValAssign &ArgLoc = ArgLocs[I];
81     if (!ArgLoc.isRegLoc())
82       continue;
83     unsigned Reg = ArgLoc.getLocReg();
84     // Only look at callee saved registers.
85     if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
86       continue;
87     // Check that we pass the value used for the caller.
88     // (We look for a CopyFromReg reading a virtual register that is used
89     //  for the function live-in value of register Reg)
90     SDValue Value = OutVals[I];
91     if (Value->getOpcode() != ISD::CopyFromReg)
92       return false;
93     unsigned ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
94     if (MRI.getLiveInPhysReg(ArgReg) != Reg)
95       return false;
96   }
97   return true;
98 }
99 
100 /// Set CallLoweringInfo attribute flags based on a call instruction
101 /// and called function attributes.
102 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase *Call,
103                                                      unsigned ArgIdx) {
104   IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt);
105   IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt);
106   IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg);
107   IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet);
108   IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest);
109   IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal);
110   IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca);
111   IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned);
112   IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf);
113   IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError);
114   Alignment = Call->getParamAlignment(ArgIdx);
115   ByValType = nullptr;
116   if (Call->paramHasAttr(ArgIdx, Attribute::ByVal))
117     ByValType = Call->getParamByValType(ArgIdx);
118 }
119 
120 /// Generate a libcall taking the given operands as arguments and returning a
121 /// result of type RetVT.
122 std::pair<SDValue, SDValue>
123 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
124                             ArrayRef<SDValue> Ops, bool isSigned,
125                             const SDLoc &dl, bool doesNotReturn,
126                             bool isReturnValueUsed,
127                             bool isPostTypeLegalization) const {
128   TargetLowering::ArgListTy Args;
129   Args.reserve(Ops.size());
130 
131   TargetLowering::ArgListEntry Entry;
132   for (SDValue Op : Ops) {
133     Entry.Node = Op;
134     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
135     Entry.IsSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
136     Entry.IsZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
137     Args.push_back(Entry);
138   }
139 
140   if (LC == RTLIB::UNKNOWN_LIBCALL)
141     report_fatal_error("Unsupported library call operation!");
142   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
143                                          getPointerTy(DAG.getDataLayout()));
144 
145   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
146   TargetLowering::CallLoweringInfo CLI(DAG);
147   bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned);
148   CLI.setDebugLoc(dl)
149       .setChain(DAG.getEntryNode())
150       .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
151       .setNoReturn(doesNotReturn)
152       .setDiscardResult(!isReturnValueUsed)
153       .setIsPostTypeLegalization(isPostTypeLegalization)
154       .setSExtResult(signExtend)
155       .setZExtResult(!signExtend);
156   return LowerCallTo(CLI);
157 }
158 
159 bool
160 TargetLowering::findOptimalMemOpLowering(std::vector<EVT> &MemOps,
161                                          unsigned Limit, uint64_t Size,
162                                          unsigned DstAlign, unsigned SrcAlign,
163                                          bool IsMemset,
164                                          bool ZeroMemset,
165                                          bool MemcpyStrSrc,
166                                          bool AllowOverlap,
167                                          unsigned DstAS, unsigned SrcAS,
168                                          const AttributeList &FuncAttributes) const {
169   // If 'SrcAlign' is zero, that means the memory operation does not need to
170   // load the value, i.e. memset or memcpy from constant string. Otherwise,
171   // it's the inferred alignment of the source. 'DstAlign', on the other hand,
172   // is the specified alignment of the memory operation. If it is zero, that
173   // means it's possible to change the alignment of the destination.
174   // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
175   // not need to be loaded.
176   if (!(SrcAlign == 0 || SrcAlign >= DstAlign))
177     return false;
178 
179   EVT VT = getOptimalMemOpType(Size, DstAlign, SrcAlign,
180                                IsMemset, ZeroMemset, MemcpyStrSrc,
181                                FuncAttributes);
182 
183   if (VT == MVT::Other) {
184     // Use the largest integer type whose alignment constraints are satisfied.
185     // We only need to check DstAlign here as SrcAlign is always greater or
186     // equal to DstAlign (or zero).
187     VT = MVT::i64;
188     while (DstAlign && DstAlign < VT.getSizeInBits() / 8 &&
189            !allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign))
190       VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
191     assert(VT.isInteger());
192 
193     // Find the largest legal integer type.
194     MVT LVT = MVT::i64;
195     while (!isTypeLegal(LVT))
196       LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
197     assert(LVT.isInteger());
198 
199     // If the type we've chosen is larger than the largest legal integer type
200     // then use that instead.
201     if (VT.bitsGT(LVT))
202       VT = LVT;
203   }
204 
205   unsigned NumMemOps = 0;
206   while (Size != 0) {
207     unsigned VTSize = VT.getSizeInBits() / 8;
208     while (VTSize > Size) {
209       // For now, only use non-vector load / store's for the left-over pieces.
210       EVT NewVT = VT;
211       unsigned NewVTSize;
212 
213       bool Found = false;
214       if (VT.isVector() || VT.isFloatingPoint()) {
215         NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
216         if (isOperationLegalOrCustom(ISD::STORE, NewVT) &&
217             isSafeMemOpType(NewVT.getSimpleVT()))
218           Found = true;
219         else if (NewVT == MVT::i64 &&
220                  isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
221                  isSafeMemOpType(MVT::f64)) {
222           // i64 is usually not legal on 32-bit targets, but f64 may be.
223           NewVT = MVT::f64;
224           Found = true;
225         }
226       }
227 
228       if (!Found) {
229         do {
230           NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
231           if (NewVT == MVT::i8)
232             break;
233         } while (!isSafeMemOpType(NewVT.getSimpleVT()));
234       }
235       NewVTSize = NewVT.getSizeInBits() / 8;
236 
237       // If the new VT cannot cover all of the remaining bits, then consider
238       // issuing a (or a pair of) unaligned and overlapping load / store.
239       bool Fast;
240       if (NumMemOps && AllowOverlap && NewVTSize < Size &&
241           allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign,
242                                          MachineMemOperand::MONone, &Fast) &&
243           Fast)
244         VTSize = Size;
245       else {
246         VT = NewVT;
247         VTSize = NewVTSize;
248       }
249     }
250 
251     if (++NumMemOps > Limit)
252       return false;
253 
254     MemOps.push_back(VT);
255     Size -= VTSize;
256   }
257 
258   return true;
259 }
260 
261 /// Soften the operands of a comparison. This code is shared among BR_CC,
262 /// SELECT_CC, and SETCC handlers.
263 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
264                                          SDValue &NewLHS, SDValue &NewRHS,
265                                          ISD::CondCode &CCCode,
266                                          const SDLoc &dl) const {
267   assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
268          && "Unsupported setcc type!");
269 
270   // Expand into one or more soft-fp libcall(s).
271   RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
272   bool ShouldInvertCC = false;
273   switch (CCCode) {
274   case ISD::SETEQ:
275   case ISD::SETOEQ:
276     LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
277           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
278           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
279     break;
280   case ISD::SETNE:
281   case ISD::SETUNE:
282     LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
283           (VT == MVT::f64) ? RTLIB::UNE_F64 :
284           (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
285     break;
286   case ISD::SETGE:
287   case ISD::SETOGE:
288     LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
289           (VT == MVT::f64) ? RTLIB::OGE_F64 :
290           (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
291     break;
292   case ISD::SETLT:
293   case ISD::SETOLT:
294     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
295           (VT == MVT::f64) ? RTLIB::OLT_F64 :
296           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
297     break;
298   case ISD::SETLE:
299   case ISD::SETOLE:
300     LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
301           (VT == MVT::f64) ? RTLIB::OLE_F64 :
302           (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
303     break;
304   case ISD::SETGT:
305   case ISD::SETOGT:
306     LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
307           (VT == MVT::f64) ? RTLIB::OGT_F64 :
308           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
309     break;
310   case ISD::SETUO:
311     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
312           (VT == MVT::f64) ? RTLIB::UO_F64 :
313           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
314     break;
315   case ISD::SETO:
316     LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
317           (VT == MVT::f64) ? RTLIB::O_F64 :
318           (VT == MVT::f128) ? RTLIB::O_F128 : RTLIB::O_PPCF128;
319     break;
320   case ISD::SETONE:
321     // SETONE = SETOLT | SETOGT
322     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
323           (VT == MVT::f64) ? RTLIB::OLT_F64 :
324           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
325     LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
326           (VT == MVT::f64) ? RTLIB::OGT_F64 :
327           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
328     break;
329   case ISD::SETUEQ:
330     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
331           (VT == MVT::f64) ? RTLIB::UO_F64 :
332           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
333     LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
334           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
335           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
336     break;
337   default:
338     // Invert CC for unordered comparisons
339     ShouldInvertCC = true;
340     switch (CCCode) {
341     case ISD::SETULT:
342       LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
343             (VT == MVT::f64) ? RTLIB::OGE_F64 :
344             (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
345       break;
346     case ISD::SETULE:
347       LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
348             (VT == MVT::f64) ? RTLIB::OGT_F64 :
349             (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
350       break;
351     case ISD::SETUGT:
352       LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
353             (VT == MVT::f64) ? RTLIB::OLE_F64 :
354             (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
355       break;
356     case ISD::SETUGE:
357       LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
358             (VT == MVT::f64) ? RTLIB::OLT_F64 :
359             (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
360       break;
361     default: llvm_unreachable("Do not know how to soften this setcc!");
362     }
363   }
364 
365   // Use the target specific return value for comparions lib calls.
366   EVT RetVT = getCmpLibcallReturnType();
367   SDValue Ops[2] = {NewLHS, NewRHS};
368   NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/,
369                        dl).first;
370   NewRHS = DAG.getConstant(0, dl, RetVT);
371 
372   CCCode = getCmpLibcallCC(LC1);
373   if (ShouldInvertCC)
374     CCCode = getSetCCInverse(CCCode, /*isInteger=*/true);
375 
376   if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
377     SDValue Tmp = DAG.getNode(
378         ISD::SETCC, dl,
379         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
380         NewLHS, NewRHS, DAG.getCondCode(CCCode));
381     NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, false/*sign irrelevant*/,
382                          dl).first;
383     NewLHS = DAG.getNode(
384         ISD::SETCC, dl,
385         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
386         NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
387     NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
388     NewRHS = SDValue();
389   }
390 }
391 
392 /// Return the entry encoding for a jump table in the current function. The
393 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
394 unsigned TargetLowering::getJumpTableEncoding() const {
395   // In non-pic modes, just use the address of a block.
396   if (!isPositionIndependent())
397     return MachineJumpTableInfo::EK_BlockAddress;
398 
399   // In PIC mode, if the target supports a GPRel32 directive, use it.
400   if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
401     return MachineJumpTableInfo::EK_GPRel32BlockAddress;
402 
403   // Otherwise, use a label difference.
404   return MachineJumpTableInfo::EK_LabelDifference32;
405 }
406 
407 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
408                                                  SelectionDAG &DAG) const {
409   // If our PIC model is GP relative, use the global offset table as the base.
410   unsigned JTEncoding = getJumpTableEncoding();
411 
412   if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
413       (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
414     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
415 
416   return Table;
417 }
418 
419 /// This returns the relocation base for the given PIC jumptable, the same as
420 /// getPICJumpTableRelocBase, but as an MCExpr.
421 const MCExpr *
422 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
423                                              unsigned JTI,MCContext &Ctx) const{
424   // The normal PIC reloc base is the label at the start of the jump table.
425   return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
426 }
427 
428 bool
429 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
430   const TargetMachine &TM = getTargetMachine();
431   const GlobalValue *GV = GA->getGlobal();
432 
433   // If the address is not even local to this DSO we will have to load it from
434   // a got and then add the offset.
435   if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
436     return false;
437 
438   // If the code is position independent we will have to add a base register.
439   if (isPositionIndependent())
440     return false;
441 
442   // Otherwise we can do it.
443   return true;
444 }
445 
446 //===----------------------------------------------------------------------===//
447 //  Optimization Methods
448 //===----------------------------------------------------------------------===//
449 
450 /// If the specified instruction has a constant integer operand and there are
451 /// bits set in that constant that are not demanded, then clear those bits and
452 /// return true.
453 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
454                                             TargetLoweringOpt &TLO) const {
455   SDLoc DL(Op);
456   unsigned Opcode = Op.getOpcode();
457 
458   // Do target-specific constant optimization.
459   if (targetShrinkDemandedConstant(Op, Demanded, TLO))
460     return TLO.New.getNode();
461 
462   // FIXME: ISD::SELECT, ISD::SELECT_CC
463   switch (Opcode) {
464   default:
465     break;
466   case ISD::XOR:
467   case ISD::AND:
468   case ISD::OR: {
469     auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
470     if (!Op1C)
471       return false;
472 
473     // If this is a 'not' op, don't touch it because that's a canonical form.
474     const APInt &C = Op1C->getAPIntValue();
475     if (Opcode == ISD::XOR && Demanded.isSubsetOf(C))
476       return false;
477 
478     if (!C.isSubsetOf(Demanded)) {
479       EVT VT = Op.getValueType();
480       SDValue NewC = TLO.DAG.getConstant(Demanded & C, DL, VT);
481       SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC);
482       return TLO.CombineTo(Op, NewOp);
483     }
484 
485     break;
486   }
487   }
488 
489   return false;
490 }
491 
492 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
493 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
494 /// generalized for targets with other types of implicit widening casts.
495 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth,
496                                       const APInt &Demanded,
497                                       TargetLoweringOpt &TLO) const {
498   assert(Op.getNumOperands() == 2 &&
499          "ShrinkDemandedOp only supports binary operators!");
500   assert(Op.getNode()->getNumValues() == 1 &&
501          "ShrinkDemandedOp only supports nodes with one result!");
502 
503   SelectionDAG &DAG = TLO.DAG;
504   SDLoc dl(Op);
505 
506   // Early return, as this function cannot handle vector types.
507   if (Op.getValueType().isVector())
508     return false;
509 
510   // Don't do this if the node has another user, which may require the
511   // full value.
512   if (!Op.getNode()->hasOneUse())
513     return false;
514 
515   // Search for the smallest integer type with free casts to and from
516   // Op's type. For expedience, just check power-of-2 integer types.
517   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
518   unsigned DemandedSize = Demanded.getActiveBits();
519   unsigned SmallVTBits = DemandedSize;
520   if (!isPowerOf2_32(SmallVTBits))
521     SmallVTBits = NextPowerOf2(SmallVTBits);
522   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
523     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
524     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
525         TLI.isZExtFree(SmallVT, Op.getValueType())) {
526       // We found a type with free casts.
527       SDValue X = DAG.getNode(
528           Op.getOpcode(), dl, SmallVT,
529           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
530           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)));
531       assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
532       SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X);
533       return TLO.CombineTo(Op, Z);
534     }
535   }
536   return false;
537 }
538 
539 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
540                                           DAGCombinerInfo &DCI) const {
541   SelectionDAG &DAG = DCI.DAG;
542   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
543                         !DCI.isBeforeLegalizeOps());
544   KnownBits Known;
545 
546   bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO);
547   if (Simplified) {
548     DCI.AddToWorklist(Op.getNode());
549     DCI.CommitTargetLoweringOpt(TLO);
550   }
551   return Simplified;
552 }
553 
554 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
555                                           KnownBits &Known,
556                                           TargetLoweringOpt &TLO,
557                                           unsigned Depth,
558                                           bool AssumeSingleUse) const {
559   EVT VT = Op.getValueType();
560   APInt DemandedElts = VT.isVector()
561                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
562                            : APInt(1, 1);
563   return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth,
564                               AssumeSingleUse);
565 }
566 
567 // TODO: Can we merge SelectionDAG::GetDemandedBits into this?
568 // TODO: Under what circumstances can we create nodes? BITCAST? Constant?
569 SDValue TargetLowering::SimplifyMultipleUseDemandedBits(
570     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
571     SelectionDAG &DAG, unsigned Depth) const {
572   KnownBits LHSKnown, RHSKnown;
573   switch (Op.getOpcode()) {
574   case ISD::AND: {
575     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
576     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
577 
578     // If all of the demanded bits are known 1 on one side, return the other.
579     // These bits cannot contribute to the result of the 'and' in this
580     // context.
581     if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
582       return Op.getOperand(0);
583     if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
584       return Op.getOperand(1);
585     break;
586   }
587   case ISD::OR: {
588     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
589     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
590 
591     // If all of the demanded bits are known zero on one side, return the
592     // other.  These bits cannot contribute to the result of the 'or' in this
593     // context.
594     if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
595       return Op.getOperand(0);
596     if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
597       return Op.getOperand(1);
598     break;
599   }
600   case ISD::XOR: {
601     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
602     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
603 
604     // If all of the demanded bits are known zero on one side, return the
605     // other.
606     if (DemandedBits.isSubsetOf(RHSKnown.Zero))
607       return Op.getOperand(0);
608     if (DemandedBits.isSubsetOf(LHSKnown.Zero))
609       return Op.getOperand(1);
610     break;
611   }
612   case ISD::VECTOR_SHUFFLE: {
613     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
614 
615     // If all the demanded elts are from one operand and are inline,
616     // then we can use the operand directly.
617     bool AllUndef = true, IdentityLHS = true, IdentityRHS = true;
618     for (unsigned i = 0, NumElts = ShuffleMask.size(); i != NumElts; ++i) {
619       int M = ShuffleMask[i];
620       if (M < 0 || !DemandedElts[i])
621         continue;
622       AllUndef = false;
623       IdentityLHS &= (M == (int)i);
624       IdentityRHS &= ((M - NumElts) == i);
625     }
626 
627     if (AllUndef)
628       return DAG.getUNDEF(Op.getValueType());
629     if (IdentityLHS)
630       return Op.getOperand(0);
631     if (IdentityRHS)
632       return Op.getOperand(1);
633     break;
634   }
635   default:
636     if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
637       if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode(
638               Op, DemandedBits, DemandedElts, DAG, Depth))
639         return V;
640     break;
641   }
642   return SDValue();
643 }
644 
645 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the
646 /// result of Op are ever used downstream. If we can use this information to
647 /// simplify Op, create a new simplified DAG node and return true, returning the
648 /// original and new nodes in Old and New. Otherwise, analyze the expression and
649 /// return a mask of Known bits for the expression (used to simplify the
650 /// caller).  The Known bits may only be accurate for those bits in the
651 /// OriginalDemandedBits and OriginalDemandedElts.
652 bool TargetLowering::SimplifyDemandedBits(
653     SDValue Op, const APInt &OriginalDemandedBits,
654     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
655     unsigned Depth, bool AssumeSingleUse) const {
656   unsigned BitWidth = OriginalDemandedBits.getBitWidth();
657   assert(Op.getScalarValueSizeInBits() == BitWidth &&
658          "Mask size mismatches value type size!");
659 
660   unsigned NumElts = OriginalDemandedElts.getBitWidth();
661   assert((!Op.getValueType().isVector() ||
662           NumElts == Op.getValueType().getVectorNumElements()) &&
663          "Unexpected vector size");
664 
665   APInt DemandedBits = OriginalDemandedBits;
666   APInt DemandedElts = OriginalDemandedElts;
667   SDLoc dl(Op);
668   auto &DL = TLO.DAG.getDataLayout();
669 
670   // Don't know anything.
671   Known = KnownBits(BitWidth);
672 
673   // Undef operand.
674   if (Op.isUndef())
675     return false;
676 
677   if (Op.getOpcode() == ISD::Constant) {
678     // We know all of the bits for a constant!
679     Known.One = cast<ConstantSDNode>(Op)->getAPIntValue();
680     Known.Zero = ~Known.One;
681     return false;
682   }
683 
684   // Other users may use these bits.
685   EVT VT = Op.getValueType();
686   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) {
687     if (Depth != 0) {
688       // If not at the root, Just compute the Known bits to
689       // simplify things downstream.
690       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
691       return false;
692     }
693     // If this is the root being simplified, allow it to have multiple uses,
694     // just set the DemandedBits/Elts to all bits.
695     DemandedBits = APInt::getAllOnesValue(BitWidth);
696     DemandedElts = APInt::getAllOnesValue(NumElts);
697   } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
698     // Not demanding any bits/elts from Op.
699     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
700   } else if (Depth == 6) { // Limit search depth.
701     return false;
702   }
703 
704   KnownBits Known2, KnownOut;
705   switch (Op.getOpcode()) {
706   case ISD::SCALAR_TO_VECTOR: {
707     if (!DemandedElts[0])
708       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
709 
710     KnownBits SrcKnown;
711     SDValue Src = Op.getOperand(0);
712     unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
713     APInt SrcDemandedBits = DemandedBits.zextOrSelf(SrcBitWidth);
714     if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
715       return true;
716     Known = SrcKnown.zextOrTrunc(BitWidth, false);
717     break;
718   }
719   case ISD::BUILD_VECTOR:
720     // Collect the known bits that are shared by every demanded element.
721     // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
722     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
723     return false; // Don't fall through, will infinitely loop.
724   case ISD::LOAD: {
725     LoadSDNode *LD = cast<LoadSDNode>(Op);
726     if (getTargetConstantFromLoad(LD)) {
727       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
728       return false; // Don't fall through, will infinitely loop.
729     }
730     break;
731   }
732   case ISD::INSERT_VECTOR_ELT: {
733     SDValue Vec = Op.getOperand(0);
734     SDValue Scl = Op.getOperand(1);
735     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
736     EVT VecVT = Vec.getValueType();
737 
738     // If index isn't constant, assume we need all vector elements AND the
739     // inserted element.
740     APInt DemandedVecElts(DemandedElts);
741     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
742       unsigned Idx = CIdx->getZExtValue();
743       DemandedVecElts.clearBit(Idx);
744 
745       // Inserted element is not required.
746       if (!DemandedElts[Idx])
747         return TLO.CombineTo(Op, Vec);
748     }
749 
750     KnownBits KnownScl;
751     unsigned NumSclBits = Scl.getScalarValueSizeInBits();
752     APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits);
753     if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
754       return true;
755 
756     Known = KnownScl.zextOrTrunc(BitWidth, false);
757 
758     KnownBits KnownVec;
759     if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO,
760                              Depth + 1))
761       return true;
762 
763     if (!!DemandedVecElts) {
764       Known.One &= KnownVec.One;
765       Known.Zero &= KnownVec.Zero;
766     }
767 
768     return false;
769   }
770   case ISD::INSERT_SUBVECTOR: {
771     SDValue Base = Op.getOperand(0);
772     SDValue Sub = Op.getOperand(1);
773     EVT SubVT = Sub.getValueType();
774     unsigned NumSubElts = SubVT.getVectorNumElements();
775 
776     // If index isn't constant, assume we need the original demanded base
777     // elements and ALL the inserted subvector elements.
778     APInt BaseElts = DemandedElts;
779     APInt SubElts = APInt::getAllOnesValue(NumSubElts);
780     if (isa<ConstantSDNode>(Op.getOperand(2))) {
781       const APInt &Idx = Op.getConstantOperandAPInt(2);
782       if (Idx.ule(NumElts - NumSubElts)) {
783         unsigned SubIdx = Idx.getZExtValue();
784         SubElts = DemandedElts.extractBits(NumSubElts, SubIdx);
785         BaseElts.insertBits(APInt::getNullValue(NumSubElts), SubIdx);
786       }
787     }
788 
789     KnownBits KnownSub, KnownBase;
790     if (SimplifyDemandedBits(Sub, DemandedBits, SubElts, KnownSub, TLO,
791                              Depth + 1))
792       return true;
793     if (SimplifyDemandedBits(Base, DemandedBits, BaseElts, KnownBase, TLO,
794                              Depth + 1))
795       return true;
796 
797     Known.Zero.setAllBits();
798     Known.One.setAllBits();
799     if (!!SubElts) {
800         Known.One &= KnownSub.One;
801         Known.Zero &= KnownSub.Zero;
802     }
803     if (!!BaseElts) {
804         Known.One &= KnownBase.One;
805         Known.Zero &= KnownBase.Zero;
806     }
807     break;
808   }
809   case ISD::CONCAT_VECTORS: {
810     Known.Zero.setAllBits();
811     Known.One.setAllBits();
812     EVT SubVT = Op.getOperand(0).getValueType();
813     unsigned NumSubVecs = Op.getNumOperands();
814     unsigned NumSubElts = SubVT.getVectorNumElements();
815     for (unsigned i = 0; i != NumSubVecs; ++i) {
816       APInt DemandedSubElts =
817           DemandedElts.extractBits(NumSubElts, i * NumSubElts);
818       if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
819                                Known2, TLO, Depth + 1))
820         return true;
821       // Known bits are shared by every demanded subvector element.
822       if (!!DemandedSubElts) {
823         Known.One &= Known2.One;
824         Known.Zero &= Known2.Zero;
825       }
826     }
827     break;
828   }
829   case ISD::VECTOR_SHUFFLE: {
830     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
831 
832     // Collect demanded elements from shuffle operands..
833     APInt DemandedLHS(NumElts, 0);
834     APInt DemandedRHS(NumElts, 0);
835     for (unsigned i = 0; i != NumElts; ++i) {
836       if (!DemandedElts[i])
837         continue;
838       int M = ShuffleMask[i];
839       if (M < 0) {
840         // For UNDEF elements, we don't know anything about the common state of
841         // the shuffle result.
842         DemandedLHS.clearAllBits();
843         DemandedRHS.clearAllBits();
844         break;
845       }
846       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
847       if (M < (int)NumElts)
848         DemandedLHS.setBit(M);
849       else
850         DemandedRHS.setBit(M - NumElts);
851     }
852 
853     if (!!DemandedLHS || !!DemandedRHS) {
854       Known.Zero.setAllBits();
855       Known.One.setAllBits();
856       if (!!DemandedLHS) {
857         if (SimplifyDemandedBits(Op.getOperand(0), DemandedBits, DemandedLHS,
858                                  Known2, TLO, Depth + 1))
859           return true;
860         Known.One &= Known2.One;
861         Known.Zero &= Known2.Zero;
862       }
863       if (!!DemandedRHS) {
864         if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedRHS,
865                                  Known2, TLO, Depth + 1))
866           return true;
867         Known.One &= Known2.One;
868         Known.Zero &= Known2.Zero;
869       }
870     }
871     break;
872   }
873   case ISD::AND: {
874     SDValue Op0 = Op.getOperand(0);
875     SDValue Op1 = Op.getOperand(1);
876 
877     // If the RHS is a constant, check to see if the LHS would be zero without
878     // using the bits from the RHS.  Below, we use knowledge about the RHS to
879     // simplify the LHS, here we're using information from the LHS to simplify
880     // the RHS.
881     if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) {
882       // Do not increment Depth here; that can cause an infinite loop.
883       KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
884       // If the LHS already has zeros where RHSC does, this 'and' is dead.
885       if ((LHSKnown.Zero & DemandedBits) ==
886           (~RHSC->getAPIntValue() & DemandedBits))
887         return TLO.CombineTo(Op, Op0);
888 
889       // If any of the set bits in the RHS are known zero on the LHS, shrink
890       // the constant.
891       if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits, TLO))
892         return true;
893 
894       // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
895       // constant, but if this 'and' is only clearing bits that were just set by
896       // the xor, then this 'and' can be eliminated by shrinking the mask of
897       // the xor. For example, for a 32-bit X:
898       // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
899       if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
900           LHSKnown.One == ~RHSC->getAPIntValue()) {
901         SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
902         return TLO.CombineTo(Op, Xor);
903       }
904     }
905 
906     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
907                              Depth + 1))
908       return true;
909     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
910     if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
911                              Known2, TLO, Depth + 1))
912       return true;
913     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
914 
915     // Attempt to avoid multi-use ops if we don't need anything from them.
916     if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
917       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
918           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
919       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
920           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
921       if (DemandedOp0 || DemandedOp1) {
922         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
923         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
924         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
925         return TLO.CombineTo(Op, NewOp);
926       }
927     }
928 
929     // If all of the demanded bits are known one on one side, return the other.
930     // These bits cannot contribute to the result of the 'and'.
931     if (DemandedBits.isSubsetOf(Known2.Zero | Known.One))
932       return TLO.CombineTo(Op, Op0);
933     if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
934       return TLO.CombineTo(Op, Op1);
935     // If all of the demanded bits in the inputs are known zeros, return zero.
936     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
937       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
938     // If the RHS is a constant, see if we can simplify it.
939     if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, TLO))
940       return true;
941     // If the operation can be done in a smaller type, do so.
942     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
943       return true;
944 
945     // Output known-1 bits are only known if set in both the LHS & RHS.
946     Known.One &= Known2.One;
947     // Output known-0 are known to be clear if zero in either the LHS | RHS.
948     Known.Zero |= Known2.Zero;
949     break;
950   }
951   case ISD::OR: {
952     SDValue Op0 = Op.getOperand(0);
953     SDValue Op1 = Op.getOperand(1);
954 
955     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
956                              Depth + 1))
957       return true;
958     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
959     if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
960                              Known2, TLO, Depth + 1))
961       return true;
962     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
963 
964     // Attempt to avoid multi-use ops if we don't need anything from them.
965     if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
966       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
967           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
968       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
969           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
970       if (DemandedOp0 || DemandedOp1) {
971         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
972         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
973         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
974         return TLO.CombineTo(Op, NewOp);
975       }
976     }
977 
978     // If all of the demanded bits are known zero on one side, return the other.
979     // These bits cannot contribute to the result of the 'or'.
980     if (DemandedBits.isSubsetOf(Known2.One | Known.Zero))
981       return TLO.CombineTo(Op, Op0);
982     if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
983       return TLO.CombineTo(Op, Op1);
984     // If the RHS is a constant, see if we can simplify it.
985     if (ShrinkDemandedConstant(Op, DemandedBits, TLO))
986       return true;
987     // If the operation can be done in a smaller type, do so.
988     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
989       return true;
990 
991     // Output known-0 bits are only known if clear in both the LHS & RHS.
992     Known.Zero &= Known2.Zero;
993     // Output known-1 are known to be set if set in either the LHS | RHS.
994     Known.One |= Known2.One;
995     break;
996   }
997   case ISD::XOR: {
998     SDValue Op0 = Op.getOperand(0);
999     SDValue Op1 = Op.getOperand(1);
1000 
1001     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1002                              Depth + 1))
1003       return true;
1004     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1005     if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
1006                              Depth + 1))
1007       return true;
1008     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1009 
1010     // Attempt to avoid multi-use ops if we don't need anything from them.
1011     if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
1012       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1013           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1014       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1015           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1016       if (DemandedOp0 || DemandedOp1) {
1017         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1018         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1019         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1020         return TLO.CombineTo(Op, NewOp);
1021       }
1022     }
1023 
1024     // If all of the demanded bits are known zero on one side, return the other.
1025     // These bits cannot contribute to the result of the 'xor'.
1026     if (DemandedBits.isSubsetOf(Known.Zero))
1027       return TLO.CombineTo(Op, Op0);
1028     if (DemandedBits.isSubsetOf(Known2.Zero))
1029       return TLO.CombineTo(Op, Op1);
1030     // If the operation can be done in a smaller type, do so.
1031     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1032       return true;
1033 
1034     // If all of the unknown bits are known to be zero on one side or the other
1035     // (but not both) turn this into an *inclusive* or.
1036     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1037     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1038       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
1039 
1040     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1041     KnownOut.Zero = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
1042     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1043     KnownOut.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
1044 
1045     if (ConstantSDNode *C = isConstOrConstSplat(Op1)) {
1046       // If one side is a constant, and all of the known set bits on the other
1047       // side are also set in the constant, turn this into an AND, as we know
1048       // the bits will be cleared.
1049       //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1050       // NB: it is okay if more bits are known than are requested
1051       if (C->getAPIntValue() == Known2.One) {
1052         SDValue ANDC =
1053             TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
1054         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
1055       }
1056 
1057       // If the RHS is a constant, see if we can change it. Don't alter a -1
1058       // constant because that's a 'not' op, and that is better for combining
1059       // and codegen.
1060       if (!C->isAllOnesValue()) {
1061         if (DemandedBits.isSubsetOf(C->getAPIntValue())) {
1062           // We're flipping all demanded bits. Flip the undemanded bits too.
1063           SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
1064           return TLO.CombineTo(Op, New);
1065         }
1066         // If we can't turn this into a 'not', try to shrink the constant.
1067         if (ShrinkDemandedConstant(Op, DemandedBits, TLO))
1068           return true;
1069       }
1070     }
1071 
1072     Known = std::move(KnownOut);
1073     break;
1074   }
1075   case ISD::SELECT:
1076     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO,
1077                              Depth + 1))
1078       return true;
1079     if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO,
1080                              Depth + 1))
1081       return true;
1082     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1083     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1084 
1085     // If the operands are constants, see if we can simplify them.
1086     if (ShrinkDemandedConstant(Op, DemandedBits, TLO))
1087       return true;
1088 
1089     // Only known if known in both the LHS and RHS.
1090     Known.One &= Known2.One;
1091     Known.Zero &= Known2.Zero;
1092     break;
1093   case ISD::SELECT_CC:
1094     if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO,
1095                              Depth + 1))
1096       return true;
1097     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO,
1098                              Depth + 1))
1099       return true;
1100     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1101     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1102 
1103     // If the operands are constants, see if we can simplify them.
1104     if (ShrinkDemandedConstant(Op, DemandedBits, TLO))
1105       return true;
1106 
1107     // Only known if known in both the LHS and RHS.
1108     Known.One &= Known2.One;
1109     Known.Zero &= Known2.Zero;
1110     break;
1111   case ISD::SETCC: {
1112     SDValue Op0 = Op.getOperand(0);
1113     SDValue Op1 = Op.getOperand(1);
1114     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1115     // If (1) we only need the sign-bit, (2) the setcc operands are the same
1116     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
1117     // -1, we may be able to bypass the setcc.
1118     if (DemandedBits.isSignMask() &&
1119         Op0.getScalarValueSizeInBits() == BitWidth &&
1120         getBooleanContents(VT) ==
1121             BooleanContent::ZeroOrNegativeOneBooleanContent) {
1122       // If we're testing X < 0, then this compare isn't needed - just use X!
1123       // FIXME: We're limiting to integer types here, but this should also work
1124       // if we don't care about FP signed-zero. The use of SETLT with FP means
1125       // that we don't care about NaNs.
1126       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
1127           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
1128         return TLO.CombineTo(Op, Op0);
1129 
1130       // TODO: Should we check for other forms of sign-bit comparisons?
1131       // Examples: X <= -1, X >= 0
1132     }
1133     if (getBooleanContents(Op0.getValueType()) ==
1134             TargetLowering::ZeroOrOneBooleanContent &&
1135         BitWidth > 1)
1136       Known.Zero.setBitsFrom(1);
1137     break;
1138   }
1139   case ISD::SHL: {
1140     SDValue Op0 = Op.getOperand(0);
1141     SDValue Op1 = Op.getOperand(1);
1142 
1143     if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
1144       // If the shift count is an invalid immediate, don't do anything.
1145       if (SA->getAPIntValue().uge(BitWidth))
1146         break;
1147 
1148       unsigned ShAmt = SA->getZExtValue();
1149       if (ShAmt == 0)
1150         return TLO.CombineTo(Op, Op0);
1151 
1152       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1153       // single shift.  We can do this if the bottom bits (which are shifted
1154       // out) are never demanded.
1155       // TODO - support non-uniform vector amounts.
1156       if (Op0.getOpcode() == ISD::SRL) {
1157         if ((DemandedBits & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
1158           if (ConstantSDNode *SA2 =
1159                   isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) {
1160             if (SA2->getAPIntValue().ult(BitWidth)) {
1161               unsigned C1 = SA2->getZExtValue();
1162               unsigned Opc = ISD::SHL;
1163               int Diff = ShAmt - C1;
1164               if (Diff < 0) {
1165                 Diff = -Diff;
1166                 Opc = ISD::SRL;
1167               }
1168 
1169               SDValue NewSA = TLO.DAG.getConstant(Diff, dl, Op1.getValueType());
1170               return TLO.CombineTo(
1171                   Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1172             }
1173           }
1174         }
1175       }
1176 
1177       if (SimplifyDemandedBits(Op0, DemandedBits.lshr(ShAmt), DemandedElts,
1178                                Known, TLO, Depth + 1))
1179         return true;
1180 
1181       // Try shrinking the operation as long as the shift amount will still be
1182       // in range.
1183       if ((ShAmt < DemandedBits.getActiveBits()) &&
1184           ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1185         return true;
1186 
1187       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1188       // are not demanded. This will likely allow the anyext to be folded away.
1189       if (Op0.getOpcode() == ISD::ANY_EXTEND) {
1190         SDValue InnerOp = Op0.getOperand(0);
1191         EVT InnerVT = InnerOp.getValueType();
1192         unsigned InnerBits = InnerVT.getScalarSizeInBits();
1193         if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
1194             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
1195           EVT ShTy = getShiftAmountTy(InnerVT, DL);
1196           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
1197             ShTy = InnerVT;
1198           SDValue NarrowShl =
1199               TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
1200                               TLO.DAG.getConstant(ShAmt, dl, ShTy));
1201           return TLO.CombineTo(
1202               Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
1203         }
1204         // Repeat the SHL optimization above in cases where an extension
1205         // intervenes: (shl (anyext (shr x, c1)), c2) to
1206         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
1207         // aren't demanded (as above) and that the shifted upper c1 bits of
1208         // x aren't demanded.
1209         if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL &&
1210             InnerOp.hasOneUse()) {
1211           if (ConstantSDNode *SA2 =
1212                   isConstOrConstSplat(InnerOp.getOperand(1))) {
1213             unsigned InnerShAmt = SA2->getLimitedValue(InnerBits);
1214             if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
1215                 DemandedBits.getActiveBits() <=
1216                     (InnerBits - InnerShAmt + ShAmt) &&
1217                 DemandedBits.countTrailingZeros() >= ShAmt) {
1218               SDValue NewSA = TLO.DAG.getConstant(ShAmt - InnerShAmt, dl,
1219                                                   Op1.getValueType());
1220               SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
1221                                                InnerOp.getOperand(0));
1222               return TLO.CombineTo(
1223                   Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
1224             }
1225           }
1226         }
1227       }
1228 
1229       Known.Zero <<= ShAmt;
1230       Known.One <<= ShAmt;
1231       // low bits known zero.
1232       Known.Zero.setLowBits(ShAmt);
1233     }
1234     break;
1235   }
1236   case ISD::SRL: {
1237     SDValue Op0 = Op.getOperand(0);
1238     SDValue Op1 = Op.getOperand(1);
1239 
1240     if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
1241       // If the shift count is an invalid immediate, don't do anything.
1242       if (SA->getAPIntValue().uge(BitWidth))
1243         break;
1244 
1245       unsigned ShAmt = SA->getZExtValue();
1246       if (ShAmt == 0)
1247         return TLO.CombineTo(Op, Op0);
1248 
1249       EVT ShiftVT = Op1.getValueType();
1250       APInt InDemandedMask = (DemandedBits << ShAmt);
1251 
1252       // If the shift is exact, then it does demand the low bits (and knows that
1253       // they are zero).
1254       if (Op->getFlags().hasExact())
1255         InDemandedMask.setLowBits(ShAmt);
1256 
1257       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
1258       // single shift.  We can do this if the top bits (which are shifted out)
1259       // are never demanded.
1260       // TODO - support non-uniform vector amounts.
1261       if (Op0.getOpcode() == ISD::SHL) {
1262         if (ConstantSDNode *SA2 =
1263                 isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) {
1264           if ((DemandedBits & APInt::getHighBitsSet(BitWidth, ShAmt)) == 0) {
1265             if (SA2->getAPIntValue().ult(BitWidth)) {
1266               unsigned C1 = SA2->getZExtValue();
1267               unsigned Opc = ISD::SRL;
1268               int Diff = ShAmt - C1;
1269               if (Diff < 0) {
1270                 Diff = -Diff;
1271                 Opc = ISD::SHL;
1272               }
1273 
1274               SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1275               return TLO.CombineTo(
1276                   Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1277             }
1278           }
1279         }
1280       }
1281 
1282       // Compute the new bits that are at the top now.
1283       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1284                                Depth + 1))
1285         return true;
1286       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1287       Known.Zero.lshrInPlace(ShAmt);
1288       Known.One.lshrInPlace(ShAmt);
1289 
1290       Known.Zero.setHighBits(ShAmt); // High bits known zero.
1291     }
1292     break;
1293   }
1294   case ISD::SRA: {
1295     SDValue Op0 = Op.getOperand(0);
1296     SDValue Op1 = Op.getOperand(1);
1297 
1298     // If this is an arithmetic shift right and only the low-bit is set, we can
1299     // always convert this into a logical shr, even if the shift amount is
1300     // variable.  The low bit of the shift cannot be an input sign bit unless
1301     // the shift amount is >= the size of the datatype, which is undefined.
1302     if (DemandedBits.isOneValue())
1303       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
1304 
1305     if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
1306       // If the shift count is an invalid immediate, don't do anything.
1307       if (SA->getAPIntValue().uge(BitWidth))
1308         break;
1309 
1310       unsigned ShAmt = SA->getZExtValue();
1311       if (ShAmt == 0)
1312         return TLO.CombineTo(Op, Op0);
1313 
1314       APInt InDemandedMask = (DemandedBits << ShAmt);
1315 
1316       // If the shift is exact, then it does demand the low bits (and knows that
1317       // they are zero).
1318       if (Op->getFlags().hasExact())
1319         InDemandedMask.setLowBits(ShAmt);
1320 
1321       // If any of the demanded bits are produced by the sign extension, we also
1322       // demand the input sign bit.
1323       if (DemandedBits.countLeadingZeros() < ShAmt)
1324         InDemandedMask.setSignBit();
1325 
1326       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1327                                Depth + 1))
1328         return true;
1329       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1330       Known.Zero.lshrInPlace(ShAmt);
1331       Known.One.lshrInPlace(ShAmt);
1332 
1333       // If the input sign bit is known to be zero, or if none of the top bits
1334       // are demanded, turn this into an unsigned shift right.
1335       if (Known.Zero[BitWidth - ShAmt - 1] ||
1336           DemandedBits.countLeadingZeros() >= ShAmt) {
1337         SDNodeFlags Flags;
1338         Flags.setExact(Op->getFlags().hasExact());
1339         return TLO.CombineTo(
1340             Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
1341       }
1342 
1343       int Log2 = DemandedBits.exactLogBase2();
1344       if (Log2 >= 0) {
1345         // The bit must come from the sign.
1346         SDValue NewSA =
1347             TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, Op1.getValueType());
1348         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
1349       }
1350 
1351       if (Known.One[BitWidth - ShAmt - 1])
1352         // New bits are known one.
1353         Known.One.setHighBits(ShAmt);
1354     }
1355     break;
1356   }
1357   case ISD::FSHL:
1358   case ISD::FSHR: {
1359     SDValue Op0 = Op.getOperand(0);
1360     SDValue Op1 = Op.getOperand(1);
1361     SDValue Op2 = Op.getOperand(2);
1362     bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
1363 
1364     if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) {
1365       unsigned Amt = SA->getAPIntValue().urem(BitWidth);
1366 
1367       // For fshl, 0-shift returns the 1st arg.
1368       // For fshr, 0-shift returns the 2nd arg.
1369       if (Amt == 0) {
1370         if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
1371                                  Known, TLO, Depth + 1))
1372           return true;
1373         break;
1374       }
1375 
1376       // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
1377       // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
1378       APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
1379       APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
1380       if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
1381                                Depth + 1))
1382         return true;
1383       if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
1384                                Depth + 1))
1385         return true;
1386 
1387       Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt));
1388       Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt));
1389       Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
1390       Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
1391       Known.One |= Known2.One;
1392       Known.Zero |= Known2.Zero;
1393     }
1394     break;
1395   }
1396   case ISD::BITREVERSE: {
1397     SDValue Src = Op.getOperand(0);
1398     APInt DemandedSrcBits = DemandedBits.reverseBits();
1399     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
1400                              Depth + 1))
1401       return true;
1402     Known.One = Known2.One.reverseBits();
1403     Known.Zero = Known2.Zero.reverseBits();
1404     break;
1405   }
1406   case ISD::SIGN_EXTEND_INREG: {
1407     SDValue Op0 = Op.getOperand(0);
1408     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1409     unsigned ExVTBits = ExVT.getScalarSizeInBits();
1410 
1411     // If we only care about the highest bit, don't bother shifting right.
1412     if (DemandedBits.isSignMask()) {
1413       unsigned NumSignBits = TLO.DAG.ComputeNumSignBits(Op0);
1414       bool AlreadySignExtended = NumSignBits >= BitWidth - ExVTBits + 1;
1415       // However if the input is already sign extended we expect the sign
1416       // extension to be dropped altogether later and do not simplify.
1417       if (!AlreadySignExtended) {
1418         // Compute the correct shift amount type, which must be getShiftAmountTy
1419         // for scalar types after legalization.
1420         EVT ShiftAmtTy = VT;
1421         if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
1422           ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL);
1423 
1424         SDValue ShiftAmt =
1425             TLO.DAG.getConstant(BitWidth - ExVTBits, dl, ShiftAmtTy);
1426         return TLO.CombineTo(Op,
1427                              TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
1428       }
1429     }
1430 
1431     // If none of the extended bits are demanded, eliminate the sextinreg.
1432     if (DemandedBits.getActiveBits() <= ExVTBits)
1433       return TLO.CombineTo(Op, Op0);
1434 
1435     APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
1436 
1437     // Since the sign extended bits are demanded, we know that the sign
1438     // bit is demanded.
1439     InputDemandedBits.setBit(ExVTBits - 1);
1440 
1441     if (SimplifyDemandedBits(Op0, InputDemandedBits, Known, TLO, Depth + 1))
1442       return true;
1443     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1444 
1445     // If the sign bit of the input is known set or clear, then we know the
1446     // top bits of the result.
1447 
1448     // If the input sign bit is known zero, convert this into a zero extension.
1449     if (Known.Zero[ExVTBits - 1])
1450       return TLO.CombineTo(
1451           Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT.getScalarType()));
1452 
1453     APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
1454     if (Known.One[ExVTBits - 1]) { // Input sign bit known set
1455       Known.One.setBitsFrom(ExVTBits);
1456       Known.Zero &= Mask;
1457     } else { // Input sign bit unknown
1458       Known.Zero &= Mask;
1459       Known.One &= Mask;
1460     }
1461     break;
1462   }
1463   case ISD::BUILD_PAIR: {
1464     EVT HalfVT = Op.getOperand(0).getValueType();
1465     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
1466 
1467     APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
1468     APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
1469 
1470     KnownBits KnownLo, KnownHi;
1471 
1472     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
1473       return true;
1474 
1475     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
1476       return true;
1477 
1478     Known.Zero = KnownLo.Zero.zext(BitWidth) |
1479                  KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth);
1480 
1481     Known.One = KnownLo.One.zext(BitWidth) |
1482                 KnownHi.One.zext(BitWidth).shl(HalfBitWidth);
1483     break;
1484   }
1485   case ISD::ZERO_EXTEND:
1486   case ISD::ZERO_EXTEND_VECTOR_INREG: {
1487     SDValue Src = Op.getOperand(0);
1488     EVT SrcVT = Src.getValueType();
1489     unsigned InBits = SrcVT.getScalarSizeInBits();
1490     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
1491     bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
1492 
1493     // If none of the top bits are demanded, convert this into an any_extend.
1494     if (DemandedBits.getActiveBits() <= InBits) {
1495       // If we only need the non-extended bits of the bottom element
1496       // then we can just bitcast to the result.
1497       if (IsVecInReg && DemandedElts == 1 &&
1498           VT.getSizeInBits() == SrcVT.getSizeInBits() &&
1499           TLO.DAG.getDataLayout().isLittleEndian())
1500         return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
1501 
1502       unsigned Opc =
1503           IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND;
1504       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
1505         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
1506     }
1507 
1508     APInt InDemandedBits = DemandedBits.trunc(InBits);
1509     APInt InDemandedElts = DemandedElts.zextOrSelf(InElts);
1510     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
1511                              Depth + 1))
1512       return true;
1513     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1514     assert(Known.getBitWidth() == InBits && "Src width has changed?");
1515     Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
1516     break;
1517   }
1518   case ISD::SIGN_EXTEND:
1519   case ISD::SIGN_EXTEND_VECTOR_INREG: {
1520     SDValue Src = Op.getOperand(0);
1521     EVT SrcVT = Src.getValueType();
1522     unsigned InBits = SrcVT.getScalarSizeInBits();
1523     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
1524     bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
1525 
1526     // If none of the top bits are demanded, convert this into an any_extend.
1527     if (DemandedBits.getActiveBits() <= InBits) {
1528       // If we only need the non-extended bits of the bottom element
1529       // then we can just bitcast to the result.
1530       if (IsVecInReg && DemandedElts == 1 &&
1531           VT.getSizeInBits() == SrcVT.getSizeInBits() &&
1532           TLO.DAG.getDataLayout().isLittleEndian())
1533         return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
1534 
1535       unsigned Opc =
1536           IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND;
1537       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
1538         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
1539     }
1540 
1541     APInt InDemandedBits = DemandedBits.trunc(InBits);
1542     APInt InDemandedElts = DemandedElts.zextOrSelf(InElts);
1543 
1544     // Since some of the sign extended bits are demanded, we know that the sign
1545     // bit is demanded.
1546     InDemandedBits.setBit(InBits - 1);
1547 
1548     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
1549                              Depth + 1))
1550       return true;
1551     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1552     assert(Known.getBitWidth() == InBits && "Src width has changed?");
1553 
1554     // If the sign bit is known one, the top bits match.
1555     Known = Known.sext(BitWidth);
1556 
1557     // If the sign bit is known zero, convert this to a zero extend.
1558     if (Known.isNonNegative()) {
1559       unsigned Opc =
1560           IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND;
1561       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
1562         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
1563     }
1564     break;
1565   }
1566   case ISD::ANY_EXTEND:
1567   case ISD::ANY_EXTEND_VECTOR_INREG: {
1568     SDValue Src = Op.getOperand(0);
1569     EVT SrcVT = Src.getValueType();
1570     unsigned InBits = SrcVT.getScalarSizeInBits();
1571     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
1572     bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG;
1573 
1574     // If we only need the bottom element then we can just bitcast.
1575     // TODO: Handle ANY_EXTEND?
1576     if (IsVecInReg && DemandedElts == 1 &&
1577         VT.getSizeInBits() == SrcVT.getSizeInBits() &&
1578         TLO.DAG.getDataLayout().isLittleEndian())
1579       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
1580 
1581     APInt InDemandedBits = DemandedBits.trunc(InBits);
1582     APInt InDemandedElts = DemandedElts.zextOrSelf(InElts);
1583     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
1584                              Depth + 1))
1585       return true;
1586     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1587     assert(Known.getBitWidth() == InBits && "Src width has changed?");
1588     Known = Known.zext(BitWidth, false /* => any extend */);
1589     break;
1590   }
1591   case ISD::TRUNCATE: {
1592     SDValue Src = Op.getOperand(0);
1593 
1594     // Simplify the input, using demanded bit information, and compute the known
1595     // zero/one bits live out.
1596     unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
1597     APInt TruncMask = DemandedBits.zext(OperandBitWidth);
1598     if (SimplifyDemandedBits(Src, TruncMask, Known, TLO, Depth + 1))
1599       return true;
1600     Known = Known.trunc(BitWidth);
1601 
1602     // If the input is only used by this truncate, see if we can shrink it based
1603     // on the known demanded bits.
1604     if (Src.getNode()->hasOneUse()) {
1605       switch (Src.getOpcode()) {
1606       default:
1607         break;
1608       case ISD::SRL:
1609         // Shrink SRL by a constant if none of the high bits shifted in are
1610         // demanded.
1611         if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
1612           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1613           // undesirable.
1614           break;
1615 
1616         auto *ShAmt = dyn_cast<ConstantSDNode>(Src.getOperand(1));
1617         if (!ShAmt || ShAmt->getAPIntValue().uge(BitWidth))
1618           break;
1619 
1620         SDValue Shift = Src.getOperand(1);
1621         uint64_t ShVal = ShAmt->getZExtValue();
1622 
1623         if (TLO.LegalTypes())
1624           Shift = TLO.DAG.getConstant(ShVal, dl, getShiftAmountTy(VT, DL));
1625 
1626         APInt HighBits =
1627             APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
1628         HighBits.lshrInPlace(ShVal);
1629         HighBits = HighBits.trunc(BitWidth);
1630 
1631         if (!(HighBits & DemandedBits)) {
1632           // None of the shifted in bits are needed.  Add a truncate of the
1633           // shift input, then shift it.
1634           SDValue NewTrunc =
1635               TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
1636           return TLO.CombineTo(
1637               Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, Shift));
1638         }
1639         break;
1640       }
1641     }
1642 
1643     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1644     break;
1645   }
1646   case ISD::AssertZext: {
1647     // AssertZext demands all of the high bits, plus any of the low bits
1648     // demanded by its users.
1649     EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1650     APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits());
1651     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
1652                              TLO, Depth + 1))
1653       return true;
1654     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1655 
1656     Known.Zero |= ~InMask;
1657     break;
1658   }
1659   case ISD::EXTRACT_VECTOR_ELT: {
1660     SDValue Src = Op.getOperand(0);
1661     SDValue Idx = Op.getOperand(1);
1662     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1663     unsigned EltBitWidth = Src.getScalarValueSizeInBits();
1664 
1665     // Demand the bits from every vector element without a constant index.
1666     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
1667     if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
1668       if (CIdx->getAPIntValue().ult(NumSrcElts))
1669         DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
1670 
1671     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
1672     // anything about the extended bits.
1673     APInt DemandedSrcBits = DemandedBits;
1674     if (BitWidth > EltBitWidth)
1675       DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
1676 
1677     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
1678                              Depth + 1))
1679       return true;
1680 
1681     Known = Known2;
1682     if (BitWidth > EltBitWidth)
1683       Known = Known.zext(BitWidth, false /* => any extend */);
1684     break;
1685   }
1686   case ISD::BITCAST: {
1687     SDValue Src = Op.getOperand(0);
1688     EVT SrcVT = Src.getValueType();
1689     unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
1690 
1691     // If this is an FP->Int bitcast and if the sign bit is the only
1692     // thing demanded, turn this into a FGETSIGN.
1693     if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
1694         DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
1695         SrcVT.isFloatingPoint()) {
1696       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT);
1697       bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
1698       if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 &&
1699           SrcVT != MVT::f128) {
1700         // Cannot eliminate/lower SHL for f128 yet.
1701         EVT Ty = OpVTLegal ? VT : MVT::i32;
1702         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1703         // place.  We expect the SHL to be eliminated by other optimizations.
1704         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src);
1705         unsigned OpVTSizeInBits = Op.getValueSizeInBits();
1706         if (!OpVTLegal && OpVTSizeInBits > 32)
1707           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign);
1708         unsigned ShVal = Op.getValueSizeInBits() - 1;
1709         SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT);
1710         return TLO.CombineTo(Op,
1711                              TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
1712       }
1713     }
1714 
1715     // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
1716     // Demand the elt/bit if any of the original elts/bits are demanded.
1717     // TODO - bigendian once we have test coverage.
1718     // TODO - bool vectors once SimplifyDemandedVectorElts has SETCC support.
1719     if (SrcVT.isVector() && NumSrcEltBits > 1 &&
1720         (BitWidth % NumSrcEltBits) == 0 &&
1721         TLO.DAG.getDataLayout().isLittleEndian()) {
1722       unsigned Scale = BitWidth / NumSrcEltBits;
1723       unsigned NumSrcElts = SrcVT.getVectorNumElements();
1724       APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits);
1725       APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts);
1726       for (unsigned i = 0; i != Scale; ++i) {
1727         unsigned Offset = i * NumSrcEltBits;
1728         APInt Sub = DemandedBits.extractBits(NumSrcEltBits, Offset);
1729         if (!Sub.isNullValue()) {
1730           DemandedSrcBits |= Sub;
1731           for (unsigned j = 0; j != NumElts; ++j)
1732             if (DemandedElts[j])
1733               DemandedSrcElts.setBit((j * Scale) + i);
1734         }
1735       }
1736 
1737       APInt KnownSrcUndef, KnownSrcZero;
1738       if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
1739                                      KnownSrcZero, TLO, Depth + 1))
1740         return true;
1741 
1742       KnownBits KnownSrcBits;
1743       if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
1744                                KnownSrcBits, TLO, Depth + 1))
1745         return true;
1746     } else if ((NumSrcEltBits % BitWidth) == 0 &&
1747                TLO.DAG.getDataLayout().isLittleEndian()) {
1748       unsigned Scale = NumSrcEltBits / BitWidth;
1749       unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
1750       APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits);
1751       APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts);
1752       for (unsigned i = 0; i != NumElts; ++i)
1753         if (DemandedElts[i]) {
1754           unsigned Offset = (i % Scale) * BitWidth;
1755           DemandedSrcBits.insertBits(DemandedBits, Offset);
1756           DemandedSrcElts.setBit(i / Scale);
1757         }
1758 
1759       if (SrcVT.isVector()) {
1760         APInt KnownSrcUndef, KnownSrcZero;
1761         if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
1762                                        KnownSrcZero, TLO, Depth + 1))
1763           return true;
1764       }
1765 
1766       KnownBits KnownSrcBits;
1767       if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
1768                                KnownSrcBits, TLO, Depth + 1))
1769         return true;
1770     }
1771 
1772     // If this is a bitcast, let computeKnownBits handle it.  Only do this on a
1773     // recursive call where Known may be useful to the caller.
1774     if (Depth > 0) {
1775       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1776       return false;
1777     }
1778     break;
1779   }
1780   case ISD::ADD:
1781   case ISD::MUL:
1782   case ISD::SUB: {
1783     // Add, Sub, and Mul don't demand any bits in positions beyond that
1784     // of the highest bit demanded of them.
1785     SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
1786     SDNodeFlags Flags = Op.getNode()->getFlags();
1787     unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros();
1788     APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
1789     if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO,
1790                              Depth + 1) ||
1791         SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO,
1792                              Depth + 1) ||
1793         // See if the operation should be performed at a smaller bit width.
1794         ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) {
1795       if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
1796         // Disable the nsw and nuw flags. We can no longer guarantee that we
1797         // won't wrap after simplification.
1798         Flags.setNoSignedWrap(false);
1799         Flags.setNoUnsignedWrap(false);
1800         SDValue NewOp =
1801             TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
1802         return TLO.CombineTo(Op, NewOp);
1803       }
1804       return true;
1805     }
1806 
1807     // Attempt to avoid multi-use ops if we don't need anything from them.
1808     if (!LoMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
1809       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1810           Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
1811       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1812           Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
1813       if (DemandedOp0 || DemandedOp1) {
1814         Flags.setNoSignedWrap(false);
1815         Flags.setNoUnsignedWrap(false);
1816         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1817         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1818         SDValue NewOp =
1819             TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
1820         return TLO.CombineTo(Op, NewOp);
1821       }
1822     }
1823 
1824     // If we have a constant operand, we may be able to turn it into -1 if we
1825     // do not demand the high bits. This can make the constant smaller to
1826     // encode, allow more general folding, or match specialized instruction
1827     // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
1828     // is probably not useful (and could be detrimental).
1829     ConstantSDNode *C = isConstOrConstSplat(Op1);
1830     APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
1831     if (C && !C->isAllOnesValue() && !C->isOne() &&
1832         (C->getAPIntValue() | HighMask).isAllOnesValue()) {
1833       SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
1834       // We can't guarantee that the new math op doesn't wrap, so explicitly
1835       // clear those flags to prevent folding with a potential existing node
1836       // that has those flags set.
1837       SDNodeFlags Flags;
1838       Flags.setNoSignedWrap(false);
1839       Flags.setNoUnsignedWrap(false);
1840       SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags);
1841       return TLO.CombineTo(Op, NewOp);
1842     }
1843 
1844     LLVM_FALLTHROUGH;
1845   }
1846   default:
1847     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1848       if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts,
1849                                             Known, TLO, Depth))
1850         return true;
1851       break;
1852     }
1853 
1854     // Just use computeKnownBits to compute output bits.
1855     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1856     break;
1857   }
1858 
1859   // If we know the value of all of the demanded bits, return this as a
1860   // constant.
1861   if (DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
1862     // Avoid folding to a constant if any OpaqueConstant is involved.
1863     const SDNode *N = Op.getNode();
1864     for (SDNodeIterator I = SDNodeIterator::begin(N),
1865                         E = SDNodeIterator::end(N);
1866          I != E; ++I) {
1867       SDNode *Op = *I;
1868       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
1869         if (C->isOpaque())
1870           return false;
1871     }
1872     // TODO: Handle float bits as well.
1873     if (VT.isInteger())
1874       return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
1875   }
1876 
1877   return false;
1878 }
1879 
1880 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op,
1881                                                 const APInt &DemandedElts,
1882                                                 APInt &KnownUndef,
1883                                                 APInt &KnownZero,
1884                                                 DAGCombinerInfo &DCI) const {
1885   SelectionDAG &DAG = DCI.DAG;
1886   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
1887                         !DCI.isBeforeLegalizeOps());
1888 
1889   bool Simplified =
1890       SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
1891   if (Simplified) {
1892     DCI.AddToWorklist(Op.getNode());
1893     DCI.CommitTargetLoweringOpt(TLO);
1894   }
1895 
1896   return Simplified;
1897 }
1898 
1899 /// Given a vector binary operation and known undefined elements for each input
1900 /// operand, compute whether each element of the output is undefined.
1901 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG,
1902                                          const APInt &UndefOp0,
1903                                          const APInt &UndefOp1) {
1904   EVT VT = BO.getValueType();
1905   assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() &&
1906          "Vector binop only");
1907 
1908   EVT EltVT = VT.getVectorElementType();
1909   unsigned NumElts = VT.getVectorNumElements();
1910   assert(UndefOp0.getBitWidth() == NumElts &&
1911          UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
1912 
1913   auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
1914                                    const APInt &UndefVals) {
1915     if (UndefVals[Index])
1916       return DAG.getUNDEF(EltVT);
1917 
1918     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1919       // Try hard to make sure that the getNode() call is not creating temporary
1920       // nodes. Ignore opaque integers because they do not constant fold.
1921       SDValue Elt = BV->getOperand(Index);
1922       auto *C = dyn_cast<ConstantSDNode>(Elt);
1923       if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
1924         return Elt;
1925     }
1926 
1927     return SDValue();
1928   };
1929 
1930   APInt KnownUndef = APInt::getNullValue(NumElts);
1931   for (unsigned i = 0; i != NumElts; ++i) {
1932     // If both inputs for this element are either constant or undef and match
1933     // the element type, compute the constant/undef result for this element of
1934     // the vector.
1935     // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
1936     // not handle FP constants. The code within getNode() should be refactored
1937     // to avoid the danger of creating a bogus temporary node here.
1938     SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
1939     SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
1940     if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
1941       if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
1942         KnownUndef.setBit(i);
1943   }
1944   return KnownUndef;
1945 }
1946 
1947 bool TargetLowering::SimplifyDemandedVectorElts(
1948     SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
1949     APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
1950     bool AssumeSingleUse) const {
1951   EVT VT = Op.getValueType();
1952   APInt DemandedElts = OriginalDemandedElts;
1953   unsigned NumElts = DemandedElts.getBitWidth();
1954   assert(VT.isVector() && "Expected vector op");
1955   assert(VT.getVectorNumElements() == NumElts &&
1956          "Mask size mismatches value type element count!");
1957 
1958   KnownUndef = KnownZero = APInt::getNullValue(NumElts);
1959 
1960   // Undef operand.
1961   if (Op.isUndef()) {
1962     KnownUndef.setAllBits();
1963     return false;
1964   }
1965 
1966   // If Op has other users, assume that all elements are needed.
1967   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse)
1968     DemandedElts.setAllBits();
1969 
1970   // Not demanding any elements from Op.
1971   if (DemandedElts == 0) {
1972     KnownUndef.setAllBits();
1973     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1974   }
1975 
1976   // Limit search depth.
1977   if (Depth >= 6)
1978     return false;
1979 
1980   SDLoc DL(Op);
1981   unsigned EltSizeInBits = VT.getScalarSizeInBits();
1982 
1983   switch (Op.getOpcode()) {
1984   case ISD::SCALAR_TO_VECTOR: {
1985     if (!DemandedElts[0]) {
1986       KnownUndef.setAllBits();
1987       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1988     }
1989     KnownUndef.setHighBits(NumElts - 1);
1990     break;
1991   }
1992   case ISD::BITCAST: {
1993     SDValue Src = Op.getOperand(0);
1994     EVT SrcVT = Src.getValueType();
1995 
1996     // We only handle vectors here.
1997     // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits?
1998     if (!SrcVT.isVector())
1999       break;
2000 
2001     // Fast handling of 'identity' bitcasts.
2002     unsigned NumSrcElts = SrcVT.getVectorNumElements();
2003     if (NumSrcElts == NumElts)
2004       return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
2005                                         KnownZero, TLO, Depth + 1);
2006 
2007     APInt SrcZero, SrcUndef;
2008     APInt SrcDemandedElts = APInt::getNullValue(NumSrcElts);
2009 
2010     // Bitcast from 'large element' src vector to 'small element' vector, we
2011     // must demand a source element if any DemandedElt maps to it.
2012     if ((NumElts % NumSrcElts) == 0) {
2013       unsigned Scale = NumElts / NumSrcElts;
2014       for (unsigned i = 0; i != NumElts; ++i)
2015         if (DemandedElts[i])
2016           SrcDemandedElts.setBit(i / Scale);
2017 
2018       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2019                                      TLO, Depth + 1))
2020         return true;
2021 
2022       // Try calling SimplifyDemandedBits, converting demanded elts to the bits
2023       // of the large element.
2024       // TODO - bigendian once we have test coverage.
2025       if (TLO.DAG.getDataLayout().isLittleEndian()) {
2026         unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
2027         APInt SrcDemandedBits = APInt::getNullValue(SrcEltSizeInBits);
2028         for (unsigned i = 0; i != NumElts; ++i)
2029           if (DemandedElts[i]) {
2030             unsigned Ofs = (i % Scale) * EltSizeInBits;
2031             SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
2032           }
2033 
2034         KnownBits Known;
2035         if (SimplifyDemandedBits(Src, SrcDemandedBits, Known, TLO, Depth + 1))
2036           return true;
2037       }
2038 
2039       // If the src element is zero/undef then all the output elements will be -
2040       // only demanded elements are guaranteed to be correct.
2041       for (unsigned i = 0; i != NumSrcElts; ++i) {
2042         if (SrcDemandedElts[i]) {
2043           if (SrcZero[i])
2044             KnownZero.setBits(i * Scale, (i + 1) * Scale);
2045           if (SrcUndef[i])
2046             KnownUndef.setBits(i * Scale, (i + 1) * Scale);
2047         }
2048       }
2049     }
2050 
2051     // Bitcast from 'small element' src vector to 'large element' vector, we
2052     // demand all smaller source elements covered by the larger demanded element
2053     // of this vector.
2054     if ((NumSrcElts % NumElts) == 0) {
2055       unsigned Scale = NumSrcElts / NumElts;
2056       for (unsigned i = 0; i != NumElts; ++i)
2057         if (DemandedElts[i])
2058           SrcDemandedElts.setBits(i * Scale, (i + 1) * Scale);
2059 
2060       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2061                                      TLO, Depth + 1))
2062         return true;
2063 
2064       // If all the src elements covering an output element are zero/undef, then
2065       // the output element will be as well, assuming it was demanded.
2066       for (unsigned i = 0; i != NumElts; ++i) {
2067         if (DemandedElts[i]) {
2068           if (SrcZero.extractBits(Scale, i * Scale).isAllOnesValue())
2069             KnownZero.setBit(i);
2070           if (SrcUndef.extractBits(Scale, i * Scale).isAllOnesValue())
2071             KnownUndef.setBit(i);
2072         }
2073       }
2074     }
2075     break;
2076   }
2077   case ISD::BUILD_VECTOR: {
2078     // Check all elements and simplify any unused elements with UNDEF.
2079     if (!DemandedElts.isAllOnesValue()) {
2080       // Don't simplify BROADCASTS.
2081       if (llvm::any_of(Op->op_values(),
2082                        [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
2083         SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end());
2084         bool Updated = false;
2085         for (unsigned i = 0; i != NumElts; ++i) {
2086           if (!DemandedElts[i] && !Ops[i].isUndef()) {
2087             Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
2088             KnownUndef.setBit(i);
2089             Updated = true;
2090           }
2091         }
2092         if (Updated)
2093           return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
2094       }
2095     }
2096     for (unsigned i = 0; i != NumElts; ++i) {
2097       SDValue SrcOp = Op.getOperand(i);
2098       if (SrcOp.isUndef()) {
2099         KnownUndef.setBit(i);
2100       } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
2101                  (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) {
2102         KnownZero.setBit(i);
2103       }
2104     }
2105     break;
2106   }
2107   case ISD::CONCAT_VECTORS: {
2108     EVT SubVT = Op.getOperand(0).getValueType();
2109     unsigned NumSubVecs = Op.getNumOperands();
2110     unsigned NumSubElts = SubVT.getVectorNumElements();
2111     for (unsigned i = 0; i != NumSubVecs; ++i) {
2112       SDValue SubOp = Op.getOperand(i);
2113       APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
2114       APInt SubUndef, SubZero;
2115       if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
2116                                      Depth + 1))
2117         return true;
2118       KnownUndef.insertBits(SubUndef, i * NumSubElts);
2119       KnownZero.insertBits(SubZero, i * NumSubElts);
2120     }
2121     break;
2122   }
2123   case ISD::INSERT_SUBVECTOR: {
2124     if (!isa<ConstantSDNode>(Op.getOperand(2)))
2125       break;
2126     SDValue Base = Op.getOperand(0);
2127     SDValue Sub = Op.getOperand(1);
2128     EVT SubVT = Sub.getValueType();
2129     unsigned NumSubElts = SubVT.getVectorNumElements();
2130     const APInt &Idx = Op.getConstantOperandAPInt(2);
2131     if (Idx.ugt(NumElts - NumSubElts))
2132       break;
2133     unsigned SubIdx = Idx.getZExtValue();
2134     APInt SubElts = DemandedElts.extractBits(NumSubElts, SubIdx);
2135     APInt SubUndef, SubZero;
2136     if (SimplifyDemandedVectorElts(Sub, SubElts, SubUndef, SubZero, TLO,
2137                                    Depth + 1))
2138       return true;
2139     APInt BaseElts = DemandedElts;
2140     BaseElts.insertBits(APInt::getNullValue(NumSubElts), SubIdx);
2141     if (SimplifyDemandedVectorElts(Base, BaseElts, KnownUndef, KnownZero, TLO,
2142                                    Depth + 1))
2143       return true;
2144     KnownUndef.insertBits(SubUndef, SubIdx);
2145     KnownZero.insertBits(SubZero, SubIdx);
2146     break;
2147   }
2148   case ISD::EXTRACT_SUBVECTOR: {
2149     SDValue Src = Op.getOperand(0);
2150     ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2151     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2152     if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2153       // Offset the demanded elts by the subvector index.
2154       uint64_t Idx = SubIdx->getZExtValue();
2155       APInt SrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2156       APInt SrcUndef, SrcZero;
2157       if (SimplifyDemandedVectorElts(Src, SrcElts, SrcUndef, SrcZero, TLO,
2158                                      Depth + 1))
2159         return true;
2160       KnownUndef = SrcUndef.extractBits(NumElts, Idx);
2161       KnownZero = SrcZero.extractBits(NumElts, Idx);
2162     }
2163     break;
2164   }
2165   case ISD::INSERT_VECTOR_ELT: {
2166     SDValue Vec = Op.getOperand(0);
2167     SDValue Scl = Op.getOperand(1);
2168     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2169 
2170     // For a legal, constant insertion index, if we don't need this insertion
2171     // then strip it, else remove it from the demanded elts.
2172     if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
2173       unsigned Idx = CIdx->getZExtValue();
2174       if (!DemandedElts[Idx])
2175         return TLO.CombineTo(Op, Vec);
2176 
2177       APInt DemandedVecElts(DemandedElts);
2178       DemandedVecElts.clearBit(Idx);
2179       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
2180                                      KnownZero, TLO, Depth + 1))
2181         return true;
2182 
2183       KnownUndef.clearBit(Idx);
2184       if (Scl.isUndef())
2185         KnownUndef.setBit(Idx);
2186 
2187       KnownZero.clearBit(Idx);
2188       if (isNullConstant(Scl) || isNullFPConstant(Scl))
2189         KnownZero.setBit(Idx);
2190       break;
2191     }
2192 
2193     APInt VecUndef, VecZero;
2194     if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
2195                                    Depth + 1))
2196       return true;
2197     // Without knowing the insertion index we can't set KnownUndef/KnownZero.
2198     break;
2199   }
2200   case ISD::VSELECT: {
2201     // Try to transform the select condition based on the current demanded
2202     // elements.
2203     // TODO: If a condition element is undef, we can choose from one arm of the
2204     //       select (and if one arm is undef, then we can propagate that to the
2205     //       result).
2206     // TODO - add support for constant vselect masks (see IR version of this).
2207     APInt UnusedUndef, UnusedZero;
2208     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef,
2209                                    UnusedZero, TLO, Depth + 1))
2210       return true;
2211 
2212     // See if we can simplify either vselect operand.
2213     APInt DemandedLHS(DemandedElts);
2214     APInt DemandedRHS(DemandedElts);
2215     APInt UndefLHS, ZeroLHS;
2216     APInt UndefRHS, ZeroRHS;
2217     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS,
2218                                    ZeroLHS, TLO, Depth + 1))
2219       return true;
2220     if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS,
2221                                    ZeroRHS, TLO, Depth + 1))
2222       return true;
2223 
2224     KnownUndef = UndefLHS & UndefRHS;
2225     KnownZero = ZeroLHS & ZeroRHS;
2226     break;
2227   }
2228   case ISD::VECTOR_SHUFFLE: {
2229     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
2230 
2231     // Collect demanded elements from shuffle operands..
2232     APInt DemandedLHS(NumElts, 0);
2233     APInt DemandedRHS(NumElts, 0);
2234     for (unsigned i = 0; i != NumElts; ++i) {
2235       int M = ShuffleMask[i];
2236       if (M < 0 || !DemandedElts[i])
2237         continue;
2238       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
2239       if (M < (int)NumElts)
2240         DemandedLHS.setBit(M);
2241       else
2242         DemandedRHS.setBit(M - NumElts);
2243     }
2244 
2245     // See if we can simplify either shuffle operand.
2246     APInt UndefLHS, ZeroLHS;
2247     APInt UndefRHS, ZeroRHS;
2248     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS,
2249                                    ZeroLHS, TLO, Depth + 1))
2250       return true;
2251     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS,
2252                                    ZeroRHS, TLO, Depth + 1))
2253       return true;
2254 
2255     // Simplify mask using undef elements from LHS/RHS.
2256     bool Updated = false;
2257     bool IdentityLHS = true, IdentityRHS = true;
2258     SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end());
2259     for (unsigned i = 0; i != NumElts; ++i) {
2260       int &M = NewMask[i];
2261       if (M < 0)
2262         continue;
2263       if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
2264           (M >= (int)NumElts && UndefRHS[M - NumElts])) {
2265         Updated = true;
2266         M = -1;
2267       }
2268       IdentityLHS &= (M < 0) || (M == (int)i);
2269       IdentityRHS &= (M < 0) || ((M - NumElts) == i);
2270     }
2271 
2272     // Update legal shuffle masks based on demanded elements if it won't reduce
2273     // to Identity which can cause premature removal of the shuffle mask.
2274     if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps &&
2275         isShuffleMaskLegal(NewMask, VT))
2276       return TLO.CombineTo(Op,
2277                            TLO.DAG.getVectorShuffle(VT, DL, Op.getOperand(0),
2278                                                     Op.getOperand(1), NewMask));
2279 
2280     // Propagate undef/zero elements from LHS/RHS.
2281     for (unsigned i = 0; i != NumElts; ++i) {
2282       int M = ShuffleMask[i];
2283       if (M < 0) {
2284         KnownUndef.setBit(i);
2285       } else if (M < (int)NumElts) {
2286         if (UndefLHS[M])
2287           KnownUndef.setBit(i);
2288         if (ZeroLHS[M])
2289           KnownZero.setBit(i);
2290       } else {
2291         if (UndefRHS[M - NumElts])
2292           KnownUndef.setBit(i);
2293         if (ZeroRHS[M - NumElts])
2294           KnownZero.setBit(i);
2295       }
2296     }
2297     break;
2298   }
2299   case ISD::ANY_EXTEND_VECTOR_INREG:
2300   case ISD::SIGN_EXTEND_VECTOR_INREG:
2301   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2302     APInt SrcUndef, SrcZero;
2303     SDValue Src = Op.getOperand(0);
2304     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2305     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts);
2306     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
2307                                    Depth + 1))
2308       return true;
2309     KnownZero = SrcZero.zextOrTrunc(NumElts);
2310     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
2311 
2312     if (Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
2313         Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
2314         DemandedSrcElts == 1 && TLO.DAG.getDataLayout().isLittleEndian()) {
2315       // aext - if we just need the bottom element then we can bitcast.
2316       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2317     }
2318 
2319     if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
2320       // zext(undef) upper bits are guaranteed to be zero.
2321       if (DemandedElts.isSubsetOf(KnownUndef))
2322         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
2323       KnownUndef.clearAllBits();
2324     }
2325     break;
2326   }
2327 
2328   // TODO: There are more binop opcodes that could be handled here - MUL, MIN,
2329   // MAX, saturated math, etc.
2330   case ISD::OR:
2331   case ISD::XOR:
2332   case ISD::ADD:
2333   case ISD::SUB:
2334   case ISD::FADD:
2335   case ISD::FSUB:
2336   case ISD::FMUL:
2337   case ISD::FDIV:
2338   case ISD::FREM: {
2339     APInt UndefRHS, ZeroRHS;
2340     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, UndefRHS,
2341                                    ZeroRHS, TLO, Depth + 1))
2342       return true;
2343     APInt UndefLHS, ZeroLHS;
2344     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UndefLHS,
2345                                    ZeroLHS, TLO, Depth + 1))
2346       return true;
2347 
2348     KnownZero = ZeroLHS & ZeroRHS;
2349     KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
2350     break;
2351   }
2352   case ISD::SHL:
2353   case ISD::SRL:
2354   case ISD::SRA:
2355   case ISD::ROTL:
2356   case ISD::ROTR: {
2357     APInt UndefRHS, ZeroRHS;
2358     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, UndefRHS,
2359                                    ZeroRHS, TLO, Depth + 1))
2360       return true;
2361     APInt UndefLHS, ZeroLHS;
2362     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UndefLHS,
2363                                    ZeroLHS, TLO, Depth + 1))
2364       return true;
2365 
2366     KnownZero = ZeroLHS;
2367     KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
2368     break;
2369   }
2370   case ISD::MUL:
2371   case ISD::AND: {
2372     APInt SrcUndef, SrcZero;
2373     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedElts, SrcUndef,
2374                                    SrcZero, TLO, Depth + 1))
2375       return true;
2376     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
2377                                    KnownZero, TLO, Depth + 1))
2378       return true;
2379 
2380     // If either side has a zero element, then the result element is zero, even
2381     // if the other is an UNDEF.
2382     // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
2383     // and then handle 'and' nodes with the rest of the binop opcodes.
2384     KnownZero |= SrcZero;
2385     KnownUndef &= SrcUndef;
2386     KnownUndef &= ~KnownZero;
2387     break;
2388   }
2389   case ISD::TRUNCATE:
2390   case ISD::SIGN_EXTEND:
2391   case ISD::ZERO_EXTEND:
2392     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
2393                                    KnownZero, TLO, Depth + 1))
2394       return true;
2395 
2396     if (Op.getOpcode() == ISD::ZERO_EXTEND) {
2397       // zext(undef) upper bits are guaranteed to be zero.
2398       if (DemandedElts.isSubsetOf(KnownUndef))
2399         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
2400       KnownUndef.clearAllBits();
2401     }
2402     break;
2403   default: {
2404     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
2405       if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
2406                                                   KnownZero, TLO, Depth))
2407         return true;
2408     } else {
2409       KnownBits Known;
2410       APInt DemandedBits = APInt::getAllOnesValue(EltSizeInBits);
2411       if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
2412                                TLO, Depth, AssumeSingleUse))
2413         return true;
2414     }
2415     break;
2416   }
2417   }
2418   assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
2419 
2420   // Constant fold all undef cases.
2421   // TODO: Handle zero cases as well.
2422   if (DemandedElts.isSubsetOf(KnownUndef))
2423     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2424 
2425   return false;
2426 }
2427 
2428 /// Determine which of the bits specified in Mask are known to be either zero or
2429 /// one and return them in the Known.
2430 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
2431                                                    KnownBits &Known,
2432                                                    const APInt &DemandedElts,
2433                                                    const SelectionDAG &DAG,
2434                                                    unsigned Depth) const {
2435   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2436           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2437           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2438           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2439          "Should use MaskedValueIsZero if you don't know whether Op"
2440          " is a target node!");
2441   Known.resetAll();
2442 }
2443 
2444 void TargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
2445                                                    KnownBits &Known,
2446                                                    const APInt &DemandedElts,
2447                                                    const SelectionDAG &DAG,
2448                                                    unsigned Depth) const {
2449   assert(isa<FrameIndexSDNode>(Op) && "expected FrameIndex");
2450 
2451   if (unsigned Align = DAG.InferPtrAlignment(Op)) {
2452     // The low bits are known zero if the pointer is aligned.
2453     Known.Zero.setLowBits(Log2_32(Align));
2454   }
2455 }
2456 
2457 /// This method can be implemented by targets that want to expose additional
2458 /// information about sign bits to the DAG Combiner.
2459 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
2460                                                          const APInt &,
2461                                                          const SelectionDAG &,
2462                                                          unsigned Depth) const {
2463   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2464           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2465           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2466           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2467          "Should use ComputeNumSignBits if you don't know whether Op"
2468          " is a target node!");
2469   return 1;
2470 }
2471 
2472 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
2473     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
2474     TargetLoweringOpt &TLO, unsigned Depth) const {
2475   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2476           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2477           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2478           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2479          "Should use SimplifyDemandedVectorElts if you don't know whether Op"
2480          " is a target node!");
2481   return false;
2482 }
2483 
2484 bool TargetLowering::SimplifyDemandedBitsForTargetNode(
2485     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
2486     KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
2487   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2488           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2489           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2490           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2491          "Should use SimplifyDemandedBits if you don't know whether Op"
2492          " is a target node!");
2493   computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
2494   return false;
2495 }
2496 
2497 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
2498     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
2499     SelectionDAG &DAG, unsigned Depth) const {
2500   assert(
2501       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2502        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2503        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2504        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2505       "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
2506       " is a target node!");
2507   return SDValue();
2508 }
2509 
2510 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const {
2511   return nullptr;
2512 }
2513 
2514 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
2515                                                   const SelectionDAG &DAG,
2516                                                   bool SNaN,
2517                                                   unsigned Depth) const {
2518   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2519           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2520           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2521           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2522          "Should use isKnownNeverNaN if you don't know whether Op"
2523          " is a target node!");
2524   return false;
2525 }
2526 
2527 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
2528 // work with truncating build vectors and vectors with elements of less than
2529 // 8 bits.
2530 bool TargetLowering::isConstTrueVal(const SDNode *N) const {
2531   if (!N)
2532     return false;
2533 
2534   APInt CVal;
2535   if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
2536     CVal = CN->getAPIntValue();
2537   } else if (auto *BV = dyn_cast<BuildVectorSDNode>(N)) {
2538     auto *CN = BV->getConstantSplatNode();
2539     if (!CN)
2540       return false;
2541 
2542     // If this is a truncating build vector, truncate the splat value.
2543     // Otherwise, we may fail to match the expected values below.
2544     unsigned BVEltWidth = BV->getValueType(0).getScalarSizeInBits();
2545     CVal = CN->getAPIntValue();
2546     if (BVEltWidth < CVal.getBitWidth())
2547       CVal = CVal.trunc(BVEltWidth);
2548   } else {
2549     return false;
2550   }
2551 
2552   switch (getBooleanContents(N->getValueType(0))) {
2553   case UndefinedBooleanContent:
2554     return CVal[0];
2555   case ZeroOrOneBooleanContent:
2556     return CVal.isOneValue();
2557   case ZeroOrNegativeOneBooleanContent:
2558     return CVal.isAllOnesValue();
2559   }
2560 
2561   llvm_unreachable("Invalid boolean contents");
2562 }
2563 
2564 bool TargetLowering::isConstFalseVal(const SDNode *N) const {
2565   if (!N)
2566     return false;
2567 
2568   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
2569   if (!CN) {
2570     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
2571     if (!BV)
2572       return false;
2573 
2574     // Only interested in constant splats, we don't care about undef
2575     // elements in identifying boolean constants and getConstantSplatNode
2576     // returns NULL if all ops are undef;
2577     CN = BV->getConstantSplatNode();
2578     if (!CN)
2579       return false;
2580   }
2581 
2582   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
2583     return !CN->getAPIntValue()[0];
2584 
2585   return CN->isNullValue();
2586 }
2587 
2588 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
2589                                        bool SExt) const {
2590   if (VT == MVT::i1)
2591     return N->isOne();
2592 
2593   TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
2594   switch (Cnt) {
2595   case TargetLowering::ZeroOrOneBooleanContent:
2596     // An extended value of 1 is always true, unless its original type is i1,
2597     // in which case it will be sign extended to -1.
2598     return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
2599   case TargetLowering::UndefinedBooleanContent:
2600   case TargetLowering::ZeroOrNegativeOneBooleanContent:
2601     return N->isAllOnesValue() && SExt;
2602   }
2603   llvm_unreachable("Unexpected enumeration.");
2604 }
2605 
2606 /// This helper function of SimplifySetCC tries to optimize the comparison when
2607 /// either operand of the SetCC node is a bitwise-and instruction.
2608 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
2609                                          ISD::CondCode Cond, const SDLoc &DL,
2610                                          DAGCombinerInfo &DCI) const {
2611   // Match these patterns in any of their permutations:
2612   // (X & Y) == Y
2613   // (X & Y) != Y
2614   if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
2615     std::swap(N0, N1);
2616 
2617   EVT OpVT = N0.getValueType();
2618   if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
2619       (Cond != ISD::SETEQ && Cond != ISD::SETNE))
2620     return SDValue();
2621 
2622   SDValue X, Y;
2623   if (N0.getOperand(0) == N1) {
2624     X = N0.getOperand(1);
2625     Y = N0.getOperand(0);
2626   } else if (N0.getOperand(1) == N1) {
2627     X = N0.getOperand(0);
2628     Y = N0.getOperand(1);
2629   } else {
2630     return SDValue();
2631   }
2632 
2633   SelectionDAG &DAG = DCI.DAG;
2634   SDValue Zero = DAG.getConstant(0, DL, OpVT);
2635   if (DAG.isKnownToBeAPowerOfTwo(Y)) {
2636     // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
2637     // Note that where Y is variable and is known to have at most one bit set
2638     // (for example, if it is Z & 1) we cannot do this; the expressions are not
2639     // equivalent when Y == 0.
2640     Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
2641     if (DCI.isBeforeLegalizeOps() ||
2642         isCondCodeLegal(Cond, N0.getSimpleValueType()))
2643       return DAG.getSetCC(DL, VT, N0, Zero, Cond);
2644   } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
2645     // If the target supports an 'and-not' or 'and-complement' logic operation,
2646     // try to use that to make a comparison operation more efficient.
2647     // But don't do this transform if the mask is a single bit because there are
2648     // more efficient ways to deal with that case (for example, 'bt' on x86 or
2649     // 'rlwinm' on PPC).
2650 
2651     // Bail out if the compare operand that we want to turn into a zero is
2652     // already a zero (otherwise, infinite loop).
2653     auto *YConst = dyn_cast<ConstantSDNode>(Y);
2654     if (YConst && YConst->isNullValue())
2655       return SDValue();
2656 
2657     // Transform this into: ~X & Y == 0.
2658     SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
2659     SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
2660     return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
2661   }
2662 
2663   return SDValue();
2664 }
2665 
2666 /// There are multiple IR patterns that could be checking whether certain
2667 /// truncation of a signed number would be lossy or not. The pattern which is
2668 /// best at IR level, may not lower optimally. Thus, we want to unfold it.
2669 /// We are looking for the following pattern: (KeptBits is a constant)
2670 ///   (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
2671 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
2672 /// KeptBits also can't be 1, that would have been folded to  %x dstcond 0
2673 /// We will unfold it into the natural trunc+sext pattern:
2674 ///   ((%x << C) a>> C) dstcond %x
2675 /// Where  C = bitwidth(x) - KeptBits  and  C u< bitwidth(x)
2676 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
2677     EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
2678     const SDLoc &DL) const {
2679   // We must be comparing with a constant.
2680   ConstantSDNode *C1;
2681   if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
2682     return SDValue();
2683 
2684   // N0 should be:  add %x, (1 << (KeptBits-1))
2685   if (N0->getOpcode() != ISD::ADD)
2686     return SDValue();
2687 
2688   // And we must be 'add'ing a constant.
2689   ConstantSDNode *C01;
2690   if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
2691     return SDValue();
2692 
2693   SDValue X = N0->getOperand(0);
2694   EVT XVT = X.getValueType();
2695 
2696   // Validate constants ...
2697 
2698   APInt I1 = C1->getAPIntValue();
2699 
2700   ISD::CondCode NewCond;
2701   if (Cond == ISD::CondCode::SETULT) {
2702     NewCond = ISD::CondCode::SETEQ;
2703   } else if (Cond == ISD::CondCode::SETULE) {
2704     NewCond = ISD::CondCode::SETEQ;
2705     // But need to 'canonicalize' the constant.
2706     I1 += 1;
2707   } else if (Cond == ISD::CondCode::SETUGT) {
2708     NewCond = ISD::CondCode::SETNE;
2709     // But need to 'canonicalize' the constant.
2710     I1 += 1;
2711   } else if (Cond == ISD::CondCode::SETUGE) {
2712     NewCond = ISD::CondCode::SETNE;
2713   } else
2714     return SDValue();
2715 
2716   APInt I01 = C01->getAPIntValue();
2717 
2718   auto checkConstants = [&I1, &I01]() -> bool {
2719     // Both of them must be power-of-two, and the constant from setcc is bigger.
2720     return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
2721   };
2722 
2723   if (checkConstants()) {
2724     // Great, e.g. got  icmp ult i16 (add i16 %x, 128), 256
2725   } else {
2726     // What if we invert constants? (and the target predicate)
2727     I1.negate();
2728     I01.negate();
2729     NewCond = getSetCCInverse(NewCond, /*isInteger=*/true);
2730     if (!checkConstants())
2731       return SDValue();
2732     // Great, e.g. got  icmp uge i16 (add i16 %x, -128), -256
2733   }
2734 
2735   // They are power-of-two, so which bit is set?
2736   const unsigned KeptBits = I1.logBase2();
2737   const unsigned KeptBitsMinusOne = I01.logBase2();
2738 
2739   // Magic!
2740   if (KeptBits != (KeptBitsMinusOne + 1))
2741     return SDValue();
2742   assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
2743 
2744   // We don't want to do this in every single case.
2745   SelectionDAG &DAG = DCI.DAG;
2746   if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck(
2747           XVT, KeptBits))
2748     return SDValue();
2749 
2750   const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits;
2751   assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable");
2752 
2753   // Unfold into:  ((%x << C) a>> C) cond %x
2754   // Where 'cond' will be either 'eq' or 'ne'.
2755   SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT);
2756   SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt);
2757   SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt);
2758   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond);
2759 
2760   return T2;
2761 }
2762 
2763 // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
2764 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
2765     EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
2766     DAGCombinerInfo &DCI, const SDLoc &DL) const {
2767   assert(isConstOrConstSplat(N1C) &&
2768          isConstOrConstSplat(N1C)->getAPIntValue().isNullValue() &&
2769          "Should be a comparison with 0.");
2770   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2771          "Valid only for [in]equality comparisons.");
2772 
2773   unsigned NewShiftOpcode;
2774   SDValue X, C, Y;
2775 
2776   SelectionDAG &DAG = DCI.DAG;
2777   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2778 
2779   // Look for '(C l>>/<< Y)'.
2780   auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) {
2781     // The shift should be one-use.
2782     if (!V.hasOneUse())
2783       return false;
2784     unsigned OldShiftOpcode = V.getOpcode();
2785     switch (OldShiftOpcode) {
2786     case ISD::SHL:
2787       NewShiftOpcode = ISD::SRL;
2788       break;
2789     case ISD::SRL:
2790       NewShiftOpcode = ISD::SHL;
2791       break;
2792     default:
2793       return false; // must be a logical shift.
2794     }
2795     // We should be shifting a constant.
2796     // FIXME: best to use isConstantOrConstantVector().
2797     C = V.getOperand(0);
2798     ConstantSDNode *CC =
2799         isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
2800     if (!CC)
2801       return false;
2802     Y = V.getOperand(1);
2803 
2804     ConstantSDNode *XC =
2805         isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
2806     return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
2807         X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
2808   };
2809 
2810   // LHS of comparison should be an one-use 'and'.
2811   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
2812     return SDValue();
2813 
2814   X = N0.getOperand(0);
2815   SDValue Mask = N0.getOperand(1);
2816 
2817   // 'and' is commutative!
2818   if (!Match(Mask)) {
2819     std::swap(X, Mask);
2820     if (!Match(Mask))
2821       return SDValue();
2822   }
2823 
2824   EVT VT = X.getValueType();
2825 
2826   // Produce:
2827   // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
2828   SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
2829   SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
2830   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
2831   return T2;
2832 }
2833 
2834 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as
2835 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
2836 /// handle the commuted versions of these patterns.
2837 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
2838                                            ISD::CondCode Cond, const SDLoc &DL,
2839                                            DAGCombinerInfo &DCI) const {
2840   unsigned BOpcode = N0.getOpcode();
2841   assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
2842          "Unexpected binop");
2843   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
2844 
2845   // (X + Y) == X --> Y == 0
2846   // (X - Y) == X --> Y == 0
2847   // (X ^ Y) == X --> Y == 0
2848   SelectionDAG &DAG = DCI.DAG;
2849   EVT OpVT = N0.getValueType();
2850   SDValue X = N0.getOperand(0);
2851   SDValue Y = N0.getOperand(1);
2852   if (X == N1)
2853     return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
2854 
2855   if (Y != N1)
2856     return SDValue();
2857 
2858   // (X + Y) == Y --> X == 0
2859   // (X ^ Y) == Y --> X == 0
2860   if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
2861     return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
2862 
2863   // The shift would not be valid if the operands are boolean (i1).
2864   if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
2865     return SDValue();
2866 
2867   // (X - Y) == Y --> X == Y << 1
2868   EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(),
2869                                  !DCI.isBeforeLegalize());
2870   SDValue One = DAG.getConstant(1, DL, ShiftVT);
2871   SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
2872   if (!DCI.isCalledByLegalizer())
2873     DCI.AddToWorklist(YShl1.getNode());
2874   return DAG.getSetCC(DL, VT, X, YShl1, Cond);
2875 }
2876 
2877 /// Try to simplify a setcc built with the specified operands and cc. If it is
2878 /// unable to simplify it, return a null SDValue.
2879 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
2880                                       ISD::CondCode Cond, bool foldBooleans,
2881                                       DAGCombinerInfo &DCI,
2882                                       const SDLoc &dl) const {
2883   SelectionDAG &DAG = DCI.DAG;
2884   EVT OpVT = N0.getValueType();
2885 
2886   // Constant fold or commute setcc.
2887   if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
2888     return Fold;
2889 
2890   // Ensure that the constant occurs on the RHS and fold constant comparisons.
2891   // TODO: Handle non-splat vector constants. All undef causes trouble.
2892   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
2893   if (isConstOrConstSplat(N0) &&
2894       (DCI.isBeforeLegalizeOps() ||
2895        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
2896     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
2897 
2898   // If we have a subtract with the same 2 non-constant operands as this setcc
2899   // -- but in reverse order -- then try to commute the operands of this setcc
2900   // to match. A matching pair of setcc (cmp) and sub may be combined into 1
2901   // instruction on some targets.
2902   if (!isConstOrConstSplat(N0) && !isConstOrConstSplat(N1) &&
2903       (DCI.isBeforeLegalizeOps() ||
2904        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
2905       DAG.getNodeIfExists(ISD::SUB, DAG.getVTList(OpVT), { N1, N0 } ) &&
2906       !DAG.getNodeIfExists(ISD::SUB, DAG.getVTList(OpVT), { N0, N1 } ))
2907     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
2908 
2909   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
2910     const APInt &C1 = N1C->getAPIntValue();
2911 
2912     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
2913     // equality comparison, then we're just comparing whether X itself is
2914     // zero.
2915     if (N0.getOpcode() == ISD::SRL && (C1.isNullValue() || C1.isOneValue()) &&
2916         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
2917         N0.getOperand(1).getOpcode() == ISD::Constant) {
2918       const APInt &ShAmt = N0.getConstantOperandAPInt(1);
2919       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2920           ShAmt == Log2_32(N0.getValueSizeInBits())) {
2921         if ((C1 == 0) == (Cond == ISD::SETEQ)) {
2922           // (srl (ctlz x), 5) == 0  -> X != 0
2923           // (srl (ctlz x), 5) != 1  -> X != 0
2924           Cond = ISD::SETNE;
2925         } else {
2926           // (srl (ctlz x), 5) != 0  -> X == 0
2927           // (srl (ctlz x), 5) == 1  -> X == 0
2928           Cond = ISD::SETEQ;
2929         }
2930         SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
2931         return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
2932                             Zero, Cond);
2933       }
2934     }
2935 
2936     SDValue CTPOP = N0;
2937     // Look through truncs that don't change the value of a ctpop.
2938     if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
2939       CTPOP = N0.getOperand(0);
2940 
2941     if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
2942         (N0 == CTPOP ||
2943          N0.getValueSizeInBits() > Log2_32_Ceil(CTPOP.getValueSizeInBits()))) {
2944       EVT CTVT = CTPOP.getValueType();
2945       SDValue CTOp = CTPOP.getOperand(0);
2946 
2947       // (ctpop x) u< 2 -> (x & x-1) == 0
2948       // (ctpop x) u> 1 -> (x & x-1) != 0
2949       if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
2950         SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
2951         SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
2952         SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
2953         ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
2954         return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
2955       }
2956 
2957       // If ctpop is not supported, expand a power-of-2 comparison based on it.
2958       if (C1 == 1 && !isOperationLegalOrCustom(ISD::CTPOP, CTVT) &&
2959           (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
2960         // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0)
2961         // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0)
2962         SDValue Zero = DAG.getConstant(0, dl, CTVT);
2963         SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
2964         ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, true);
2965         SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
2966         SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
2967         SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond);
2968         SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
2969         unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR;
2970         return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS);
2971       }
2972     }
2973 
2974     // (zext x) == C --> x == (trunc C)
2975     // (sext x) == C --> x == (trunc C)
2976     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2977         DCI.isBeforeLegalize() && N0->hasOneUse()) {
2978       unsigned MinBits = N0.getValueSizeInBits();
2979       SDValue PreExt;
2980       bool Signed = false;
2981       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
2982         // ZExt
2983         MinBits = N0->getOperand(0).getValueSizeInBits();
2984         PreExt = N0->getOperand(0);
2985       } else if (N0->getOpcode() == ISD::AND) {
2986         // DAGCombine turns costly ZExts into ANDs
2987         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
2988           if ((C->getAPIntValue()+1).isPowerOf2()) {
2989             MinBits = C->getAPIntValue().countTrailingOnes();
2990             PreExt = N0->getOperand(0);
2991           }
2992       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
2993         // SExt
2994         MinBits = N0->getOperand(0).getValueSizeInBits();
2995         PreExt = N0->getOperand(0);
2996         Signed = true;
2997       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
2998         // ZEXTLOAD / SEXTLOAD
2999         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
3000           MinBits = LN0->getMemoryVT().getSizeInBits();
3001           PreExt = N0;
3002         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
3003           Signed = true;
3004           MinBits = LN0->getMemoryVT().getSizeInBits();
3005           PreExt = N0;
3006         }
3007       }
3008 
3009       // Figure out how many bits we need to preserve this constant.
3010       unsigned ReqdBits = Signed ?
3011         C1.getBitWidth() - C1.getNumSignBits() + 1 :
3012         C1.getActiveBits();
3013 
3014       // Make sure we're not losing bits from the constant.
3015       if (MinBits > 0 &&
3016           MinBits < C1.getBitWidth() &&
3017           MinBits >= ReqdBits) {
3018         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
3019         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
3020           // Will get folded away.
3021           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
3022           if (MinBits == 1 && C1 == 1)
3023             // Invert the condition.
3024             return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
3025                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3026           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
3027           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
3028         }
3029 
3030         // If truncating the setcc operands is not desirable, we can still
3031         // simplify the expression in some cases:
3032         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
3033         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
3034         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
3035         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
3036         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
3037         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
3038         SDValue TopSetCC = N0->getOperand(0);
3039         unsigned N0Opc = N0->getOpcode();
3040         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
3041         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
3042             TopSetCC.getOpcode() == ISD::SETCC &&
3043             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
3044             (isConstFalseVal(N1C) ||
3045              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
3046 
3047           bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) ||
3048                          (!N1C->isNullValue() && Cond == ISD::SETNE);
3049 
3050           if (!Inverse)
3051             return TopSetCC;
3052 
3053           ISD::CondCode InvCond = ISD::getSetCCInverse(
3054               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
3055               TopSetCC.getOperand(0).getValueType().isInteger());
3056           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
3057                                       TopSetCC.getOperand(1),
3058                                       InvCond);
3059         }
3060       }
3061     }
3062 
3063     // If the LHS is '(and load, const)', the RHS is 0, the test is for
3064     // equality or unsigned, and all 1 bits of the const are in the same
3065     // partial word, see if we can shorten the load.
3066     if (DCI.isBeforeLegalize() &&
3067         !ISD::isSignedIntSetCC(Cond) &&
3068         N0.getOpcode() == ISD::AND && C1 == 0 &&
3069         N0.getNode()->hasOneUse() &&
3070         isa<LoadSDNode>(N0.getOperand(0)) &&
3071         N0.getOperand(0).getNode()->hasOneUse() &&
3072         isa<ConstantSDNode>(N0.getOperand(1))) {
3073       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
3074       APInt bestMask;
3075       unsigned bestWidth = 0, bestOffset = 0;
3076       if (!Lod->isVolatile() && Lod->isUnindexed()) {
3077         unsigned origWidth = N0.getValueSizeInBits();
3078         unsigned maskWidth = origWidth;
3079         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
3080         // 8 bits, but have to be careful...
3081         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
3082           origWidth = Lod->getMemoryVT().getSizeInBits();
3083         const APInt &Mask = N0.getConstantOperandAPInt(1);
3084         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
3085           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
3086           for (unsigned offset=0; offset<origWidth/width; offset++) {
3087             if (Mask.isSubsetOf(newMask)) {
3088               if (DAG.getDataLayout().isLittleEndian())
3089                 bestOffset = (uint64_t)offset * (width/8);
3090               else
3091                 bestOffset = (origWidth/width - offset - 1) * (width/8);
3092               bestMask = Mask.lshr(offset * (width/8) * 8);
3093               bestWidth = width;
3094               break;
3095             }
3096             newMask <<= width;
3097           }
3098         }
3099       }
3100       if (bestWidth) {
3101         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
3102         if (newVT.isRound() &&
3103             shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) {
3104           EVT PtrType = Lod->getOperand(1).getValueType();
3105           SDValue Ptr = Lod->getBasePtr();
3106           if (bestOffset != 0)
3107             Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
3108                               DAG.getConstant(bestOffset, dl, PtrType));
3109           unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
3110           SDValue NewLoad = DAG.getLoad(
3111               newVT, dl, Lod->getChain(), Ptr,
3112               Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign);
3113           return DAG.getSetCC(dl, VT,
3114                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
3115                                       DAG.getConstant(bestMask.trunc(bestWidth),
3116                                                       dl, newVT)),
3117                               DAG.getConstant(0LL, dl, newVT), Cond);
3118         }
3119       }
3120     }
3121 
3122     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
3123     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
3124       unsigned InSize = N0.getOperand(0).getValueSizeInBits();
3125 
3126       // If the comparison constant has bits in the upper part, the
3127       // zero-extended value could never match.
3128       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
3129                                               C1.getBitWidth() - InSize))) {
3130         switch (Cond) {
3131         case ISD::SETUGT:
3132         case ISD::SETUGE:
3133         case ISD::SETEQ:
3134           return DAG.getConstant(0, dl, VT);
3135         case ISD::SETULT:
3136         case ISD::SETULE:
3137         case ISD::SETNE:
3138           return DAG.getConstant(1, dl, VT);
3139         case ISD::SETGT:
3140         case ISD::SETGE:
3141           // True if the sign bit of C1 is set.
3142           return DAG.getConstant(C1.isNegative(), dl, VT);
3143         case ISD::SETLT:
3144         case ISD::SETLE:
3145           // True if the sign bit of C1 isn't set.
3146           return DAG.getConstant(C1.isNonNegative(), dl, VT);
3147         default:
3148           break;
3149         }
3150       }
3151 
3152       // Otherwise, we can perform the comparison with the low bits.
3153       switch (Cond) {
3154       case ISD::SETEQ:
3155       case ISD::SETNE:
3156       case ISD::SETUGT:
3157       case ISD::SETUGE:
3158       case ISD::SETULT:
3159       case ISD::SETULE: {
3160         EVT newVT = N0.getOperand(0).getValueType();
3161         if (DCI.isBeforeLegalizeOps() ||
3162             (isOperationLegal(ISD::SETCC, newVT) &&
3163              isCondCodeLegal(Cond, newVT.getSimpleVT()))) {
3164           EVT NewSetCCVT =
3165               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT);
3166           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
3167 
3168           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
3169                                           NewConst, Cond);
3170           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
3171         }
3172         break;
3173       }
3174       default:
3175         break; // todo, be more careful with signed comparisons
3176       }
3177     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3178                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3179       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
3180       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
3181       EVT ExtDstTy = N0.getValueType();
3182       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
3183 
3184       // If the constant doesn't fit into the number of bits for the source of
3185       // the sign extension, it is impossible for both sides to be equal.
3186       if (C1.getMinSignedBits() > ExtSrcTyBits)
3187         return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
3188 
3189       SDValue ZextOp;
3190       EVT Op0Ty = N0.getOperand(0).getValueType();
3191       if (Op0Ty == ExtSrcTy) {
3192         ZextOp = N0.getOperand(0);
3193       } else {
3194         APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
3195         ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
3196                              DAG.getConstant(Imm, dl, Op0Ty));
3197       }
3198       if (!DCI.isCalledByLegalizer())
3199         DCI.AddToWorklist(ZextOp.getNode());
3200       // Otherwise, make this a use of a zext.
3201       return DAG.getSetCC(dl, VT, ZextOp,
3202                           DAG.getConstant(C1 & APInt::getLowBitsSet(
3203                                                               ExtDstTyBits,
3204                                                               ExtSrcTyBits),
3205                                           dl, ExtDstTy),
3206                           Cond);
3207     } else if ((N1C->isNullValue() || N1C->isOne()) &&
3208                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3209       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
3210       if (N0.getOpcode() == ISD::SETCC &&
3211           isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
3212         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
3213         if (TrueWhenTrue)
3214           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
3215         // Invert the condition.
3216         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
3217         CC = ISD::getSetCCInverse(CC,
3218                                   N0.getOperand(0).getValueType().isInteger());
3219         if (DCI.isBeforeLegalizeOps() ||
3220             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
3221           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
3222       }
3223 
3224       if ((N0.getOpcode() == ISD::XOR ||
3225            (N0.getOpcode() == ISD::AND &&
3226             N0.getOperand(0).getOpcode() == ISD::XOR &&
3227             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
3228           isa<ConstantSDNode>(N0.getOperand(1)) &&
3229           cast<ConstantSDNode>(N0.getOperand(1))->isOne()) {
3230         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
3231         // can only do this if the top bits are known zero.
3232         unsigned BitWidth = N0.getValueSizeInBits();
3233         if (DAG.MaskedValueIsZero(N0,
3234                                   APInt::getHighBitsSet(BitWidth,
3235                                                         BitWidth-1))) {
3236           // Okay, get the un-inverted input value.
3237           SDValue Val;
3238           if (N0.getOpcode() == ISD::XOR) {
3239             Val = N0.getOperand(0);
3240           } else {
3241             assert(N0.getOpcode() == ISD::AND &&
3242                     N0.getOperand(0).getOpcode() == ISD::XOR);
3243             // ((X^1)&1)^1 -> X & 1
3244             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
3245                               N0.getOperand(0).getOperand(0),
3246                               N0.getOperand(1));
3247           }
3248 
3249           return DAG.getSetCC(dl, VT, Val, N1,
3250                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3251         }
3252       } else if (N1C->isOne() &&
3253                  (VT == MVT::i1 ||
3254                   getBooleanContents(N0->getValueType(0)) ==
3255                       ZeroOrOneBooleanContent)) {
3256         SDValue Op0 = N0;
3257         if (Op0.getOpcode() == ISD::TRUNCATE)
3258           Op0 = Op0.getOperand(0);
3259 
3260         if ((Op0.getOpcode() == ISD::XOR) &&
3261             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
3262             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
3263           // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
3264           Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
3265           return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
3266                               Cond);
3267         }
3268         if (Op0.getOpcode() == ISD::AND &&
3269             isa<ConstantSDNode>(Op0.getOperand(1)) &&
3270             cast<ConstantSDNode>(Op0.getOperand(1))->isOne()) {
3271           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
3272           if (Op0.getValueType().bitsGT(VT))
3273             Op0 = DAG.getNode(ISD::AND, dl, VT,
3274                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
3275                           DAG.getConstant(1, dl, VT));
3276           else if (Op0.getValueType().bitsLT(VT))
3277             Op0 = DAG.getNode(ISD::AND, dl, VT,
3278                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
3279                         DAG.getConstant(1, dl, VT));
3280 
3281           return DAG.getSetCC(dl, VT, Op0,
3282                               DAG.getConstant(0, dl, Op0.getValueType()),
3283                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3284         }
3285         if (Op0.getOpcode() == ISD::AssertZext &&
3286             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
3287           return DAG.getSetCC(dl, VT, Op0,
3288                               DAG.getConstant(0, dl, Op0.getValueType()),
3289                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3290       }
3291     }
3292 
3293     // Given:
3294     //   icmp eq/ne (urem %x, %y), 0
3295     // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
3296     //   icmp eq/ne %x, 0
3297     if (N0.getOpcode() == ISD::UREM && N1C->isNullValue() &&
3298         (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3299       KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
3300       KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
3301       if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
3302         return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
3303     }
3304 
3305     if (SDValue V =
3306             optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
3307       return V;
3308   }
3309 
3310   // These simplifications apply to splat vectors as well.
3311   // TODO: Handle more splat vector cases.
3312   if (auto *N1C = isConstOrConstSplat(N1)) {
3313     const APInt &C1 = N1C->getAPIntValue();
3314 
3315     APInt MinVal, MaxVal;
3316     unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
3317     if (ISD::isSignedIntSetCC(Cond)) {
3318       MinVal = APInt::getSignedMinValue(OperandBitSize);
3319       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
3320     } else {
3321       MinVal = APInt::getMinValue(OperandBitSize);
3322       MaxVal = APInt::getMaxValue(OperandBitSize);
3323     }
3324 
3325     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
3326     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
3327       // X >= MIN --> true
3328       if (C1 == MinVal)
3329         return DAG.getBoolConstant(true, dl, VT, OpVT);
3330 
3331       if (!VT.isVector()) { // TODO: Support this for vectors.
3332         // X >= C0 --> X > (C0 - 1)
3333         APInt C = C1 - 1;
3334         ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
3335         if ((DCI.isBeforeLegalizeOps() ||
3336              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
3337             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
3338                                   isLegalICmpImmediate(C.getSExtValue())))) {
3339           return DAG.getSetCC(dl, VT, N0,
3340                               DAG.getConstant(C, dl, N1.getValueType()),
3341                               NewCC);
3342         }
3343       }
3344     }
3345 
3346     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
3347       // X <= MAX --> true
3348       if (C1 == MaxVal)
3349         return DAG.getBoolConstant(true, dl, VT, OpVT);
3350 
3351       // X <= C0 --> X < (C0 + 1)
3352       if (!VT.isVector()) { // TODO: Support this for vectors.
3353         APInt C = C1 + 1;
3354         ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
3355         if ((DCI.isBeforeLegalizeOps() ||
3356              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
3357             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
3358                                   isLegalICmpImmediate(C.getSExtValue())))) {
3359           return DAG.getSetCC(dl, VT, N0,
3360                               DAG.getConstant(C, dl, N1.getValueType()),
3361                               NewCC);
3362         }
3363       }
3364     }
3365 
3366     if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
3367       if (C1 == MinVal)
3368         return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
3369 
3370       // TODO: Support this for vectors after legalize ops.
3371       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
3372         // Canonicalize setlt X, Max --> setne X, Max
3373         if (C1 == MaxVal)
3374           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
3375 
3376         // If we have setult X, 1, turn it into seteq X, 0
3377         if (C1 == MinVal+1)
3378           return DAG.getSetCC(dl, VT, N0,
3379                               DAG.getConstant(MinVal, dl, N0.getValueType()),
3380                               ISD::SETEQ);
3381       }
3382     }
3383 
3384     if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
3385       if (C1 == MaxVal)
3386         return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
3387 
3388       // TODO: Support this for vectors after legalize ops.
3389       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
3390         // Canonicalize setgt X, Min --> setne X, Min
3391         if (C1 == MinVal)
3392           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
3393 
3394         // If we have setugt X, Max-1, turn it into seteq X, Max
3395         if (C1 == MaxVal-1)
3396           return DAG.getSetCC(dl, VT, N0,
3397                               DAG.getConstant(MaxVal, dl, N0.getValueType()),
3398                               ISD::SETEQ);
3399       }
3400     }
3401 
3402     if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
3403       // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
3404       if (C1.isNullValue())
3405         if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
3406                 VT, N0, N1, Cond, DCI, dl))
3407           return CC;
3408     }
3409 
3410     // If we have "setcc X, C0", check to see if we can shrink the immediate
3411     // by changing cc.
3412     // TODO: Support this for vectors after legalize ops.
3413     if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
3414       // SETUGT X, SINTMAX  -> SETLT X, 0
3415       if (Cond == ISD::SETUGT &&
3416           C1 == APInt::getSignedMaxValue(OperandBitSize))
3417         return DAG.getSetCC(dl, VT, N0,
3418                             DAG.getConstant(0, dl, N1.getValueType()),
3419                             ISD::SETLT);
3420 
3421       // SETULT X, SINTMIN  -> SETGT X, -1
3422       if (Cond == ISD::SETULT &&
3423           C1 == APInt::getSignedMinValue(OperandBitSize)) {
3424         SDValue ConstMinusOne =
3425             DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
3426                             N1.getValueType());
3427         return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
3428       }
3429     }
3430   }
3431 
3432   // Back to non-vector simplifications.
3433   // TODO: Can we do these for vector splats?
3434   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
3435     const APInt &C1 = N1C->getAPIntValue();
3436 
3437     // Fold bit comparisons when we can.
3438     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3439         (VT == N0.getValueType() ||
3440          (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
3441         N0.getOpcode() == ISD::AND) {
3442       auto &DL = DAG.getDataLayout();
3443       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3444         EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL,
3445                                        !DCI.isBeforeLegalize());
3446         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
3447           // Perform the xform if the AND RHS is a single bit.
3448           if (AndRHS->getAPIntValue().isPowerOf2()) {
3449             return DAG.getNode(ISD::TRUNCATE, dl, VT,
3450                               DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
3451                    DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl,
3452                                    ShiftTy)));
3453           }
3454         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
3455           // (X & 8) == 8  -->  (X & 8) >> 3
3456           // Perform the xform if C1 is a single bit.
3457           if (C1.isPowerOf2()) {
3458             return DAG.getNode(ISD::TRUNCATE, dl, VT,
3459                                DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
3460                                       DAG.getConstant(C1.logBase2(), dl,
3461                                                       ShiftTy)));
3462           }
3463         }
3464       }
3465     }
3466 
3467     if (C1.getMinSignedBits() <= 64 &&
3468         !isLegalICmpImmediate(C1.getSExtValue())) {
3469       // (X & -256) == 256 -> (X >> 8) == 1
3470       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3471           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
3472         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3473           const APInt &AndRHSC = AndRHS->getAPIntValue();
3474           if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
3475             unsigned ShiftBits = AndRHSC.countTrailingZeros();
3476             auto &DL = DAG.getDataLayout();
3477             EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL,
3478                                            !DCI.isBeforeLegalize());
3479             EVT CmpTy = N0.getValueType();
3480             SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
3481                                         DAG.getConstant(ShiftBits, dl,
3482                                                         ShiftTy));
3483             SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy);
3484             return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
3485           }
3486         }
3487       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
3488                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
3489         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
3490         // X <  0x100000000 -> (X >> 32) <  1
3491         // X >= 0x100000000 -> (X >> 32) >= 1
3492         // X <= 0x0ffffffff -> (X >> 32) <  1
3493         // X >  0x0ffffffff -> (X >> 32) >= 1
3494         unsigned ShiftBits;
3495         APInt NewC = C1;
3496         ISD::CondCode NewCond = Cond;
3497         if (AdjOne) {
3498           ShiftBits = C1.countTrailingOnes();
3499           NewC = NewC + 1;
3500           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3501         } else {
3502           ShiftBits = C1.countTrailingZeros();
3503         }
3504         NewC.lshrInPlace(ShiftBits);
3505         if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
3506           isLegalICmpImmediate(NewC.getSExtValue())) {
3507           auto &DL = DAG.getDataLayout();
3508           EVT ShiftTy = getShiftAmountTy(N0.getValueType(), DL,
3509                                          !DCI.isBeforeLegalize());
3510           EVT CmpTy = N0.getValueType();
3511           SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
3512                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
3513           SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy);
3514           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
3515         }
3516       }
3517     }
3518   }
3519 
3520   if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) {
3521     auto *CFP = cast<ConstantFPSDNode>(N1);
3522     assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
3523 
3524     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
3525     // constant if knowing that the operand is non-nan is enough.  We prefer to
3526     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
3527     // materialize 0.0.
3528     if (Cond == ISD::SETO || Cond == ISD::SETUO)
3529       return DAG.getSetCC(dl, VT, N0, N0, Cond);
3530 
3531     // setcc (fneg x), C -> setcc swap(pred) x, -C
3532     if (N0.getOpcode() == ISD::FNEG) {
3533       ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
3534       if (DCI.isBeforeLegalizeOps() ||
3535           isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
3536         SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
3537         return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
3538       }
3539     }
3540 
3541     // If the condition is not legal, see if we can find an equivalent one
3542     // which is legal.
3543     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
3544       // If the comparison was an awkward floating-point == or != and one of
3545       // the comparison operands is infinity or negative infinity, convert the
3546       // condition to a less-awkward <= or >=.
3547       if (CFP->getValueAPF().isInfinity()) {
3548         if (CFP->getValueAPF().isNegative()) {
3549           if (Cond == ISD::SETOEQ &&
3550               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
3551             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
3552           if (Cond == ISD::SETUEQ &&
3553               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
3554             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
3555           if (Cond == ISD::SETUNE &&
3556               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
3557             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
3558           if (Cond == ISD::SETONE &&
3559               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
3560             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
3561         } else {
3562           if (Cond == ISD::SETOEQ &&
3563               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
3564             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
3565           if (Cond == ISD::SETUEQ &&
3566               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
3567             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
3568           if (Cond == ISD::SETUNE &&
3569               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
3570             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
3571           if (Cond == ISD::SETONE &&
3572               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
3573             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
3574         }
3575       }
3576     }
3577   }
3578 
3579   if (N0 == N1) {
3580     // The sext(setcc()) => setcc() optimization relies on the appropriate
3581     // constant being emitted.
3582     assert(!N0.getValueType().isInteger() &&
3583            "Integer types should be handled by FoldSetCC");
3584 
3585     bool EqTrue = ISD::isTrueWhenEqual(Cond);
3586     unsigned UOF = ISD::getUnorderedFlavor(Cond);
3587     if (UOF == 2) // FP operators that are undefined on NaNs.
3588       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
3589     if (UOF == unsigned(EqTrue))
3590       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
3591     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
3592     // if it is not already.
3593     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
3594     if (NewCond != Cond &&
3595         (DCI.isBeforeLegalizeOps() ||
3596                             isCondCodeLegal(NewCond, N0.getSimpleValueType())))
3597       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
3598   }
3599 
3600   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3601       N0.getValueType().isInteger()) {
3602     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
3603         N0.getOpcode() == ISD::XOR) {
3604       // Simplify (X+Y) == (X+Z) -->  Y == Z
3605       if (N0.getOpcode() == N1.getOpcode()) {
3606         if (N0.getOperand(0) == N1.getOperand(0))
3607           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
3608         if (N0.getOperand(1) == N1.getOperand(1))
3609           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
3610         if (isCommutativeBinOp(N0.getOpcode())) {
3611           // If X op Y == Y op X, try other combinations.
3612           if (N0.getOperand(0) == N1.getOperand(1))
3613             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
3614                                 Cond);
3615           if (N0.getOperand(1) == N1.getOperand(0))
3616             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
3617                                 Cond);
3618         }
3619       }
3620 
3621       // If RHS is a legal immediate value for a compare instruction, we need
3622       // to be careful about increasing register pressure needlessly.
3623       bool LegalRHSImm = false;
3624 
3625       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
3626         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3627           // Turn (X+C1) == C2 --> X == C2-C1
3628           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
3629             return DAG.getSetCC(dl, VT, N0.getOperand(0),
3630                                 DAG.getConstant(RHSC->getAPIntValue()-
3631                                                 LHSR->getAPIntValue(),
3632                                 dl, N0.getValueType()), Cond);
3633           }
3634 
3635           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
3636           if (N0.getOpcode() == ISD::XOR)
3637             // If we know that all of the inverted bits are zero, don't bother
3638             // performing the inversion.
3639             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
3640               return
3641                 DAG.getSetCC(dl, VT, N0.getOperand(0),
3642                              DAG.getConstant(LHSR->getAPIntValue() ^
3643                                                RHSC->getAPIntValue(),
3644                                              dl, N0.getValueType()),
3645                              Cond);
3646         }
3647 
3648         // Turn (C1-X) == C2 --> X == C1-C2
3649         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
3650           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
3651             return
3652               DAG.getSetCC(dl, VT, N0.getOperand(1),
3653                            DAG.getConstant(SUBC->getAPIntValue() -
3654                                              RHSC->getAPIntValue(),
3655                                            dl, N0.getValueType()),
3656                            Cond);
3657           }
3658         }
3659 
3660         // Could RHSC fold directly into a compare?
3661         if (RHSC->getValueType(0).getSizeInBits() <= 64)
3662           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
3663       }
3664 
3665       // (X+Y) == X --> Y == 0 and similar folds.
3666       // Don't do this if X is an immediate that can fold into a cmp
3667       // instruction and X+Y has other uses. It could be an induction variable
3668       // chain, and the transform would increase register pressure.
3669       if (!LegalRHSImm || N0.hasOneUse())
3670         if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
3671           return V;
3672     }
3673 
3674     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
3675         N1.getOpcode() == ISD::XOR)
3676       if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
3677         return V;
3678 
3679     if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
3680       return V;
3681   }
3682 
3683   // Fold remainder of division by a constant.
3684   if (N0.getOpcode() == ISD::UREM && N0.hasOneUse() &&
3685       (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3686     AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
3687 
3688     // When division is cheap or optimizing for minimum size,
3689     // fall through to DIVREM creation by skipping this fold.
3690     if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttribute(Attribute::MinSize))
3691       if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
3692         return Folded;
3693   }
3694 
3695   // Fold away ALL boolean setcc's.
3696   if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
3697     SDValue Temp;
3698     switch (Cond) {
3699     default: llvm_unreachable("Unknown integer setcc!");
3700     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
3701       Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
3702       N0 = DAG.getNOT(dl, Temp, OpVT);
3703       if (!DCI.isCalledByLegalizer())
3704         DCI.AddToWorklist(Temp.getNode());
3705       break;
3706     case ISD::SETNE:  // X != Y   -->  (X^Y)
3707       N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
3708       break;
3709     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
3710     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
3711       Temp = DAG.getNOT(dl, N0, OpVT);
3712       N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
3713       if (!DCI.isCalledByLegalizer())
3714         DCI.AddToWorklist(Temp.getNode());
3715       break;
3716     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
3717     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
3718       Temp = DAG.getNOT(dl, N1, OpVT);
3719       N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
3720       if (!DCI.isCalledByLegalizer())
3721         DCI.AddToWorklist(Temp.getNode());
3722       break;
3723     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
3724     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
3725       Temp = DAG.getNOT(dl, N0, OpVT);
3726       N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
3727       if (!DCI.isCalledByLegalizer())
3728         DCI.AddToWorklist(Temp.getNode());
3729       break;
3730     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
3731     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
3732       Temp = DAG.getNOT(dl, N1, OpVT);
3733       N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
3734       break;
3735     }
3736     if (VT.getScalarType() != MVT::i1) {
3737       if (!DCI.isCalledByLegalizer())
3738         DCI.AddToWorklist(N0.getNode());
3739       // FIXME: If running after legalize, we probably can't do this.
3740       ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT));
3741       N0 = DAG.getNode(ExtendCode, dl, VT, N0);
3742     }
3743     return N0;
3744   }
3745 
3746   // Could not fold it.
3747   return SDValue();
3748 }
3749 
3750 /// Returns true (and the GlobalValue and the offset) if the node is a
3751 /// GlobalAddress + offset.
3752 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA,
3753                                     int64_t &Offset) const {
3754 
3755   SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
3756 
3757   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
3758     GA = GASD->getGlobal();
3759     Offset += GASD->getOffset();
3760     return true;
3761   }
3762 
3763   if (N->getOpcode() == ISD::ADD) {
3764     SDValue N1 = N->getOperand(0);
3765     SDValue N2 = N->getOperand(1);
3766     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
3767       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
3768         Offset += V->getSExtValue();
3769         return true;
3770       }
3771     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
3772       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
3773         Offset += V->getSExtValue();
3774         return true;
3775       }
3776     }
3777   }
3778 
3779   return false;
3780 }
3781 
3782 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
3783                                           DAGCombinerInfo &DCI) const {
3784   // Default implementation: no optimization.
3785   return SDValue();
3786 }
3787 
3788 //===----------------------------------------------------------------------===//
3789 //  Inline Assembler Implementation Methods
3790 //===----------------------------------------------------------------------===//
3791 
3792 TargetLowering::ConstraintType
3793 TargetLowering::getConstraintType(StringRef Constraint) const {
3794   unsigned S = Constraint.size();
3795 
3796   if (S == 1) {
3797     switch (Constraint[0]) {
3798     default: break;
3799     case 'r': return C_RegisterClass;
3800     case 'm': // memory
3801     case 'o': // offsetable
3802     case 'V': // not offsetable
3803       return C_Memory;
3804     case 'i': // Simple Integer or Relocatable Constant
3805     case 'n': // Simple Integer
3806     case 'E': // Floating Point Constant
3807     case 'F': // Floating Point Constant
3808     case 's': // Relocatable Constant
3809     case 'p': // Address.
3810     case 'X': // Allow ANY value.
3811     case 'I': // Target registers.
3812     case 'J':
3813     case 'K':
3814     case 'L':
3815     case 'M':
3816     case 'N':
3817     case 'O':
3818     case 'P':
3819     case '<':
3820     case '>':
3821       return C_Other;
3822     }
3823   }
3824 
3825   if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
3826     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
3827       return C_Memory;
3828     return C_Register;
3829   }
3830   return C_Unknown;
3831 }
3832 
3833 /// Try to replace an X constraint, which matches anything, with another that
3834 /// has more specific requirements based on the type of the corresponding
3835 /// operand.
3836 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
3837   if (ConstraintVT.isInteger())
3838     return "r";
3839   if (ConstraintVT.isFloatingPoint())
3840     return "f"; // works for many targets
3841   return nullptr;
3842 }
3843 
3844 SDValue TargetLowering::LowerAsmOutputForConstraint(
3845     SDValue &Chain, SDValue &Flag, SDLoc DL, const AsmOperandInfo &OpInfo,
3846     SelectionDAG &DAG) const {
3847   return SDValue();
3848 }
3849 
3850 /// Lower the specified operand into the Ops vector.
3851 /// If it is invalid, don't add anything to Ops.
3852 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3853                                                   std::string &Constraint,
3854                                                   std::vector<SDValue> &Ops,
3855                                                   SelectionDAG &DAG) const {
3856 
3857   if (Constraint.length() > 1) return;
3858 
3859   char ConstraintLetter = Constraint[0];
3860   switch (ConstraintLetter) {
3861   default: break;
3862   case 'X':     // Allows any operand; labels (basic block) use this.
3863     if (Op.getOpcode() == ISD::BasicBlock ||
3864         Op.getOpcode() == ISD::TargetBlockAddress) {
3865       Ops.push_back(Op);
3866       return;
3867     }
3868     LLVM_FALLTHROUGH;
3869   case 'i':    // Simple Integer or Relocatable Constant
3870   case 'n':    // Simple Integer
3871   case 's': {  // Relocatable Constant
3872 
3873     GlobalAddressSDNode *GA;
3874     ConstantSDNode *C;
3875     BlockAddressSDNode *BA;
3876     uint64_t Offset = 0;
3877 
3878     // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
3879     // etc., since getelementpointer is variadic. We can't use
3880     // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
3881     // while in this case the GA may be furthest from the root node which is
3882     // likely an ISD::ADD.
3883     while (1) {
3884       if ((GA = dyn_cast<GlobalAddressSDNode>(Op)) && ConstraintLetter != 'n') {
3885         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
3886                                                  GA->getValueType(0),
3887                                                  Offset + GA->getOffset()));
3888         return;
3889       } else if ((C = dyn_cast<ConstantSDNode>(Op)) &&
3890                  ConstraintLetter != 's') {
3891         // gcc prints these as sign extended.  Sign extend value to 64 bits
3892         // now; without this it would get ZExt'd later in
3893         // ScheduleDAGSDNodes::EmitNode, which is very generic.
3894         bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
3895         BooleanContent BCont = getBooleanContents(MVT::i64);
3896         ISD::NodeType ExtOpc = IsBool ? getExtendForContent(BCont)
3897                                       : ISD::SIGN_EXTEND;
3898         int64_t ExtVal = ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue()
3899                                                     : C->getSExtValue();
3900         Ops.push_back(DAG.getTargetConstant(Offset + ExtVal,
3901                                             SDLoc(C), MVT::i64));
3902         return;
3903       } else if ((BA = dyn_cast<BlockAddressSDNode>(Op)) &&
3904                  ConstraintLetter != 'n') {
3905         Ops.push_back(DAG.getTargetBlockAddress(
3906             BA->getBlockAddress(), BA->getValueType(0),
3907             Offset + BA->getOffset(), BA->getTargetFlags()));
3908         return;
3909       } else {
3910         const unsigned OpCode = Op.getOpcode();
3911         if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
3912           if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
3913             Op = Op.getOperand(1);
3914           // Subtraction is not commutative.
3915           else if (OpCode == ISD::ADD &&
3916                    (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
3917             Op = Op.getOperand(0);
3918           else
3919             return;
3920           Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
3921           continue;
3922         }
3923       }
3924       return;
3925     }
3926     break;
3927   }
3928   }
3929 }
3930 
3931 std::pair<unsigned, const TargetRegisterClass *>
3932 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
3933                                              StringRef Constraint,
3934                                              MVT VT) const {
3935   if (Constraint.empty() || Constraint[0] != '{')
3936     return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
3937   assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
3938 
3939   // Remove the braces from around the name.
3940   StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
3941 
3942   std::pair<unsigned, const TargetRegisterClass *> R =
3943       std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
3944 
3945   // Figure out which register class contains this reg.
3946   for (const TargetRegisterClass *RC : RI->regclasses()) {
3947     // If none of the value types for this register class are valid, we
3948     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
3949     if (!isLegalRC(*RI, *RC))
3950       continue;
3951 
3952     for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
3953          I != E; ++I) {
3954       if (RegName.equals_lower(RI->getRegAsmName(*I))) {
3955         std::pair<unsigned, const TargetRegisterClass *> S =
3956             std::make_pair(*I, RC);
3957 
3958         // If this register class has the requested value type, return it,
3959         // otherwise keep searching and return the first class found
3960         // if no other is found which explicitly has the requested type.
3961         if (RI->isTypeLegalForClass(*RC, VT))
3962           return S;
3963         if (!R.second)
3964           R = S;
3965       }
3966     }
3967   }
3968 
3969   return R;
3970 }
3971 
3972 //===----------------------------------------------------------------------===//
3973 // Constraint Selection.
3974 
3975 /// Return true of this is an input operand that is a matching constraint like
3976 /// "4".
3977 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
3978   assert(!ConstraintCode.empty() && "No known constraint!");
3979   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
3980 }
3981 
3982 /// If this is an input matching constraint, this method returns the output
3983 /// operand it matches.
3984 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
3985   assert(!ConstraintCode.empty() && "No known constraint!");
3986   return atoi(ConstraintCode.c_str());
3987 }
3988 
3989 /// Split up the constraint string from the inline assembly value into the
3990 /// specific constraints and their prefixes, and also tie in the associated
3991 /// operand values.
3992 /// If this returns an empty vector, and if the constraint string itself
3993 /// isn't empty, there was an error parsing.
3994 TargetLowering::AsmOperandInfoVector
3995 TargetLowering::ParseConstraints(const DataLayout &DL,
3996                                  const TargetRegisterInfo *TRI,
3997                                  ImmutableCallSite CS) const {
3998   /// Information about all of the constraints.
3999   AsmOperandInfoVector ConstraintOperands;
4000   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4001   unsigned maCount = 0; // Largest number of multiple alternative constraints.
4002 
4003   // Do a prepass over the constraints, canonicalizing them, and building up the
4004   // ConstraintOperands list.
4005   unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4006   unsigned ResNo = 0; // ResNo - The result number of the next output.
4007 
4008   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
4009     ConstraintOperands.emplace_back(std::move(CI));
4010     AsmOperandInfo &OpInfo = ConstraintOperands.back();
4011 
4012     // Update multiple alternative constraint count.
4013     if (OpInfo.multipleAlternatives.size() > maCount)
4014       maCount = OpInfo.multipleAlternatives.size();
4015 
4016     OpInfo.ConstraintVT = MVT::Other;
4017 
4018     // Compute the value type for each operand.
4019     switch (OpInfo.Type) {
4020     case InlineAsm::isOutput:
4021       // Indirect outputs just consume an argument.
4022       if (OpInfo.isIndirect) {
4023         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
4024         break;
4025       }
4026 
4027       // The return value of the call is this value.  As such, there is no
4028       // corresponding argument.
4029       assert(!CS.getType()->isVoidTy() &&
4030              "Bad inline asm!");
4031       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
4032         OpInfo.ConstraintVT =
4033             getSimpleValueType(DL, STy->getElementType(ResNo));
4034       } else {
4035         assert(ResNo == 0 && "Asm only has one result!");
4036         OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType());
4037       }
4038       ++ResNo;
4039       break;
4040     case InlineAsm::isInput:
4041       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
4042       break;
4043     case InlineAsm::isClobber:
4044       // Nothing to do.
4045       break;
4046     }
4047 
4048     if (OpInfo.CallOperandVal) {
4049       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
4050       if (OpInfo.isIndirect) {
4051         llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
4052         if (!PtrTy)
4053           report_fatal_error("Indirect operand for inline asm not a pointer!");
4054         OpTy = PtrTy->getElementType();
4055       }
4056 
4057       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
4058       if (StructType *STy = dyn_cast<StructType>(OpTy))
4059         if (STy->getNumElements() == 1)
4060           OpTy = STy->getElementType(0);
4061 
4062       // If OpTy is not a single value, it may be a struct/union that we
4063       // can tile with integers.
4064       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4065         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
4066         switch (BitSize) {
4067         default: break;
4068         case 1:
4069         case 8:
4070         case 16:
4071         case 32:
4072         case 64:
4073         case 128:
4074           OpInfo.ConstraintVT =
4075               MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
4076           break;
4077         }
4078       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
4079         unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
4080         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
4081       } else {
4082         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
4083       }
4084     }
4085   }
4086 
4087   // If we have multiple alternative constraints, select the best alternative.
4088   if (!ConstraintOperands.empty()) {
4089     if (maCount) {
4090       unsigned bestMAIndex = 0;
4091       int bestWeight = -1;
4092       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
4093       int weight = -1;
4094       unsigned maIndex;
4095       // Compute the sums of the weights for each alternative, keeping track
4096       // of the best (highest weight) one so far.
4097       for (maIndex = 0; maIndex < maCount; ++maIndex) {
4098         int weightSum = 0;
4099         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
4100              cIndex != eIndex; ++cIndex) {
4101           AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
4102           if (OpInfo.Type == InlineAsm::isClobber)
4103             continue;
4104 
4105           // If this is an output operand with a matching input operand,
4106           // look up the matching input. If their types mismatch, e.g. one
4107           // is an integer, the other is floating point, or their sizes are
4108           // different, flag it as an maCantMatch.
4109           if (OpInfo.hasMatchingInput()) {
4110             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4111             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
4112               if ((OpInfo.ConstraintVT.isInteger() !=
4113                    Input.ConstraintVT.isInteger()) ||
4114                   (OpInfo.ConstraintVT.getSizeInBits() !=
4115                    Input.ConstraintVT.getSizeInBits())) {
4116                 weightSum = -1; // Can't match.
4117                 break;
4118               }
4119             }
4120           }
4121           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
4122           if (weight == -1) {
4123             weightSum = -1;
4124             break;
4125           }
4126           weightSum += weight;
4127         }
4128         // Update best.
4129         if (weightSum > bestWeight) {
4130           bestWeight = weightSum;
4131           bestMAIndex = maIndex;
4132         }
4133       }
4134 
4135       // Now select chosen alternative in each constraint.
4136       for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
4137            cIndex != eIndex; ++cIndex) {
4138         AsmOperandInfo &cInfo = ConstraintOperands[cIndex];
4139         if (cInfo.Type == InlineAsm::isClobber)
4140           continue;
4141         cInfo.selectAlternative(bestMAIndex);
4142       }
4143     }
4144   }
4145 
4146   // Check and hook up tied operands, choose constraint code to use.
4147   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
4148        cIndex != eIndex; ++cIndex) {
4149     AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
4150 
4151     // If this is an output operand with a matching input operand, look up the
4152     // matching input. If their types mismatch, e.g. one is an integer, the
4153     // other is floating point, or their sizes are different, flag it as an
4154     // error.
4155     if (OpInfo.hasMatchingInput()) {
4156       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4157 
4158       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
4159         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
4160             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
4161                                          OpInfo.ConstraintVT);
4162         std::pair<unsigned, const TargetRegisterClass *> InputRC =
4163             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
4164                                          Input.ConstraintVT);
4165         if ((OpInfo.ConstraintVT.isInteger() !=
4166              Input.ConstraintVT.isInteger()) ||
4167             (MatchRC.second != InputRC.second)) {
4168           report_fatal_error("Unsupported asm: input constraint"
4169                              " with a matching output constraint of"
4170                              " incompatible type!");
4171         }
4172       }
4173     }
4174   }
4175 
4176   return ConstraintOperands;
4177 }
4178 
4179 /// Return an integer indicating how general CT is.
4180 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
4181   switch (CT) {
4182   case TargetLowering::C_Other:
4183   case TargetLowering::C_Unknown:
4184     return 0;
4185   case TargetLowering::C_Register:
4186     return 1;
4187   case TargetLowering::C_RegisterClass:
4188     return 2;
4189   case TargetLowering::C_Memory:
4190     return 3;
4191   }
4192   llvm_unreachable("Invalid constraint type");
4193 }
4194 
4195 /// Examine constraint type and operand type and determine a weight value.
4196 /// This object must already have been set up with the operand type
4197 /// and the current alternative constraint selected.
4198 TargetLowering::ConstraintWeight
4199   TargetLowering::getMultipleConstraintMatchWeight(
4200     AsmOperandInfo &info, int maIndex) const {
4201   InlineAsm::ConstraintCodeVector *rCodes;
4202   if (maIndex >= (int)info.multipleAlternatives.size())
4203     rCodes = &info.Codes;
4204   else
4205     rCodes = &info.multipleAlternatives[maIndex].Codes;
4206   ConstraintWeight BestWeight = CW_Invalid;
4207 
4208   // Loop over the options, keeping track of the most general one.
4209   for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
4210     ConstraintWeight weight =
4211       getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
4212     if (weight > BestWeight)
4213       BestWeight = weight;
4214   }
4215 
4216   return BestWeight;
4217 }
4218 
4219 /// Examine constraint type and operand type and determine a weight value.
4220 /// This object must already have been set up with the operand type
4221 /// and the current alternative constraint selected.
4222 TargetLowering::ConstraintWeight
4223   TargetLowering::getSingleConstraintMatchWeight(
4224     AsmOperandInfo &info, const char *constraint) const {
4225   ConstraintWeight weight = CW_Invalid;
4226   Value *CallOperandVal = info.CallOperandVal;
4227     // If we don't have a value, we can't do a match,
4228     // but allow it at the lowest weight.
4229   if (!CallOperandVal)
4230     return CW_Default;
4231   // Look at the constraint type.
4232   switch (*constraint) {
4233     case 'i': // immediate integer.
4234     case 'n': // immediate integer with a known value.
4235       if (isa<ConstantInt>(CallOperandVal))
4236         weight = CW_Constant;
4237       break;
4238     case 's': // non-explicit intregal immediate.
4239       if (isa<GlobalValue>(CallOperandVal))
4240         weight = CW_Constant;
4241       break;
4242     case 'E': // immediate float if host format.
4243     case 'F': // immediate float.
4244       if (isa<ConstantFP>(CallOperandVal))
4245         weight = CW_Constant;
4246       break;
4247     case '<': // memory operand with autodecrement.
4248     case '>': // memory operand with autoincrement.
4249     case 'm': // memory operand.
4250     case 'o': // offsettable memory operand
4251     case 'V': // non-offsettable memory operand
4252       weight = CW_Memory;
4253       break;
4254     case 'r': // general register.
4255     case 'g': // general register, memory operand or immediate integer.
4256               // note: Clang converts "g" to "imr".
4257       if (CallOperandVal->getType()->isIntegerTy())
4258         weight = CW_Register;
4259       break;
4260     case 'X': // any operand.
4261   default:
4262     weight = CW_Default;
4263     break;
4264   }
4265   return weight;
4266 }
4267 
4268 /// If there are multiple different constraints that we could pick for this
4269 /// operand (e.g. "imr") try to pick the 'best' one.
4270 /// This is somewhat tricky: constraints fall into four classes:
4271 ///    Other         -> immediates and magic values
4272 ///    Register      -> one specific register
4273 ///    RegisterClass -> a group of regs
4274 ///    Memory        -> memory
4275 /// Ideally, we would pick the most specific constraint possible: if we have
4276 /// something that fits into a register, we would pick it.  The problem here
4277 /// is that if we have something that could either be in a register or in
4278 /// memory that use of the register could cause selection of *other*
4279 /// operands to fail: they might only succeed if we pick memory.  Because of
4280 /// this the heuristic we use is:
4281 ///
4282 ///  1) If there is an 'other' constraint, and if the operand is valid for
4283 ///     that constraint, use it.  This makes us take advantage of 'i'
4284 ///     constraints when available.
4285 ///  2) Otherwise, pick the most general constraint present.  This prefers
4286 ///     'm' over 'r', for example.
4287 ///
4288 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
4289                              const TargetLowering &TLI,
4290                              SDValue Op, SelectionDAG *DAG) {
4291   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
4292   unsigned BestIdx = 0;
4293   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
4294   int BestGenerality = -1;
4295 
4296   // Loop over the options, keeping track of the most general one.
4297   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
4298     TargetLowering::ConstraintType CType =
4299       TLI.getConstraintType(OpInfo.Codes[i]);
4300 
4301     // If this is an 'other' constraint, see if the operand is valid for it.
4302     // For example, on X86 we might have an 'rI' constraint.  If the operand
4303     // is an integer in the range [0..31] we want to use I (saving a load
4304     // of a register), otherwise we must use 'r'.
4305     if (CType == TargetLowering::C_Other && Op.getNode()) {
4306       assert(OpInfo.Codes[i].size() == 1 &&
4307              "Unhandled multi-letter 'other' constraint");
4308       std::vector<SDValue> ResultOps;
4309       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
4310                                        ResultOps, *DAG);
4311       if (!ResultOps.empty()) {
4312         BestType = CType;
4313         BestIdx = i;
4314         break;
4315       }
4316     }
4317 
4318     // Things with matching constraints can only be registers, per gcc
4319     // documentation.  This mainly affects "g" constraints.
4320     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
4321       continue;
4322 
4323     // This constraint letter is more general than the previous one, use it.
4324     int Generality = getConstraintGenerality(CType);
4325     if (Generality > BestGenerality) {
4326       BestType = CType;
4327       BestIdx = i;
4328       BestGenerality = Generality;
4329     }
4330   }
4331 
4332   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
4333   OpInfo.ConstraintType = BestType;
4334 }
4335 
4336 /// Determines the constraint code and constraint type to use for the specific
4337 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
4338 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
4339                                             SDValue Op,
4340                                             SelectionDAG *DAG) const {
4341   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
4342 
4343   // Single-letter constraints ('r') are very common.
4344   if (OpInfo.Codes.size() == 1) {
4345     OpInfo.ConstraintCode = OpInfo.Codes[0];
4346     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
4347   } else {
4348     ChooseConstraint(OpInfo, *this, Op, DAG);
4349   }
4350 
4351   // 'X' matches anything.
4352   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
4353     // Labels and constants are handled elsewhere ('X' is the only thing
4354     // that matches labels).  For Functions, the type here is the type of
4355     // the result, which is not what we want to look at; leave them alone.
4356     Value *v = OpInfo.CallOperandVal;
4357     if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
4358       OpInfo.CallOperandVal = v;
4359       return;
4360     }
4361 
4362     if (Op.getNode() && Op.getOpcode() == ISD::TargetBlockAddress)
4363       return;
4364 
4365     // Otherwise, try to resolve it to something we know about by looking at
4366     // the actual operand type.
4367     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
4368       OpInfo.ConstraintCode = Repl;
4369       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
4370     }
4371   }
4372 }
4373 
4374 /// Given an exact SDIV by a constant, create a multiplication
4375 /// with the multiplicative inverse of the constant.
4376 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N,
4377                               const SDLoc &dl, SelectionDAG &DAG,
4378                               SmallVectorImpl<SDNode *> &Created) {
4379   SDValue Op0 = N->getOperand(0);
4380   SDValue Op1 = N->getOperand(1);
4381   EVT VT = N->getValueType(0);
4382   EVT SVT = VT.getScalarType();
4383   EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
4384   EVT ShSVT = ShVT.getScalarType();
4385 
4386   bool UseSRA = false;
4387   SmallVector<SDValue, 16> Shifts, Factors;
4388 
4389   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
4390     if (C->isNullValue())
4391       return false;
4392     APInt Divisor = C->getAPIntValue();
4393     unsigned Shift = Divisor.countTrailingZeros();
4394     if (Shift) {
4395       Divisor.ashrInPlace(Shift);
4396       UseSRA = true;
4397     }
4398     // Calculate the multiplicative inverse, using Newton's method.
4399     APInt t;
4400     APInt Factor = Divisor;
4401     while ((t = Divisor * Factor) != 1)
4402       Factor *= APInt(Divisor.getBitWidth(), 2) - t;
4403     Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
4404     Factors.push_back(DAG.getConstant(Factor, dl, SVT));
4405     return true;
4406   };
4407 
4408   // Collect all magic values from the build vector.
4409   if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
4410     return SDValue();
4411 
4412   SDValue Shift, Factor;
4413   if (VT.isVector()) {
4414     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
4415     Factor = DAG.getBuildVector(VT, dl, Factors);
4416   } else {
4417     Shift = Shifts[0];
4418     Factor = Factors[0];
4419   }
4420 
4421   SDValue Res = Op0;
4422 
4423   // Shift the value upfront if it is even, so the LSB is one.
4424   if (UseSRA) {
4425     // TODO: For UDIV use SRL instead of SRA.
4426     SDNodeFlags Flags;
4427     Flags.setExact(true);
4428     Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags);
4429     Created.push_back(Res.getNode());
4430   }
4431 
4432   return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
4433 }
4434 
4435 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
4436                               SelectionDAG &DAG,
4437                               SmallVectorImpl<SDNode *> &Created) const {
4438   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4439   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4440   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
4441     return SDValue(N, 0); // Lower SDIV as SDIV
4442   return SDValue();
4443 }
4444 
4445 /// Given an ISD::SDIV node expressing a divide by constant,
4446 /// return a DAG expression to select that will generate the same value by
4447 /// multiplying by a magic number.
4448 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
4449 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
4450                                   bool IsAfterLegalization,
4451                                   SmallVectorImpl<SDNode *> &Created) const {
4452   SDLoc dl(N);
4453   EVT VT = N->getValueType(0);
4454   EVT SVT = VT.getScalarType();
4455   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
4456   EVT ShSVT = ShVT.getScalarType();
4457   unsigned EltBits = VT.getScalarSizeInBits();
4458 
4459   // Check to see if we can do this.
4460   // FIXME: We should be more aggressive here.
4461   if (!isTypeLegal(VT))
4462     return SDValue();
4463 
4464   // If the sdiv has an 'exact' bit we can use a simpler lowering.
4465   if (N->getFlags().hasExact())
4466     return BuildExactSDIV(*this, N, dl, DAG, Created);
4467 
4468   SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
4469 
4470   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
4471     if (C->isNullValue())
4472       return false;
4473 
4474     const APInt &Divisor = C->getAPIntValue();
4475     APInt::ms magics = Divisor.magic();
4476     int NumeratorFactor = 0;
4477     int ShiftMask = -1;
4478 
4479     if (Divisor.isOneValue() || Divisor.isAllOnesValue()) {
4480       // If d is +1/-1, we just multiply the numerator by +1/-1.
4481       NumeratorFactor = Divisor.getSExtValue();
4482       magics.m = 0;
4483       magics.s = 0;
4484       ShiftMask = 0;
4485     } else if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
4486       // If d > 0 and m < 0, add the numerator.
4487       NumeratorFactor = 1;
4488     } else if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
4489       // If d < 0 and m > 0, subtract the numerator.
4490       NumeratorFactor = -1;
4491     }
4492 
4493     MagicFactors.push_back(DAG.getConstant(magics.m, dl, SVT));
4494     Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT));
4495     Shifts.push_back(DAG.getConstant(magics.s, dl, ShSVT));
4496     ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT));
4497     return true;
4498   };
4499 
4500   SDValue N0 = N->getOperand(0);
4501   SDValue N1 = N->getOperand(1);
4502 
4503   // Collect the shifts / magic values from each element.
4504   if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern))
4505     return SDValue();
4506 
4507   SDValue MagicFactor, Factor, Shift, ShiftMask;
4508   if (VT.isVector()) {
4509     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
4510     Factor = DAG.getBuildVector(VT, dl, Factors);
4511     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
4512     ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
4513   } else {
4514     MagicFactor = MagicFactors[0];
4515     Factor = Factors[0];
4516     Shift = Shifts[0];
4517     ShiftMask = ShiftMasks[0];
4518   }
4519 
4520   // Multiply the numerator (operand 0) by the magic value.
4521   // FIXME: We should support doing a MUL in a wider type.
4522   SDValue Q;
4523   if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT)
4524                           : isOperationLegalOrCustom(ISD::MULHS, VT))
4525     Q = DAG.getNode(ISD::MULHS, dl, VT, N0, MagicFactor);
4526   else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT)
4527                                : isOperationLegalOrCustom(ISD::SMUL_LOHI, VT)) {
4528     SDValue LoHi =
4529         DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), N0, MagicFactor);
4530     Q = SDValue(LoHi.getNode(), 1);
4531   } else
4532     return SDValue(); // No mulhs or equivalent.
4533   Created.push_back(Q.getNode());
4534 
4535   // (Optionally) Add/subtract the numerator using Factor.
4536   Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
4537   Created.push_back(Factor.getNode());
4538   Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
4539   Created.push_back(Q.getNode());
4540 
4541   // Shift right algebraic by shift value.
4542   Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
4543   Created.push_back(Q.getNode());
4544 
4545   // Extract the sign bit, mask it and add it to the quotient.
4546   SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
4547   SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
4548   Created.push_back(T.getNode());
4549   T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
4550   Created.push_back(T.getNode());
4551   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
4552 }
4553 
4554 /// Given an ISD::UDIV node expressing a divide by constant,
4555 /// return a DAG expression to select that will generate the same value by
4556 /// multiplying by a magic number.
4557 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
4558 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
4559                                   bool IsAfterLegalization,
4560                                   SmallVectorImpl<SDNode *> &Created) const {
4561   SDLoc dl(N);
4562   EVT VT = N->getValueType(0);
4563   EVT SVT = VT.getScalarType();
4564   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
4565   EVT ShSVT = ShVT.getScalarType();
4566   unsigned EltBits = VT.getScalarSizeInBits();
4567 
4568   // Check to see if we can do this.
4569   // FIXME: We should be more aggressive here.
4570   if (!isTypeLegal(VT))
4571     return SDValue();
4572 
4573   bool UseNPQ = false;
4574   SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
4575 
4576   auto BuildUDIVPattern = [&](ConstantSDNode *C) {
4577     if (C->isNullValue())
4578       return false;
4579     // FIXME: We should use a narrower constant when the upper
4580     // bits are known to be zero.
4581     APInt Divisor = C->getAPIntValue();
4582     APInt::mu magics = Divisor.magicu();
4583     unsigned PreShift = 0, PostShift = 0;
4584 
4585     // If the divisor is even, we can avoid using the expensive fixup by
4586     // shifting the divided value upfront.
4587     if (magics.a != 0 && !Divisor[0]) {
4588       PreShift = Divisor.countTrailingZeros();
4589       // Get magic number for the shifted divisor.
4590       magics = Divisor.lshr(PreShift).magicu(PreShift);
4591       assert(magics.a == 0 && "Should use cheap fixup now");
4592     }
4593 
4594     APInt Magic = magics.m;
4595 
4596     unsigned SelNPQ;
4597     if (magics.a == 0 || Divisor.isOneValue()) {
4598       assert(magics.s < Divisor.getBitWidth() &&
4599              "We shouldn't generate an undefined shift!");
4600       PostShift = magics.s;
4601       SelNPQ = false;
4602     } else {
4603       PostShift = magics.s - 1;
4604       SelNPQ = true;
4605     }
4606 
4607     PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT));
4608     MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT));
4609     NPQFactors.push_back(
4610         DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
4611                                : APInt::getNullValue(EltBits),
4612                         dl, SVT));
4613     PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT));
4614     UseNPQ |= SelNPQ;
4615     return true;
4616   };
4617 
4618   SDValue N0 = N->getOperand(0);
4619   SDValue N1 = N->getOperand(1);
4620 
4621   // Collect the shifts/magic values from each element.
4622   if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern))
4623     return SDValue();
4624 
4625   SDValue PreShift, PostShift, MagicFactor, NPQFactor;
4626   if (VT.isVector()) {
4627     PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
4628     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
4629     NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
4630     PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
4631   } else {
4632     PreShift = PreShifts[0];
4633     MagicFactor = MagicFactors[0];
4634     PostShift = PostShifts[0];
4635   }
4636 
4637   SDValue Q = N0;
4638   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
4639   Created.push_back(Q.getNode());
4640 
4641   // FIXME: We should support doing a MUL in a wider type.
4642   auto GetMULHU = [&](SDValue X, SDValue Y) {
4643     if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT)
4644                             : isOperationLegalOrCustom(ISD::MULHU, VT))
4645       return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
4646     if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT)
4647                             : isOperationLegalOrCustom(ISD::UMUL_LOHI, VT)) {
4648       SDValue LoHi =
4649           DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
4650       return SDValue(LoHi.getNode(), 1);
4651     }
4652     return SDValue(); // No mulhu or equivalent
4653   };
4654 
4655   // Multiply the numerator (operand 0) by the magic value.
4656   Q = GetMULHU(Q, MagicFactor);
4657   if (!Q)
4658     return SDValue();
4659 
4660   Created.push_back(Q.getNode());
4661 
4662   if (UseNPQ) {
4663     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
4664     Created.push_back(NPQ.getNode());
4665 
4666     // For vectors we might have a mix of non-NPQ/NPQ paths, so use
4667     // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
4668     if (VT.isVector())
4669       NPQ = GetMULHU(NPQ, NPQFactor);
4670     else
4671       NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
4672 
4673     Created.push_back(NPQ.getNode());
4674 
4675     Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
4676     Created.push_back(Q.getNode());
4677   }
4678 
4679   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
4680   Created.push_back(Q.getNode());
4681 
4682   SDValue One = DAG.getConstant(1, dl, VT);
4683   SDValue IsOne = DAG.getSetCC(dl, VT, N1, One, ISD::SETEQ);
4684   return DAG.getSelect(dl, VT, IsOne, N0, Q);
4685 }
4686 
4687 /// If all values in Values that *don't* match the predicate are same 'splat'
4688 /// value, then replace all values with that splat value.
4689 /// Else, if AlternativeReplacement was provided, then replace all values that
4690 /// do match predicate with AlternativeReplacement value.
4691 static void
4692 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values,
4693                           std::function<bool(SDValue)> Predicate,
4694                           SDValue AlternativeReplacement = SDValue()) {
4695   SDValue Replacement;
4696   // Is there a value for which the Predicate does *NOT* match? What is it?
4697   auto SplatValue = llvm::find_if_not(Values, Predicate);
4698   if (SplatValue != Values.end()) {
4699     // Does Values consist only of SplatValue's and values matching Predicate?
4700     if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
4701           return Value == *SplatValue || Predicate(Value);
4702         })) // Then we shall replace values matching predicate with SplatValue.
4703       Replacement = *SplatValue;
4704   }
4705   if (!Replacement) {
4706     // Oops, we did not find the "baseline" splat value.
4707     if (!AlternativeReplacement)
4708       return; // Nothing to do.
4709     // Let's replace with provided value then.
4710     Replacement = AlternativeReplacement;
4711   }
4712   std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
4713 }
4714 
4715 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
4716 /// where the divisor is constant and the comparison target is zero,
4717 /// return a DAG expression that will generate the same comparison result
4718 /// using only multiplications, additions and shifts/rotations.
4719 /// Ref: "Hacker's Delight" 10-17.
4720 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
4721                                         SDValue CompTargetNode,
4722                                         ISD::CondCode Cond,
4723                                         DAGCombinerInfo &DCI,
4724                                         const SDLoc &DL) const {
4725   SmallVector<SDNode *, 2> Built;
4726   if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
4727                                          DCI, DL, Built)) {
4728     for (SDNode *N : Built)
4729       DCI.AddToWorklist(N);
4730     return Folded;
4731   }
4732 
4733   return SDValue();
4734 }
4735 
4736 SDValue
4737 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
4738                                   SDValue CompTargetNode, ISD::CondCode Cond,
4739                                   DAGCombinerInfo &DCI, const SDLoc &DL,
4740                                   SmallVectorImpl<SDNode *> &Created) const {
4741   // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q)
4742   // - D must be constant, with D = D0 * 2^K where D0 is odd
4743   // - P is the multiplicative inverse of D0 modulo 2^W
4744   // - Q = floor((2^W - 1) / D0)
4745   // where W is the width of the common type of N and D.
4746   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4747          "Only applicable for (in)equality comparisons.");
4748 
4749   SelectionDAG &DAG = DCI.DAG;
4750 
4751   EVT VT = REMNode.getValueType();
4752   EVT SVT = VT.getScalarType();
4753   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
4754   EVT ShSVT = ShVT.getScalarType();
4755 
4756   // If MUL is unavailable, we cannot proceed in any case.
4757   if (!isOperationLegalOrCustom(ISD::MUL, VT))
4758     return SDValue();
4759 
4760   // TODO: Could support comparing with non-zero too.
4761   ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
4762   if (!CompTarget || !CompTarget->isNullValue())
4763     return SDValue();
4764 
4765   bool HadOneDivisor = false;
4766   bool AllDivisorsAreOnes = true;
4767   bool HadEvenDivisor = false;
4768   bool AllDivisorsArePowerOfTwo = true;
4769   SmallVector<SDValue, 16> PAmts, KAmts, QAmts;
4770 
4771   auto BuildUREMPattern = [&](ConstantSDNode *C) {
4772     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
4773     if (C->isNullValue())
4774       return false;
4775 
4776     const APInt &D = C->getAPIntValue();
4777     // If all divisors are ones, we will prefer to avoid the fold.
4778     HadOneDivisor |= D.isOneValue();
4779     AllDivisorsAreOnes &= D.isOneValue();
4780 
4781     // Decompose D into D0 * 2^K
4782     unsigned K = D.countTrailingZeros();
4783     assert((!D.isOneValue() || (K == 0)) && "For divisor '1' we won't rotate.");
4784     APInt D0 = D.lshr(K);
4785 
4786     // D is even if it has trailing zeros.
4787     HadEvenDivisor |= (K != 0);
4788     // D is a power-of-two if D0 is one.
4789     // If all divisors are power-of-two, we will prefer to avoid the fold.
4790     AllDivisorsArePowerOfTwo &= D0.isOneValue();
4791 
4792     // P = inv(D0, 2^W)
4793     // 2^W requires W + 1 bits, so we have to extend and then truncate.
4794     unsigned W = D.getBitWidth();
4795     APInt P = D0.zext(W + 1)
4796                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
4797                   .trunc(W);
4798     assert(!P.isNullValue() && "No multiplicative inverse!"); // unreachable
4799     assert((D0 * P).isOneValue() && "Multiplicative inverse sanity check.");
4800 
4801     // Q = floor((2^W - 1) / D)
4802     APInt Q = APInt::getAllOnesValue(W).udiv(D);
4803 
4804     assert(APInt::getAllOnesValue(ShSVT.getSizeInBits()).ugt(K) &&
4805            "We are expecting that K is always less than all-ones for ShSVT");
4806 
4807     // If the divisor is 1 the result can be constant-folded.
4808     if (D.isOneValue()) {
4809       // Set P and K amount to a bogus values so we can try to splat them.
4810       P = 0;
4811       K = -1;
4812       assert(Q.isAllOnesValue() &&
4813              "Expecting all-ones comparison for one divisor");
4814     }
4815 
4816     PAmts.push_back(DAG.getConstant(P, DL, SVT));
4817     KAmts.push_back(
4818         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
4819     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
4820     return true;
4821   };
4822 
4823   SDValue N = REMNode.getOperand(0);
4824   SDValue D = REMNode.getOperand(1);
4825 
4826   // Collect the values from each element.
4827   if (!ISD::matchUnaryPredicate(D, BuildUREMPattern))
4828     return SDValue();
4829 
4830   // If this is a urem by a one, avoid the fold since it can be constant-folded.
4831   if (AllDivisorsAreOnes)
4832     return SDValue();
4833 
4834   // If this is a urem by a powers-of-two, avoid the fold since it can be
4835   // best implemented as a bit test.
4836   if (AllDivisorsArePowerOfTwo)
4837     return SDValue();
4838 
4839   SDValue PVal, KVal, QVal;
4840   if (VT.isVector()) {
4841     if (HadOneDivisor) {
4842       // Try to turn PAmts into a splat, since we don't care about the values
4843       // that are currently '0'. If we can't, just keep '0'`s.
4844       turnVectorIntoSplatVector(PAmts, isNullConstant);
4845       // Try to turn KAmts into a splat, since we don't care about the values
4846       // that are currently '-1'. If we can't, change them to '0'`s.
4847       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
4848                                 DAG.getConstant(0, DL, ShSVT));
4849     }
4850 
4851     PVal = DAG.getBuildVector(VT, DL, PAmts);
4852     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
4853     QVal = DAG.getBuildVector(VT, DL, QAmts);
4854   } else {
4855     PVal = PAmts[0];
4856     KVal = KAmts[0];
4857     QVal = QAmts[0];
4858   }
4859 
4860   // (mul N, P)
4861   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
4862   Created.push_back(Op0.getNode());
4863 
4864   // Rotate right only if any divisor was even. We avoid rotates for all-odd
4865   // divisors as a performance improvement, since rotating by 0 is a no-op.
4866   if (HadEvenDivisor) {
4867     // We need ROTR to do this.
4868     if (!isOperationLegalOrCustom(ISD::ROTR, VT))
4869       return SDValue();
4870     SDNodeFlags Flags;
4871     Flags.setExact(true);
4872     // UREM: (rotr (mul N, P), K)
4873     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal, Flags);
4874     Created.push_back(Op0.getNode());
4875   }
4876 
4877   // UREM: (setule/setugt (rotr (mul N, P), K), Q)
4878   return DAG.getSetCC(DL, SETCCVT, Op0, QVal,
4879                       ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
4880 }
4881 
4882 bool TargetLowering::
4883 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
4884   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
4885     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
4886                                 "be a constant integer");
4887     return true;
4888   }
4889 
4890   return false;
4891 }
4892 
4893 //===----------------------------------------------------------------------===//
4894 // Legalization Utilities
4895 //===----------------------------------------------------------------------===//
4896 
4897 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl,
4898                                     SDValue LHS, SDValue RHS,
4899                                     SmallVectorImpl<SDValue> &Result,
4900                                     EVT HiLoVT, SelectionDAG &DAG,
4901                                     MulExpansionKind Kind, SDValue LL,
4902                                     SDValue LH, SDValue RL, SDValue RH) const {
4903   assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
4904          Opcode == ISD::SMUL_LOHI);
4905 
4906   bool HasMULHS = (Kind == MulExpansionKind::Always) ||
4907                   isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
4908   bool HasMULHU = (Kind == MulExpansionKind::Always) ||
4909                   isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
4910   bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
4911                       isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
4912   bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
4913                       isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
4914 
4915   if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
4916     return false;
4917 
4918   unsigned OuterBitSize = VT.getScalarSizeInBits();
4919   unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
4920   unsigned LHSSB = DAG.ComputeNumSignBits(LHS);
4921   unsigned RHSSB = DAG.ComputeNumSignBits(RHS);
4922 
4923   // LL, LH, RL, and RH must be either all NULL or all set to a value.
4924   assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
4925          (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
4926 
4927   SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
4928   auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
4929                           bool Signed) -> bool {
4930     if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
4931       Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
4932       Hi = SDValue(Lo.getNode(), 1);
4933       return true;
4934     }
4935     if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
4936       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
4937       Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
4938       return true;
4939     }
4940     return false;
4941   };
4942 
4943   SDValue Lo, Hi;
4944 
4945   if (!LL.getNode() && !RL.getNode() &&
4946       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
4947     LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
4948     RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
4949   }
4950 
4951   if (!LL.getNode())
4952     return false;
4953 
4954   APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
4955   if (DAG.MaskedValueIsZero(LHS, HighMask) &&
4956       DAG.MaskedValueIsZero(RHS, HighMask)) {
4957     // The inputs are both zero-extended.
4958     if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
4959       Result.push_back(Lo);
4960       Result.push_back(Hi);
4961       if (Opcode != ISD::MUL) {
4962         SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
4963         Result.push_back(Zero);
4964         Result.push_back(Zero);
4965       }
4966       return true;
4967     }
4968   }
4969 
4970   if (!VT.isVector() && Opcode == ISD::MUL && LHSSB > InnerBitSize &&
4971       RHSSB > InnerBitSize) {
4972     // The input values are both sign-extended.
4973     // TODO non-MUL case?
4974     if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
4975       Result.push_back(Lo);
4976       Result.push_back(Hi);
4977       return true;
4978     }
4979   }
4980 
4981   unsigned ShiftAmount = OuterBitSize - InnerBitSize;
4982   EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout());
4983   if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) {
4984     // FIXME getShiftAmountTy does not always return a sensible result when VT
4985     // is an illegal type, and so the type may be too small to fit the shift
4986     // amount. Override it with i32. The shift will have to be legalized.
4987     ShiftAmountTy = MVT::i32;
4988   }
4989   SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy);
4990 
4991   if (!LH.getNode() && !RH.getNode() &&
4992       isOperationLegalOrCustom(ISD::SRL, VT) &&
4993       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
4994     LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
4995     LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
4996     RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
4997     RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
4998   }
4999 
5000   if (!LH.getNode())
5001     return false;
5002 
5003   if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
5004     return false;
5005 
5006   Result.push_back(Lo);
5007 
5008   if (Opcode == ISD::MUL) {
5009     RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
5010     LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
5011     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
5012     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
5013     Result.push_back(Hi);
5014     return true;
5015   }
5016 
5017   // Compute the full width result.
5018   auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
5019     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
5020     Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
5021     Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
5022     return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
5023   };
5024 
5025   SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
5026   if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
5027     return false;
5028 
5029   // This is effectively the add part of a multiply-add of half-sized operands,
5030   // so it cannot overflow.
5031   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
5032 
5033   if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
5034     return false;
5035 
5036   SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
5037   EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
5038 
5039   bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
5040                   isOperationLegalOrCustom(ISD::ADDE, VT));
5041   if (UseGlue)
5042     Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
5043                        Merge(Lo, Hi));
5044   else
5045     Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next,
5046                        Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
5047 
5048   SDValue Carry = Next.getValue(1);
5049   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
5050   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
5051 
5052   if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
5053     return false;
5054 
5055   if (UseGlue)
5056     Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
5057                      Carry);
5058   else
5059     Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
5060                      Zero, Carry);
5061 
5062   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
5063 
5064   if (Opcode == ISD::SMUL_LOHI) {
5065     SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
5066                                   DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
5067     Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
5068 
5069     NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
5070                           DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
5071     Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
5072   }
5073 
5074   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
5075   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
5076   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
5077   return true;
5078 }
5079 
5080 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
5081                                SelectionDAG &DAG, MulExpansionKind Kind,
5082                                SDValue LL, SDValue LH, SDValue RL,
5083                                SDValue RH) const {
5084   SmallVector<SDValue, 2> Result;
5085   bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), N,
5086                            N->getOperand(0), N->getOperand(1), Result, HiLoVT,
5087                            DAG, Kind, LL, LH, RL, RH);
5088   if (Ok) {
5089     assert(Result.size() == 2);
5090     Lo = Result[0];
5091     Hi = Result[1];
5092   }
5093   return Ok;
5094 }
5095 
5096 bool TargetLowering::expandFunnelShift(SDNode *Node, SDValue &Result,
5097                                        SelectionDAG &DAG) const {
5098   EVT VT = Node->getValueType(0);
5099 
5100   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
5101                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
5102                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
5103                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
5104     return false;
5105 
5106   // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
5107   // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
5108   SDValue X = Node->getOperand(0);
5109   SDValue Y = Node->getOperand(1);
5110   SDValue Z = Node->getOperand(2);
5111 
5112   unsigned EltSizeInBits = VT.getScalarSizeInBits();
5113   bool IsFSHL = Node->getOpcode() == ISD::FSHL;
5114   SDLoc DL(SDValue(Node, 0));
5115 
5116   EVT ShVT = Z.getValueType();
5117   SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
5118   SDValue Zero = DAG.getConstant(0, DL, ShVT);
5119 
5120   SDValue ShAmt;
5121   if (isPowerOf2_32(EltSizeInBits)) {
5122     SDValue Mask = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
5123     ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
5124   } else {
5125     ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
5126   }
5127 
5128   SDValue InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
5129   SDValue ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
5130   SDValue ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
5131   SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
5132 
5133   // If (Z % BW == 0), then the opposite direction shift is shift-by-bitwidth,
5134   // and that is undefined. We must compare and select to avoid UB.
5135   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShVT);
5136 
5137   // For fshl, 0-shift returns the 1st arg (X).
5138   // For fshr, 0-shift returns the 2nd arg (Y).
5139   SDValue IsZeroShift = DAG.getSetCC(DL, CCVT, ShAmt, Zero, ISD::SETEQ);
5140   Result = DAG.getSelect(DL, VT, IsZeroShift, IsFSHL ? X : Y, Or);
5141   return true;
5142 }
5143 
5144 // TODO: Merge with expandFunnelShift.
5145 bool TargetLowering::expandROT(SDNode *Node, SDValue &Result,
5146                                SelectionDAG &DAG) const {
5147   EVT VT = Node->getValueType(0);
5148   unsigned EltSizeInBits = VT.getScalarSizeInBits();
5149   bool IsLeft = Node->getOpcode() == ISD::ROTL;
5150   SDValue Op0 = Node->getOperand(0);
5151   SDValue Op1 = Node->getOperand(1);
5152   SDLoc DL(SDValue(Node, 0));
5153 
5154   EVT ShVT = Op1.getValueType();
5155   SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
5156 
5157   // If a rotate in the other direction is legal, use it.
5158   unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
5159   if (isOperationLegal(RevRot, VT)) {
5160     SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, Op1);
5161     Result = DAG.getNode(RevRot, DL, VT, Op0, Sub);
5162     return true;
5163   }
5164 
5165   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
5166                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
5167                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
5168                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT) ||
5169                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT)))
5170     return false;
5171 
5172   // Otherwise,
5173   //   (rotl x, c) -> (or (shl x, (and c, w-1)), (srl x, (and w-c, w-1)))
5174   //   (rotr x, c) -> (or (srl x, (and c, w-1)), (shl x, (and w-c, w-1)))
5175   //
5176   assert(isPowerOf2_32(EltSizeInBits) && EltSizeInBits > 1 &&
5177          "Expecting the type bitwidth to be a power of 2");
5178   unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
5179   unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
5180   SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
5181   SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, Op1);
5182   SDValue And0 = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
5183   SDValue And1 = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
5184   Result = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ShOpc, DL, VT, Op0, And0),
5185                        DAG.getNode(HsOpc, DL, VT, Op0, And1));
5186   return true;
5187 }
5188 
5189 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
5190                                       SelectionDAG &DAG) const {
5191   SDValue Src = Node->getOperand(0);
5192   EVT SrcVT = Src.getValueType();
5193   EVT DstVT = Node->getValueType(0);
5194   SDLoc dl(SDValue(Node, 0));
5195 
5196   // FIXME: Only f32 to i64 conversions are supported.
5197   if (SrcVT != MVT::f32 || DstVT != MVT::i64)
5198     return false;
5199 
5200   // Expand f32 -> i64 conversion
5201   // This algorithm comes from compiler-rt's implementation of fixsfdi:
5202   // https://github.com/llvm/llvm-project/blob/master/compiler-rt/lib/builtins/fixsfdi.c
5203   unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
5204   EVT IntVT = SrcVT.changeTypeToInteger();
5205   EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
5206 
5207   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
5208   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
5209   SDValue Bias = DAG.getConstant(127, dl, IntVT);
5210   SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
5211   SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
5212   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
5213 
5214   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
5215 
5216   SDValue ExponentBits = DAG.getNode(
5217       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
5218       DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
5219   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
5220 
5221   SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
5222                              DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
5223                              DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
5224   Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
5225 
5226   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
5227                           DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
5228                           DAG.getConstant(0x00800000, dl, IntVT));
5229 
5230   R = DAG.getZExtOrTrunc(R, dl, DstVT);
5231 
5232   R = DAG.getSelectCC(
5233       dl, Exponent, ExponentLoBit,
5234       DAG.getNode(ISD::SHL, dl, DstVT, R,
5235                   DAG.getZExtOrTrunc(
5236                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
5237                       dl, IntShVT)),
5238       DAG.getNode(ISD::SRL, dl, DstVT, R,
5239                   DAG.getZExtOrTrunc(
5240                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
5241                       dl, IntShVT)),
5242       ISD::SETGT);
5243 
5244   SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
5245                             DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
5246 
5247   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
5248                            DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
5249   return true;
5250 }
5251 
5252 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result,
5253                                       SelectionDAG &DAG) const {
5254   SDLoc dl(SDValue(Node, 0));
5255   SDValue Src = Node->getOperand(0);
5256 
5257   EVT SrcVT = Src.getValueType();
5258   EVT DstVT = Node->getValueType(0);
5259   EVT SetCCVT =
5260       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
5261 
5262   // Only expand vector types if we have the appropriate vector bit operations.
5263   if (DstVT.isVector() && (!isOperationLegalOrCustom(ISD::FP_TO_SINT, DstVT) ||
5264                            !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT)))
5265     return false;
5266 
5267   // If the maximum float value is smaller then the signed integer range,
5268   // the destination signmask can't be represented by the float, so we can
5269   // just use FP_TO_SINT directly.
5270   const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT);
5271   APFloat APF(APFSem, APInt::getNullValue(SrcVT.getScalarSizeInBits()));
5272   APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
5273   if (APFloat::opOverflow &
5274       APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
5275     Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
5276     return true;
5277   }
5278 
5279   SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
5280   SDValue Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
5281 
5282   bool Strict = shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
5283   if (Strict) {
5284     // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
5285     // signmask then offset (the result of which should be fully representable).
5286     // Sel = Src < 0x8000000000000000
5287     // Val = select Sel, Src, Src - 0x8000000000000000
5288     // Ofs = select Sel, 0, 0x8000000000000000
5289     // Result = fp_to_sint(Val) ^ Ofs
5290 
5291     // TODO: Should any fast-math-flags be set for the FSUB?
5292     SDValue Val = DAG.getSelect(dl, SrcVT, Sel, Src,
5293                                 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
5294     SDValue Ofs = DAG.getSelect(dl, DstVT, Sel, DAG.getConstant(0, dl, DstVT),
5295                                 DAG.getConstant(SignMask, dl, DstVT));
5296     Result = DAG.getNode(ISD::XOR, dl, DstVT,
5297                          DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val), Ofs);
5298   } else {
5299     // Expand based on maximum range of FP_TO_SINT:
5300     // True = fp_to_sint(Src)
5301     // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
5302     // Result = select (Src < 0x8000000000000000), True, False
5303 
5304     SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
5305     // TODO: Should any fast-math-flags be set for the FSUB?
5306     SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
5307                                 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
5308     False = DAG.getNode(ISD::XOR, dl, DstVT, False,
5309                         DAG.getConstant(SignMask, dl, DstVT));
5310     Result = DAG.getSelect(dl, DstVT, Sel, True, False);
5311   }
5312   return true;
5313 }
5314 
5315 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result,
5316                                       SelectionDAG &DAG) const {
5317   SDValue Src = Node->getOperand(0);
5318   EVT SrcVT = Src.getValueType();
5319   EVT DstVT = Node->getValueType(0);
5320 
5321   if (SrcVT.getScalarType() != MVT::i64)
5322     return false;
5323 
5324   SDLoc dl(SDValue(Node, 0));
5325   EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout());
5326 
5327   if (DstVT.getScalarType() == MVT::f32) {
5328     // Only expand vector types if we have the appropriate vector bit
5329     // operations.
5330     if (SrcVT.isVector() &&
5331         (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
5332          !isOperationLegalOrCustom(ISD::FADD, DstVT) ||
5333          !isOperationLegalOrCustom(ISD::SINT_TO_FP, SrcVT) ||
5334          !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) ||
5335          !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT)))
5336       return false;
5337 
5338     // For unsigned conversions, convert them to signed conversions using the
5339     // algorithm from the x86_64 __floatundidf in compiler_rt.
5340     SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Src);
5341 
5342     SDValue ShiftConst = DAG.getConstant(1, dl, ShiftVT);
5343     SDValue Shr = DAG.getNode(ISD::SRL, dl, SrcVT, Src, ShiftConst);
5344     SDValue AndConst = DAG.getConstant(1, dl, SrcVT);
5345     SDValue And = DAG.getNode(ISD::AND, dl, SrcVT, Src, AndConst);
5346     SDValue Or = DAG.getNode(ISD::OR, dl, SrcVT, And, Shr);
5347 
5348     SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Or);
5349     SDValue Slow = DAG.getNode(ISD::FADD, dl, DstVT, SignCvt, SignCvt);
5350 
5351     // TODO: This really should be implemented using a branch rather than a
5352     // select.  We happen to get lucky and machinesink does the right
5353     // thing most of the time.  This would be a good candidate for a
5354     // pseudo-op, or, even better, for whole-function isel.
5355     EVT SetCCVT =
5356         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
5357 
5358     SDValue SignBitTest = DAG.getSetCC(
5359         dl, SetCCVT, Src, DAG.getConstant(0, dl, SrcVT), ISD::SETLT);
5360     Result = DAG.getSelect(dl, DstVT, SignBitTest, Slow, Fast);
5361     return true;
5362   }
5363 
5364   if (DstVT.getScalarType() == MVT::f64) {
5365     // Only expand vector types if we have the appropriate vector bit
5366     // operations.
5367     if (SrcVT.isVector() &&
5368         (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
5369          !isOperationLegalOrCustom(ISD::FADD, DstVT) ||
5370          !isOperationLegalOrCustom(ISD::FSUB, DstVT) ||
5371          !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) ||
5372          !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT)))
5373       return false;
5374 
5375     // Implementation of unsigned i64 to f64 following the algorithm in
5376     // __floatundidf in compiler_rt. This implementation has the advantage
5377     // of performing rounding correctly, both in the default rounding mode
5378     // and in all alternate rounding modes.
5379     SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
5380     SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
5381         BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT);
5382     SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
5383     SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
5384     SDValue HiShift = DAG.getConstant(32, dl, ShiftVT);
5385 
5386     SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
5387     SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
5388     SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
5389     SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
5390     SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
5391     SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
5392     SDValue HiSub = DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
5393     Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
5394     return true;
5395   }
5396 
5397   return false;
5398 }
5399 
5400 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node,
5401                                               SelectionDAG &DAG) const {
5402   SDLoc dl(Node);
5403   unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ?
5404     ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
5405   EVT VT = Node->getValueType(0);
5406   if (isOperationLegalOrCustom(NewOp, VT)) {
5407     SDValue Quiet0 = Node->getOperand(0);
5408     SDValue Quiet1 = Node->getOperand(1);
5409 
5410     if (!Node->getFlags().hasNoNaNs()) {
5411       // Insert canonicalizes if it's possible we need to quiet to get correct
5412       // sNaN behavior.
5413       if (!DAG.isKnownNeverSNaN(Quiet0)) {
5414         Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
5415                              Node->getFlags());
5416       }
5417       if (!DAG.isKnownNeverSNaN(Quiet1)) {
5418         Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
5419                              Node->getFlags());
5420       }
5421     }
5422 
5423     return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
5424   }
5425 
5426   // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
5427   // instead if there are no NaNs.
5428   if (Node->getFlags().hasNoNaNs()) {
5429     unsigned IEEE2018Op =
5430         Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
5431     if (isOperationLegalOrCustom(IEEE2018Op, VT)) {
5432       return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
5433                          Node->getOperand(1), Node->getFlags());
5434     }
5435   }
5436 
5437   return SDValue();
5438 }
5439 
5440 bool TargetLowering::expandCTPOP(SDNode *Node, SDValue &Result,
5441                                  SelectionDAG &DAG) const {
5442   SDLoc dl(Node);
5443   EVT VT = Node->getValueType(0);
5444   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5445   SDValue Op = Node->getOperand(0);
5446   unsigned Len = VT.getScalarSizeInBits();
5447   assert(VT.isInteger() && "CTPOP not implemented for this type.");
5448 
5449   // TODO: Add support for irregular type lengths.
5450   if (!(Len <= 128 && Len % 8 == 0))
5451     return false;
5452 
5453   // Only expand vector types if we have the appropriate vector bit operations.
5454   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::ADD, VT) ||
5455                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
5456                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
5457                         (Len != 8 && !isOperationLegalOrCustom(ISD::MUL, VT)) ||
5458                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT)))
5459     return false;
5460 
5461   // This is the "best" algorithm from
5462   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
5463   SDValue Mask55 =
5464       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
5465   SDValue Mask33 =
5466       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
5467   SDValue Mask0F =
5468       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
5469   SDValue Mask01 =
5470       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
5471 
5472   // v = v - ((v >> 1) & 0x55555555...)
5473   Op = DAG.getNode(ISD::SUB, dl, VT, Op,
5474                    DAG.getNode(ISD::AND, dl, VT,
5475                                DAG.getNode(ISD::SRL, dl, VT, Op,
5476                                            DAG.getConstant(1, dl, ShVT)),
5477                                Mask55));
5478   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
5479   Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
5480                    DAG.getNode(ISD::AND, dl, VT,
5481                                DAG.getNode(ISD::SRL, dl, VT, Op,
5482                                            DAG.getConstant(2, dl, ShVT)),
5483                                Mask33));
5484   // v = (v + (v >> 4)) & 0x0F0F0F0F...
5485   Op = DAG.getNode(ISD::AND, dl, VT,
5486                    DAG.getNode(ISD::ADD, dl, VT, Op,
5487                                DAG.getNode(ISD::SRL, dl, VT, Op,
5488                                            DAG.getConstant(4, dl, ShVT))),
5489                    Mask0F);
5490   // v = (v * 0x01010101...) >> (Len - 8)
5491   if (Len > 8)
5492     Op =
5493         DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
5494                     DAG.getConstant(Len - 8, dl, ShVT));
5495 
5496   Result = Op;
5497   return true;
5498 }
5499 
5500 bool TargetLowering::expandCTLZ(SDNode *Node, SDValue &Result,
5501                                 SelectionDAG &DAG) const {
5502   SDLoc dl(Node);
5503   EVT VT = Node->getValueType(0);
5504   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5505   SDValue Op = Node->getOperand(0);
5506   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
5507 
5508   // If the non-ZERO_UNDEF version is supported we can use that instead.
5509   if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF &&
5510       isOperationLegalOrCustom(ISD::CTLZ, VT)) {
5511     Result = DAG.getNode(ISD::CTLZ, dl, VT, Op);
5512     return true;
5513   }
5514 
5515   // If the ZERO_UNDEF version is supported use that and handle the zero case.
5516   if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) {
5517     EVT SetCCVT =
5518         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
5519     SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op);
5520     SDValue Zero = DAG.getConstant(0, dl, VT);
5521     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
5522     Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero,
5523                          DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
5524     return true;
5525   }
5526 
5527   // Only expand vector types if we have the appropriate vector bit operations.
5528   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
5529                         !isOperationLegalOrCustom(ISD::CTPOP, VT) ||
5530                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
5531                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
5532     return false;
5533 
5534   // for now, we do this:
5535   // x = x | (x >> 1);
5536   // x = x | (x >> 2);
5537   // ...
5538   // x = x | (x >>16);
5539   // x = x | (x >>32); // for 64-bit input
5540   // return popcount(~x);
5541   //
5542   // Ref: "Hacker's Delight" by Henry Warren
5543   for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) {
5544     SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
5545     Op = DAG.getNode(ISD::OR, dl, VT, Op,
5546                      DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
5547   }
5548   Op = DAG.getNOT(dl, Op, VT);
5549   Result = DAG.getNode(ISD::CTPOP, dl, VT, Op);
5550   return true;
5551 }
5552 
5553 bool TargetLowering::expandCTTZ(SDNode *Node, SDValue &Result,
5554                                 SelectionDAG &DAG) const {
5555   SDLoc dl(Node);
5556   EVT VT = Node->getValueType(0);
5557   SDValue Op = Node->getOperand(0);
5558   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
5559 
5560   // If the non-ZERO_UNDEF version is supported we can use that instead.
5561   if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
5562       isOperationLegalOrCustom(ISD::CTTZ, VT)) {
5563     Result = DAG.getNode(ISD::CTTZ, dl, VT, Op);
5564     return true;
5565   }
5566 
5567   // If the ZERO_UNDEF version is supported use that and handle the zero case.
5568   if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) {
5569     EVT SetCCVT =
5570         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
5571     SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op);
5572     SDValue Zero = DAG.getConstant(0, dl, VT);
5573     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
5574     Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero,
5575                          DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
5576     return true;
5577   }
5578 
5579   // Only expand vector types if we have the appropriate vector bit operations.
5580   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
5581                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
5582                          !isOperationLegalOrCustom(ISD::CTLZ, VT)) ||
5583                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
5584                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
5585                         !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
5586     return false;
5587 
5588   // for now, we use: { return popcount(~x & (x - 1)); }
5589   // unless the target has ctlz but not ctpop, in which case we use:
5590   // { return 32 - nlz(~x & (x-1)); }
5591   // Ref: "Hacker's Delight" by Henry Warren
5592   SDValue Tmp = DAG.getNode(
5593       ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
5594       DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
5595 
5596   // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
5597   if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) {
5598     Result =
5599         DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
5600                     DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
5601     return true;
5602   }
5603 
5604   Result = DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
5605   return true;
5606 }
5607 
5608 bool TargetLowering::expandABS(SDNode *N, SDValue &Result,
5609                                SelectionDAG &DAG) const {
5610   SDLoc dl(N);
5611   EVT VT = N->getValueType(0);
5612   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5613   SDValue Op = N->getOperand(0);
5614 
5615   // Only expand vector types if we have the appropriate vector operations.
5616   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SRA, VT) ||
5617                         !isOperationLegalOrCustom(ISD::ADD, VT) ||
5618                         !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
5619     return false;
5620 
5621   SDValue Shift =
5622       DAG.getNode(ISD::SRA, dl, VT, Op,
5623                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT));
5624   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, Op, Shift);
5625   Result = DAG.getNode(ISD::XOR, dl, VT, Add, Shift);
5626   return true;
5627 }
5628 
5629 SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
5630                                             SelectionDAG &DAG) const {
5631   SDLoc SL(LD);
5632   SDValue Chain = LD->getChain();
5633   SDValue BasePTR = LD->getBasePtr();
5634   EVT SrcVT = LD->getMemoryVT();
5635   ISD::LoadExtType ExtType = LD->getExtensionType();
5636 
5637   unsigned NumElem = SrcVT.getVectorNumElements();
5638 
5639   EVT SrcEltVT = SrcVT.getScalarType();
5640   EVT DstEltVT = LD->getValueType(0).getScalarType();
5641 
5642   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
5643   assert(SrcEltVT.isByteSized());
5644 
5645   SmallVector<SDValue, 8> Vals;
5646   SmallVector<SDValue, 8> LoadChains;
5647 
5648   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
5649     SDValue ScalarLoad =
5650         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
5651                        LD->getPointerInfo().getWithOffset(Idx * Stride),
5652                        SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride),
5653                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
5654 
5655     BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, Stride);
5656 
5657     Vals.push_back(ScalarLoad.getValue(0));
5658     LoadChains.push_back(ScalarLoad.getValue(1));
5659   }
5660 
5661   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
5662   SDValue Value = DAG.getBuildVector(LD->getValueType(0), SL, Vals);
5663 
5664   return DAG.getMergeValues({Value, NewChain}, SL);
5665 }
5666 
5667 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
5668                                              SelectionDAG &DAG) const {
5669   SDLoc SL(ST);
5670 
5671   SDValue Chain = ST->getChain();
5672   SDValue BasePtr = ST->getBasePtr();
5673   SDValue Value = ST->getValue();
5674   EVT StVT = ST->getMemoryVT();
5675 
5676   // The type of the data we want to save
5677   EVT RegVT = Value.getValueType();
5678   EVT RegSclVT = RegVT.getScalarType();
5679 
5680   // The type of data as saved in memory.
5681   EVT MemSclVT = StVT.getScalarType();
5682 
5683   EVT IdxVT = getVectorIdxTy(DAG.getDataLayout());
5684   unsigned NumElem = StVT.getVectorNumElements();
5685 
5686   // A vector must always be stored in memory as-is, i.e. without any padding
5687   // between the elements, since various code depend on it, e.g. in the
5688   // handling of a bitcast of a vector type to int, which may be done with a
5689   // vector store followed by an integer load. A vector that does not have
5690   // elements that are byte-sized must therefore be stored as an integer
5691   // built out of the extracted vector elements.
5692   if (!MemSclVT.isByteSized()) {
5693     unsigned NumBits = StVT.getSizeInBits();
5694     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
5695 
5696     SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
5697 
5698     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
5699       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
5700                                 DAG.getConstant(Idx, SL, IdxVT));
5701       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
5702       SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
5703       unsigned ShiftIntoIdx =
5704           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
5705       SDValue ShiftAmount =
5706           DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
5707       SDValue ShiftedElt =
5708           DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
5709       CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
5710     }
5711 
5712     return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
5713                         ST->getAlignment(), ST->getMemOperand()->getFlags(),
5714                         ST->getAAInfo());
5715   }
5716 
5717   // Store Stride in bytes
5718   unsigned Stride = MemSclVT.getSizeInBits() / 8;
5719   assert(Stride && "Zero stride!");
5720   // Extract each of the elements from the original vector and save them into
5721   // memory individually.
5722   SmallVector<SDValue, 8> Stores;
5723   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
5724     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
5725                               DAG.getConstant(Idx, SL, IdxVT));
5726 
5727     SDValue Ptr = DAG.getObjectPtrOffset(SL, BasePtr, Idx * Stride);
5728 
5729     // This scalar TruncStore may be illegal, but we legalize it later.
5730     SDValue Store = DAG.getTruncStore(
5731         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
5732         MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride),
5733         ST->getMemOperand()->getFlags(), ST->getAAInfo());
5734 
5735     Stores.push_back(Store);
5736   }
5737 
5738   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
5739 }
5740 
5741 std::pair<SDValue, SDValue>
5742 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
5743   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
5744          "unaligned indexed loads not implemented!");
5745   SDValue Chain = LD->getChain();
5746   SDValue Ptr = LD->getBasePtr();
5747   EVT VT = LD->getValueType(0);
5748   EVT LoadedVT = LD->getMemoryVT();
5749   SDLoc dl(LD);
5750   auto &MF = DAG.getMachineFunction();
5751 
5752   if (VT.isFloatingPoint() || VT.isVector()) {
5753     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
5754     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
5755       if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
5756           LoadedVT.isVector()) {
5757         // Scalarize the load and let the individual components be handled.
5758         SDValue Scalarized = scalarizeVectorLoad(LD, DAG);
5759         if (Scalarized->getOpcode() == ISD::MERGE_VALUES)
5760           return std::make_pair(Scalarized.getOperand(0), Scalarized.getOperand(1));
5761         return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1));
5762       }
5763 
5764       // Expand to a (misaligned) integer load of the same size,
5765       // then bitconvert to floating point or vector.
5766       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
5767                                     LD->getMemOperand());
5768       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
5769       if (LoadedVT != VT)
5770         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
5771                              ISD::ANY_EXTEND, dl, VT, Result);
5772 
5773       return std::make_pair(Result, newLoad.getValue(1));
5774     }
5775 
5776     // Copy the value to a (aligned) stack slot using (unaligned) integer
5777     // loads and stores, then do a (aligned) load from the stack slot.
5778     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
5779     unsigned LoadedBytes = LoadedVT.getStoreSize();
5780     unsigned RegBytes = RegVT.getSizeInBits() / 8;
5781     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
5782 
5783     // Make sure the stack slot is also aligned for the register type.
5784     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
5785     auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
5786     SmallVector<SDValue, 8> Stores;
5787     SDValue StackPtr = StackBase;
5788     unsigned Offset = 0;
5789 
5790     EVT PtrVT = Ptr.getValueType();
5791     EVT StackPtrVT = StackPtr.getValueType();
5792 
5793     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
5794     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
5795 
5796     // Do all but one copies using the full register width.
5797     for (unsigned i = 1; i < NumRegs; i++) {
5798       // Load one integer register's worth from the original location.
5799       SDValue Load = DAG.getLoad(
5800           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
5801           MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(),
5802           LD->getAAInfo());
5803       // Follow the load with a store to the stack slot.  Remember the store.
5804       Stores.push_back(DAG.getStore(
5805           Load.getValue(1), dl, Load, StackPtr,
5806           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
5807       // Increment the pointers.
5808       Offset += RegBytes;
5809 
5810       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
5811       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
5812     }
5813 
5814     // The last copy may be partial.  Do an extending load.
5815     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
5816                                   8 * (LoadedBytes - Offset));
5817     SDValue Load =
5818         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
5819                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
5820                        MinAlign(LD->getAlignment(), Offset),
5821                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
5822     // Follow the load with a store to the stack slot.  Remember the store.
5823     // On big-endian machines this requires a truncating store to ensure
5824     // that the bits end up in the right place.
5825     Stores.push_back(DAG.getTruncStore(
5826         Load.getValue(1), dl, Load, StackPtr,
5827         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
5828 
5829     // The order of the stores doesn't matter - say it with a TokenFactor.
5830     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
5831 
5832     // Finally, perform the original load only redirected to the stack slot.
5833     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
5834                           MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
5835                           LoadedVT);
5836 
5837     // Callers expect a MERGE_VALUES node.
5838     return std::make_pair(Load, TF);
5839   }
5840 
5841   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
5842          "Unaligned load of unsupported type.");
5843 
5844   // Compute the new VT that is half the size of the old one.  This is an
5845   // integer MVT.
5846   unsigned NumBits = LoadedVT.getSizeInBits();
5847   EVT NewLoadedVT;
5848   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
5849   NumBits >>= 1;
5850 
5851   unsigned Alignment = LD->getAlignment();
5852   unsigned IncrementSize = NumBits / 8;
5853   ISD::LoadExtType HiExtType = LD->getExtensionType();
5854 
5855   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
5856   if (HiExtType == ISD::NON_EXTLOAD)
5857     HiExtType = ISD::ZEXTLOAD;
5858 
5859   // Load the value in two parts
5860   SDValue Lo, Hi;
5861   if (DAG.getDataLayout().isLittleEndian()) {
5862     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
5863                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
5864                         LD->getAAInfo());
5865 
5866     Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
5867     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
5868                         LD->getPointerInfo().getWithOffset(IncrementSize),
5869                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
5870                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
5871   } else {
5872     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
5873                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
5874                         LD->getAAInfo());
5875 
5876     Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
5877     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
5878                         LD->getPointerInfo().getWithOffset(IncrementSize),
5879                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
5880                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
5881   }
5882 
5883   // aggregate the two parts
5884   SDValue ShiftAmount =
5885       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
5886                                                     DAG.getDataLayout()));
5887   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
5888   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
5889 
5890   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
5891                              Hi.getValue(1));
5892 
5893   return std::make_pair(Result, TF);
5894 }
5895 
5896 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
5897                                              SelectionDAG &DAG) const {
5898   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
5899          "unaligned indexed stores not implemented!");
5900   SDValue Chain = ST->getChain();
5901   SDValue Ptr = ST->getBasePtr();
5902   SDValue Val = ST->getValue();
5903   EVT VT = Val.getValueType();
5904   int Alignment = ST->getAlignment();
5905   auto &MF = DAG.getMachineFunction();
5906   EVT StoreMemVT = ST->getMemoryVT();
5907 
5908   SDLoc dl(ST);
5909   if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
5910     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
5911     if (isTypeLegal(intVT)) {
5912       if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
5913           StoreMemVT.isVector()) {
5914         // Scalarize the store and let the individual components be handled.
5915         SDValue Result = scalarizeVectorStore(ST, DAG);
5916         return Result;
5917       }
5918       // Expand to a bitconvert of the value to the integer type of the
5919       // same size, then a (misaligned) int store.
5920       // FIXME: Does not handle truncating floating point stores!
5921       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
5922       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
5923                             Alignment, ST->getMemOperand()->getFlags());
5924       return Result;
5925     }
5926     // Do a (aligned) store to a stack slot, then copy from the stack slot
5927     // to the final destination using (unaligned) integer loads and stores.
5928     MVT RegVT = getRegisterType(
5929         *DAG.getContext(),
5930         EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
5931     EVT PtrVT = Ptr.getValueType();
5932     unsigned StoredBytes = StoreMemVT.getStoreSize();
5933     unsigned RegBytes = RegVT.getSizeInBits() / 8;
5934     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
5935 
5936     // Make sure the stack slot is also aligned for the register type.
5937     SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
5938     auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
5939 
5940     // Perform the original store, only redirected to the stack slot.
5941     SDValue Store = DAG.getTruncStore(
5942         Chain, dl, Val, StackPtr,
5943         MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
5944 
5945     EVT StackPtrVT = StackPtr.getValueType();
5946 
5947     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
5948     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
5949     SmallVector<SDValue, 8> Stores;
5950     unsigned Offset = 0;
5951 
5952     // Do all but one copies using the full register width.
5953     for (unsigned i = 1; i < NumRegs; i++) {
5954       // Load one integer register's worth from the stack slot.
5955       SDValue Load = DAG.getLoad(
5956           RegVT, dl, Store, StackPtr,
5957           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
5958       // Store it to the final location.  Remember the store.
5959       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
5960                                     ST->getPointerInfo().getWithOffset(Offset),
5961                                     MinAlign(ST->getAlignment(), Offset),
5962                                     ST->getMemOperand()->getFlags()));
5963       // Increment the pointers.
5964       Offset += RegBytes;
5965       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
5966       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
5967     }
5968 
5969     // The last store may be partial.  Do a truncating store.  On big-endian
5970     // machines this requires an extending load from the stack slot to ensure
5971     // that the bits are in the right place.
5972     EVT LoadMemVT =
5973         EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
5974 
5975     // Load from the stack slot.
5976     SDValue Load = DAG.getExtLoad(
5977         ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
5978         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
5979 
5980     Stores.push_back(
5981         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
5982                           ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
5983                           MinAlign(ST->getAlignment(), Offset),
5984                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
5985     // The order of the stores doesn't matter - say it with a TokenFactor.
5986     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
5987     return Result;
5988   }
5989 
5990   assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
5991          "Unaligned store of unknown type.");
5992   // Get the half-size VT
5993   EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
5994   int NumBits = NewStoredVT.getSizeInBits();
5995   int IncrementSize = NumBits / 8;
5996 
5997   // Divide the stored value in two parts.
5998   SDValue ShiftAmount = DAG.getConstant(
5999       NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout()));
6000   SDValue Lo = Val;
6001   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
6002 
6003   // Store the two parts
6004   SDValue Store1, Store2;
6005   Store1 = DAG.getTruncStore(Chain, dl,
6006                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
6007                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
6008                              ST->getMemOperand()->getFlags());
6009 
6010   Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
6011   Alignment = MinAlign(Alignment, IncrementSize);
6012   Store2 = DAG.getTruncStore(
6013       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
6014       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
6015       ST->getMemOperand()->getFlags(), ST->getAAInfo());
6016 
6017   SDValue Result =
6018       DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
6019   return Result;
6020 }
6021 
6022 SDValue
6023 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
6024                                        const SDLoc &DL, EVT DataVT,
6025                                        SelectionDAG &DAG,
6026                                        bool IsCompressedMemory) const {
6027   SDValue Increment;
6028   EVT AddrVT = Addr.getValueType();
6029   EVT MaskVT = Mask.getValueType();
6030   assert(DataVT.getVectorNumElements() == MaskVT.getVectorNumElements() &&
6031          "Incompatible types of Data and Mask");
6032   if (IsCompressedMemory) {
6033     // Incrementing the pointer according to number of '1's in the mask.
6034     EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
6035     SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
6036     if (MaskIntVT.getSizeInBits() < 32) {
6037       MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
6038       MaskIntVT = MVT::i32;
6039     }
6040 
6041     // Count '1's with POPCNT.
6042     Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
6043     Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
6044     // Scale is an element size in bytes.
6045     SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
6046                                     AddrVT);
6047     Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
6048   } else
6049     Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT);
6050 
6051   return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
6052 }
6053 
6054 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG,
6055                                        SDValue Idx,
6056                                        EVT VecVT,
6057                                        const SDLoc &dl) {
6058   if (isa<ConstantSDNode>(Idx))
6059     return Idx;
6060 
6061   EVT IdxVT = Idx.getValueType();
6062   unsigned NElts = VecVT.getVectorNumElements();
6063   if (isPowerOf2_32(NElts)) {
6064     APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(),
6065                                      Log2_32(NElts));
6066     return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
6067                        DAG.getConstant(Imm, dl, IdxVT));
6068   }
6069 
6070   return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
6071                      DAG.getConstant(NElts - 1, dl, IdxVT));
6072 }
6073 
6074 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
6075                                                 SDValue VecPtr, EVT VecVT,
6076                                                 SDValue Index) const {
6077   SDLoc dl(Index);
6078   // Make sure the index type is big enough to compute in.
6079   Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
6080 
6081   EVT EltVT = VecVT.getVectorElementType();
6082 
6083   // Calculate the element offset and add it to the pointer.
6084   unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
6085   assert(EltSize * 8 == EltVT.getSizeInBits() &&
6086          "Converting bits to bytes lost precision");
6087 
6088   Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl);
6089 
6090   EVT IdxVT = Index.getValueType();
6091 
6092   Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
6093                       DAG.getConstant(EltSize, dl, IdxVT));
6094   return DAG.getNode(ISD::ADD, dl, IdxVT, VecPtr, Index);
6095 }
6096 
6097 //===----------------------------------------------------------------------===//
6098 // Implementation of Emulated TLS Model
6099 //===----------------------------------------------------------------------===//
6100 
6101 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
6102                                                 SelectionDAG &DAG) const {
6103   // Access to address of TLS varialbe xyz is lowered to a function call:
6104   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
6105   EVT PtrVT = getPointerTy(DAG.getDataLayout());
6106   PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
6107   SDLoc dl(GA);
6108 
6109   ArgListTy Args;
6110   ArgListEntry Entry;
6111   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
6112   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
6113   StringRef EmuTlsVarName(NameString);
6114   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
6115   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
6116   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
6117   Entry.Ty = VoidPtrType;
6118   Args.push_back(Entry);
6119 
6120   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
6121 
6122   TargetLowering::CallLoweringInfo CLI(DAG);
6123   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
6124   CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
6125   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
6126 
6127   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
6128   // At last for X86 targets, maybe good for other targets too?
6129   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
6130   MFI.setAdjustsStack(true); // Is this only for X86 target?
6131   MFI.setHasCalls(true);
6132 
6133   assert((GA->getOffset() == 0) &&
6134          "Emulated TLS must have zero offset in GlobalAddressSDNode");
6135   return CallResult.first;
6136 }
6137 
6138 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
6139                                                 SelectionDAG &DAG) const {
6140   assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
6141   if (!isCtlzFast())
6142     return SDValue();
6143   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6144   SDLoc dl(Op);
6145   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
6146     if (C->isNullValue() && CC == ISD::SETEQ) {
6147       EVT VT = Op.getOperand(0).getValueType();
6148       SDValue Zext = Op.getOperand(0);
6149       if (VT.bitsLT(MVT::i32)) {
6150         VT = MVT::i32;
6151         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
6152       }
6153       unsigned Log2b = Log2_32(VT.getSizeInBits());
6154       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
6155       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
6156                                 DAG.getConstant(Log2b, dl, MVT::i32));
6157       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
6158     }
6159   }
6160   return SDValue();
6161 }
6162 
6163 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const {
6164   unsigned Opcode = Node->getOpcode();
6165   SDValue LHS = Node->getOperand(0);
6166   SDValue RHS = Node->getOperand(1);
6167   EVT VT = LHS.getValueType();
6168   SDLoc dl(Node);
6169 
6170   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
6171   assert(VT.isInteger() && "Expected operands to be integers");
6172 
6173   // usub.sat(a, b) -> umax(a, b) - b
6174   if (Opcode == ISD::USUBSAT && isOperationLegalOrCustom(ISD::UMAX, VT)) {
6175     SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
6176     return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
6177   }
6178 
6179   if (Opcode == ISD::UADDSAT && isOperationLegalOrCustom(ISD::UMIN, VT)) {
6180     SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
6181     SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
6182     return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
6183   }
6184 
6185   unsigned OverflowOp;
6186   switch (Opcode) {
6187   case ISD::SADDSAT:
6188     OverflowOp = ISD::SADDO;
6189     break;
6190   case ISD::UADDSAT:
6191     OverflowOp = ISD::UADDO;
6192     break;
6193   case ISD::SSUBSAT:
6194     OverflowOp = ISD::SSUBO;
6195     break;
6196   case ISD::USUBSAT:
6197     OverflowOp = ISD::USUBO;
6198     break;
6199   default:
6200     llvm_unreachable("Expected method to receive signed or unsigned saturation "
6201                      "addition or subtraction node.");
6202   }
6203 
6204   unsigned BitWidth = LHS.getScalarValueSizeInBits();
6205   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6206   SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT),
6207                                LHS, RHS);
6208   SDValue SumDiff = Result.getValue(0);
6209   SDValue Overflow = Result.getValue(1);
6210   SDValue Zero = DAG.getConstant(0, dl, VT);
6211   SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
6212 
6213   if (Opcode == ISD::UADDSAT) {
6214     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
6215       // (LHS + RHS) | OverflowMask
6216       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
6217       return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
6218     }
6219     // Overflow ? 0xffff.... : (LHS + RHS)
6220     return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
6221   } else if (Opcode == ISD::USUBSAT) {
6222     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
6223       // (LHS - RHS) & ~OverflowMask
6224       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
6225       SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
6226       return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
6227     }
6228     // Overflow ? 0 : (LHS - RHS)
6229     return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
6230   } else {
6231     // SatMax -> Overflow && SumDiff < 0
6232     // SatMin -> Overflow && SumDiff >= 0
6233     APInt MinVal = APInt::getSignedMinValue(BitWidth);
6234     APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
6235     SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
6236     SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
6237     SDValue SumNeg = DAG.getSetCC(dl, BoolVT, SumDiff, Zero, ISD::SETLT);
6238     Result = DAG.getSelect(dl, VT, SumNeg, SatMax, SatMin);
6239     return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
6240   }
6241 }
6242 
6243 SDValue
6244 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const {
6245   assert((Node->getOpcode() == ISD::SMULFIX ||
6246           Node->getOpcode() == ISD::UMULFIX ||
6247           Node->getOpcode() == ISD::SMULFIXSAT) &&
6248          "Expected a fixed point multiplication opcode");
6249 
6250   SDLoc dl(Node);
6251   SDValue LHS = Node->getOperand(0);
6252   SDValue RHS = Node->getOperand(1);
6253   EVT VT = LHS.getValueType();
6254   unsigned Scale = Node->getConstantOperandVal(2);
6255   bool Saturating = Node->getOpcode() == ISD::SMULFIXSAT;
6256   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6257   unsigned VTSize = VT.getScalarSizeInBits();
6258 
6259   if (!Scale) {
6260     // [us]mul.fix(a, b, 0) -> mul(a, b)
6261     if (!Saturating && isOperationLegalOrCustom(ISD::MUL, VT)) {
6262       return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
6263     } else if (Saturating && isOperationLegalOrCustom(ISD::SMULO, VT)) {
6264       SDValue Result =
6265           DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
6266       SDValue Product = Result.getValue(0);
6267       SDValue Overflow = Result.getValue(1);
6268       SDValue Zero = DAG.getConstant(0, dl, VT);
6269 
6270       APInt MinVal = APInt::getSignedMinValue(VTSize);
6271       APInt MaxVal = APInt::getSignedMaxValue(VTSize);
6272       SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
6273       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
6274       SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Product, Zero, ISD::SETLT);
6275       Result = DAG.getSelect(dl, VT, ProdNeg, SatMax, SatMin);
6276       return DAG.getSelect(dl, VT, Overflow, Result, Product);
6277     }
6278   }
6279 
6280   bool Signed =
6281       Node->getOpcode() == ISD::SMULFIX || Node->getOpcode() == ISD::SMULFIXSAT;
6282   assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
6283          "Expected scale to be less than the number of bits if signed or at "
6284          "most the number of bits if unsigned.");
6285   assert(LHS.getValueType() == RHS.getValueType() &&
6286          "Expected both operands to be the same type");
6287 
6288   // Get the upper and lower bits of the result.
6289   SDValue Lo, Hi;
6290   unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
6291   unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
6292   if (isOperationLegalOrCustom(LoHiOp, VT)) {
6293     SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
6294     Lo = Result.getValue(0);
6295     Hi = Result.getValue(1);
6296   } else if (isOperationLegalOrCustom(HiOp, VT)) {
6297     Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
6298     Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
6299   } else if (VT.isVector()) {
6300     return SDValue();
6301   } else {
6302     report_fatal_error("Unable to expand fixed point multiplication.");
6303   }
6304 
6305   if (Scale == VTSize)
6306     // Result is just the top half since we'd be shifting by the width of the
6307     // operand.
6308     return Hi;
6309 
6310   // The result will need to be shifted right by the scale since both operands
6311   // are scaled. The result is given to us in 2 halves, so we only want part of
6312   // both in the result.
6313   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
6314   SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
6315                                DAG.getConstant(Scale, dl, ShiftTy));
6316   if (!Saturating)
6317     return Result;
6318 
6319   unsigned OverflowBits = VTSize - Scale + 1; // +1 for the sign
6320   SDValue HiMask =
6321       DAG.getConstant(APInt::getHighBitsSet(VTSize, OverflowBits), dl, VT);
6322   SDValue LoMask = DAG.getConstant(
6323       APInt::getLowBitsSet(VTSize, VTSize - OverflowBits), dl, VT);
6324   APInt MaxVal = APInt::getSignedMaxValue(VTSize);
6325   APInt MinVal = APInt::getSignedMinValue(VTSize);
6326 
6327   Result = DAG.getSelectCC(dl, Hi, LoMask,
6328                            DAG.getConstant(MaxVal, dl, VT), Result,
6329                            ISD::SETGT);
6330   return DAG.getSelectCC(dl, Hi, HiMask,
6331                          DAG.getConstant(MinVal, dl, VT), Result,
6332                          ISD::SETLT);
6333 }
6334 
6335 void TargetLowering::expandUADDSUBO(
6336     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
6337   SDLoc dl(Node);
6338   SDValue LHS = Node->getOperand(0);
6339   SDValue RHS = Node->getOperand(1);
6340   bool IsAdd = Node->getOpcode() == ISD::UADDO;
6341 
6342   // If ADD/SUBCARRY is legal, use that instead.
6343   unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY;
6344   if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
6345     SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
6346     SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
6347                                     { LHS, RHS, CarryIn });
6348     Result = SDValue(NodeCarry.getNode(), 0);
6349     Overflow = SDValue(NodeCarry.getNode(), 1);
6350     return;
6351   }
6352 
6353   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
6354                             LHS.getValueType(), LHS, RHS);
6355 
6356   EVT ResultType = Node->getValueType(1);
6357   EVT SetCCType = getSetCCResultType(
6358       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
6359   ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
6360   SDValue SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
6361   Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
6362 }
6363 
6364 void TargetLowering::expandSADDSUBO(
6365     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
6366   SDLoc dl(Node);
6367   SDValue LHS = Node->getOperand(0);
6368   SDValue RHS = Node->getOperand(1);
6369   bool IsAdd = Node->getOpcode() == ISD::SADDO;
6370 
6371   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
6372                             LHS.getValueType(), LHS, RHS);
6373 
6374   EVT ResultType = Node->getValueType(1);
6375   EVT OType = getSetCCResultType(
6376       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
6377 
6378   // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
6379   unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
6380   if (isOperationLegalOrCustom(OpcSat, LHS.getValueType())) {
6381     SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
6382     SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
6383     Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
6384     return;
6385   }
6386 
6387   SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
6388 
6389   //   LHSSign -> LHS >= 0
6390   //   RHSSign -> RHS >= 0
6391   //   SumSign -> Result >= 0
6392   //
6393   //   Add:
6394   //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
6395   //   Sub:
6396   //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
6397   SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
6398   SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
6399   SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
6400                                     IsAdd ? ISD::SETEQ : ISD::SETNE);
6401 
6402   SDValue SumSign = DAG.getSetCC(dl, OType, Result, Zero, ISD::SETGE);
6403   SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
6404 
6405   SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
6406   Overflow = DAG.getBoolExtOrTrunc(Cmp, dl, ResultType, ResultType);
6407 }
6408 
6409 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result,
6410                                 SDValue &Overflow, SelectionDAG &DAG) const {
6411   SDLoc dl(Node);
6412   EVT VT = Node->getValueType(0);
6413   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6414   SDValue LHS = Node->getOperand(0);
6415   SDValue RHS = Node->getOperand(1);
6416   bool isSigned = Node->getOpcode() == ISD::SMULO;
6417 
6418   // For power-of-two multiplications we can use a simpler shift expansion.
6419   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
6420     const APInt &C = RHSC->getAPIntValue();
6421     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
6422     if (C.isPowerOf2()) {
6423       // smulo(x, signed_min) is same as umulo(x, signed_min).
6424       bool UseArithShift = isSigned && !C.isMinSignedValue();
6425       EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout());
6426       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy);
6427       Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
6428       Overflow = DAG.getSetCC(dl, SetCCVT,
6429           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
6430                       dl, VT, Result, ShiftAmt),
6431           LHS, ISD::SETNE);
6432       return true;
6433     }
6434   }
6435 
6436   EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2);
6437   if (VT.isVector())
6438     WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT,
6439                               VT.getVectorNumElements());
6440 
6441   SDValue BottomHalf;
6442   SDValue TopHalf;
6443   static const unsigned Ops[2][3] =
6444       { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
6445         { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
6446   if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
6447     BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
6448     TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
6449   } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
6450     BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
6451                              RHS);
6452     TopHalf = BottomHalf.getValue(1);
6453   } else if (isTypeLegal(WideVT)) {
6454     LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
6455     RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
6456     SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
6457     BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
6458     SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl,
6459         getShiftAmountTy(WideVT, DAG.getDataLayout()));
6460     TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
6461                           DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
6462   } else {
6463     if (VT.isVector())
6464       return false;
6465 
6466     // We can fall back to a libcall with an illegal type for the MUL if we
6467     // have a libcall big enough.
6468     // Also, we can fall back to a division in some cases, but that's a big
6469     // performance hit in the general case.
6470     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
6471     if (WideVT == MVT::i16)
6472       LC = RTLIB::MUL_I16;
6473     else if (WideVT == MVT::i32)
6474       LC = RTLIB::MUL_I32;
6475     else if (WideVT == MVT::i64)
6476       LC = RTLIB::MUL_I64;
6477     else if (WideVT == MVT::i128)
6478       LC = RTLIB::MUL_I128;
6479     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
6480 
6481     SDValue HiLHS;
6482     SDValue HiRHS;
6483     if (isSigned) {
6484       // The high part is obtained by SRA'ing all but one of the bits of low
6485       // part.
6486       unsigned LoSize = VT.getSizeInBits();
6487       HiLHS =
6488           DAG.getNode(ISD::SRA, dl, VT, LHS,
6489                       DAG.getConstant(LoSize - 1, dl,
6490                                       getPointerTy(DAG.getDataLayout())));
6491       HiRHS =
6492           DAG.getNode(ISD::SRA, dl, VT, RHS,
6493                       DAG.getConstant(LoSize - 1, dl,
6494                                       getPointerTy(DAG.getDataLayout())));
6495     } else {
6496         HiLHS = DAG.getConstant(0, dl, VT);
6497         HiRHS = DAG.getConstant(0, dl, VT);
6498     }
6499 
6500     // Here we're passing the 2 arguments explicitly as 4 arguments that are
6501     // pre-lowered to the correct types. This all depends upon WideVT not
6502     // being a legal type for the architecture and thus has to be split to
6503     // two arguments.
6504     SDValue Ret;
6505     if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) {
6506       // Halves of WideVT are packed into registers in different order
6507       // depending on platform endianness. This is usually handled by
6508       // the C calling convention, but we can't defer to it in
6509       // the legalizer.
6510       SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
6511       Ret = makeLibCall(DAG, LC, WideVT, Args, isSigned, dl,
6512           /* doesNotReturn */ false, /* isReturnValueUsed */ true,
6513           /* isPostTypeLegalization */ true).first;
6514     } else {
6515       SDValue Args[] = { HiLHS, LHS, HiRHS, RHS };
6516       Ret = makeLibCall(DAG, LC, WideVT, Args, isSigned, dl,
6517           /* doesNotReturn */ false, /* isReturnValueUsed */ true,
6518           /* isPostTypeLegalization */ true).first;
6519     }
6520     assert(Ret.getOpcode() == ISD::MERGE_VALUES &&
6521            "Ret value is a collection of constituent nodes holding result.");
6522     if (DAG.getDataLayout().isLittleEndian()) {
6523       // Same as above.
6524       BottomHalf = Ret.getOperand(0);
6525       TopHalf = Ret.getOperand(1);
6526     } else {
6527       BottomHalf = Ret.getOperand(1);
6528       TopHalf = Ret.getOperand(0);
6529     }
6530   }
6531 
6532   Result = BottomHalf;
6533   if (isSigned) {
6534     SDValue ShiftAmt = DAG.getConstant(
6535         VT.getScalarSizeInBits() - 1, dl,
6536         getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout()));
6537     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
6538     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
6539   } else {
6540     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
6541                             DAG.getConstant(0, dl, VT), ISD::SETNE);
6542   }
6543 
6544   // Truncate the result if SetCC returns a larger type than needed.
6545   EVT RType = Node->getValueType(1);
6546   if (RType.getSizeInBits() < Overflow.getValueSizeInBits())
6547     Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
6548 
6549   assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
6550          "Unexpected result type for S/UMULO legalization");
6551   return true;
6552 }
6553 
6554 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const {
6555   SDLoc dl(Node);
6556   bool NoNaN = Node->getFlags().hasNoNaNs();
6557   unsigned BaseOpcode = 0;
6558   switch (Node->getOpcode()) {
6559   default: llvm_unreachable("Expected VECREDUCE opcode");
6560   case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break;
6561   case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break;
6562   case ISD::VECREDUCE_ADD:  BaseOpcode = ISD::ADD; break;
6563   case ISD::VECREDUCE_MUL:  BaseOpcode = ISD::MUL; break;
6564   case ISD::VECREDUCE_AND:  BaseOpcode = ISD::AND; break;
6565   case ISD::VECREDUCE_OR:   BaseOpcode = ISD::OR; break;
6566   case ISD::VECREDUCE_XOR:  BaseOpcode = ISD::XOR; break;
6567   case ISD::VECREDUCE_SMAX: BaseOpcode = ISD::SMAX; break;
6568   case ISD::VECREDUCE_SMIN: BaseOpcode = ISD::SMIN; break;
6569   case ISD::VECREDUCE_UMAX: BaseOpcode = ISD::UMAX; break;
6570   case ISD::VECREDUCE_UMIN: BaseOpcode = ISD::UMIN; break;
6571   case ISD::VECREDUCE_FMAX:
6572     BaseOpcode = NoNaN ? ISD::FMAXNUM : ISD::FMAXIMUM;
6573     break;
6574   case ISD::VECREDUCE_FMIN:
6575     BaseOpcode = NoNaN ? ISD::FMINNUM : ISD::FMINIMUM;
6576     break;
6577   }
6578 
6579   SDValue Op = Node->getOperand(0);
6580   EVT VT = Op.getValueType();
6581 
6582   // Try to use a shuffle reduction for power of two vectors.
6583   if (VT.isPow2VectorType()) {
6584     while (VT.getVectorNumElements() > 1) {
6585       EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
6586       if (!isOperationLegalOrCustom(BaseOpcode, HalfVT))
6587         break;
6588 
6589       SDValue Lo, Hi;
6590       std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
6591       Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi);
6592       VT = HalfVT;
6593     }
6594   }
6595 
6596   EVT EltVT = VT.getVectorElementType();
6597   unsigned NumElts = VT.getVectorNumElements();
6598 
6599   SmallVector<SDValue, 8> Ops;
6600   DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
6601 
6602   SDValue Res = Ops[0];
6603   for (unsigned i = 1; i < NumElts; i++)
6604     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags());
6605 
6606   // Result type may be wider than element type.
6607   if (EltVT != Node->getValueType(0))
6608     Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
6609   return Res;
6610 }
6611