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