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