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