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