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