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/Target/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/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Target/TargetLoweringObjectFile.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetRegisterInfo.h"
34 #include "llvm/Target/TargetSubtargetInfo.h"
35 #include <cctype>
36 using namespace llvm;
37 
38 /// NOTE: The TargetMachine owns TLOF.
39 TargetLowering::TargetLowering(const TargetMachine &tm)
40   : TargetLoweringBase(tm) {}
41 
42 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
43   return nullptr;
44 }
45 
46 bool TargetLowering::isPositionIndependent() const {
47   return getTargetMachine().isPositionIndependent();
48 }
49 
50 /// Check whether a given call node is in tail position within its function. If
51 /// so, it sets Chain to the input chain of the tail call.
52 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
53                                           SDValue &Chain) const {
54   const Function *F = DAG.getMachineFunction().getFunction();
55 
56   // Conservatively require the attributes of the call to match those of
57   // the return. Ignore noalias because it doesn't affect the call sequence.
58   AttributeList CallerAttrs = F->getAttributes();
59   if (AttrBuilder(CallerAttrs, AttributeList::ReturnIndex)
60           .removeAttribute(Attribute::NoAlias)
61           .hasAttributes())
62     return false;
63 
64   // It's not safe to eliminate the sign / zero extension of the return value.
65   if (CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt) ||
66       CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
67     return false;
68 
69   // Check if the only use is a function return node.
70   return isUsedByReturnOnly(Node, Chain);
71 }
72 
73 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
74     const uint32_t *CallerPreservedMask,
75     const SmallVectorImpl<CCValAssign> &ArgLocs,
76     const SmallVectorImpl<SDValue> &OutVals) const {
77   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
78     const CCValAssign &ArgLoc = ArgLocs[I];
79     if (!ArgLoc.isRegLoc())
80       continue;
81     unsigned Reg = ArgLoc.getLocReg();
82     // Only look at callee saved registers.
83     if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
84       continue;
85     // Check that we pass the value used for the caller.
86     // (We look for a CopyFromReg reading a virtual register that is used
87     //  for the function live-in value of register Reg)
88     SDValue Value = OutVals[I];
89     if (Value->getOpcode() != ISD::CopyFromReg)
90       return false;
91     unsigned ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
92     if (MRI.getLiveInPhysReg(ArgReg) != Reg)
93       return false;
94   }
95   return true;
96 }
97 
98 /// \brief Set CallLoweringInfo attribute flags based on a call instruction
99 /// and called function attributes.
100 void TargetLoweringBase::ArgListEntry::setAttributes(ImmutableCallSite *CS,
101                                                      unsigned AttrIdx) {
102   IsSExt = CS->paramHasAttr(AttrIdx, Attribute::SExt);
103   IsZExt = CS->paramHasAttr(AttrIdx, Attribute::ZExt);
104   IsInReg = CS->paramHasAttr(AttrIdx, Attribute::InReg);
105   IsSRet = CS->paramHasAttr(AttrIdx, Attribute::StructRet);
106   IsNest = CS->paramHasAttr(AttrIdx, Attribute::Nest);
107   IsByVal = CS->paramHasAttr(AttrIdx, Attribute::ByVal);
108   IsInAlloca = CS->paramHasAttr(AttrIdx, Attribute::InAlloca);
109   IsReturned = CS->paramHasAttr(AttrIdx, Attribute::Returned);
110   IsSwiftSelf = CS->paramHasAttr(AttrIdx, Attribute::SwiftSelf);
111   IsSwiftError = CS->paramHasAttr(AttrIdx, Attribute::SwiftError);
112   Alignment  = CS->getParamAlignment(AttrIdx);
113 }
114 
115 /// Generate a libcall taking the given operands as arguments and returning a
116 /// result of type RetVT.
117 std::pair<SDValue, SDValue>
118 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
119                             ArrayRef<SDValue> Ops, bool isSigned,
120                             const SDLoc &dl, bool doesNotReturn,
121                             bool isReturnValueUsed) const {
122   TargetLowering::ArgListTy Args;
123   Args.reserve(Ops.size());
124 
125   TargetLowering::ArgListEntry Entry;
126   for (SDValue Op : Ops) {
127     Entry.Node = Op;
128     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
129     Entry.IsSExt = shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
130     Entry.IsZExt = !shouldSignExtendTypeInLibCall(Op.getValueType(), isSigned);
131     Args.push_back(Entry);
132   }
133 
134   if (LC == RTLIB::UNKNOWN_LIBCALL)
135     report_fatal_error("Unsupported library call operation!");
136   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
137                                          getPointerTy(DAG.getDataLayout()));
138 
139   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
140   TargetLowering::CallLoweringInfo CLI(DAG);
141   bool signExtend = shouldSignExtendTypeInLibCall(RetVT, isSigned);
142   CLI.setDebugLoc(dl)
143       .setChain(DAG.getEntryNode())
144       .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
145       .setNoReturn(doesNotReturn)
146       .setDiscardResult(!isReturnValueUsed)
147       .setSExtResult(signExtend)
148       .setZExtResult(!signExtend);
149   return LowerCallTo(CLI);
150 }
151 
152 /// Soften the operands of a comparison. This code is shared among BR_CC,
153 /// SELECT_CC, and SETCC handlers.
154 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
155                                          SDValue &NewLHS, SDValue &NewRHS,
156                                          ISD::CondCode &CCCode,
157                                          const SDLoc &dl) const {
158   assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
159          && "Unsupported setcc type!");
160 
161   // Expand into one or more soft-fp libcall(s).
162   RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
163   bool ShouldInvertCC = false;
164   switch (CCCode) {
165   case ISD::SETEQ:
166   case ISD::SETOEQ:
167     LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
168           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
169           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
170     break;
171   case ISD::SETNE:
172   case ISD::SETUNE:
173     LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
174           (VT == MVT::f64) ? RTLIB::UNE_F64 :
175           (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
176     break;
177   case ISD::SETGE:
178   case ISD::SETOGE:
179     LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
180           (VT == MVT::f64) ? RTLIB::OGE_F64 :
181           (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
182     break;
183   case ISD::SETLT:
184   case ISD::SETOLT:
185     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
186           (VT == MVT::f64) ? RTLIB::OLT_F64 :
187           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
188     break;
189   case ISD::SETLE:
190   case ISD::SETOLE:
191     LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
192           (VT == MVT::f64) ? RTLIB::OLE_F64 :
193           (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
194     break;
195   case ISD::SETGT:
196   case ISD::SETOGT:
197     LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
198           (VT == MVT::f64) ? RTLIB::OGT_F64 :
199           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
200     break;
201   case ISD::SETUO:
202     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
203           (VT == MVT::f64) ? RTLIB::UO_F64 :
204           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
205     break;
206   case ISD::SETO:
207     LC1 = (VT == MVT::f32) ? RTLIB::O_F32 :
208           (VT == MVT::f64) ? RTLIB::O_F64 :
209           (VT == MVT::f128) ? RTLIB::O_F128 : RTLIB::O_PPCF128;
210     break;
211   case ISD::SETONE:
212     // SETONE = SETOLT | SETOGT
213     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
214           (VT == MVT::f64) ? RTLIB::OLT_F64 :
215           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
216     LC2 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
217           (VT == MVT::f64) ? RTLIB::OGT_F64 :
218           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
219     break;
220   case ISD::SETUEQ:
221     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
222           (VT == MVT::f64) ? RTLIB::UO_F64 :
223           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
224     LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
225           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
226           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
227     break;
228   default:
229     // Invert CC for unordered comparisons
230     ShouldInvertCC = true;
231     switch (CCCode) {
232     case ISD::SETULT:
233       LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
234             (VT == MVT::f64) ? RTLIB::OGE_F64 :
235             (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
236       break;
237     case ISD::SETULE:
238       LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
239             (VT == MVT::f64) ? RTLIB::OGT_F64 :
240             (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
241       break;
242     case ISD::SETUGT:
243       LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
244             (VT == MVT::f64) ? RTLIB::OLE_F64 :
245             (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
246       break;
247     case ISD::SETUGE:
248       LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
249             (VT == MVT::f64) ? RTLIB::OLT_F64 :
250             (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
251       break;
252     default: llvm_unreachable("Do not know how to soften this setcc!");
253     }
254   }
255 
256   // Use the target specific return value for comparions lib calls.
257   EVT RetVT = getCmpLibcallReturnType();
258   SDValue Ops[2] = {NewLHS, NewRHS};
259   NewLHS = makeLibCall(DAG, LC1, RetVT, Ops, false /*sign irrelevant*/,
260                        dl).first;
261   NewRHS = DAG.getConstant(0, dl, RetVT);
262 
263   CCCode = getCmpLibcallCC(LC1);
264   if (ShouldInvertCC)
265     CCCode = getSetCCInverse(CCCode, /*isInteger=*/true);
266 
267   if (LC2 != RTLIB::UNKNOWN_LIBCALL) {
268     SDValue Tmp = DAG.getNode(
269         ISD::SETCC, dl,
270         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
271         NewLHS, NewRHS, DAG.getCondCode(CCCode));
272     NewLHS = makeLibCall(DAG, LC2, RetVT, Ops, false/*sign irrelevant*/,
273                          dl).first;
274     NewLHS = DAG.getNode(
275         ISD::SETCC, dl,
276         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT),
277         NewLHS, NewRHS, DAG.getCondCode(getCmpLibcallCC(LC2)));
278     NewLHS = DAG.getNode(ISD::OR, dl, Tmp.getValueType(), Tmp, NewLHS);
279     NewRHS = SDValue();
280   }
281 }
282 
283 /// Return the entry encoding for a jump table in the current function. The
284 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
285 unsigned TargetLowering::getJumpTableEncoding() const {
286   // In non-pic modes, just use the address of a block.
287   if (!isPositionIndependent())
288     return MachineJumpTableInfo::EK_BlockAddress;
289 
290   // In PIC mode, if the target supports a GPRel32 directive, use it.
291   if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
292     return MachineJumpTableInfo::EK_GPRel32BlockAddress;
293 
294   // Otherwise, use a label difference.
295   return MachineJumpTableInfo::EK_LabelDifference32;
296 }
297 
298 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
299                                                  SelectionDAG &DAG) const {
300   // If our PIC model is GP relative, use the global offset table as the base.
301   unsigned JTEncoding = getJumpTableEncoding();
302 
303   if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
304       (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
305     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
306 
307   return Table;
308 }
309 
310 /// This returns the relocation base for the given PIC jumptable, the same as
311 /// getPICJumpTableRelocBase, but as an MCExpr.
312 const MCExpr *
313 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
314                                              unsigned JTI,MCContext &Ctx) const{
315   // The normal PIC reloc base is the label at the start of the jump table.
316   return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
317 }
318 
319 bool
320 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
321   const TargetMachine &TM = getTargetMachine();
322   const GlobalValue *GV = GA->getGlobal();
323 
324   // If the address is not even local to this DSO we will have to load it from
325   // a got and then add the offset.
326   if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
327     return false;
328 
329   // If the code is position independent we will have to add a base register.
330   if (isPositionIndependent())
331     return false;
332 
333   // Otherwise we can do it.
334   return true;
335 }
336 
337 //===----------------------------------------------------------------------===//
338 //  Optimization Methods
339 //===----------------------------------------------------------------------===//
340 
341 /// If the specified instruction has a constant integer operand and there are
342 /// bits set in that constant that are not demanded, then clear those bits and
343 /// return true.
344 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedConstant(
345     SDValue Op, const APInt &Demanded) {
346   SDLoc DL(Op);
347   unsigned Opcode = Op.getOpcode();
348 
349   // FIXME: ISD::SELECT, ISD::SELECT_CC
350   switch (Opcode) {
351   default:
352     break;
353   case ISD::XOR:
354   case ISD::AND:
355   case ISD::OR: {
356     auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
357     if (!Op1C)
358       return false;
359 
360     // If this is a 'not' op, don't touch it because that's a canonical form.
361     const APInt &C = Op1C->getAPIntValue();
362     if (Opcode == ISD::XOR && (C | ~Demanded).isAllOnesValue())
363       return false;
364 
365     if (C.intersects(~Demanded)) {
366       EVT VT = Op.getValueType();
367       SDValue NewC = DAG.getConstant(Demanded & C, DL, VT);
368       SDValue NewOp = DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC);
369       return CombineTo(Op, NewOp);
370     }
371 
372     break;
373   }
374   }
375 
376   return false;
377 }
378 
379 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
380 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
381 /// generalized for targets with other types of implicit widening casts.
382 bool TargetLowering::TargetLoweringOpt::ShrinkDemandedOp(SDValue Op,
383                                                          unsigned BitWidth,
384                                                          const APInt &Demanded,
385                                                          const SDLoc &dl) {
386   assert(Op.getNumOperands() == 2 &&
387          "ShrinkDemandedOp only supports binary operators!");
388   assert(Op.getNode()->getNumValues() == 1 &&
389          "ShrinkDemandedOp only supports nodes with one result!");
390 
391   // Early return, as this function cannot handle vector types.
392   if (Op.getValueType().isVector())
393     return false;
394 
395   // Don't do this if the node has another user, which may require the
396   // full value.
397   if (!Op.getNode()->hasOneUse())
398     return false;
399 
400   // Search for the smallest integer type with free casts to and from
401   // Op's type. For expedience, just check power-of-2 integer types.
402   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
403   unsigned DemandedSize = BitWidth - Demanded.countLeadingZeros();
404   unsigned SmallVTBits = DemandedSize;
405   if (!isPowerOf2_32(SmallVTBits))
406     SmallVTBits = NextPowerOf2(SmallVTBits);
407   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
408     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
409     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
410         TLI.isZExtFree(SmallVT, Op.getValueType())) {
411       // We found a type with free casts.
412       SDValue X = DAG.getNode(Op.getOpcode(), dl, SmallVT,
413                               DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
414                                           Op.getNode()->getOperand(0)),
415                               DAG.getNode(ISD::TRUNCATE, dl, SmallVT,
416                                           Op.getNode()->getOperand(1)));
417       bool NeedZext = DemandedSize > SmallVTBits;
418       SDValue Z = DAG.getNode(NeedZext ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND,
419                               dl, Op.getValueType(), X);
420       return CombineTo(Op, Z);
421     }
422   }
423   return false;
424 }
425 
426 bool
427 TargetLowering::TargetLoweringOpt::SimplifyDemandedBits(SDNode *User,
428                                                         unsigned OpIdx,
429                                                         const APInt &Demanded,
430                                                         DAGCombinerInfo &DCI) {
431   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
432   SDValue Op = User->getOperand(OpIdx);
433   APInt KnownZero, KnownOne;
434 
435   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne,
436                                 *this, 0, true))
437     return false;
438 
439 
440   // Old will not always be the same as Op.  For example:
441   //
442   // Demanded = 0xffffff
443   // Op = i64 truncate (i32 and x, 0xffffff)
444   // In this case simplify demand bits will want to replace the 'and' node
445   // with the value 'x', which will give us:
446   // Old = i32 and x, 0xffffff
447   // New = x
448   if (Old.hasOneUse()) {
449     // For the one use case, we just commit the change.
450     DCI.CommitTargetLoweringOpt(*this);
451     return true;
452   }
453 
454   // If Old has more than one use then it must be Op, because the
455   // AssumeSingleUse flag is not propogated to recursive calls of
456   // SimplifyDemanded bits, so the only node with multiple use that
457   // it will attempt to combine will be opt.
458   assert(Old == Op);
459 
460   SmallVector <SDValue, 4> NewOps;
461   for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
462     if (i == OpIdx) {
463       NewOps.push_back(New);
464       continue;
465     }
466     NewOps.push_back(User->getOperand(i));
467   }
468   DAG.UpdateNodeOperands(User, NewOps);
469   // Op has less users now, so we may be able to perform additional combines
470   // with it.
471   DCI.AddToWorklist(Op.getNode());
472   // User's operands have been updated, so we may be able to do new combines
473   // with it.
474   DCI.AddToWorklist(User);
475   return true;
476 }
477 
478 bool TargetLowering::SimplifyDemandedBits(SDValue Op, APInt &DemandedMask,
479                                           DAGCombinerInfo &DCI) const {
480 
481   SelectionDAG &DAG = DCI.DAG;
482   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
483                         !DCI.isBeforeLegalizeOps());
484   APInt KnownZero, KnownOne;
485 
486   bool Simplified = SimplifyDemandedBits(Op, DemandedMask, KnownZero, KnownOne,
487                                          TLO);
488   if (Simplified)
489     DCI.CommitTargetLoweringOpt(TLO);
490   return Simplified;
491 }
492 
493 /// Look at Op. At this point, we know that only the DemandedMask bits of the
494 /// result of Op are ever used downstream. If we can use this information to
495 /// simplify Op, create a new simplified DAG node and return true, returning the
496 /// original and new nodes in Old and New. Otherwise, analyze the expression and
497 /// return a mask of KnownOne and KnownZero bits for the expression (used to
498 /// simplify the caller).  The KnownZero/One bits may only be accurate for those
499 /// bits in the DemandedMask.
500 bool TargetLowering::SimplifyDemandedBits(SDValue Op,
501                                           const APInt &DemandedMask,
502                                           APInt &KnownZero,
503                                           APInt &KnownOne,
504                                           TargetLoweringOpt &TLO,
505                                           unsigned Depth,
506                                           bool AssumeSingleUse) const {
507   unsigned BitWidth = DemandedMask.getBitWidth();
508   assert(Op.getScalarValueSizeInBits() == BitWidth &&
509          "Mask size mismatches value type size!");
510   APInt NewMask = DemandedMask;
511   SDLoc dl(Op);
512   auto &DL = TLO.DAG.getDataLayout();
513 
514   // Don't know anything.
515   KnownZero = KnownOne = APInt(BitWidth, 0);
516 
517   // Other users may use these bits.
518   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) {
519     if (Depth != 0) {
520       // If not at the root, Just compute the KnownZero/KnownOne bits to
521       // simplify things downstream.
522       TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
523       return false;
524     }
525     // If this is the root being simplified, allow it to have multiple uses,
526     // just set the NewMask to all bits.
527     NewMask = APInt::getAllOnesValue(BitWidth);
528   } else if (DemandedMask == 0) {
529     // Not demanding any bits from Op.
530     if (!Op.isUndef())
531       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(Op.getValueType()));
532     return false;
533   } else if (Depth == 6) {        // Limit search depth.
534     return false;
535   }
536 
537   APInt KnownZero2, KnownOne2, KnownZeroOut, KnownOneOut;
538   switch (Op.getOpcode()) {
539   case ISD::Constant:
540     // We know all of the bits for a constant!
541     KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue();
542     KnownZero = ~KnownOne;
543     return false;   // Don't fall through, will infinitely loop.
544   case ISD::BUILD_VECTOR:
545     // Collect the known bits that are shared by every constant vector element.
546     KnownZero = KnownOne = APInt::getAllOnesValue(BitWidth);
547     for (SDValue SrcOp : Op->ops()) {
548       if (!isa<ConstantSDNode>(SrcOp)) {
549         // We can only handle all constant values - bail out with no known bits.
550         KnownZero = KnownOne = APInt(BitWidth, 0);
551         return false;
552       }
553       KnownOne2 = cast<ConstantSDNode>(SrcOp)->getAPIntValue();
554       KnownZero2 = ~KnownOne2;
555 
556       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
557       if (KnownOne2.getBitWidth() != BitWidth) {
558         assert(KnownOne2.getBitWidth() > BitWidth &&
559                KnownZero2.getBitWidth() > BitWidth &&
560                "Expected BUILD_VECTOR implicit truncation");
561         KnownOne2 = KnownOne2.trunc(BitWidth);
562         KnownZero2 = KnownZero2.trunc(BitWidth);
563       }
564 
565       // Known bits are the values that are shared by every element.
566       // TODO: support per-element known bits.
567       KnownOne &= KnownOne2;
568       KnownZero &= KnownZero2;
569     }
570     return false;   // Don't fall through, will infinitely loop.
571   case ISD::AND:
572     // If the RHS is a constant, check to see if the LHS would be zero without
573     // using the bits from the RHS.  Below, we use knowledge about the RHS to
574     // simplify the LHS, here we're using information from the LHS to simplify
575     // the RHS.
576     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
577       SDValue Op0 = Op.getOperand(0);
578       APInt LHSZero, LHSOne;
579       // Do not increment Depth here; that can cause an infinite loop.
580       TLO.DAG.computeKnownBits(Op0, LHSZero, LHSOne, Depth);
581       // If the LHS already has zeros where RHSC does, this and is dead.
582       if ((LHSZero & NewMask) == (~RHSC->getAPIntValue() & NewMask))
583         return TLO.CombineTo(Op, Op0);
584 
585       // If any of the set bits in the RHS are known zero on the LHS, shrink
586       // the constant.
587       if (TLO.ShrinkDemandedConstant(Op, ~LHSZero & NewMask))
588         return true;
589 
590       // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
591       // constant, but if this 'and' is only clearing bits that were just set by
592       // the xor, then this 'and' can be eliminated by shrinking the mask of
593       // the xor. For example, for a 32-bit X:
594       // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
595       if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
596           LHSOne == ~RHSC->getAPIntValue()) {
597         SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, Op.getValueType(),
598                                       Op0.getOperand(0), Op.getOperand(1));
599         return TLO.CombineTo(Op, Xor);
600       }
601     }
602 
603     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
604                              KnownOne, TLO, Depth+1))
605       return true;
606     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
607     if (SimplifyDemandedBits(Op.getOperand(0), ~KnownZero & NewMask,
608                              KnownZero2, KnownOne2, TLO, Depth+1))
609       return true;
610     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
611 
612     // If all of the demanded bits are known one on one side, return the other.
613     // These bits cannot contribute to the result of the 'and'.
614     if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
615       return TLO.CombineTo(Op, Op.getOperand(0));
616     if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
617       return TLO.CombineTo(Op, Op.getOperand(1));
618     // If all of the demanded bits in the inputs are known zeros, return zero.
619     if ((NewMask & (KnownZero|KnownZero2)) == NewMask)
620       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, Op.getValueType()));
621     // If the RHS is a constant, see if we can simplify it.
622     if (TLO.ShrinkDemandedConstant(Op, ~KnownZero2 & NewMask))
623       return true;
624     // If the operation can be done in a smaller type, do so.
625     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
626       return true;
627 
628     // Output known-1 bits are only known if set in both the LHS & RHS.
629     KnownOne &= KnownOne2;
630     // Output known-0 are known to be clear if zero in either the LHS | RHS.
631     KnownZero |= KnownZero2;
632     break;
633   case ISD::OR:
634     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
635                              KnownOne, TLO, Depth+1))
636       return true;
637     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
638     if (SimplifyDemandedBits(Op.getOperand(0), ~KnownOne & NewMask,
639                              KnownZero2, KnownOne2, TLO, Depth+1))
640       return true;
641     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
642 
643     // If all of the demanded bits are known zero on one side, return the other.
644     // These bits cannot contribute to the result of the 'or'.
645     if ((NewMask & ~KnownOne2 & KnownZero) == (~KnownOne2 & NewMask))
646       return TLO.CombineTo(Op, Op.getOperand(0));
647     if ((NewMask & ~KnownOne & KnownZero2) == (~KnownOne & NewMask))
648       return TLO.CombineTo(Op, Op.getOperand(1));
649     // If all of the potentially set bits on one side are known to be set on
650     // the other side, just use the 'other' side.
651     if ((NewMask & ~KnownZero & KnownOne2) == (~KnownZero & NewMask))
652       return TLO.CombineTo(Op, Op.getOperand(0));
653     if ((NewMask & ~KnownZero2 & KnownOne) == (~KnownZero2 & NewMask))
654       return TLO.CombineTo(Op, Op.getOperand(1));
655     // If the RHS is a constant, see if we can simplify it.
656     if (TLO.ShrinkDemandedConstant(Op, NewMask))
657       return true;
658     // If the operation can be done in a smaller type, do so.
659     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
660       return true;
661 
662     // Output known-0 bits are only known if clear in both the LHS & RHS.
663     KnownZero &= KnownZero2;
664     // Output known-1 are known to be set if set in either the LHS | RHS.
665     KnownOne |= KnownOne2;
666     break;
667   case ISD::XOR:
668     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero,
669                              KnownOne, TLO, Depth+1))
670       return true;
671     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
672     if (SimplifyDemandedBits(Op.getOperand(0), NewMask, KnownZero2,
673                              KnownOne2, TLO, Depth+1))
674       return true;
675     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
676 
677     // If all of the demanded bits are known zero on one side, return the other.
678     // These bits cannot contribute to the result of the 'xor'.
679     if ((KnownZero & NewMask) == NewMask)
680       return TLO.CombineTo(Op, Op.getOperand(0));
681     if ((KnownZero2 & NewMask) == NewMask)
682       return TLO.CombineTo(Op, Op.getOperand(1));
683     // If the operation can be done in a smaller type, do so.
684     if (TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl))
685       return true;
686 
687     // If all of the unknown bits are known to be zero on one side or the other
688     // (but not both) turn this into an *inclusive* or.
689     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
690     if ((NewMask & ~KnownZero & ~KnownZero2) == 0)
691       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, Op.getValueType(),
692                                                Op.getOperand(0),
693                                                Op.getOperand(1)));
694 
695     // Output known-0 bits are known if clear or set in both the LHS & RHS.
696     KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
697     // Output known-1 are known to be set if set in only one of the LHS, RHS.
698     KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
699 
700     // If all of the demanded bits on one side are known, and all of the set
701     // bits on that side are also known to be set on the other side, turn this
702     // into an AND, as we know the bits will be cleared.
703     //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
704     // NB: it is okay if more bits are known than are requested
705     if ((NewMask & (KnownZero|KnownOne)) == NewMask) { // all known on one side
706       if (KnownOne == KnownOne2) { // set bits are the same on both sides
707         EVT VT = Op.getValueType();
708         SDValue ANDC = TLO.DAG.getConstant(~KnownOne & NewMask, dl, VT);
709         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT,
710                                                  Op.getOperand(0), ANDC));
711       }
712     }
713 
714     // If the RHS is a constant, see if we can simplify it.
715     // for XOR, we prefer to force bits to 1 if they will make a -1.
716     // If we can't force bits, try to shrink the constant.
717     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
718       APInt Expanded = C->getAPIntValue() | (~NewMask);
719       // If we can expand it to have all bits set, do it.
720       if (Expanded.isAllOnesValue()) {
721         if (Expanded != C->getAPIntValue()) {
722           EVT VT = Op.getValueType();
723           SDValue New = TLO.DAG.getNode(Op.getOpcode(), dl,VT, Op.getOperand(0),
724                                         TLO.DAG.getConstant(Expanded, dl, VT));
725           return TLO.CombineTo(Op, New);
726         }
727         // If it already has all the bits set, nothing to change
728         // but don't shrink either!
729       } else if (TLO.ShrinkDemandedConstant(Op, NewMask)) {
730         return true;
731       }
732     }
733 
734     KnownZero = std::move(KnownZeroOut);
735     KnownOne  = std::move(KnownOneOut);
736     break;
737   case ISD::SELECT:
738     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero,
739                              KnownOne, TLO, Depth+1))
740       return true;
741     if (SimplifyDemandedBits(Op.getOperand(1), NewMask, KnownZero2,
742                              KnownOne2, TLO, Depth+1))
743       return true;
744     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
745     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
746 
747     // If the operands are constants, see if we can simplify them.
748     if (TLO.ShrinkDemandedConstant(Op, NewMask))
749       return true;
750 
751     // Only known if known in both the LHS and RHS.
752     KnownOne &= KnownOne2;
753     KnownZero &= KnownZero2;
754     break;
755   case ISD::SELECT_CC:
756     if (SimplifyDemandedBits(Op.getOperand(3), NewMask, KnownZero,
757                              KnownOne, TLO, Depth+1))
758       return true;
759     if (SimplifyDemandedBits(Op.getOperand(2), NewMask, KnownZero2,
760                              KnownOne2, TLO, Depth+1))
761       return true;
762     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
763     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
764 
765     // If the operands are constants, see if we can simplify them.
766     if (TLO.ShrinkDemandedConstant(Op, NewMask))
767       return true;
768 
769     // Only known if known in both the LHS and RHS.
770     KnownOne &= KnownOne2;
771     KnownZero &= KnownZero2;
772     break;
773   case ISD::SETCC: {
774     SDValue Op0 = Op.getOperand(0);
775     SDValue Op1 = Op.getOperand(1);
776     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
777     // If (1) we only need the sign-bit, (2) the setcc operands are the same
778     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
779     // -1, we may be able to bypass the setcc.
780     if (NewMask.isSignBit() && Op0.getScalarValueSizeInBits() == BitWidth &&
781         getBooleanContents(Op.getValueType()) ==
782             BooleanContent::ZeroOrNegativeOneBooleanContent) {
783       // If we're testing X < 0, then this compare isn't needed - just use X!
784       // FIXME: We're limiting to integer types here, but this should also work
785       // if we don't care about FP signed-zero. The use of SETLT with FP means
786       // that we don't care about NaNs.
787       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
788           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
789         return TLO.CombineTo(Op, Op0);
790 
791       // TODO: Should we check for other forms of sign-bit comparisons?
792       // Examples: X <= -1, X >= 0
793     }
794     if (getBooleanContents(Op0.getValueType()) ==
795             TargetLowering::ZeroOrOneBooleanContent &&
796         BitWidth > 1)
797       KnownZero.setBitsFrom(1);
798     break;
799   }
800   case ISD::SHL:
801     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
802       unsigned ShAmt = SA->getZExtValue();
803       SDValue InOp = Op.getOperand(0);
804 
805       // If the shift count is an invalid immediate, don't do anything.
806       if (ShAmt >= BitWidth)
807         break;
808 
809       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
810       // single shift.  We can do this if the bottom bits (which are shifted
811       // out) are never demanded.
812       if (InOp.getOpcode() == ISD::SRL &&
813           isa<ConstantSDNode>(InOp.getOperand(1))) {
814         if (ShAmt && (NewMask & APInt::getLowBitsSet(BitWidth, ShAmt)) == 0) {
815           unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
816           unsigned Opc = ISD::SHL;
817           int Diff = ShAmt-C1;
818           if (Diff < 0) {
819             Diff = -Diff;
820             Opc = ISD::SRL;
821           }
822 
823           SDValue NewSA =
824             TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
825           EVT VT = Op.getValueType();
826           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
827                                                    InOp.getOperand(0), NewSA));
828         }
829       }
830 
831       if (SimplifyDemandedBits(InOp, NewMask.lshr(ShAmt),
832                                KnownZero, KnownOne, TLO, Depth+1))
833         return true;
834 
835       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
836       // are not demanded. This will likely allow the anyext to be folded away.
837       if (InOp.getNode()->getOpcode() == ISD::ANY_EXTEND) {
838         SDValue InnerOp = InOp.getNode()->getOperand(0);
839         EVT InnerVT = InnerOp.getValueType();
840         unsigned InnerBits = InnerVT.getSizeInBits();
841         if (ShAmt < InnerBits && NewMask.lshr(InnerBits) == 0 &&
842             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
843           EVT ShTy = getShiftAmountTy(InnerVT, DL);
844           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
845             ShTy = InnerVT;
846           SDValue NarrowShl =
847             TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
848                             TLO.DAG.getConstant(ShAmt, dl, ShTy));
849           return
850             TLO.CombineTo(Op,
851                           TLO.DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(),
852                                           NarrowShl));
853         }
854         // Repeat the SHL optimization above in cases where an extension
855         // intervenes: (shl (anyext (shr x, c1)), c2) to
856         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
857         // aren't demanded (as above) and that the shifted upper c1 bits of
858         // x aren't demanded.
859         if (InOp.hasOneUse() &&
860             InnerOp.getOpcode() == ISD::SRL &&
861             InnerOp.hasOneUse() &&
862             isa<ConstantSDNode>(InnerOp.getOperand(1))) {
863           uint64_t InnerShAmt = cast<ConstantSDNode>(InnerOp.getOperand(1))
864             ->getZExtValue();
865           if (InnerShAmt < ShAmt &&
866               InnerShAmt < InnerBits &&
867               NewMask.lshr(InnerBits - InnerShAmt + ShAmt) == 0 &&
868               NewMask.trunc(ShAmt) == 0) {
869             SDValue NewSA =
870               TLO.DAG.getConstant(ShAmt - InnerShAmt, dl,
871                                   Op.getOperand(1).getValueType());
872             EVT VT = Op.getValueType();
873             SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
874                                              InnerOp.getOperand(0));
875             return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT,
876                                                      NewExt, NewSA));
877           }
878         }
879       }
880 
881       KnownZero <<= SA->getZExtValue();
882       KnownOne  <<= SA->getZExtValue();
883       // low bits known zero.
884       KnownZero.setLowBits(SA->getZExtValue());
885     }
886     break;
887   case ISD::SRL:
888     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
889       EVT VT = Op.getValueType();
890       unsigned ShAmt = SA->getZExtValue();
891       unsigned VTSize = VT.getSizeInBits();
892       SDValue InOp = Op.getOperand(0);
893 
894       // If the shift count is an invalid immediate, don't do anything.
895       if (ShAmt >= BitWidth)
896         break;
897 
898       APInt InDemandedMask = (NewMask << ShAmt);
899 
900       // If the shift is exact, then it does demand the low bits (and knows that
901       // they are zero).
902       if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
903         InDemandedMask.setLowBits(ShAmt);
904 
905       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
906       // single shift.  We can do this if the top bits (which are shifted out)
907       // are never demanded.
908       if (InOp.getOpcode() == ISD::SHL &&
909           isa<ConstantSDNode>(InOp.getOperand(1))) {
910         if (ShAmt && (NewMask & APInt::getHighBitsSet(VTSize, ShAmt)) == 0) {
911           unsigned C1= cast<ConstantSDNode>(InOp.getOperand(1))->getZExtValue();
912           unsigned Opc = ISD::SRL;
913           int Diff = ShAmt-C1;
914           if (Diff < 0) {
915             Diff = -Diff;
916             Opc = ISD::SHL;
917           }
918 
919           SDValue NewSA =
920             TLO.DAG.getConstant(Diff, dl, Op.getOperand(1).getValueType());
921           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT,
922                                                    InOp.getOperand(0), NewSA));
923         }
924       }
925 
926       // Compute the new bits that are at the top now.
927       if (SimplifyDemandedBits(InOp, InDemandedMask,
928                                KnownZero, KnownOne, TLO, Depth+1))
929         return true;
930       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
931       KnownZero = KnownZero.lshr(ShAmt);
932       KnownOne  = KnownOne.lshr(ShAmt);
933 
934       KnownZero.setHighBits(ShAmt);  // High bits known zero.
935     }
936     break;
937   case ISD::SRA:
938     // If this is an arithmetic shift right and only the low-bit is set, we can
939     // always convert this into a logical shr, even if the shift amount is
940     // variable.  The low bit of the shift cannot be an input sign bit unless
941     // the shift amount is >= the size of the datatype, which is undefined.
942     if (NewMask == 1)
943       return TLO.CombineTo(Op,
944                            TLO.DAG.getNode(ISD::SRL, dl, Op.getValueType(),
945                                            Op.getOperand(0), Op.getOperand(1)));
946 
947     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
948       EVT VT = Op.getValueType();
949       unsigned ShAmt = SA->getZExtValue();
950 
951       // If the shift count is an invalid immediate, don't do anything.
952       if (ShAmt >= BitWidth)
953         break;
954 
955       APInt InDemandedMask = (NewMask << ShAmt);
956 
957       // If the shift is exact, then it does demand the low bits (and knows that
958       // they are zero).
959       if (cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact())
960         InDemandedMask.setLowBits(ShAmt);
961 
962       // If any of the demanded bits are produced by the sign extension, we also
963       // demand the input sign bit.
964       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt);
965       if (HighBits.intersects(NewMask))
966         InDemandedMask |= APInt::getSignBit(VT.getScalarSizeInBits());
967 
968       if (SimplifyDemandedBits(Op.getOperand(0), InDemandedMask,
969                                KnownZero, KnownOne, TLO, Depth+1))
970         return true;
971       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
972       KnownZero = KnownZero.lshr(ShAmt);
973       KnownOne  = KnownOne.lshr(ShAmt);
974 
975       // Handle the sign bit, adjusted to where it is now in the mask.
976       APInt SignBit = APInt::getSignBit(BitWidth).lshr(ShAmt);
977 
978       // If the input sign bit is known to be zero, or if none of the top bits
979       // are demanded, turn this into an unsigned shift right.
980       if (KnownZero.intersects(SignBit) || (HighBits & ~NewMask) == HighBits) {
981         SDNodeFlags Flags;
982         Flags.setExact(cast<BinaryWithFlagsSDNode>(Op)->Flags.hasExact());
983         return TLO.CombineTo(Op,
984                              TLO.DAG.getNode(ISD::SRL, dl, VT, Op.getOperand(0),
985                                              Op.getOperand(1), &Flags));
986       }
987 
988       int Log2 = NewMask.exactLogBase2();
989       if (Log2 >= 0) {
990         // The bit must come from the sign.
991         SDValue NewSA =
992           TLO.DAG.getConstant(BitWidth - 1 - Log2, dl,
993                               Op.getOperand(1).getValueType());
994         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT,
995                                                  Op.getOperand(0), NewSA));
996       }
997 
998       if (KnownOne.intersects(SignBit))
999         // New bits are known one.
1000         KnownOne |= HighBits;
1001     }
1002     break;
1003   case ISD::SIGN_EXTEND_INREG: {
1004     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1005 
1006     APInt MsbMask = APInt::getHighBitsSet(BitWidth, 1);
1007     // If we only care about the highest bit, don't bother shifting right.
1008     if (MsbMask == NewMask) {
1009       unsigned ShAmt = ExVT.getScalarSizeInBits();
1010       SDValue InOp = Op.getOperand(0);
1011       unsigned VTBits = Op->getValueType(0).getScalarSizeInBits();
1012       bool AlreadySignExtended =
1013         TLO.DAG.ComputeNumSignBits(InOp) >= VTBits-ShAmt+1;
1014       // However if the input is already sign extended we expect the sign
1015       // extension to be dropped altogether later and do not simplify.
1016       if (!AlreadySignExtended) {
1017         // Compute the correct shift amount type, which must be getShiftAmountTy
1018         // for scalar types after legalization.
1019         EVT ShiftAmtTy = Op.getValueType();
1020         if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
1021           ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL);
1022 
1023         SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ShAmt, dl,
1024                                                ShiftAmtTy);
1025         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1026                                                  Op.getValueType(), InOp,
1027                                                  ShiftAmt));
1028       }
1029     }
1030 
1031     // Sign extension.  Compute the demanded bits in the result that are not
1032     // present in the input.
1033     APInt NewBits =
1034       APInt::getHighBitsSet(BitWidth,
1035                             BitWidth - ExVT.getScalarSizeInBits());
1036 
1037     // If none of the extended bits are demanded, eliminate the sextinreg.
1038     if ((NewBits & NewMask) == 0)
1039       return TLO.CombineTo(Op, Op.getOperand(0));
1040 
1041     APInt InSignBit =
1042       APInt::getSignBit(ExVT.getScalarSizeInBits()).zext(BitWidth);
1043     APInt InputDemandedBits =
1044       APInt::getLowBitsSet(BitWidth,
1045                            ExVT.getScalarSizeInBits()) &
1046       NewMask;
1047 
1048     // Since the sign extended bits are demanded, we know that the sign
1049     // bit is demanded.
1050     InputDemandedBits |= InSignBit;
1051 
1052     if (SimplifyDemandedBits(Op.getOperand(0), InputDemandedBits,
1053                              KnownZero, KnownOne, TLO, Depth+1))
1054       return true;
1055     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1056 
1057     // If the sign bit of the input is known set or clear, then we know the
1058     // top bits of the result.
1059 
1060     // If the input sign bit is known zero, convert this into a zero extension.
1061     if (KnownZero.intersects(InSignBit))
1062       return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(
1063                                    Op.getOperand(0), dl, ExVT.getScalarType()));
1064 
1065     if (KnownOne.intersects(InSignBit)) {    // Input sign bit known set
1066       KnownOne |= NewBits;
1067       KnownZero &= ~NewBits;
1068     } else {                       // Input sign bit unknown
1069       KnownZero &= ~NewBits;
1070       KnownOne &= ~NewBits;
1071     }
1072     break;
1073   }
1074   case ISD::BUILD_PAIR: {
1075     EVT HalfVT = Op.getOperand(0).getValueType();
1076     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
1077 
1078     APInt MaskLo = NewMask.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
1079     APInt MaskHi = NewMask.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
1080 
1081     APInt KnownZeroLo, KnownOneLo;
1082     APInt KnownZeroHi, KnownOneHi;
1083 
1084     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownZeroLo,
1085                              KnownOneLo, TLO, Depth + 1))
1086       return true;
1087 
1088     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownZeroHi,
1089                              KnownOneHi, TLO, Depth + 1))
1090       return true;
1091 
1092     KnownZero = KnownZeroLo.zext(BitWidth) |
1093                 KnownZeroHi.zext(BitWidth).shl(HalfBitWidth);
1094 
1095     KnownOne = KnownOneLo.zext(BitWidth) |
1096                KnownOneHi.zext(BitWidth).shl(HalfBitWidth);
1097     break;
1098   }
1099   case ISD::ZERO_EXTEND: {
1100     unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
1101     APInt InMask = NewMask.trunc(OperandBitWidth);
1102 
1103     // If none of the top bits are demanded, convert this into an any_extend.
1104     APInt NewBits =
1105       APInt::getHighBitsSet(BitWidth, BitWidth - OperandBitWidth) & NewMask;
1106     if (!NewBits.intersects(NewMask))
1107       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
1108                                                Op.getValueType(),
1109                                                Op.getOperand(0)));
1110 
1111     if (SimplifyDemandedBits(Op.getOperand(0), InMask,
1112                              KnownZero, KnownOne, TLO, Depth+1))
1113       return true;
1114     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1115     KnownZero = KnownZero.zext(BitWidth);
1116     KnownOne = KnownOne.zext(BitWidth);
1117     KnownZero |= NewBits;
1118     break;
1119   }
1120   case ISD::SIGN_EXTEND: {
1121     EVT InVT = Op.getOperand(0).getValueType();
1122     unsigned InBits = InVT.getScalarSizeInBits();
1123     APInt InMask    = APInt::getLowBitsSet(BitWidth, InBits);
1124     APInt InSignBit = APInt::getOneBitSet(BitWidth, InBits - 1);
1125     APInt NewBits   = ~InMask & NewMask;
1126 
1127     // If none of the top bits are demanded, convert this into an any_extend.
1128     if (NewBits == 0)
1129       return TLO.CombineTo(Op,TLO.DAG.getNode(ISD::ANY_EXTEND, dl,
1130                                               Op.getValueType(),
1131                                               Op.getOperand(0)));
1132 
1133     // Since some of the sign extended bits are demanded, we know that the sign
1134     // bit is demanded.
1135     APInt InDemandedBits = InMask & NewMask;
1136     InDemandedBits |= InSignBit;
1137     InDemandedBits = InDemandedBits.trunc(InBits);
1138 
1139     if (SimplifyDemandedBits(Op.getOperand(0), InDemandedBits, KnownZero,
1140                              KnownOne, TLO, Depth+1))
1141       return true;
1142     KnownZero = KnownZero.zext(BitWidth);
1143     KnownOne = KnownOne.zext(BitWidth);
1144 
1145     // If the sign bit is known zero, convert this to a zero extend.
1146     if (KnownZero.intersects(InSignBit))
1147       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl,
1148                                                Op.getValueType(),
1149                                                Op.getOperand(0)));
1150 
1151     // If the sign bit is known one, the top bits match.
1152     if (KnownOne.intersects(InSignBit)) {
1153       KnownOne |= NewBits;
1154       assert((KnownZero & NewBits) == 0);
1155     } else {   // Otherwise, top bits aren't known.
1156       assert((KnownOne & NewBits) == 0);
1157       assert((KnownZero & NewBits) == 0);
1158     }
1159     break;
1160   }
1161   case ISD::ANY_EXTEND: {
1162     unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
1163     APInt InMask = NewMask.trunc(OperandBitWidth);
1164     if (SimplifyDemandedBits(Op.getOperand(0), InMask,
1165                              KnownZero, KnownOne, TLO, Depth+1))
1166       return true;
1167     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1168     KnownZero = KnownZero.zext(BitWidth);
1169     KnownOne = KnownOne.zext(BitWidth);
1170     break;
1171   }
1172   case ISD::TRUNCATE: {
1173     // Simplify the input, using demanded bit information, and compute the known
1174     // zero/one bits live out.
1175     unsigned OperandBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
1176     APInt TruncMask = NewMask.zext(OperandBitWidth);
1177     if (SimplifyDemandedBits(Op.getOperand(0), TruncMask,
1178                              KnownZero, KnownOne, TLO, Depth+1))
1179       return true;
1180     KnownZero = KnownZero.trunc(BitWidth);
1181     KnownOne = KnownOne.trunc(BitWidth);
1182 
1183     // If the input is only used by this truncate, see if we can shrink it based
1184     // on the known demanded bits.
1185     if (Op.getOperand(0).getNode()->hasOneUse()) {
1186       SDValue In = Op.getOperand(0);
1187       switch (In.getOpcode()) {
1188       default: break;
1189       case ISD::SRL:
1190         // Shrink SRL by a constant if none of the high bits shifted in are
1191         // demanded.
1192         if (TLO.LegalTypes() &&
1193             !isTypeDesirableForOp(ISD::SRL, Op.getValueType()))
1194           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1195           // undesirable.
1196           break;
1197         ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(In.getOperand(1));
1198         if (!ShAmt)
1199           break;
1200         SDValue Shift = In.getOperand(1);
1201         if (TLO.LegalTypes()) {
1202           uint64_t ShVal = ShAmt->getZExtValue();
1203           Shift = TLO.DAG.getConstant(ShVal, dl,
1204                                       getShiftAmountTy(Op.getValueType(), DL));
1205         }
1206 
1207         APInt HighBits = APInt::getHighBitsSet(OperandBitWidth,
1208                                                OperandBitWidth - BitWidth);
1209         HighBits = HighBits.lshr(ShAmt->getZExtValue()).trunc(BitWidth);
1210 
1211         if (ShAmt->getZExtValue() < BitWidth && !(HighBits & NewMask)) {
1212           // None of the shifted in bits are needed.  Add a truncate of the
1213           // shift input, then shift it.
1214           SDValue NewTrunc = TLO.DAG.getNode(ISD::TRUNCATE, dl,
1215                                              Op.getValueType(),
1216                                              In.getOperand(0));
1217           return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl,
1218                                                    Op.getValueType(),
1219                                                    NewTrunc,
1220                                                    Shift));
1221         }
1222         break;
1223       }
1224     }
1225 
1226     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1227     break;
1228   }
1229   case ISD::AssertZext: {
1230     // AssertZext demands all of the high bits, plus any of the low bits
1231     // demanded by its users.
1232     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1233     APInt InMask = APInt::getLowBitsSet(BitWidth,
1234                                         VT.getSizeInBits());
1235     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | NewMask,
1236                              KnownZero, KnownOne, TLO, Depth+1))
1237       return true;
1238     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1239 
1240     KnownZero |= ~InMask;
1241     break;
1242   }
1243   case ISD::BITCAST:
1244     // If this is an FP->Int bitcast and if the sign bit is the only
1245     // thing demanded, turn this into a FGETSIGN.
1246     if (!TLO.LegalOperations() &&
1247         !Op.getValueType().isVector() &&
1248         !Op.getOperand(0).getValueType().isVector() &&
1249         NewMask == APInt::getSignBit(Op.getValueSizeInBits()) &&
1250         Op.getOperand(0).getValueType().isFloatingPoint()) {
1251       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, Op.getValueType());
1252       bool i32Legal  = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
1253       if ((OpVTLegal || i32Legal) && Op.getValueType().isSimple() &&
1254            Op.getOperand(0).getValueType() != MVT::f128) {
1255         // Cannot eliminate/lower SHL for f128 yet.
1256         EVT Ty = OpVTLegal ? Op.getValueType() : MVT::i32;
1257         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
1258         // place.  We expect the SHL to be eliminated by other optimizations.
1259         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Op.getOperand(0));
1260         unsigned OpVTSizeInBits = Op.getValueSizeInBits();
1261         if (!OpVTLegal && OpVTSizeInBits > 32)
1262           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, Op.getValueType(), Sign);
1263         unsigned ShVal = Op.getValueSizeInBits() - 1;
1264         SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, Op.getValueType());
1265         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl,
1266                                                  Op.getValueType(),
1267                                                  Sign, ShAmt));
1268       }
1269     }
1270     break;
1271   case ISD::ADD:
1272   case ISD::MUL:
1273   case ISD::SUB: {
1274     // Add, Sub, and Mul don't demand any bits in positions beyond that
1275     // of the highest bit demanded of them.
1276     APInt LoMask = APInt::getLowBitsSet(BitWidth,
1277                                         BitWidth - NewMask.countLeadingZeros());
1278     if (SimplifyDemandedBits(Op.getOperand(0), LoMask, KnownZero2,
1279                              KnownOne2, TLO, Depth+1) ||
1280         SimplifyDemandedBits(Op.getOperand(1), LoMask, KnownZero2,
1281                              KnownOne2, TLO, Depth+1) ||
1282         // See if the operation should be performed at a smaller bit width.
1283         TLO.ShrinkDemandedOp(Op, BitWidth, NewMask, dl)) {
1284       const SDNodeFlags *Flags = Op.getNode()->getFlags();
1285       if (Flags->hasNoSignedWrap() || Flags->hasNoUnsignedWrap()) {
1286         // Disable the nsw and nuw flags. We can no longer guarantee that we
1287         // won't wrap after simplification.
1288         SDNodeFlags NewFlags = *Flags;
1289         NewFlags.setNoSignedWrap(false);
1290         NewFlags.setNoUnsignedWrap(false);
1291         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, Op.getValueType(),
1292                                         Op.getOperand(0), Op.getOperand(1),
1293                                         &NewFlags);
1294         return TLO.CombineTo(Op, NewOp);
1295       }
1296       return true;
1297     }
1298     LLVM_FALLTHROUGH;
1299   }
1300   default:
1301     // Just use computeKnownBits to compute output bits.
1302     TLO.DAG.computeKnownBits(Op, KnownZero, KnownOne, Depth);
1303     break;
1304   }
1305 
1306   // If we know the value of all of the demanded bits, return this as a
1307   // constant.
1308   if ((NewMask & (KnownZero|KnownOne)) == NewMask) {
1309     // Avoid folding to a constant if any OpaqueConstant is involved.
1310     const SDNode *N = Op.getNode();
1311     for (SDNodeIterator I = SDNodeIterator::begin(N),
1312          E = SDNodeIterator::end(N); I != E; ++I) {
1313       SDNode *Op = *I;
1314       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
1315         if (C->isOpaque())
1316           return false;
1317     }
1318     return TLO.CombineTo(Op,
1319                          TLO.DAG.getConstant(KnownOne, dl, Op.getValueType()));
1320   }
1321 
1322   return false;
1323 }
1324 
1325 /// Determine which of the bits specified in Mask are known to be either zero or
1326 /// one and return them in the KnownZero/KnownOne bitsets.
1327 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
1328                                                    APInt &KnownZero,
1329                                                    APInt &KnownOne,
1330                                                    const APInt &DemandedElts,
1331                                                    const SelectionDAG &DAG,
1332                                                    unsigned Depth) const {
1333   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1334           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1335           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1336           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1337          "Should use MaskedValueIsZero if you don't know whether Op"
1338          " is a target node!");
1339   KnownZero = KnownOne = APInt(KnownOne.getBitWidth(), 0);
1340 }
1341 
1342 /// This method can be implemented by targets that want to expose additional
1343 /// information about sign bits to the DAG Combiner.
1344 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
1345                                                          const APInt &,
1346                                                          const SelectionDAG &,
1347                                                          unsigned Depth) const {
1348   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1349           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
1350           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1351           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
1352          "Should use ComputeNumSignBits if you don't know whether Op"
1353          " is a target node!");
1354   return 1;
1355 }
1356 
1357 bool TargetLowering::isConstTrueVal(const SDNode *N) const {
1358   if (!N)
1359     return false;
1360 
1361   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
1362   if (!CN) {
1363     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1364     if (!BV)
1365       return false;
1366 
1367     // Only interested in constant splats, we don't care about undef
1368     // elements in identifying boolean constants and getConstantSplatNode
1369     // returns NULL if all ops are undef;
1370     CN = BV->getConstantSplatNode();
1371     if (!CN)
1372       return false;
1373   }
1374 
1375   switch (getBooleanContents(N->getValueType(0))) {
1376   case UndefinedBooleanContent:
1377     return CN->getAPIntValue()[0];
1378   case ZeroOrOneBooleanContent:
1379     return CN->isOne();
1380   case ZeroOrNegativeOneBooleanContent:
1381     return CN->isAllOnesValue();
1382   }
1383 
1384   llvm_unreachable("Invalid boolean contents");
1385 }
1386 
1387 SDValue TargetLowering::getConstTrueVal(SelectionDAG &DAG, EVT VT,
1388                                         const SDLoc &DL) const {
1389   unsigned ElementWidth = VT.getScalarSizeInBits();
1390   APInt TrueInt =
1391       getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent
1392           ? APInt(ElementWidth, 1)
1393           : APInt::getAllOnesValue(ElementWidth);
1394   return DAG.getConstant(TrueInt, DL, VT);
1395 }
1396 
1397 bool TargetLowering::isConstFalseVal(const SDNode *N) const {
1398   if (!N)
1399     return false;
1400 
1401   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
1402   if (!CN) {
1403     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
1404     if (!BV)
1405       return false;
1406 
1407     // Only interested in constant splats, we don't care about undef
1408     // elements in identifying boolean constants and getConstantSplatNode
1409     // returns NULL if all ops are undef;
1410     CN = BV->getConstantSplatNode();
1411     if (!CN)
1412       return false;
1413   }
1414 
1415   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
1416     return !CN->getAPIntValue()[0];
1417 
1418   return CN->isNullValue();
1419 }
1420 
1421 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
1422                                        bool SExt) const {
1423   if (VT == MVT::i1)
1424     return N->isOne();
1425 
1426   TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
1427   switch (Cnt) {
1428   case TargetLowering::ZeroOrOneBooleanContent:
1429     // An extended value of 1 is always true, unless its original type is i1,
1430     // in which case it will be sign extended to -1.
1431     return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
1432   case TargetLowering::UndefinedBooleanContent:
1433   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1434     return N->isAllOnesValue() && SExt;
1435   }
1436   llvm_unreachable("Unexpected enumeration.");
1437 }
1438 
1439 /// This helper function of SimplifySetCC tries to optimize the comparison when
1440 /// either operand of the SetCC node is a bitwise-and instruction.
1441 SDValue TargetLowering::simplifySetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
1442                                              ISD::CondCode Cond,
1443                                              DAGCombinerInfo &DCI,
1444                                              const SDLoc &DL) const {
1445   // Match these patterns in any of their permutations:
1446   // (X & Y) == Y
1447   // (X & Y) != Y
1448   if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
1449     std::swap(N0, N1);
1450 
1451   EVT OpVT = N0.getValueType();
1452   if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
1453       (Cond != ISD::SETEQ && Cond != ISD::SETNE))
1454     return SDValue();
1455 
1456   SDValue X, Y;
1457   if (N0.getOperand(0) == N1) {
1458     X = N0.getOperand(1);
1459     Y = N0.getOperand(0);
1460   } else if (N0.getOperand(1) == N1) {
1461     X = N0.getOperand(0);
1462     Y = N0.getOperand(1);
1463   } else {
1464     return SDValue();
1465   }
1466 
1467   SelectionDAG &DAG = DCI.DAG;
1468   SDValue Zero = DAG.getConstant(0, DL, OpVT);
1469   if (DAG.isKnownToBeAPowerOfTwo(Y)) {
1470     // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
1471     // Note that where Y is variable and is known to have at most one bit set
1472     // (for example, if it is Z & 1) we cannot do this; the expressions are not
1473     // equivalent when Y == 0.
1474     Cond = ISD::getSetCCInverse(Cond, /*isInteger=*/true);
1475     if (DCI.isBeforeLegalizeOps() ||
1476         isCondCodeLegal(Cond, N0.getSimpleValueType()))
1477       return DAG.getSetCC(DL, VT, N0, Zero, Cond);
1478   } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
1479     // If the target supports an 'and-not' or 'and-complement' logic operation,
1480     // try to use that to make a comparison operation more efficient.
1481     // But don't do this transform if the mask is a single bit because there are
1482     // more efficient ways to deal with that case (for example, 'bt' on x86 or
1483     // 'rlwinm' on PPC).
1484 
1485     // Bail out if the compare operand that we want to turn into a zero is
1486     // already a zero (otherwise, infinite loop).
1487     auto *YConst = dyn_cast<ConstantSDNode>(Y);
1488     if (YConst && YConst->isNullValue())
1489       return SDValue();
1490 
1491     // Transform this into: ~X & Y == 0.
1492     SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
1493     SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
1494     return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
1495   }
1496 
1497   return SDValue();
1498 }
1499 
1500 /// Try to simplify a setcc built with the specified operands and cc. If it is
1501 /// unable to simplify it, return a null SDValue.
1502 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
1503                                       ISD::CondCode Cond, bool foldBooleans,
1504                                       DAGCombinerInfo &DCI,
1505                                       const SDLoc &dl) const {
1506   SelectionDAG &DAG = DCI.DAG;
1507 
1508   // These setcc operations always fold.
1509   switch (Cond) {
1510   default: break;
1511   case ISD::SETFALSE:
1512   case ISD::SETFALSE2: return DAG.getConstant(0, dl, VT);
1513   case ISD::SETTRUE:
1514   case ISD::SETTRUE2: {
1515     TargetLowering::BooleanContent Cnt =
1516         getBooleanContents(N0->getValueType(0));
1517     return DAG.getConstant(
1518         Cnt == TargetLowering::ZeroOrNegativeOneBooleanContent ? -1ULL : 1, dl,
1519         VT);
1520   }
1521   }
1522 
1523   // Ensure that the constant occurs on the RHS, and fold constant
1524   // comparisons.
1525   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
1526   if (isa<ConstantSDNode>(N0.getNode()) &&
1527       (DCI.isBeforeLegalizeOps() ||
1528        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
1529     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
1530 
1531   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
1532     const APInt &C1 = N1C->getAPIntValue();
1533 
1534     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
1535     // equality comparison, then we're just comparing whether X itself is
1536     // zero.
1537     if (N0.getOpcode() == ISD::SRL && (C1 == 0 || C1 == 1) &&
1538         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
1539         N0.getOperand(1).getOpcode() == ISD::Constant) {
1540       const APInt &ShAmt
1541         = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1542       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1543           ShAmt == Log2_32(N0.getValueSizeInBits())) {
1544         if ((C1 == 0) == (Cond == ISD::SETEQ)) {
1545           // (srl (ctlz x), 5) == 0  -> X != 0
1546           // (srl (ctlz x), 5) != 1  -> X != 0
1547           Cond = ISD::SETNE;
1548         } else {
1549           // (srl (ctlz x), 5) != 0  -> X == 0
1550           // (srl (ctlz x), 5) == 1  -> X == 0
1551           Cond = ISD::SETEQ;
1552         }
1553         SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
1554         return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
1555                             Zero, Cond);
1556       }
1557     }
1558 
1559     SDValue CTPOP = N0;
1560     // Look through truncs that don't change the value of a ctpop.
1561     if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
1562       CTPOP = N0.getOperand(0);
1563 
1564     if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
1565         (N0 == CTPOP ||
1566          N0.getValueSizeInBits() > Log2_32_Ceil(CTPOP.getValueSizeInBits()))) {
1567       EVT CTVT = CTPOP.getValueType();
1568       SDValue CTOp = CTPOP.getOperand(0);
1569 
1570       // (ctpop x) u< 2 -> (x & x-1) == 0
1571       // (ctpop x) u> 1 -> (x & x-1) != 0
1572       if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
1573         SDValue Sub = DAG.getNode(ISD::SUB, dl, CTVT, CTOp,
1574                                   DAG.getConstant(1, dl, CTVT));
1575         SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Sub);
1576         ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
1577         return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
1578       }
1579 
1580       // TODO: (ctpop x) == 1 -> x && (x & x-1) == 0 iff ctpop is illegal.
1581     }
1582 
1583     // (zext x) == C --> x == (trunc C)
1584     // (sext x) == C --> x == (trunc C)
1585     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1586         DCI.isBeforeLegalize() && N0->hasOneUse()) {
1587       unsigned MinBits = N0.getValueSizeInBits();
1588       SDValue PreExt;
1589       bool Signed = false;
1590       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
1591         // ZExt
1592         MinBits = N0->getOperand(0).getValueSizeInBits();
1593         PreExt = N0->getOperand(0);
1594       } else if (N0->getOpcode() == ISD::AND) {
1595         // DAGCombine turns costly ZExts into ANDs
1596         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
1597           if ((C->getAPIntValue()+1).isPowerOf2()) {
1598             MinBits = C->getAPIntValue().countTrailingOnes();
1599             PreExt = N0->getOperand(0);
1600           }
1601       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
1602         // SExt
1603         MinBits = N0->getOperand(0).getValueSizeInBits();
1604         PreExt = N0->getOperand(0);
1605         Signed = true;
1606       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
1607         // ZEXTLOAD / SEXTLOAD
1608         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
1609           MinBits = LN0->getMemoryVT().getSizeInBits();
1610           PreExt = N0;
1611         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
1612           Signed = true;
1613           MinBits = LN0->getMemoryVT().getSizeInBits();
1614           PreExt = N0;
1615         }
1616       }
1617 
1618       // Figure out how many bits we need to preserve this constant.
1619       unsigned ReqdBits = Signed ?
1620         C1.getBitWidth() - C1.getNumSignBits() + 1 :
1621         C1.getActiveBits();
1622 
1623       // Make sure we're not losing bits from the constant.
1624       if (MinBits > 0 &&
1625           MinBits < C1.getBitWidth() &&
1626           MinBits >= ReqdBits) {
1627         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
1628         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
1629           // Will get folded away.
1630           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
1631           if (MinBits == 1 && C1 == 1)
1632             // Invert the condition.
1633             return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
1634                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1635           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
1636           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
1637         }
1638 
1639         // If truncating the setcc operands is not desirable, we can still
1640         // simplify the expression in some cases:
1641         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
1642         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
1643         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
1644         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
1645         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
1646         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
1647         SDValue TopSetCC = N0->getOperand(0);
1648         unsigned N0Opc = N0->getOpcode();
1649         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
1650         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
1651             TopSetCC.getOpcode() == ISD::SETCC &&
1652             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
1653             (isConstFalseVal(N1C) ||
1654              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
1655 
1656           bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) ||
1657                          (!N1C->isNullValue() && Cond == ISD::SETNE);
1658 
1659           if (!Inverse)
1660             return TopSetCC;
1661 
1662           ISD::CondCode InvCond = ISD::getSetCCInverse(
1663               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
1664               TopSetCC.getOperand(0).getValueType().isInteger());
1665           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
1666                                       TopSetCC.getOperand(1),
1667                                       InvCond);
1668 
1669         }
1670       }
1671     }
1672 
1673     // If the LHS is '(and load, const)', the RHS is 0,
1674     // the test is for equality or unsigned, and all 1 bits of the const are
1675     // in the same partial word, see if we can shorten the load.
1676     if (DCI.isBeforeLegalize() &&
1677         !ISD::isSignedIntSetCC(Cond) &&
1678         N0.getOpcode() == ISD::AND && C1 == 0 &&
1679         N0.getNode()->hasOneUse() &&
1680         isa<LoadSDNode>(N0.getOperand(0)) &&
1681         N0.getOperand(0).getNode()->hasOneUse() &&
1682         isa<ConstantSDNode>(N0.getOperand(1))) {
1683       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
1684       APInt bestMask;
1685       unsigned bestWidth = 0, bestOffset = 0;
1686       if (!Lod->isVolatile() && Lod->isUnindexed()) {
1687         unsigned origWidth = N0.getValueSizeInBits();
1688         unsigned maskWidth = origWidth;
1689         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
1690         // 8 bits, but have to be careful...
1691         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
1692           origWidth = Lod->getMemoryVT().getSizeInBits();
1693         const APInt &Mask =
1694           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1695         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
1696           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
1697           for (unsigned offset=0; offset<origWidth/width; offset++) {
1698             if ((newMask & Mask) == Mask) {
1699               if (!DAG.getDataLayout().isLittleEndian())
1700                 bestOffset = (origWidth/width - offset - 1) * (width/8);
1701               else
1702                 bestOffset = (uint64_t)offset * (width/8);
1703               bestMask = Mask.lshr(offset * (width/8) * 8);
1704               bestWidth = width;
1705               break;
1706             }
1707             newMask = newMask << width;
1708           }
1709         }
1710       }
1711       if (bestWidth) {
1712         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
1713         if (newVT.isRound()) {
1714           EVT PtrType = Lod->getOperand(1).getValueType();
1715           SDValue Ptr = Lod->getBasePtr();
1716           if (bestOffset != 0)
1717             Ptr = DAG.getNode(ISD::ADD, dl, PtrType, Lod->getBasePtr(),
1718                               DAG.getConstant(bestOffset, dl, PtrType));
1719           unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
1720           SDValue NewLoad = DAG.getLoad(
1721               newVT, dl, Lod->getChain(), Ptr,
1722               Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign);
1723           return DAG.getSetCC(dl, VT,
1724                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
1725                                       DAG.getConstant(bestMask.trunc(bestWidth),
1726                                                       dl, newVT)),
1727                               DAG.getConstant(0LL, dl, newVT), Cond);
1728         }
1729       }
1730     }
1731 
1732     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
1733     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
1734       unsigned InSize = N0.getOperand(0).getValueSizeInBits();
1735 
1736       // If the comparison constant has bits in the upper part, the
1737       // zero-extended value could never match.
1738       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
1739                                               C1.getBitWidth() - InSize))) {
1740         switch (Cond) {
1741         case ISD::SETUGT:
1742         case ISD::SETUGE:
1743         case ISD::SETEQ: return DAG.getConstant(0, dl, VT);
1744         case ISD::SETULT:
1745         case ISD::SETULE:
1746         case ISD::SETNE: return DAG.getConstant(1, dl, VT);
1747         case ISD::SETGT:
1748         case ISD::SETGE:
1749           // True if the sign bit of C1 is set.
1750           return DAG.getConstant(C1.isNegative(), dl, VT);
1751         case ISD::SETLT:
1752         case ISD::SETLE:
1753           // True if the sign bit of C1 isn't set.
1754           return DAG.getConstant(C1.isNonNegative(), dl, VT);
1755         default:
1756           break;
1757         }
1758       }
1759 
1760       // Otherwise, we can perform the comparison with the low bits.
1761       switch (Cond) {
1762       case ISD::SETEQ:
1763       case ISD::SETNE:
1764       case ISD::SETUGT:
1765       case ISD::SETUGE:
1766       case ISD::SETULT:
1767       case ISD::SETULE: {
1768         EVT newVT = N0.getOperand(0).getValueType();
1769         if (DCI.isBeforeLegalizeOps() ||
1770             (isOperationLegal(ISD::SETCC, newVT) &&
1771              getCondCodeAction(Cond, newVT.getSimpleVT()) == Legal)) {
1772           EVT NewSetCCVT =
1773               getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), newVT);
1774           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
1775 
1776           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
1777                                           NewConst, Cond);
1778           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
1779         }
1780         break;
1781       }
1782       default:
1783         break;   // todo, be more careful with signed comparisons
1784       }
1785     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1786                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1787       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
1788       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
1789       EVT ExtDstTy = N0.getValueType();
1790       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
1791 
1792       // If the constant doesn't fit into the number of bits for the source of
1793       // the sign extension, it is impossible for both sides to be equal.
1794       if (C1.getMinSignedBits() > ExtSrcTyBits)
1795         return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
1796 
1797       SDValue ZextOp;
1798       EVT Op0Ty = N0.getOperand(0).getValueType();
1799       if (Op0Ty == ExtSrcTy) {
1800         ZextOp = N0.getOperand(0);
1801       } else {
1802         APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
1803         ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
1804                               DAG.getConstant(Imm, dl, Op0Ty));
1805       }
1806       if (!DCI.isCalledByLegalizer())
1807         DCI.AddToWorklist(ZextOp.getNode());
1808       // Otherwise, make this a use of a zext.
1809       return DAG.getSetCC(dl, VT, ZextOp,
1810                           DAG.getConstant(C1 & APInt::getLowBitsSet(
1811                                                               ExtDstTyBits,
1812                                                               ExtSrcTyBits),
1813                                           dl, ExtDstTy),
1814                           Cond);
1815     } else if ((N1C->isNullValue() || N1C->getAPIntValue() == 1) &&
1816                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
1817       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
1818       if (N0.getOpcode() == ISD::SETCC &&
1819           isTypeLegal(VT) && VT.bitsLE(N0.getValueType())) {
1820         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (N1C->getAPIntValue() != 1);
1821         if (TrueWhenTrue)
1822           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
1823         // Invert the condition.
1824         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
1825         CC = ISD::getSetCCInverse(CC,
1826                                   N0.getOperand(0).getValueType().isInteger());
1827         if (DCI.isBeforeLegalizeOps() ||
1828             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
1829           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
1830       }
1831 
1832       if ((N0.getOpcode() == ISD::XOR ||
1833            (N0.getOpcode() == ISD::AND &&
1834             N0.getOperand(0).getOpcode() == ISD::XOR &&
1835             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
1836           isa<ConstantSDNode>(N0.getOperand(1)) &&
1837           cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue() == 1) {
1838         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
1839         // can only do this if the top bits are known zero.
1840         unsigned BitWidth = N0.getValueSizeInBits();
1841         if (DAG.MaskedValueIsZero(N0,
1842                                   APInt::getHighBitsSet(BitWidth,
1843                                                         BitWidth-1))) {
1844           // Okay, get the un-inverted input value.
1845           SDValue Val;
1846           if (N0.getOpcode() == ISD::XOR)
1847             Val = N0.getOperand(0);
1848           else {
1849             assert(N0.getOpcode() == ISD::AND &&
1850                     N0.getOperand(0).getOpcode() == ISD::XOR);
1851             // ((X^1)&1)^1 -> X & 1
1852             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
1853                               N0.getOperand(0).getOperand(0),
1854                               N0.getOperand(1));
1855           }
1856 
1857           return DAG.getSetCC(dl, VT, Val, N1,
1858                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1859         }
1860       } else if (N1C->getAPIntValue() == 1 &&
1861                  (VT == MVT::i1 ||
1862                   getBooleanContents(N0->getValueType(0)) ==
1863                       ZeroOrOneBooleanContent)) {
1864         SDValue Op0 = N0;
1865         if (Op0.getOpcode() == ISD::TRUNCATE)
1866           Op0 = Op0.getOperand(0);
1867 
1868         if ((Op0.getOpcode() == ISD::XOR) &&
1869             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
1870             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
1871           // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
1872           Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
1873           return DAG.getSetCC(dl, VT, Op0.getOperand(0), Op0.getOperand(1),
1874                               Cond);
1875         }
1876         if (Op0.getOpcode() == ISD::AND &&
1877             isa<ConstantSDNode>(Op0.getOperand(1)) &&
1878             cast<ConstantSDNode>(Op0.getOperand(1))->getAPIntValue() == 1) {
1879           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
1880           if (Op0.getValueType().bitsGT(VT))
1881             Op0 = DAG.getNode(ISD::AND, dl, VT,
1882                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
1883                           DAG.getConstant(1, dl, VT));
1884           else if (Op0.getValueType().bitsLT(VT))
1885             Op0 = DAG.getNode(ISD::AND, dl, VT,
1886                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
1887                         DAG.getConstant(1, dl, VT));
1888 
1889           return DAG.getSetCC(dl, VT, Op0,
1890                               DAG.getConstant(0, dl, Op0.getValueType()),
1891                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1892         }
1893         if (Op0.getOpcode() == ISD::AssertZext &&
1894             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
1895           return DAG.getSetCC(dl, VT, Op0,
1896                               DAG.getConstant(0, dl, Op0.getValueType()),
1897                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
1898       }
1899     }
1900 
1901     APInt MinVal, MaxVal;
1902     unsigned OperandBitSize = N1C->getValueType(0).getSizeInBits();
1903     if (ISD::isSignedIntSetCC(Cond)) {
1904       MinVal = APInt::getSignedMinValue(OperandBitSize);
1905       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
1906     } else {
1907       MinVal = APInt::getMinValue(OperandBitSize);
1908       MaxVal = APInt::getMaxValue(OperandBitSize);
1909     }
1910 
1911     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
1912     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
1913       if (C1 == MinVal) return DAG.getConstant(1, dl, VT);  // X >= MIN --> true
1914       // X >= C0 --> X > (C0 - 1)
1915       APInt C = C1 - 1;
1916       ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
1917       if ((DCI.isBeforeLegalizeOps() ||
1918            isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1919           (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1920                                 isLegalICmpImmediate(C.getSExtValue())))) {
1921         return DAG.getSetCC(dl, VT, N0,
1922                             DAG.getConstant(C, dl, N1.getValueType()),
1923                             NewCC);
1924       }
1925     }
1926 
1927     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
1928       if (C1 == MaxVal) return DAG.getConstant(1, dl, VT);  // X <= MAX --> true
1929       // X <= C0 --> X < (C0 + 1)
1930       APInt C = C1 + 1;
1931       ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
1932       if ((DCI.isBeforeLegalizeOps() ||
1933            isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
1934           (!N1C->isOpaque() || (N1C->isOpaque() && C.getBitWidth() <= 64 &&
1935                                 isLegalICmpImmediate(C.getSExtValue())))) {
1936         return DAG.getSetCC(dl, VT, N0,
1937                             DAG.getConstant(C, dl, N1.getValueType()),
1938                             NewCC);
1939       }
1940     }
1941 
1942     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal)
1943       return DAG.getConstant(0, dl, VT);      // X < MIN --> false
1944     if ((Cond == ISD::SETGE || Cond == ISD::SETUGE) && C1 == MinVal)
1945       return DAG.getConstant(1, dl, VT);      // X >= MIN --> true
1946     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal)
1947       return DAG.getConstant(0, dl, VT);      // X > MAX --> false
1948     if ((Cond == ISD::SETLE || Cond == ISD::SETULE) && C1 == MaxVal)
1949       return DAG.getConstant(1, dl, VT);      // X <= MAX --> true
1950 
1951     // Canonicalize setgt X, Min --> setne X, Min
1952     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MinVal)
1953       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1954     // Canonicalize setlt X, Max --> setne X, Max
1955     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MaxVal)
1956       return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
1957 
1958     // If we have setult X, 1, turn it into seteq X, 0
1959     if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C1 == MinVal+1)
1960       return DAG.getSetCC(dl, VT, N0,
1961                           DAG.getConstant(MinVal, dl, N0.getValueType()),
1962                           ISD::SETEQ);
1963     // If we have setugt X, Max-1, turn it into seteq X, Max
1964     if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C1 == MaxVal-1)
1965       return DAG.getSetCC(dl, VT, N0,
1966                           DAG.getConstant(MaxVal, dl, N0.getValueType()),
1967                           ISD::SETEQ);
1968 
1969     // If we have "setcc X, C0", check to see if we can shrink the immediate
1970     // by changing cc.
1971 
1972     // SETUGT X, SINTMAX  -> SETLT X, 0
1973     if (Cond == ISD::SETUGT &&
1974         C1 == APInt::getSignedMaxValue(OperandBitSize))
1975       return DAG.getSetCC(dl, VT, N0,
1976                           DAG.getConstant(0, dl, N1.getValueType()),
1977                           ISD::SETLT);
1978 
1979     // SETULT X, SINTMIN  -> SETGT X, -1
1980     if (Cond == ISD::SETULT &&
1981         C1 == APInt::getSignedMinValue(OperandBitSize)) {
1982       SDValue ConstMinusOne =
1983           DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
1984                           N1.getValueType());
1985       return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
1986     }
1987 
1988     // Fold bit comparisons when we can.
1989     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
1990         (VT == N0.getValueType() ||
1991          (isTypeLegal(VT) && VT.bitsLE(N0.getValueType()))) &&
1992         N0.getOpcode() == ISD::AND) {
1993       auto &DL = DAG.getDataLayout();
1994       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
1995         EVT ShiftTy = DCI.isBeforeLegalize()
1996                           ? getPointerTy(DL)
1997                           : getShiftAmountTy(N0.getValueType(), DL);
1998         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
1999           // Perform the xform if the AND RHS is a single bit.
2000           if (AndRHS->getAPIntValue().isPowerOf2()) {
2001             return DAG.getNode(ISD::TRUNCATE, dl, VT,
2002                               DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2003                    DAG.getConstant(AndRHS->getAPIntValue().logBase2(), dl,
2004                                    ShiftTy)));
2005           }
2006         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
2007           // (X & 8) == 8  -->  (X & 8) >> 3
2008           // Perform the xform if C1 is a single bit.
2009           if (C1.isPowerOf2()) {
2010             return DAG.getNode(ISD::TRUNCATE, dl, VT,
2011                                DAG.getNode(ISD::SRL, dl, N0.getValueType(), N0,
2012                                       DAG.getConstant(C1.logBase2(), dl,
2013                                                       ShiftTy)));
2014           }
2015         }
2016       }
2017     }
2018 
2019     if (C1.getMinSignedBits() <= 64 &&
2020         !isLegalICmpImmediate(C1.getSExtValue())) {
2021       // (X & -256) == 256 -> (X >> 8) == 1
2022       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2023           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
2024         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2025           const APInt &AndRHSC = AndRHS->getAPIntValue();
2026           if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
2027             unsigned ShiftBits = AndRHSC.countTrailingZeros();
2028             auto &DL = DAG.getDataLayout();
2029             EVT ShiftTy = DCI.isBeforeLegalize()
2030                               ? getPointerTy(DL)
2031                               : getShiftAmountTy(N0.getValueType(), DL);
2032             EVT CmpTy = N0.getValueType();
2033             SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0.getOperand(0),
2034                                         DAG.getConstant(ShiftBits, dl,
2035                                                         ShiftTy));
2036             SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, CmpTy);
2037             return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
2038           }
2039         }
2040       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
2041                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
2042         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
2043         // X <  0x100000000 -> (X >> 32) <  1
2044         // X >= 0x100000000 -> (X >> 32) >= 1
2045         // X <= 0x0ffffffff -> (X >> 32) <  1
2046         // X >  0x0ffffffff -> (X >> 32) >= 1
2047         unsigned ShiftBits;
2048         APInt NewC = C1;
2049         ISD::CondCode NewCond = Cond;
2050         if (AdjOne) {
2051           ShiftBits = C1.countTrailingOnes();
2052           NewC = NewC + 1;
2053           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
2054         } else {
2055           ShiftBits = C1.countTrailingZeros();
2056         }
2057         NewC = NewC.lshr(ShiftBits);
2058         if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
2059           isLegalICmpImmediate(NewC.getSExtValue())) {
2060           auto &DL = DAG.getDataLayout();
2061           EVT ShiftTy = DCI.isBeforeLegalize()
2062                             ? getPointerTy(DL)
2063                             : getShiftAmountTy(N0.getValueType(), DL);
2064           EVT CmpTy = N0.getValueType();
2065           SDValue Shift = DAG.getNode(ISD::SRL, dl, CmpTy, N0,
2066                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
2067           SDValue CmpRHS = DAG.getConstant(NewC, dl, CmpTy);
2068           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
2069         }
2070       }
2071     }
2072   }
2073 
2074   if (isa<ConstantFPSDNode>(N0.getNode())) {
2075     // Constant fold or commute setcc.
2076     SDValue O = DAG.FoldSetCC(VT, N0, N1, Cond, dl);
2077     if (O.getNode()) return O;
2078   } else if (auto *CFP = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
2079     // If the RHS of an FP comparison is a constant, simplify it away in
2080     // some cases.
2081     if (CFP->getValueAPF().isNaN()) {
2082       // If an operand is known to be a nan, we can fold it.
2083       switch (ISD::getUnorderedFlavor(Cond)) {
2084       default: llvm_unreachable("Unknown flavor!");
2085       case 0:  // Known false.
2086         return DAG.getConstant(0, dl, VT);
2087       case 1:  // Known true.
2088         return DAG.getConstant(1, dl, VT);
2089       case 2:  // Undefined.
2090         return DAG.getUNDEF(VT);
2091       }
2092     }
2093 
2094     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
2095     // constant if knowing that the operand is non-nan is enough.  We prefer to
2096     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
2097     // materialize 0.0.
2098     if (Cond == ISD::SETO || Cond == ISD::SETUO)
2099       return DAG.getSetCC(dl, VT, N0, N0, Cond);
2100 
2101     // setcc (fneg x), C -> setcc swap(pred) x, -C
2102     if (N0.getOpcode() == ISD::FNEG) {
2103       ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
2104       if (DCI.isBeforeLegalizeOps() ||
2105           isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
2106         SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
2107         return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
2108       }
2109     }
2110 
2111     // If the condition is not legal, see if we can find an equivalent one
2112     // which is legal.
2113     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
2114       // If the comparison was an awkward floating-point == or != and one of
2115       // the comparison operands is infinity or negative infinity, convert the
2116       // condition to a less-awkward <= or >=.
2117       if (CFP->getValueAPF().isInfinity()) {
2118         if (CFP->getValueAPF().isNegative()) {
2119           if (Cond == ISD::SETOEQ &&
2120               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
2121             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLE);
2122           if (Cond == ISD::SETUEQ &&
2123               isCondCodeLegal(ISD::SETOLE, N0.getSimpleValueType()))
2124             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULE);
2125           if (Cond == ISD::SETUNE &&
2126               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
2127             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGT);
2128           if (Cond == ISD::SETONE &&
2129               isCondCodeLegal(ISD::SETUGT, N0.getSimpleValueType()))
2130             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGT);
2131         } else {
2132           if (Cond == ISD::SETOEQ &&
2133               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
2134             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOGE);
2135           if (Cond == ISD::SETUEQ &&
2136               isCondCodeLegal(ISD::SETOGE, N0.getSimpleValueType()))
2137             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETUGE);
2138           if (Cond == ISD::SETUNE &&
2139               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
2140             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETULT);
2141           if (Cond == ISD::SETONE &&
2142               isCondCodeLegal(ISD::SETULT, N0.getSimpleValueType()))
2143             return DAG.getSetCC(dl, VT, N0, N1, ISD::SETOLT);
2144         }
2145       }
2146     }
2147   }
2148 
2149   if (N0 == N1) {
2150     // The sext(setcc()) => setcc() optimization relies on the appropriate
2151     // constant being emitted.
2152     uint64_t EqVal = 0;
2153     switch (getBooleanContents(N0.getValueType())) {
2154     case UndefinedBooleanContent:
2155     case ZeroOrOneBooleanContent:
2156       EqVal = ISD::isTrueWhenEqual(Cond);
2157       break;
2158     case ZeroOrNegativeOneBooleanContent:
2159       EqVal = ISD::isTrueWhenEqual(Cond) ? -1 : 0;
2160       break;
2161     }
2162 
2163     // We can always fold X == X for integer setcc's.
2164     if (N0.getValueType().isInteger()) {
2165       return DAG.getConstant(EqVal, dl, VT);
2166     }
2167     unsigned UOF = ISD::getUnorderedFlavor(Cond);
2168     if (UOF == 2)   // FP operators that are undefined on NaNs.
2169       return DAG.getConstant(EqVal, dl, VT);
2170     if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
2171       return DAG.getConstant(EqVal, dl, VT);
2172     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
2173     // if it is not already.
2174     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
2175     if (NewCond != Cond && (DCI.isBeforeLegalizeOps() ||
2176           getCondCodeAction(NewCond, N0.getSimpleValueType()) == Legal))
2177       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
2178   }
2179 
2180   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
2181       N0.getValueType().isInteger()) {
2182     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
2183         N0.getOpcode() == ISD::XOR) {
2184       // Simplify (X+Y) == (X+Z) -->  Y == Z
2185       if (N0.getOpcode() == N1.getOpcode()) {
2186         if (N0.getOperand(0) == N1.getOperand(0))
2187           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
2188         if (N0.getOperand(1) == N1.getOperand(1))
2189           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
2190         if (DAG.isCommutativeBinOp(N0.getOpcode())) {
2191           // If X op Y == Y op X, try other combinations.
2192           if (N0.getOperand(0) == N1.getOperand(1))
2193             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
2194                                 Cond);
2195           if (N0.getOperand(1) == N1.getOperand(0))
2196             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
2197                                 Cond);
2198         }
2199       }
2200 
2201       // If RHS is a legal immediate value for a compare instruction, we need
2202       // to be careful about increasing register pressure needlessly.
2203       bool LegalRHSImm = false;
2204 
2205       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
2206         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2207           // Turn (X+C1) == C2 --> X == C2-C1
2208           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
2209             return DAG.getSetCC(dl, VT, N0.getOperand(0),
2210                                 DAG.getConstant(RHSC->getAPIntValue()-
2211                                                 LHSR->getAPIntValue(),
2212                                 dl, N0.getValueType()), Cond);
2213           }
2214 
2215           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
2216           if (N0.getOpcode() == ISD::XOR)
2217             // If we know that all of the inverted bits are zero, don't bother
2218             // performing the inversion.
2219             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
2220               return
2221                 DAG.getSetCC(dl, VT, N0.getOperand(0),
2222                              DAG.getConstant(LHSR->getAPIntValue() ^
2223                                                RHSC->getAPIntValue(),
2224                                              dl, N0.getValueType()),
2225                              Cond);
2226         }
2227 
2228         // Turn (C1-X) == C2 --> X == C1-C2
2229         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
2230           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
2231             return
2232               DAG.getSetCC(dl, VT, N0.getOperand(1),
2233                            DAG.getConstant(SUBC->getAPIntValue() -
2234                                              RHSC->getAPIntValue(),
2235                                            dl, N0.getValueType()),
2236                            Cond);
2237           }
2238         }
2239 
2240         // Could RHSC fold directly into a compare?
2241         if (RHSC->getValueType(0).getSizeInBits() <= 64)
2242           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
2243       }
2244 
2245       // Simplify (X+Z) == X -->  Z == 0
2246       // Don't do this if X is an immediate that can fold into a cmp
2247       // instruction and X+Z has other uses. It could be an induction variable
2248       // chain, and the transform would increase register pressure.
2249       if (!LegalRHSImm || N0.getNode()->hasOneUse()) {
2250         if (N0.getOperand(0) == N1)
2251           return DAG.getSetCC(dl, VT, N0.getOperand(1),
2252                               DAG.getConstant(0, dl, N0.getValueType()), Cond);
2253         if (N0.getOperand(1) == N1) {
2254           if (DAG.isCommutativeBinOp(N0.getOpcode()))
2255             return DAG.getSetCC(dl, VT, N0.getOperand(0),
2256                                 DAG.getConstant(0, dl, N0.getValueType()),
2257                                 Cond);
2258           if (N0.getNode()->hasOneUse()) {
2259             assert(N0.getOpcode() == ISD::SUB && "Unexpected operation!");
2260             auto &DL = DAG.getDataLayout();
2261             // (Z-X) == X  --> Z == X<<1
2262             SDValue SH = DAG.getNode(
2263                 ISD::SHL, dl, N1.getValueType(), N1,
2264                 DAG.getConstant(1, dl,
2265                                 getShiftAmountTy(N1.getValueType(), DL)));
2266             if (!DCI.isCalledByLegalizer())
2267               DCI.AddToWorklist(SH.getNode());
2268             return DAG.getSetCC(dl, VT, N0.getOperand(0), SH, Cond);
2269           }
2270         }
2271       }
2272     }
2273 
2274     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
2275         N1.getOpcode() == ISD::XOR) {
2276       // Simplify  X == (X+Z) -->  Z == 0
2277       if (N1.getOperand(0) == N0)
2278         return DAG.getSetCC(dl, VT, N1.getOperand(1),
2279                         DAG.getConstant(0, dl, N1.getValueType()), Cond);
2280       if (N1.getOperand(1) == N0) {
2281         if (DAG.isCommutativeBinOp(N1.getOpcode()))
2282           return DAG.getSetCC(dl, VT, N1.getOperand(0),
2283                           DAG.getConstant(0, dl, N1.getValueType()), Cond);
2284         if (N1.getNode()->hasOneUse()) {
2285           assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
2286           auto &DL = DAG.getDataLayout();
2287           // X == (Z-X)  --> X<<1 == Z
2288           SDValue SH = DAG.getNode(
2289               ISD::SHL, dl, N1.getValueType(), N0,
2290               DAG.getConstant(1, dl, getShiftAmountTy(N0.getValueType(), DL)));
2291           if (!DCI.isCalledByLegalizer())
2292             DCI.AddToWorklist(SH.getNode());
2293           return DAG.getSetCC(dl, VT, SH, N1.getOperand(0), Cond);
2294         }
2295       }
2296     }
2297 
2298     if (SDValue V = simplifySetCCWithAnd(VT, N0, N1, Cond, DCI, dl))
2299       return V;
2300   }
2301 
2302   // Fold away ALL boolean setcc's.
2303   SDValue Temp;
2304   if (N0.getValueType() == MVT::i1 && foldBooleans) {
2305     switch (Cond) {
2306     default: llvm_unreachable("Unknown integer setcc!");
2307     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
2308       Temp = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2309       N0 = DAG.getNOT(dl, Temp, MVT::i1);
2310       if (!DCI.isCalledByLegalizer())
2311         DCI.AddToWorklist(Temp.getNode());
2312       break;
2313     case ISD::SETNE:  // X != Y   -->  (X^Y)
2314       N0 = DAG.getNode(ISD::XOR, dl, MVT::i1, N0, N1);
2315       break;
2316     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
2317     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
2318       Temp = DAG.getNOT(dl, N0, MVT::i1);
2319       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N1, Temp);
2320       if (!DCI.isCalledByLegalizer())
2321         DCI.AddToWorklist(Temp.getNode());
2322       break;
2323     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
2324     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
2325       Temp = DAG.getNOT(dl, N1, MVT::i1);
2326       N0 = DAG.getNode(ISD::AND, dl, MVT::i1, N0, Temp);
2327       if (!DCI.isCalledByLegalizer())
2328         DCI.AddToWorklist(Temp.getNode());
2329       break;
2330     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
2331     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
2332       Temp = DAG.getNOT(dl, N0, MVT::i1);
2333       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N1, Temp);
2334       if (!DCI.isCalledByLegalizer())
2335         DCI.AddToWorklist(Temp.getNode());
2336       break;
2337     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
2338     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
2339       Temp = DAG.getNOT(dl, N1, MVT::i1);
2340       N0 = DAG.getNode(ISD::OR, dl, MVT::i1, N0, Temp);
2341       break;
2342     }
2343     if (VT != MVT::i1) {
2344       if (!DCI.isCalledByLegalizer())
2345         DCI.AddToWorklist(N0.getNode());
2346       // FIXME: If running after legalize, we probably can't do this.
2347       N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0);
2348     }
2349     return N0;
2350   }
2351 
2352   // Could not fold it.
2353   return SDValue();
2354 }
2355 
2356 /// Returns true (and the GlobalValue and the offset) if the node is a
2357 /// GlobalAddress + offset.
2358 bool TargetLowering::isGAPlusOffset(SDNode *N, const GlobalValue *&GA,
2359                                     int64_t &Offset) const {
2360   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
2361     GA = GASD->getGlobal();
2362     Offset += GASD->getOffset();
2363     return true;
2364   }
2365 
2366   if (N->getOpcode() == ISD::ADD) {
2367     SDValue N1 = N->getOperand(0);
2368     SDValue N2 = N->getOperand(1);
2369     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
2370       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
2371         Offset += V->getSExtValue();
2372         return true;
2373       }
2374     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
2375       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
2376         Offset += V->getSExtValue();
2377         return true;
2378       }
2379     }
2380   }
2381 
2382   return false;
2383 }
2384 
2385 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
2386                                           DAGCombinerInfo &DCI) const {
2387   // Default implementation: no optimization.
2388   return SDValue();
2389 }
2390 
2391 //===----------------------------------------------------------------------===//
2392 //  Inline Assembler Implementation Methods
2393 //===----------------------------------------------------------------------===//
2394 
2395 TargetLowering::ConstraintType
2396 TargetLowering::getConstraintType(StringRef Constraint) const {
2397   unsigned S = Constraint.size();
2398 
2399   if (S == 1) {
2400     switch (Constraint[0]) {
2401     default: break;
2402     case 'r': return C_RegisterClass;
2403     case 'm':    // memory
2404     case 'o':    // offsetable
2405     case 'V':    // not offsetable
2406       return C_Memory;
2407     case 'i':    // Simple Integer or Relocatable Constant
2408     case 'n':    // Simple Integer
2409     case 'E':    // Floating Point Constant
2410     case 'F':    // Floating Point Constant
2411     case 's':    // Relocatable Constant
2412     case 'p':    // Address.
2413     case 'X':    // Allow ANY value.
2414     case 'I':    // Target registers.
2415     case 'J':
2416     case 'K':
2417     case 'L':
2418     case 'M':
2419     case 'N':
2420     case 'O':
2421     case 'P':
2422     case '<':
2423     case '>':
2424       return C_Other;
2425     }
2426   }
2427 
2428   if (S > 1 && Constraint[0] == '{' && Constraint[S-1] == '}') {
2429     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
2430       return C_Memory;
2431     return C_Register;
2432   }
2433   return C_Unknown;
2434 }
2435 
2436 /// Try to replace an X constraint, which matches anything, with another that
2437 /// has more specific requirements based on the type of the corresponding
2438 /// operand.
2439 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const{
2440   if (ConstraintVT.isInteger())
2441     return "r";
2442   if (ConstraintVT.isFloatingPoint())
2443     return "f";      // works for many targets
2444   return nullptr;
2445 }
2446 
2447 /// Lower the specified operand into the Ops vector.
2448 /// If it is invalid, don't add anything to Ops.
2449 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2450                                                   std::string &Constraint,
2451                                                   std::vector<SDValue> &Ops,
2452                                                   SelectionDAG &DAG) const {
2453 
2454   if (Constraint.length() > 1) return;
2455 
2456   char ConstraintLetter = Constraint[0];
2457   switch (ConstraintLetter) {
2458   default: break;
2459   case 'X':     // Allows any operand; labels (basic block) use this.
2460     if (Op.getOpcode() == ISD::BasicBlock) {
2461       Ops.push_back(Op);
2462       return;
2463     }
2464     LLVM_FALLTHROUGH;
2465   case 'i':    // Simple Integer or Relocatable Constant
2466   case 'n':    // Simple Integer
2467   case 's': {  // Relocatable Constant
2468     // These operands are interested in values of the form (GV+C), where C may
2469     // be folded in as an offset of GV, or it may be explicitly added.  Also, it
2470     // is possible and fine if either GV or C are missing.
2471     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
2472     GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2473 
2474     // If we have "(add GV, C)", pull out GV/C
2475     if (Op.getOpcode() == ISD::ADD) {
2476       C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2477       GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(0));
2478       if (!C || !GA) {
2479         C = dyn_cast<ConstantSDNode>(Op.getOperand(0));
2480         GA = dyn_cast<GlobalAddressSDNode>(Op.getOperand(1));
2481       }
2482       if (!C || !GA) {
2483         C = nullptr;
2484         GA = nullptr;
2485       }
2486     }
2487 
2488     // If we find a valid operand, map to the TargetXXX version so that the
2489     // value itself doesn't get selected.
2490     if (GA) {   // Either &GV   or   &GV+C
2491       if (ConstraintLetter != 'n') {
2492         int64_t Offs = GA->getOffset();
2493         if (C) Offs += C->getZExtValue();
2494         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(),
2495                                                  C ? SDLoc(C) : SDLoc(),
2496                                                  Op.getValueType(), Offs));
2497       }
2498       return;
2499     }
2500     if (C) {   // just C, no GV.
2501       // Simple constants are not allowed for 's'.
2502       if (ConstraintLetter != 's') {
2503         // gcc prints these as sign extended.  Sign extend value to 64 bits
2504         // now; without this it would get ZExt'd later in
2505         // ScheduleDAGSDNodes::EmitNode, which is very generic.
2506         Ops.push_back(DAG.getTargetConstant(C->getAPIntValue().getSExtValue(),
2507                                             SDLoc(C), MVT::i64));
2508       }
2509       return;
2510     }
2511     break;
2512   }
2513   }
2514 }
2515 
2516 std::pair<unsigned, const TargetRegisterClass *>
2517 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
2518                                              StringRef Constraint,
2519                                              MVT VT) const {
2520   if (Constraint.empty() || Constraint[0] != '{')
2521     return std::make_pair(0u, static_cast<TargetRegisterClass*>(nullptr));
2522   assert(*(Constraint.end()-1) == '}' && "Not a brace enclosed constraint?");
2523 
2524   // Remove the braces from around the name.
2525   StringRef RegName(Constraint.data()+1, Constraint.size()-2);
2526 
2527   std::pair<unsigned, const TargetRegisterClass*> R =
2528     std::make_pair(0u, static_cast<const TargetRegisterClass*>(nullptr));
2529 
2530   // Figure out which register class contains this reg.
2531   for (const TargetRegisterClass *RC : RI->regclasses()) {
2532     // If none of the value types for this register class are valid, we
2533     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
2534     if (!isLegalRC(RC))
2535       continue;
2536 
2537     for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
2538          I != E; ++I) {
2539       if (RegName.equals_lower(RI->getRegAsmName(*I))) {
2540         std::pair<unsigned, const TargetRegisterClass*> S =
2541           std::make_pair(*I, RC);
2542 
2543         // If this register class has the requested value type, return it,
2544         // otherwise keep searching and return the first class found
2545         // if no other is found which explicitly has the requested type.
2546         if (RC->hasType(VT))
2547           return S;
2548         else if (!R.second)
2549           R = S;
2550       }
2551     }
2552   }
2553 
2554   return R;
2555 }
2556 
2557 //===----------------------------------------------------------------------===//
2558 // Constraint Selection.
2559 
2560 /// Return true of this is an input operand that is a matching constraint like
2561 /// "4".
2562 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
2563   assert(!ConstraintCode.empty() && "No known constraint!");
2564   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
2565 }
2566 
2567 /// If this is an input matching constraint, this method returns the output
2568 /// operand it matches.
2569 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
2570   assert(!ConstraintCode.empty() && "No known constraint!");
2571   return atoi(ConstraintCode.c_str());
2572 }
2573 
2574 /// Split up the constraint string from the inline assembly value into the
2575 /// specific constraints and their prefixes, and also tie in the associated
2576 /// operand values.
2577 /// If this returns an empty vector, and if the constraint string itself
2578 /// isn't empty, there was an error parsing.
2579 TargetLowering::AsmOperandInfoVector
2580 TargetLowering::ParseConstraints(const DataLayout &DL,
2581                                  const TargetRegisterInfo *TRI,
2582                                  ImmutableCallSite CS) const {
2583   /// Information about all of the constraints.
2584   AsmOperandInfoVector ConstraintOperands;
2585   const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
2586   unsigned maCount = 0; // Largest number of multiple alternative constraints.
2587 
2588   // Do a prepass over the constraints, canonicalizing them, and building up the
2589   // ConstraintOperands list.
2590   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
2591   unsigned ResNo = 0;   // ResNo - The result number of the next output.
2592 
2593   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
2594     ConstraintOperands.emplace_back(std::move(CI));
2595     AsmOperandInfo &OpInfo = ConstraintOperands.back();
2596 
2597     // Update multiple alternative constraint count.
2598     if (OpInfo.multipleAlternatives.size() > maCount)
2599       maCount = OpInfo.multipleAlternatives.size();
2600 
2601     OpInfo.ConstraintVT = MVT::Other;
2602 
2603     // Compute the value type for each operand.
2604     switch (OpInfo.Type) {
2605     case InlineAsm::isOutput:
2606       // Indirect outputs just consume an argument.
2607       if (OpInfo.isIndirect) {
2608         OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2609         break;
2610       }
2611 
2612       // The return value of the call is this value.  As such, there is no
2613       // corresponding argument.
2614       assert(!CS.getType()->isVoidTy() &&
2615              "Bad inline asm!");
2616       if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
2617         OpInfo.ConstraintVT =
2618             getSimpleValueType(DL, STy->getElementType(ResNo));
2619       } else {
2620         assert(ResNo == 0 && "Asm only has one result!");
2621         OpInfo.ConstraintVT = getSimpleValueType(DL, CS.getType());
2622       }
2623       ++ResNo;
2624       break;
2625     case InlineAsm::isInput:
2626       OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
2627       break;
2628     case InlineAsm::isClobber:
2629       // Nothing to do.
2630       break;
2631     }
2632 
2633     if (OpInfo.CallOperandVal) {
2634       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
2635       if (OpInfo.isIndirect) {
2636         llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
2637         if (!PtrTy)
2638           report_fatal_error("Indirect operand for inline asm not a pointer!");
2639         OpTy = PtrTy->getElementType();
2640       }
2641 
2642       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
2643       if (StructType *STy = dyn_cast<StructType>(OpTy))
2644         if (STy->getNumElements() == 1)
2645           OpTy = STy->getElementType(0);
2646 
2647       // If OpTy is not a single value, it may be a struct/union that we
2648       // can tile with integers.
2649       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
2650         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
2651         switch (BitSize) {
2652         default: break;
2653         case 1:
2654         case 8:
2655         case 16:
2656         case 32:
2657         case 64:
2658         case 128:
2659           OpInfo.ConstraintVT =
2660             MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
2661           break;
2662         }
2663       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
2664         unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
2665         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
2666       } else {
2667         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
2668       }
2669     }
2670   }
2671 
2672   // If we have multiple alternative constraints, select the best alternative.
2673   if (!ConstraintOperands.empty()) {
2674     if (maCount) {
2675       unsigned bestMAIndex = 0;
2676       int bestWeight = -1;
2677       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
2678       int weight = -1;
2679       unsigned maIndex;
2680       // Compute the sums of the weights for each alternative, keeping track
2681       // of the best (highest weight) one so far.
2682       for (maIndex = 0; maIndex < maCount; ++maIndex) {
2683         int weightSum = 0;
2684         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2685             cIndex != eIndex; ++cIndex) {
2686           AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2687           if (OpInfo.Type == InlineAsm::isClobber)
2688             continue;
2689 
2690           // If this is an output operand with a matching input operand,
2691           // look up the matching input. If their types mismatch, e.g. one
2692           // is an integer, the other is floating point, or their sizes are
2693           // different, flag it as an maCantMatch.
2694           if (OpInfo.hasMatchingInput()) {
2695             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2696             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2697               if ((OpInfo.ConstraintVT.isInteger() !=
2698                    Input.ConstraintVT.isInteger()) ||
2699                   (OpInfo.ConstraintVT.getSizeInBits() !=
2700                    Input.ConstraintVT.getSizeInBits())) {
2701                 weightSum = -1;  // Can't match.
2702                 break;
2703               }
2704             }
2705           }
2706           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
2707           if (weight == -1) {
2708             weightSum = -1;
2709             break;
2710           }
2711           weightSum += weight;
2712         }
2713         // Update best.
2714         if (weightSum > bestWeight) {
2715           bestWeight = weightSum;
2716           bestMAIndex = maIndex;
2717         }
2718       }
2719 
2720       // Now select chosen alternative in each constraint.
2721       for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2722           cIndex != eIndex; ++cIndex) {
2723         AsmOperandInfo& cInfo = ConstraintOperands[cIndex];
2724         if (cInfo.Type == InlineAsm::isClobber)
2725           continue;
2726         cInfo.selectAlternative(bestMAIndex);
2727       }
2728     }
2729   }
2730 
2731   // Check and hook up tied operands, choose constraint code to use.
2732   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
2733       cIndex != eIndex; ++cIndex) {
2734     AsmOperandInfo& OpInfo = ConstraintOperands[cIndex];
2735 
2736     // If this is an output operand with a matching input operand, look up the
2737     // matching input. If their types mismatch, e.g. one is an integer, the
2738     // other is floating point, or their sizes are different, flag it as an
2739     // error.
2740     if (OpInfo.hasMatchingInput()) {
2741       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
2742 
2743       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
2744         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
2745             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
2746                                          OpInfo.ConstraintVT);
2747         std::pair<unsigned, const TargetRegisterClass *> InputRC =
2748             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
2749                                          Input.ConstraintVT);
2750         if ((OpInfo.ConstraintVT.isInteger() !=
2751              Input.ConstraintVT.isInteger()) ||
2752             (MatchRC.second != InputRC.second)) {
2753           report_fatal_error("Unsupported asm: input constraint"
2754                              " with a matching output constraint of"
2755                              " incompatible type!");
2756         }
2757       }
2758     }
2759   }
2760 
2761   return ConstraintOperands;
2762 }
2763 
2764 /// Return an integer indicating how general CT is.
2765 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
2766   switch (CT) {
2767   case TargetLowering::C_Other:
2768   case TargetLowering::C_Unknown:
2769     return 0;
2770   case TargetLowering::C_Register:
2771     return 1;
2772   case TargetLowering::C_RegisterClass:
2773     return 2;
2774   case TargetLowering::C_Memory:
2775     return 3;
2776   }
2777   llvm_unreachable("Invalid constraint type");
2778 }
2779 
2780 /// Examine constraint type and operand type and determine a weight value.
2781 /// This object must already have been set up with the operand type
2782 /// and the current alternative constraint selected.
2783 TargetLowering::ConstraintWeight
2784   TargetLowering::getMultipleConstraintMatchWeight(
2785     AsmOperandInfo &info, int maIndex) const {
2786   InlineAsm::ConstraintCodeVector *rCodes;
2787   if (maIndex >= (int)info.multipleAlternatives.size())
2788     rCodes = &info.Codes;
2789   else
2790     rCodes = &info.multipleAlternatives[maIndex].Codes;
2791   ConstraintWeight BestWeight = CW_Invalid;
2792 
2793   // Loop over the options, keeping track of the most general one.
2794   for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
2795     ConstraintWeight weight =
2796       getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
2797     if (weight > BestWeight)
2798       BestWeight = weight;
2799   }
2800 
2801   return BestWeight;
2802 }
2803 
2804 /// Examine constraint type and operand type and determine a weight value.
2805 /// This object must already have been set up with the operand type
2806 /// and the current alternative constraint selected.
2807 TargetLowering::ConstraintWeight
2808   TargetLowering::getSingleConstraintMatchWeight(
2809     AsmOperandInfo &info, const char *constraint) const {
2810   ConstraintWeight weight = CW_Invalid;
2811   Value *CallOperandVal = info.CallOperandVal;
2812     // If we don't have a value, we can't do a match,
2813     // but allow it at the lowest weight.
2814   if (!CallOperandVal)
2815     return CW_Default;
2816   // Look at the constraint type.
2817   switch (*constraint) {
2818     case 'i': // immediate integer.
2819     case 'n': // immediate integer with a known value.
2820       if (isa<ConstantInt>(CallOperandVal))
2821         weight = CW_Constant;
2822       break;
2823     case 's': // non-explicit intregal immediate.
2824       if (isa<GlobalValue>(CallOperandVal))
2825         weight = CW_Constant;
2826       break;
2827     case 'E': // immediate float if host format.
2828     case 'F': // immediate float.
2829       if (isa<ConstantFP>(CallOperandVal))
2830         weight = CW_Constant;
2831       break;
2832     case '<': // memory operand with autodecrement.
2833     case '>': // memory operand with autoincrement.
2834     case 'm': // memory operand.
2835     case 'o': // offsettable memory operand
2836     case 'V': // non-offsettable memory operand
2837       weight = CW_Memory;
2838       break;
2839     case 'r': // general register.
2840     case 'g': // general register, memory operand or immediate integer.
2841               // note: Clang converts "g" to "imr".
2842       if (CallOperandVal->getType()->isIntegerTy())
2843         weight = CW_Register;
2844       break;
2845     case 'X': // any operand.
2846     default:
2847       weight = CW_Default;
2848       break;
2849   }
2850   return weight;
2851 }
2852 
2853 /// If there are multiple different constraints that we could pick for this
2854 /// operand (e.g. "imr") try to pick the 'best' one.
2855 /// This is somewhat tricky: constraints fall into four classes:
2856 ///    Other         -> immediates and magic values
2857 ///    Register      -> one specific register
2858 ///    RegisterClass -> a group of regs
2859 ///    Memory        -> memory
2860 /// Ideally, we would pick the most specific constraint possible: if we have
2861 /// something that fits into a register, we would pick it.  The problem here
2862 /// is that if we have something that could either be in a register or in
2863 /// memory that use of the register could cause selection of *other*
2864 /// operands to fail: they might only succeed if we pick memory.  Because of
2865 /// this the heuristic we use is:
2866 ///
2867 ///  1) If there is an 'other' constraint, and if the operand is valid for
2868 ///     that constraint, use it.  This makes us take advantage of 'i'
2869 ///     constraints when available.
2870 ///  2) Otherwise, pick the most general constraint present.  This prefers
2871 ///     'm' over 'r', for example.
2872 ///
2873 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
2874                              const TargetLowering &TLI,
2875                              SDValue Op, SelectionDAG *DAG) {
2876   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
2877   unsigned BestIdx = 0;
2878   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
2879   int BestGenerality = -1;
2880 
2881   // Loop over the options, keeping track of the most general one.
2882   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
2883     TargetLowering::ConstraintType CType =
2884       TLI.getConstraintType(OpInfo.Codes[i]);
2885 
2886     // If this is an 'other' constraint, see if the operand is valid for it.
2887     // For example, on X86 we might have an 'rI' constraint.  If the operand
2888     // is an integer in the range [0..31] we want to use I (saving a load
2889     // of a register), otherwise we must use 'r'.
2890     if (CType == TargetLowering::C_Other && Op.getNode()) {
2891       assert(OpInfo.Codes[i].size() == 1 &&
2892              "Unhandled multi-letter 'other' constraint");
2893       std::vector<SDValue> ResultOps;
2894       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
2895                                        ResultOps, *DAG);
2896       if (!ResultOps.empty()) {
2897         BestType = CType;
2898         BestIdx = i;
2899         break;
2900       }
2901     }
2902 
2903     // Things with matching constraints can only be registers, per gcc
2904     // documentation.  This mainly affects "g" constraints.
2905     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
2906       continue;
2907 
2908     // This constraint letter is more general than the previous one, use it.
2909     int Generality = getConstraintGenerality(CType);
2910     if (Generality > BestGenerality) {
2911       BestType = CType;
2912       BestIdx = i;
2913       BestGenerality = Generality;
2914     }
2915   }
2916 
2917   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
2918   OpInfo.ConstraintType = BestType;
2919 }
2920 
2921 /// Determines the constraint code and constraint type to use for the specific
2922 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
2923 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
2924                                             SDValue Op,
2925                                             SelectionDAG *DAG) const {
2926   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
2927 
2928   // Single-letter constraints ('r') are very common.
2929   if (OpInfo.Codes.size() == 1) {
2930     OpInfo.ConstraintCode = OpInfo.Codes[0];
2931     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2932   } else {
2933     ChooseConstraint(OpInfo, *this, Op, DAG);
2934   }
2935 
2936   // 'X' matches anything.
2937   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
2938     // Labels and constants are handled elsewhere ('X' is the only thing
2939     // that matches labels).  For Functions, the type here is the type of
2940     // the result, which is not what we want to look at; leave them alone.
2941     Value *v = OpInfo.CallOperandVal;
2942     if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
2943       OpInfo.CallOperandVal = v;
2944       return;
2945     }
2946 
2947     // Otherwise, try to resolve it to something we know about by looking at
2948     // the actual operand type.
2949     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
2950       OpInfo.ConstraintCode = Repl;
2951       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
2952     }
2953   }
2954 }
2955 
2956 /// \brief Given an exact SDIV by a constant, create a multiplication
2957 /// with the multiplicative inverse of the constant.
2958 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDValue Op1, APInt d,
2959                               const SDLoc &dl, SelectionDAG &DAG,
2960                               std::vector<SDNode *> &Created) {
2961   assert(d != 0 && "Division by zero!");
2962 
2963   // Shift the value upfront if it is even, so the LSB is one.
2964   unsigned ShAmt = d.countTrailingZeros();
2965   if (ShAmt) {
2966     // TODO: For UDIV use SRL instead of SRA.
2967     SDValue Amt =
2968         DAG.getConstant(ShAmt, dl, TLI.getShiftAmountTy(Op1.getValueType(),
2969                                                         DAG.getDataLayout()));
2970     SDNodeFlags Flags;
2971     Flags.setExact(true);
2972     Op1 = DAG.getNode(ISD::SRA, dl, Op1.getValueType(), Op1, Amt, &Flags);
2973     Created.push_back(Op1.getNode());
2974     d = d.ashr(ShAmt);
2975   }
2976 
2977   // Calculate the multiplicative inverse, using Newton's method.
2978   APInt t, xn = d;
2979   while ((t = d*xn) != 1)
2980     xn *= APInt(d.getBitWidth(), 2) - t;
2981 
2982   SDValue Op2 = DAG.getConstant(xn, dl, Op1.getValueType());
2983   SDValue Mul = DAG.getNode(ISD::MUL, dl, Op1.getValueType(), Op1, Op2);
2984   Created.push_back(Mul.getNode());
2985   return Mul;
2986 }
2987 
2988 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
2989                                       SelectionDAG &DAG,
2990                                       std::vector<SDNode *> *Created) const {
2991   AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2992   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
2993   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
2994     return SDValue(N,0); // Lower SDIV as SDIV
2995   return SDValue();
2996 }
2997 
2998 /// \brief Given an ISD::SDIV node expressing a divide by constant,
2999 /// return a DAG expression to select that will generate the same value by
3000 /// multiplying by a magic number.
3001 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
3002 SDValue TargetLowering::BuildSDIV(SDNode *N, const APInt &Divisor,
3003                                   SelectionDAG &DAG, bool IsAfterLegalization,
3004                                   std::vector<SDNode *> *Created) const {
3005   assert(Created && "No vector to hold sdiv ops.");
3006 
3007   EVT VT = N->getValueType(0);
3008   SDLoc dl(N);
3009 
3010   // Check to see if we can do this.
3011   // FIXME: We should be more aggressive here.
3012   if (!isTypeLegal(VT))
3013     return SDValue();
3014 
3015   // If the sdiv has an 'exact' bit we can use a simpler lowering.
3016   if (cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact())
3017     return BuildExactSDIV(*this, N->getOperand(0), Divisor, dl, DAG, *Created);
3018 
3019   APInt::ms magics = Divisor.magic();
3020 
3021   // Multiply the numerator (operand 0) by the magic value
3022   // FIXME: We should support doing a MUL in a wider type
3023   SDValue Q;
3024   if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT) :
3025                             isOperationLegalOrCustom(ISD::MULHS, VT))
3026     Q = DAG.getNode(ISD::MULHS, dl, VT, N->getOperand(0),
3027                     DAG.getConstant(magics.m, dl, VT));
3028   else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT) :
3029                                  isOperationLegalOrCustom(ISD::SMUL_LOHI, VT))
3030     Q = SDValue(DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT),
3031                               N->getOperand(0),
3032                               DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
3033   else
3034     return SDValue();       // No mulhs or equvialent
3035   // If d > 0 and m < 0, add the numerator
3036   if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
3037     Q = DAG.getNode(ISD::ADD, dl, VT, Q, N->getOperand(0));
3038     Created->push_back(Q.getNode());
3039   }
3040   // If d < 0 and m > 0, subtract the numerator.
3041   if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
3042     Q = DAG.getNode(ISD::SUB, dl, VT, Q, N->getOperand(0));
3043     Created->push_back(Q.getNode());
3044   }
3045   auto &DL = DAG.getDataLayout();
3046   // Shift right algebraic if shift value is nonzero
3047   if (magics.s > 0) {
3048     Q = DAG.getNode(
3049         ISD::SRA, dl, VT, Q,
3050         DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
3051     Created->push_back(Q.getNode());
3052   }
3053   // Extract the sign bit and add it to the quotient
3054   SDValue T =
3055       DAG.getNode(ISD::SRL, dl, VT, Q,
3056                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl,
3057                                   getShiftAmountTy(Q.getValueType(), DL)));
3058   Created->push_back(T.getNode());
3059   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
3060 }
3061 
3062 /// \brief Given an ISD::UDIV node expressing a divide by constant,
3063 /// return a DAG expression to select that will generate the same value by
3064 /// multiplying by a magic number.
3065 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
3066 SDValue TargetLowering::BuildUDIV(SDNode *N, const APInt &Divisor,
3067                                   SelectionDAG &DAG, bool IsAfterLegalization,
3068                                   std::vector<SDNode *> *Created) const {
3069   assert(Created && "No vector to hold udiv ops.");
3070 
3071   EVT VT = N->getValueType(0);
3072   SDLoc dl(N);
3073   auto &DL = DAG.getDataLayout();
3074 
3075   // Check to see if we can do this.
3076   // FIXME: We should be more aggressive here.
3077   if (!isTypeLegal(VT))
3078     return SDValue();
3079 
3080   // FIXME: We should use a narrower constant when the upper
3081   // bits are known to be zero.
3082   APInt::mu magics = Divisor.magicu();
3083 
3084   SDValue Q = N->getOperand(0);
3085 
3086   // If the divisor is even, we can avoid using the expensive fixup by shifting
3087   // the divided value upfront.
3088   if (magics.a != 0 && !Divisor[0]) {
3089     unsigned Shift = Divisor.countTrailingZeros();
3090     Q = DAG.getNode(
3091         ISD::SRL, dl, VT, Q,
3092         DAG.getConstant(Shift, dl, getShiftAmountTy(Q.getValueType(), DL)));
3093     Created->push_back(Q.getNode());
3094 
3095     // Get magic number for the shifted divisor.
3096     magics = Divisor.lshr(Shift).magicu(Shift);
3097     assert(magics.a == 0 && "Should use cheap fixup now");
3098   }
3099 
3100   // Multiply the numerator (operand 0) by the magic value
3101   // FIXME: We should support doing a MUL in a wider type
3102   if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT) :
3103                             isOperationLegalOrCustom(ISD::MULHU, VT))
3104     Q = DAG.getNode(ISD::MULHU, dl, VT, Q, DAG.getConstant(magics.m, dl, VT));
3105   else if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT) :
3106                                  isOperationLegalOrCustom(ISD::UMUL_LOHI, VT))
3107     Q = SDValue(DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), Q,
3108                             DAG.getConstant(magics.m, dl, VT)).getNode(), 1);
3109   else
3110     return SDValue();       // No mulhu or equivalent
3111 
3112   Created->push_back(Q.getNode());
3113 
3114   if (magics.a == 0) {
3115     assert(magics.s < Divisor.getBitWidth() &&
3116            "We shouldn't generate an undefined shift!");
3117     return DAG.getNode(
3118         ISD::SRL, dl, VT, Q,
3119         DAG.getConstant(magics.s, dl, getShiftAmountTy(Q.getValueType(), DL)));
3120   } else {
3121     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N->getOperand(0), Q);
3122     Created->push_back(NPQ.getNode());
3123     NPQ = DAG.getNode(
3124         ISD::SRL, dl, VT, NPQ,
3125         DAG.getConstant(1, dl, getShiftAmountTy(NPQ.getValueType(), DL)));
3126     Created->push_back(NPQ.getNode());
3127     NPQ = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
3128     Created->push_back(NPQ.getNode());
3129     return DAG.getNode(
3130         ISD::SRL, dl, VT, NPQ,
3131         DAG.getConstant(magics.s - 1, dl,
3132                         getShiftAmountTy(NPQ.getValueType(), DL)));
3133   }
3134 }
3135 
3136 bool TargetLowering::
3137 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
3138   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
3139     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
3140                                 "be a constant integer");
3141     return true;
3142   }
3143 
3144   return false;
3145 }
3146 
3147 //===----------------------------------------------------------------------===//
3148 // Legalization Utilities
3149 //===----------------------------------------------------------------------===//
3150 
3151 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl,
3152                                     SDValue LHS, SDValue RHS,
3153                                     SmallVectorImpl<SDValue> &Result,
3154                                     EVT HiLoVT, SelectionDAG &DAG,
3155                                     MulExpansionKind Kind, SDValue LL,
3156                                     SDValue LH, SDValue RL, SDValue RH) const {
3157   assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
3158          Opcode == ISD::SMUL_LOHI);
3159 
3160   bool HasMULHS = (Kind == MulExpansionKind::Always) ||
3161                   isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
3162   bool HasMULHU = (Kind == MulExpansionKind::Always) ||
3163                   isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
3164   bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
3165                       isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
3166   bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
3167                       isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
3168 
3169   if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
3170     return false;
3171 
3172   unsigned OuterBitSize = VT.getScalarSizeInBits();
3173   unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
3174   unsigned LHSSB = DAG.ComputeNumSignBits(LHS);
3175   unsigned RHSSB = DAG.ComputeNumSignBits(RHS);
3176 
3177   // LL, LH, RL, and RH must be either all NULL or all set to a value.
3178   assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
3179          (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
3180 
3181   SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
3182   auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
3183                           bool Signed) -> bool {
3184     if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
3185       Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
3186       Hi = SDValue(Lo.getNode(), 1);
3187       return true;
3188     }
3189     if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
3190       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
3191       Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
3192       return true;
3193     }
3194     return false;
3195   };
3196 
3197   SDValue Lo, Hi;
3198 
3199   if (!LL.getNode() && !RL.getNode() &&
3200       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
3201     LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
3202     RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
3203   }
3204 
3205   if (!LL.getNode())
3206     return false;
3207 
3208   APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
3209   if (DAG.MaskedValueIsZero(LHS, HighMask) &&
3210       DAG.MaskedValueIsZero(RHS, HighMask)) {
3211     // The inputs are both zero-extended.
3212     if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
3213       Result.push_back(Lo);
3214       Result.push_back(Hi);
3215       if (Opcode != ISD::MUL) {
3216         SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
3217         Result.push_back(Zero);
3218         Result.push_back(Zero);
3219       }
3220       return true;
3221     }
3222   }
3223 
3224   if (!VT.isVector() && Opcode == ISD::MUL && LHSSB > InnerBitSize &&
3225       RHSSB > InnerBitSize) {
3226     // The input values are both sign-extended.
3227     // TODO non-MUL case?
3228     if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
3229       Result.push_back(Lo);
3230       Result.push_back(Hi);
3231       return true;
3232     }
3233   }
3234 
3235   unsigned ShiftAmount = OuterBitSize - InnerBitSize;
3236   EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout());
3237   if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) {
3238     // FIXME getShiftAmountTy does not always return a sensible result when VT
3239     // is an illegal type, and so the type may be too small to fit the shift
3240     // amount. Override it with i32. The shift will have to be legalized.
3241     ShiftAmountTy = MVT::i32;
3242   }
3243   SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy);
3244 
3245   if (!LH.getNode() && !RH.getNode() &&
3246       isOperationLegalOrCustom(ISD::SRL, VT) &&
3247       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
3248     LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
3249     LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
3250     RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
3251     RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
3252   }
3253 
3254   if (!LH.getNode())
3255     return false;
3256 
3257   if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
3258     return false;
3259 
3260   Result.push_back(Lo);
3261 
3262   if (Opcode == ISD::MUL) {
3263     RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
3264     LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
3265     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
3266     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
3267     Result.push_back(Hi);
3268     return true;
3269   }
3270 
3271   // Compute the full width result.
3272   auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
3273     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
3274     Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
3275     Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
3276     return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
3277   };
3278 
3279   SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
3280   if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
3281     return false;
3282 
3283   // This is effectively the add part of a multiply-add of half-sized operands,
3284   // so it cannot overflow.
3285   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
3286 
3287   if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
3288     return false;
3289 
3290   Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
3291                      Merge(Lo, Hi));
3292 
3293   SDValue Carry = Next.getValue(1);
3294   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
3295   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
3296 
3297   if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
3298     return false;
3299 
3300   SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
3301   Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
3302                    Carry);
3303   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
3304 
3305   if (Opcode == ISD::SMUL_LOHI) {
3306     SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
3307                                   DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
3308     Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
3309 
3310     NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
3311                           DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
3312     Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
3313   }
3314 
3315   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
3316   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
3317   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
3318   return true;
3319 }
3320 
3321 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
3322                                SelectionDAG &DAG, MulExpansionKind Kind,
3323                                SDValue LL, SDValue LH, SDValue RL,
3324                                SDValue RH) const {
3325   SmallVector<SDValue, 2> Result;
3326   bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), N,
3327                            N->getOperand(0), N->getOperand(1), Result, HiLoVT,
3328                            DAG, Kind, LL, LH, RL, RH);
3329   if (Ok) {
3330     assert(Result.size() == 2);
3331     Lo = Result[0];
3332     Hi = Result[1];
3333   }
3334   return Ok;
3335 }
3336 
3337 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
3338                                SelectionDAG &DAG) const {
3339   EVT VT = Node->getOperand(0).getValueType();
3340   EVT NVT = Node->getValueType(0);
3341   SDLoc dl(SDValue(Node, 0));
3342 
3343   // FIXME: Only f32 to i64 conversions are supported.
3344   if (VT != MVT::f32 || NVT != MVT::i64)
3345     return false;
3346 
3347   // Expand f32 -> i64 conversion
3348   // This algorithm comes from compiler-rt's implementation of fixsfdi:
3349   // https://github.com/llvm-mirror/compiler-rt/blob/master/lib/builtins/fixsfdi.c
3350   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(),
3351                                 VT.getSizeInBits());
3352   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
3353   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
3354   SDValue Bias = DAG.getConstant(127, dl, IntVT);
3355   SDValue SignMask = DAG.getConstant(APInt::getSignBit(VT.getSizeInBits()), dl,
3356                                      IntVT);
3357   SDValue SignLowBit = DAG.getConstant(VT.getSizeInBits() - 1, dl, IntVT);
3358   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
3359 
3360   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Node->getOperand(0));
3361 
3362   auto &DL = DAG.getDataLayout();
3363   SDValue ExponentBits = DAG.getNode(
3364       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
3365       DAG.getZExtOrTrunc(ExponentLoBit, dl, getShiftAmountTy(IntVT, DL)));
3366   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
3367 
3368   SDValue Sign = DAG.getNode(
3369       ISD::SRA, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
3370       DAG.getZExtOrTrunc(SignLowBit, dl, getShiftAmountTy(IntVT, DL)));
3371   Sign = DAG.getSExtOrTrunc(Sign, dl, NVT);
3372 
3373   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
3374       DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
3375       DAG.getConstant(0x00800000, dl, IntVT));
3376 
3377   R = DAG.getZExtOrTrunc(R, dl, NVT);
3378 
3379   R = DAG.getSelectCC(
3380       dl, Exponent, ExponentLoBit,
3381       DAG.getNode(ISD::SHL, dl, NVT, R,
3382                   DAG.getZExtOrTrunc(
3383                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
3384                       dl, getShiftAmountTy(IntVT, DL))),
3385       DAG.getNode(ISD::SRL, dl, NVT, R,
3386                   DAG.getZExtOrTrunc(
3387                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
3388                       dl, getShiftAmountTy(IntVT, DL))),
3389       ISD::SETGT);
3390 
3391   SDValue Ret = DAG.getNode(ISD::SUB, dl, NVT,
3392       DAG.getNode(ISD::XOR, dl, NVT, R, Sign),
3393       Sign);
3394 
3395   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
3396       DAG.getConstant(0, dl, NVT), Ret, ISD::SETLT);
3397   return true;
3398 }
3399 
3400 SDValue TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
3401                                             SelectionDAG &DAG) const {
3402   SDLoc SL(LD);
3403   SDValue Chain = LD->getChain();
3404   SDValue BasePTR = LD->getBasePtr();
3405   EVT SrcVT = LD->getMemoryVT();
3406   ISD::LoadExtType ExtType = LD->getExtensionType();
3407 
3408   unsigned NumElem = SrcVT.getVectorNumElements();
3409 
3410   EVT SrcEltVT = SrcVT.getScalarType();
3411   EVT DstEltVT = LD->getValueType(0).getScalarType();
3412 
3413   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
3414   assert(SrcEltVT.isByteSized());
3415 
3416   EVT PtrVT = BasePTR.getValueType();
3417 
3418   SmallVector<SDValue, 8> Vals;
3419   SmallVector<SDValue, 8> LoadChains;
3420 
3421   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3422     SDValue ScalarLoad =
3423         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
3424                        LD->getPointerInfo().getWithOffset(Idx * Stride),
3425                        SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride),
3426                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
3427 
3428     BasePTR = DAG.getNode(ISD::ADD, SL, PtrVT, BasePTR,
3429                           DAG.getConstant(Stride, SL, PtrVT));
3430 
3431     Vals.push_back(ScalarLoad.getValue(0));
3432     LoadChains.push_back(ScalarLoad.getValue(1));
3433   }
3434 
3435   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
3436   SDValue Value = DAG.getBuildVector(LD->getValueType(0), SL, Vals);
3437 
3438   return DAG.getMergeValues({ Value, NewChain }, SL);
3439 }
3440 
3441 // FIXME: This relies on each element having a byte size, otherwise the stride
3442 // is 0 and just overwrites the same location. ExpandStore currently expects
3443 // this broken behavior.
3444 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
3445                                              SelectionDAG &DAG) const {
3446   SDLoc SL(ST);
3447 
3448   SDValue Chain = ST->getChain();
3449   SDValue BasePtr = ST->getBasePtr();
3450   SDValue Value = ST->getValue();
3451   EVT StVT = ST->getMemoryVT();
3452 
3453   // The type of the data we want to save
3454   EVT RegVT = Value.getValueType();
3455   EVT RegSclVT = RegVT.getScalarType();
3456 
3457   // The type of data as saved in memory.
3458   EVT MemSclVT = StVT.getScalarType();
3459 
3460   EVT PtrVT = BasePtr.getValueType();
3461 
3462   // Store Stride in bytes
3463   unsigned Stride = MemSclVT.getSizeInBits() / 8;
3464   EVT IdxVT = getVectorIdxTy(DAG.getDataLayout());
3465   unsigned NumElem = StVT.getVectorNumElements();
3466 
3467   // Extract each of the elements from the original vector and save them into
3468   // memory individually.
3469   SmallVector<SDValue, 8> Stores;
3470   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
3471     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
3472                               DAG.getConstant(Idx, SL, IdxVT));
3473 
3474     SDValue Ptr = DAG.getNode(ISD::ADD, SL, PtrVT, BasePtr,
3475                               DAG.getConstant(Idx * Stride, SL, PtrVT));
3476 
3477     // This scalar TruncStore may be illegal, but we legalize it later.
3478     SDValue Store = DAG.getTruncStore(
3479         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
3480         MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride),
3481         ST->getMemOperand()->getFlags(), ST->getAAInfo());
3482 
3483     Stores.push_back(Store);
3484   }
3485 
3486   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
3487 }
3488 
3489 std::pair<SDValue, SDValue>
3490 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
3491   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
3492          "unaligned indexed loads not implemented!");
3493   SDValue Chain = LD->getChain();
3494   SDValue Ptr = LD->getBasePtr();
3495   EVT VT = LD->getValueType(0);
3496   EVT LoadedVT = LD->getMemoryVT();
3497   SDLoc dl(LD);
3498   if (VT.isFloatingPoint() || VT.isVector()) {
3499     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
3500     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
3501       if (!isOperationLegalOrCustom(ISD::LOAD, intVT)) {
3502         // Scalarize the load and let the individual components be handled.
3503         SDValue Scalarized = scalarizeVectorLoad(LD, DAG);
3504         return std::make_pair(Scalarized.getValue(0), Scalarized.getValue(1));
3505       }
3506 
3507       // Expand to a (misaligned) integer load of the same size,
3508       // then bitconvert to floating point or vector.
3509       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
3510                                     LD->getMemOperand());
3511       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
3512       if (LoadedVT != VT)
3513         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
3514                              ISD::ANY_EXTEND, dl, VT, Result);
3515 
3516       return std::make_pair(Result, newLoad.getValue(1));
3517     }
3518 
3519     // Copy the value to a (aligned) stack slot using (unaligned) integer
3520     // loads and stores, then do a (aligned) load from the stack slot.
3521     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
3522     unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
3523     unsigned RegBytes = RegVT.getSizeInBits() / 8;
3524     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
3525 
3526     // Make sure the stack slot is also aligned for the register type.
3527     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
3528 
3529     SmallVector<SDValue, 8> Stores;
3530     SDValue StackPtr = StackBase;
3531     unsigned Offset = 0;
3532 
3533     EVT PtrVT = Ptr.getValueType();
3534     EVT StackPtrVT = StackPtr.getValueType();
3535 
3536     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3537     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3538 
3539     // Do all but one copies using the full register width.
3540     for (unsigned i = 1; i < NumRegs; i++) {
3541       // Load one integer register's worth from the original location.
3542       SDValue Load = DAG.getLoad(
3543           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
3544           MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(),
3545           LD->getAAInfo());
3546       // Follow the load with a store to the stack slot.  Remember the store.
3547       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
3548                                     MachinePointerInfo()));
3549       // Increment the pointers.
3550       Offset += RegBytes;
3551       Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
3552       StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT, StackPtr,
3553                              StackPtrIncrement);
3554     }
3555 
3556     // The last copy may be partial.  Do an extending load.
3557     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3558                                   8 * (LoadedBytes - Offset));
3559     SDValue Load =
3560         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
3561                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
3562                        MinAlign(LD->getAlignment(), Offset),
3563                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
3564     // Follow the load with a store to the stack slot.  Remember the store.
3565     // On big-endian machines this requires a truncating store to ensure
3566     // that the bits end up in the right place.
3567     Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
3568                                        MachinePointerInfo(), MemVT));
3569 
3570     // The order of the stores doesn't matter - say it with a TokenFactor.
3571     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3572 
3573     // Finally, perform the original load only redirected to the stack slot.
3574     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
3575                           MachinePointerInfo(), LoadedVT);
3576 
3577     // Callers expect a MERGE_VALUES node.
3578     return std::make_pair(Load, TF);
3579   }
3580 
3581   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
3582          "Unaligned load of unsupported type.");
3583 
3584   // Compute the new VT that is half the size of the old one.  This is an
3585   // integer MVT.
3586   unsigned NumBits = LoadedVT.getSizeInBits();
3587   EVT NewLoadedVT;
3588   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
3589   NumBits >>= 1;
3590 
3591   unsigned Alignment = LD->getAlignment();
3592   unsigned IncrementSize = NumBits / 8;
3593   ISD::LoadExtType HiExtType = LD->getExtensionType();
3594 
3595   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
3596   if (HiExtType == ISD::NON_EXTLOAD)
3597     HiExtType = ISD::ZEXTLOAD;
3598 
3599   // Load the value in two parts
3600   SDValue Lo, Hi;
3601   if (DAG.getDataLayout().isLittleEndian()) {
3602     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
3603                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
3604                         LD->getAAInfo());
3605     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3606                       DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3607     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
3608                         LD->getPointerInfo().getWithOffset(IncrementSize),
3609                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
3610                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
3611   } else {
3612     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
3613                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
3614                         LD->getAAInfo());
3615     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
3616                       DAG.getConstant(IncrementSize, dl, Ptr.getValueType()));
3617     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
3618                         LD->getPointerInfo().getWithOffset(IncrementSize),
3619                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
3620                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
3621   }
3622 
3623   // aggregate the two parts
3624   SDValue ShiftAmount =
3625       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
3626                                                     DAG.getDataLayout()));
3627   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
3628   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
3629 
3630   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
3631                              Hi.getValue(1));
3632 
3633   return std::make_pair(Result, TF);
3634 }
3635 
3636 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
3637                                              SelectionDAG &DAG) const {
3638   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
3639          "unaligned indexed stores not implemented!");
3640   SDValue Chain = ST->getChain();
3641   SDValue Ptr = ST->getBasePtr();
3642   SDValue Val = ST->getValue();
3643   EVT VT = Val.getValueType();
3644   int Alignment = ST->getAlignment();
3645 
3646   SDLoc dl(ST);
3647   if (ST->getMemoryVT().isFloatingPoint() ||
3648       ST->getMemoryVT().isVector()) {
3649     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
3650     if (isTypeLegal(intVT)) {
3651       if (!isOperationLegalOrCustom(ISD::STORE, intVT)) {
3652         // Scalarize the store and let the individual components be handled.
3653         SDValue Result = scalarizeVectorStore(ST, DAG);
3654 
3655         return Result;
3656       }
3657       // Expand to a bitconvert of the value to the integer type of the
3658       // same size, then a (misaligned) int store.
3659       // FIXME: Does not handle truncating floating point stores!
3660       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
3661       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
3662                             Alignment, ST->getMemOperand()->getFlags());
3663       return Result;
3664     }
3665     // Do a (aligned) store to a stack slot, then copy from the stack slot
3666     // to the final destination using (unaligned) integer loads and stores.
3667     EVT StoredVT = ST->getMemoryVT();
3668     MVT RegVT =
3669       getRegisterType(*DAG.getContext(),
3670                       EVT::getIntegerVT(*DAG.getContext(),
3671                                         StoredVT.getSizeInBits()));
3672     EVT PtrVT = Ptr.getValueType();
3673     unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
3674     unsigned RegBytes = RegVT.getSizeInBits() / 8;
3675     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
3676 
3677     // Make sure the stack slot is also aligned for the register type.
3678     SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
3679 
3680     // Perform the original store, only redirected to the stack slot.
3681     SDValue Store = DAG.getTruncStore(Chain, dl, Val, StackPtr,
3682                                       MachinePointerInfo(), StoredVT);
3683 
3684     EVT StackPtrVT = StackPtr.getValueType();
3685 
3686     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
3687     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
3688     SmallVector<SDValue, 8> Stores;
3689     unsigned Offset = 0;
3690 
3691     // Do all but one copies using the full register width.
3692     for (unsigned i = 1; i < NumRegs; i++) {
3693       // Load one integer register's worth from the stack slot.
3694       SDValue Load =
3695           DAG.getLoad(RegVT, dl, Store, StackPtr, MachinePointerInfo());
3696       // Store it to the final location.  Remember the store.
3697       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
3698                                     ST->getPointerInfo().getWithOffset(Offset),
3699                                     MinAlign(ST->getAlignment(), Offset),
3700                                     ST->getMemOperand()->getFlags()));
3701       // Increment the pointers.
3702       Offset += RegBytes;
3703       StackPtr = DAG.getNode(ISD::ADD, dl, StackPtrVT,
3704                              StackPtr, StackPtrIncrement);
3705       Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr, PtrIncrement);
3706     }
3707 
3708     // The last store may be partial.  Do a truncating store.  On big-endian
3709     // machines this requires an extending load from the stack slot to ensure
3710     // that the bits are in the right place.
3711     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
3712                                   8 * (StoredBytes - Offset));
3713 
3714     // Load from the stack slot.
3715     SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
3716                                   MachinePointerInfo(), MemVT);
3717 
3718     Stores.push_back(
3719         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
3720                           ST->getPointerInfo().getWithOffset(Offset), MemVT,
3721                           MinAlign(ST->getAlignment(), Offset),
3722                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
3723     // The order of the stores doesn't matter - say it with a TokenFactor.
3724     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
3725     return Result;
3726   }
3727 
3728   assert(ST->getMemoryVT().isInteger() &&
3729          !ST->getMemoryVT().isVector() &&
3730          "Unaligned store of unknown type.");
3731   // Get the half-size VT
3732   EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
3733   int NumBits = NewStoredVT.getSizeInBits();
3734   int IncrementSize = NumBits / 8;
3735 
3736   // Divide the stored value in two parts.
3737   SDValue ShiftAmount =
3738       DAG.getConstant(NumBits, dl, getShiftAmountTy(Val.getValueType(),
3739                                                     DAG.getDataLayout()));
3740   SDValue Lo = Val;
3741   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
3742 
3743   // Store the two parts
3744   SDValue Store1, Store2;
3745   Store1 = DAG.getTruncStore(Chain, dl,
3746                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
3747                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
3748                              ST->getMemOperand()->getFlags());
3749 
3750   EVT PtrVT = Ptr.getValueType();
3751   Ptr = DAG.getNode(ISD::ADD, dl, PtrVT, Ptr,
3752                     DAG.getConstant(IncrementSize, dl, PtrVT));
3753   Alignment = MinAlign(Alignment, IncrementSize);
3754   Store2 = DAG.getTruncStore(
3755       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
3756       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
3757       ST->getMemOperand()->getFlags(), ST->getAAInfo());
3758 
3759   SDValue Result =
3760     DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
3761   return Result;
3762 }
3763 
3764 SDValue
3765 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
3766                                        const SDLoc &DL, EVT DataVT,
3767                                        SelectionDAG &DAG,
3768                                        bool IsCompressedMemory) const {
3769   SDValue Increment;
3770   EVT AddrVT = Addr.getValueType();
3771   EVT MaskVT = Mask.getValueType();
3772   assert(DataVT.getVectorNumElements() == MaskVT.getVectorNumElements() &&
3773          "Incompatible types of Data and Mask");
3774   if (IsCompressedMemory) {
3775     // Incrementing the pointer according to number of '1's in the mask.
3776     EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
3777     SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
3778     if (MaskIntVT.getSizeInBits() < 32) {
3779       MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
3780       MaskIntVT = MVT::i32;
3781     }
3782 
3783     // Count '1's with POPCNT.
3784     Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
3785     Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
3786     // Scale is an element size in bytes.
3787     SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
3788                                     AddrVT);
3789     Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
3790   } else
3791     Increment = DAG.getConstant(DataVT.getSizeInBits() / 8, DL, AddrVT);
3792 
3793   return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
3794 }
3795 
3796 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG,
3797                                        SDValue Idx,
3798                                        EVT VecVT,
3799                                        const SDLoc &dl) {
3800   if (isa<ConstantSDNode>(Idx))
3801     return Idx;
3802 
3803   EVT IdxVT = Idx.getValueType();
3804   unsigned NElts = VecVT.getVectorNumElements();
3805   if (isPowerOf2_32(NElts)) {
3806     APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(),
3807                                      Log2_32(NElts));
3808     return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
3809                        DAG.getConstant(Imm, dl, IdxVT));
3810   }
3811 
3812   return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
3813                      DAG.getConstant(NElts - 1, dl, IdxVT));
3814 }
3815 
3816 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
3817                                                 SDValue VecPtr, EVT VecVT,
3818                                                 SDValue Index) const {
3819   SDLoc dl(Index);
3820   // Make sure the index type is big enough to compute in.
3821   Index = DAG.getZExtOrTrunc(Index, dl, getPointerTy(DAG.getDataLayout()));
3822 
3823   EVT EltVT = VecVT.getVectorElementType();
3824 
3825   // Calculate the element offset and add it to the pointer.
3826   unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
3827   assert(EltSize * 8 == EltVT.getSizeInBits() &&
3828          "Converting bits to bytes lost precision");
3829 
3830   Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl);
3831 
3832   EVT IdxVT = Index.getValueType();
3833 
3834   Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
3835                       DAG.getConstant(EltSize, dl, IdxVT));
3836   return DAG.getNode(ISD::ADD, dl, IdxVT, Index, VecPtr);
3837 }
3838 
3839 //===----------------------------------------------------------------------===//
3840 // Implementation of Emulated TLS Model
3841 //===----------------------------------------------------------------------===//
3842 
3843 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
3844                                                 SelectionDAG &DAG) const {
3845   // Access to address of TLS varialbe xyz is lowered to a function call:
3846   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
3847   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3848   PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
3849   SDLoc dl(GA);
3850 
3851   ArgListTy Args;
3852   ArgListEntry Entry;
3853   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
3854   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
3855   StringRef EmuTlsVarName(NameString);
3856   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
3857   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
3858   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
3859   Entry.Ty = VoidPtrType;
3860   Args.push_back(Entry);
3861 
3862   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
3863 
3864   TargetLowering::CallLoweringInfo CLI(DAG);
3865   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
3866   CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
3867   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
3868 
3869   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
3870   // At last for X86 targets, maybe good for other targets too?
3871   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3872   MFI.setAdjustsStack(true);  // Is this only for X86 target?
3873   MFI.setHasCalls(true);
3874 
3875   assert((GA->getOffset() == 0) &&
3876          "Emulated TLS must have zero offset in GlobalAddressSDNode");
3877   return CallResult.first;
3878 }
3879 
3880 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
3881                                                 SelectionDAG &DAG) const {
3882   assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
3883   if (!isCtlzFast())
3884     return SDValue();
3885   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3886   SDLoc dl(Op);
3887   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3888     if (C->isNullValue() && CC == ISD::SETEQ) {
3889       EVT VT = Op.getOperand(0).getValueType();
3890       SDValue Zext = Op.getOperand(0);
3891       if (VT.bitsLT(MVT::i32)) {
3892         VT = MVT::i32;
3893         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
3894       }
3895       unsigned Log2b = Log2_32(VT.getSizeInBits());
3896       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
3897       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
3898                                 DAG.getConstant(Log2b, dl, MVT::i32));
3899       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
3900     }
3901   }
3902   return SDValue();
3903 }
3904