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