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/STLExtras.h"
15 #include "llvm/CodeGen/CallingConvLower.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineJumpTableInfo.h"
19 #include "llvm/CodeGen/MachineRegisterInfo.h"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/CodeGen/TargetRegisterInfo.h"
22 #include "llvm/CodeGen/TargetSubtargetInfo.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/KnownBits.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include <cctype>
35 using namespace llvm;
36 
37 /// NOTE: The TargetMachine owns TLOF.
38 TargetLowering::TargetLowering(const TargetMachine &tm)
39     : TargetLoweringBase(tm) {}
40 
41 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
42   return nullptr;
43 }
44 
45 bool TargetLowering::isPositionIndependent() const {
46   return getTargetMachine().isPositionIndependent();
47 }
48 
49 /// Check whether a given call node is in tail position within its function. If
50 /// so, it sets Chain to the input chain of the tail call.
51 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
52                                           SDValue &Chain) const {
53   const Function &F = DAG.getMachineFunction().getFunction();
54 
55   // First, check if tail calls have been disabled in this function.
56   if (F.getFnAttribute("disable-tail-calls").getValueAsString() == "true")
57     return false;
58 
59   // Conservatively require the attributes of the call to match those of
60   // the return. Ignore NoAlias and NonNull because they don't affect the
61   // call sequence.
62   AttributeList CallerAttrs = F.getAttributes();
63   if (AttrBuilder(CallerAttrs, AttributeList::ReturnIndex)
64           .removeAttribute(Attribute::NoAlias)
65           .removeAttribute(Attribute::NonNull)
66           .hasAttributes())
67     return false;
68 
69   // It's not safe to eliminate the sign / zero extension of the return value.
70   if (CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::ZExt) ||
71       CallerAttrs.hasAttribute(AttributeList::ReturnIndex, Attribute::SExt))
72     return false;
73 
74   // Check if the only use is a function return node.
75   return isUsedByReturnOnly(Node, Chain);
76 }
77 
78 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
79     const uint32_t *CallerPreservedMask,
80     const SmallVectorImpl<CCValAssign> &ArgLocs,
81     const SmallVectorImpl<SDValue> &OutVals) const {
82   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
83     const CCValAssign &ArgLoc = ArgLocs[I];
84     if (!ArgLoc.isRegLoc())
85       continue;
86     MCRegister Reg = ArgLoc.getLocReg();
87     // Only look at callee saved registers.
88     if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
89       continue;
90     // Check that we pass the value used for the caller.
91     // (We look for a CopyFromReg reading a virtual register that is used
92     //  for the function live-in value of register Reg)
93     SDValue Value = OutVals[I];
94     if (Value->getOpcode() != ISD::CopyFromReg)
95       return false;
96     MCRegister ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
97     if (MRI.getLiveInPhysReg(ArgReg) != Reg)
98       return false;
99   }
100   return true;
101 }
102 
103 /// Set CallLoweringInfo attribute flags based on a call instruction
104 /// and called function attributes.
105 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase *Call,
106                                                      unsigned ArgIdx) {
107   IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt);
108   IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt);
109   IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg);
110   IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet);
111   IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest);
112   IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal);
113   IsPreallocated = Call->paramHasAttr(ArgIdx, Attribute::Preallocated);
114   IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca);
115   IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned);
116   IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf);
117   IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError);
118   Alignment = Call->getParamAlign(ArgIdx);
119   ByValType = nullptr;
120   if (IsByVal)
121     ByValType = Call->getParamByValType(ArgIdx);
122   PreallocatedType = nullptr;
123   if (IsPreallocated)
124     PreallocatedType = Call->getParamPreallocatedType(ArgIdx);
125 }
126 
127 /// Generate a libcall taking the given operands as arguments and returning a
128 /// result of type RetVT.
129 std::pair<SDValue, SDValue>
130 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
131                             ArrayRef<SDValue> Ops,
132                             MakeLibCallOptions CallOptions,
133                             const SDLoc &dl,
134                             SDValue InChain) const {
135   if (!InChain)
136     InChain = DAG.getEntryNode();
137 
138   TargetLowering::ArgListTy Args;
139   Args.reserve(Ops.size());
140 
141   TargetLowering::ArgListEntry Entry;
142   for (unsigned i = 0; i < Ops.size(); ++i) {
143     SDValue NewOp = Ops[i];
144     Entry.Node = NewOp;
145     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
146     Entry.IsSExt = shouldSignExtendTypeInLibCall(NewOp.getValueType(),
147                                                  CallOptions.IsSExt);
148     Entry.IsZExt = !Entry.IsSExt;
149 
150     if (CallOptions.IsSoften &&
151         !shouldExtendTypeInLibCall(CallOptions.OpsVTBeforeSoften[i])) {
152       Entry.IsSExt = Entry.IsZExt = false;
153     }
154     Args.push_back(Entry);
155   }
156 
157   if (LC == RTLIB::UNKNOWN_LIBCALL)
158     report_fatal_error("Unsupported library call operation!");
159   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
160                                          getPointerTy(DAG.getDataLayout()));
161 
162   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
163   TargetLowering::CallLoweringInfo CLI(DAG);
164   bool signExtend = shouldSignExtendTypeInLibCall(RetVT, CallOptions.IsSExt);
165   bool zeroExtend = !signExtend;
166 
167   if (CallOptions.IsSoften &&
168       !shouldExtendTypeInLibCall(CallOptions.RetVTBeforeSoften)) {
169     signExtend = zeroExtend = false;
170   }
171 
172   CLI.setDebugLoc(dl)
173       .setChain(InChain)
174       .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
175       .setNoReturn(CallOptions.DoesNotReturn)
176       .setDiscardResult(!CallOptions.IsReturnValueUsed)
177       .setIsPostTypeLegalization(CallOptions.IsPostTypeLegalization)
178       .setSExtResult(signExtend)
179       .setZExtResult(zeroExtend);
180   return LowerCallTo(CLI);
181 }
182 
183 bool TargetLowering::findOptimalMemOpLowering(
184     std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS,
185     unsigned SrcAS, const AttributeList &FuncAttributes) const {
186   if (Op.isMemcpyWithFixedDstAlign() && Op.getSrcAlign() < Op.getDstAlign())
187     return false;
188 
189   EVT VT = getOptimalMemOpType(Op, FuncAttributes);
190 
191   if (VT == MVT::Other) {
192     // Use the largest integer type whose alignment constraints are satisfied.
193     // We only need to check DstAlign here as SrcAlign is always greater or
194     // equal to DstAlign (or zero).
195     VT = MVT::i64;
196     if (Op.isFixedDstAlign())
197       while (
198           Op.getDstAlign() < (VT.getSizeInBits() / 8) &&
199           !allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign().value()))
200         VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
201     assert(VT.isInteger());
202 
203     // Find the largest legal integer type.
204     MVT LVT = MVT::i64;
205     while (!isTypeLegal(LVT))
206       LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
207     assert(LVT.isInteger());
208 
209     // If the type we've chosen is larger than the largest legal integer type
210     // then use that instead.
211     if (VT.bitsGT(LVT))
212       VT = LVT;
213   }
214 
215   unsigned NumMemOps = 0;
216   uint64_t Size = Op.size();
217   while (Size) {
218     unsigned VTSize = VT.getSizeInBits() / 8;
219     while (VTSize > Size) {
220       // For now, only use non-vector load / store's for the left-over pieces.
221       EVT NewVT = VT;
222       unsigned NewVTSize;
223 
224       bool Found = false;
225       if (VT.isVector() || VT.isFloatingPoint()) {
226         NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
227         if (isOperationLegalOrCustom(ISD::STORE, NewVT) &&
228             isSafeMemOpType(NewVT.getSimpleVT()))
229           Found = true;
230         else if (NewVT == MVT::i64 &&
231                  isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
232                  isSafeMemOpType(MVT::f64)) {
233           // i64 is usually not legal on 32-bit targets, but f64 may be.
234           NewVT = MVT::f64;
235           Found = true;
236         }
237       }
238 
239       if (!Found) {
240         do {
241           NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
242           if (NewVT == MVT::i8)
243             break;
244         } while (!isSafeMemOpType(NewVT.getSimpleVT()));
245       }
246       NewVTSize = NewVT.getSizeInBits() / 8;
247 
248       // If the new VT cannot cover all of the remaining bits, then consider
249       // issuing a (or a pair of) unaligned and overlapping load / store.
250       bool Fast;
251       if (NumMemOps && Op.allowOverlap() && NewVTSize < Size &&
252           allowsMisalignedMemoryAccesses(
253               VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign().value() : 0,
254               MachineMemOperand::MONone, &Fast) &&
255           Fast)
256         VTSize = Size;
257       else {
258         VT = NewVT;
259         VTSize = NewVTSize;
260       }
261     }
262 
263     if (++NumMemOps > Limit)
264       return false;
265 
266     MemOps.push_back(VT);
267     Size -= VTSize;
268   }
269 
270   return true;
271 }
272 
273 /// Soften the operands of a comparison. This code is shared among BR_CC,
274 /// SELECT_CC, and SETCC handlers.
275 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
276                                          SDValue &NewLHS, SDValue &NewRHS,
277                                          ISD::CondCode &CCCode,
278                                          const SDLoc &dl, const SDValue OldLHS,
279                                          const SDValue OldRHS) const {
280   SDValue Chain;
281   return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS,
282                              OldRHS, Chain);
283 }
284 
285 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
286                                          SDValue &NewLHS, SDValue &NewRHS,
287                                          ISD::CondCode &CCCode,
288                                          const SDLoc &dl, const SDValue OldLHS,
289                                          const SDValue OldRHS,
290                                          SDValue &Chain,
291                                          bool IsSignaling) const {
292   // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc
293   // not supporting it. We can update this code when libgcc provides such
294   // functions.
295 
296   assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
297          && "Unsupported setcc type!");
298 
299   // Expand into one or more soft-fp libcall(s).
300   RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
301   bool ShouldInvertCC = false;
302   switch (CCCode) {
303   case ISD::SETEQ:
304   case ISD::SETOEQ:
305     LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
306           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
307           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
308     break;
309   case ISD::SETNE:
310   case ISD::SETUNE:
311     LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
312           (VT == MVT::f64) ? RTLIB::UNE_F64 :
313           (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
314     break;
315   case ISD::SETGE:
316   case ISD::SETOGE:
317     LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
318           (VT == MVT::f64) ? RTLIB::OGE_F64 :
319           (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
320     break;
321   case ISD::SETLT:
322   case ISD::SETOLT:
323     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
324           (VT == MVT::f64) ? RTLIB::OLT_F64 :
325           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
326     break;
327   case ISD::SETLE:
328   case ISD::SETOLE:
329     LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
330           (VT == MVT::f64) ? RTLIB::OLE_F64 :
331           (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
332     break;
333   case ISD::SETGT:
334   case ISD::SETOGT:
335     LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
336           (VT == MVT::f64) ? RTLIB::OGT_F64 :
337           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
338     break;
339   case ISD::SETO:
340     ShouldInvertCC = true;
341     LLVM_FALLTHROUGH;
342   case ISD::SETUO:
343     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
344           (VT == MVT::f64) ? RTLIB::UO_F64 :
345           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
346     break;
347   case ISD::SETONE:
348     // SETONE = O && UNE
349     ShouldInvertCC = true;
350     LLVM_FALLTHROUGH;
351   case ISD::SETUEQ:
352     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
353           (VT == MVT::f64) ? RTLIB::UO_F64 :
354           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
355     LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
356           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
357           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
358     break;
359   default:
360     // Invert CC for unordered comparisons
361     ShouldInvertCC = true;
362     switch (CCCode) {
363     case ISD::SETULT:
364       LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
365             (VT == MVT::f64) ? RTLIB::OGE_F64 :
366             (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
367       break;
368     case ISD::SETULE:
369       LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
370             (VT == MVT::f64) ? RTLIB::OGT_F64 :
371             (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
372       break;
373     case ISD::SETUGT:
374       LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
375             (VT == MVT::f64) ? RTLIB::OLE_F64 :
376             (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
377       break;
378     case ISD::SETUGE:
379       LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
380             (VT == MVT::f64) ? RTLIB::OLT_F64 :
381             (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
382       break;
383     default: llvm_unreachable("Do not know how to soften this setcc!");
384     }
385   }
386 
387   // Use the target specific return value for comparions lib calls.
388   EVT RetVT = getCmpLibcallReturnType();
389   SDValue Ops[2] = {NewLHS, NewRHS};
390   TargetLowering::MakeLibCallOptions CallOptions;
391   EVT OpsVT[2] = { OldLHS.getValueType(),
392                    OldRHS.getValueType() };
393   CallOptions.setTypeListBeforeSoften(OpsVT, RetVT, true);
394   auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain);
395   NewLHS = Call.first;
396   NewRHS = DAG.getConstant(0, dl, RetVT);
397 
398   CCCode = getCmpLibcallCC(LC1);
399   if (ShouldInvertCC) {
400     assert(RetVT.isInteger());
401     CCCode = getSetCCInverse(CCCode, RetVT);
402   }
403 
404   if (LC2 == RTLIB::UNKNOWN_LIBCALL) {
405     // Update Chain.
406     Chain = Call.second;
407   } else {
408     EVT SetCCVT =
409         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT);
410     SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode);
411     auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain);
412     CCCode = getCmpLibcallCC(LC2);
413     if (ShouldInvertCC)
414       CCCode = getSetCCInverse(CCCode, RetVT);
415     NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode);
416     if (Chain)
417       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second,
418                           Call2.second);
419     NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl,
420                          Tmp.getValueType(), Tmp, NewLHS);
421     NewRHS = SDValue();
422   }
423 }
424 
425 /// Return the entry encoding for a jump table in the current function. The
426 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
427 unsigned TargetLowering::getJumpTableEncoding() const {
428   // In non-pic modes, just use the address of a block.
429   if (!isPositionIndependent())
430     return MachineJumpTableInfo::EK_BlockAddress;
431 
432   // In PIC mode, if the target supports a GPRel32 directive, use it.
433   if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
434     return MachineJumpTableInfo::EK_GPRel32BlockAddress;
435 
436   // Otherwise, use a label difference.
437   return MachineJumpTableInfo::EK_LabelDifference32;
438 }
439 
440 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
441                                                  SelectionDAG &DAG) const {
442   // If our PIC model is GP relative, use the global offset table as the base.
443   unsigned JTEncoding = getJumpTableEncoding();
444 
445   if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
446       (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
447     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
448 
449   return Table;
450 }
451 
452 /// This returns the relocation base for the given PIC jumptable, the same as
453 /// getPICJumpTableRelocBase, but as an MCExpr.
454 const MCExpr *
455 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
456                                              unsigned JTI,MCContext &Ctx) const{
457   // The normal PIC reloc base is the label at the start of the jump table.
458   return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
459 }
460 
461 bool
462 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
463   const TargetMachine &TM = getTargetMachine();
464   const GlobalValue *GV = GA->getGlobal();
465 
466   // If the address is not even local to this DSO we will have to load it from
467   // a got and then add the offset.
468   if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
469     return false;
470 
471   // If the code is position independent we will have to add a base register.
472   if (isPositionIndependent())
473     return false;
474 
475   // Otherwise we can do it.
476   return true;
477 }
478 
479 //===----------------------------------------------------------------------===//
480 //  Optimization Methods
481 //===----------------------------------------------------------------------===//
482 
483 /// If the specified instruction has a constant integer operand and there are
484 /// bits set in that constant that are not demanded, then clear those bits and
485 /// return true.
486 bool TargetLowering::ShrinkDemandedConstant(SDValue Op, const APInt &Demanded,
487                                             TargetLoweringOpt &TLO) const {
488   SDLoc DL(Op);
489   unsigned Opcode = Op.getOpcode();
490 
491   // Do target-specific constant optimization.
492   if (targetShrinkDemandedConstant(Op, Demanded, TLO))
493     return TLO.New.getNode();
494 
495   // FIXME: ISD::SELECT, ISD::SELECT_CC
496   switch (Opcode) {
497   default:
498     break;
499   case ISD::XOR:
500   case ISD::AND:
501   case ISD::OR: {
502     auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
503     if (!Op1C)
504       return false;
505 
506     // If this is a 'not' op, don't touch it because that's a canonical form.
507     const APInt &C = Op1C->getAPIntValue();
508     if (Opcode == ISD::XOR && Demanded.isSubsetOf(C))
509       return false;
510 
511     if (!C.isSubsetOf(Demanded)) {
512       EVT VT = Op.getValueType();
513       SDValue NewC = TLO.DAG.getConstant(Demanded & C, DL, VT);
514       SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC);
515       return TLO.CombineTo(Op, NewOp);
516     }
517 
518     break;
519   }
520   }
521 
522   return false;
523 }
524 
525 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
526 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
527 /// generalized for targets with other types of implicit widening casts.
528 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth,
529                                       const APInt &Demanded,
530                                       TargetLoweringOpt &TLO) const {
531   assert(Op.getNumOperands() == 2 &&
532          "ShrinkDemandedOp only supports binary operators!");
533   assert(Op.getNode()->getNumValues() == 1 &&
534          "ShrinkDemandedOp only supports nodes with one result!");
535 
536   SelectionDAG &DAG = TLO.DAG;
537   SDLoc dl(Op);
538 
539   // Early return, as this function cannot handle vector types.
540   if (Op.getValueType().isVector())
541     return false;
542 
543   // Don't do this if the node has another user, which may require the
544   // full value.
545   if (!Op.getNode()->hasOneUse())
546     return false;
547 
548   // Search for the smallest integer type with free casts to and from
549   // Op's type. For expedience, just check power-of-2 integer types.
550   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
551   unsigned DemandedSize = Demanded.getActiveBits();
552   unsigned SmallVTBits = DemandedSize;
553   if (!isPowerOf2_32(SmallVTBits))
554     SmallVTBits = NextPowerOf2(SmallVTBits);
555   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
556     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
557     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
558         TLI.isZExtFree(SmallVT, Op.getValueType())) {
559       // We found a type with free casts.
560       SDValue X = DAG.getNode(
561           Op.getOpcode(), dl, SmallVT,
562           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
563           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)));
564       assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
565       SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X);
566       return TLO.CombineTo(Op, Z);
567     }
568   }
569   return false;
570 }
571 
572 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
573                                           DAGCombinerInfo &DCI) const {
574   SelectionDAG &DAG = DCI.DAG;
575   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
576                         !DCI.isBeforeLegalizeOps());
577   KnownBits Known;
578 
579   bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO);
580   if (Simplified) {
581     DCI.AddToWorklist(Op.getNode());
582     DCI.CommitTargetLoweringOpt(TLO);
583   }
584   return Simplified;
585 }
586 
587 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
588                                           KnownBits &Known,
589                                           TargetLoweringOpt &TLO,
590                                           unsigned Depth,
591                                           bool AssumeSingleUse) const {
592   EVT VT = Op.getValueType();
593 
594   // TODO: We can probably do more work on calculating the known bits and
595   // simplifying the operations for scalable vectors, but for now we just
596   // bail out.
597   if (VT.isScalableVector()) {
598     // Pretend we don't know anything for now.
599     Known = KnownBits(DemandedBits.getBitWidth());
600     return false;
601   }
602 
603   APInt DemandedElts = VT.isVector()
604                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
605                            : APInt(1, 1);
606   return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth,
607                               AssumeSingleUse);
608 }
609 
610 // TODO: Can we merge SelectionDAG::GetDemandedBits into this?
611 // TODO: Under what circumstances can we create nodes? Constant folding?
612 SDValue TargetLowering::SimplifyMultipleUseDemandedBits(
613     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
614     SelectionDAG &DAG, unsigned Depth) const {
615   // Limit search depth.
616   if (Depth >= SelectionDAG::MaxRecursionDepth)
617     return SDValue();
618 
619   // Ignore UNDEFs.
620   if (Op.isUndef())
621     return SDValue();
622 
623   // Not demanding any bits/elts from Op.
624   if (DemandedBits == 0 || DemandedElts == 0)
625     return DAG.getUNDEF(Op.getValueType());
626 
627   unsigned NumElts = DemandedElts.getBitWidth();
628   unsigned BitWidth = DemandedBits.getBitWidth();
629   KnownBits LHSKnown, RHSKnown;
630   switch (Op.getOpcode()) {
631   case ISD::BITCAST: {
632     SDValue Src = peekThroughBitcasts(Op.getOperand(0));
633     EVT SrcVT = Src.getValueType();
634     EVT DstVT = Op.getValueType();
635     if (SrcVT == DstVT)
636       return Src;
637 
638     unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
639     unsigned NumDstEltBits = DstVT.getScalarSizeInBits();
640     if (NumSrcEltBits == NumDstEltBits)
641       if (SDValue V = SimplifyMultipleUseDemandedBits(
642               Src, DemandedBits, DemandedElts, DAG, Depth + 1))
643         return DAG.getBitcast(DstVT, V);
644 
645     // TODO - bigendian once we have test coverage.
646     if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0 &&
647         DAG.getDataLayout().isLittleEndian()) {
648       unsigned Scale = NumDstEltBits / NumSrcEltBits;
649       unsigned NumSrcElts = SrcVT.getVectorNumElements();
650       APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits);
651       APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts);
652       for (unsigned i = 0; i != Scale; ++i) {
653         unsigned Offset = i * NumSrcEltBits;
654         APInt Sub = DemandedBits.extractBits(NumSrcEltBits, Offset);
655         if (!Sub.isNullValue()) {
656           DemandedSrcBits |= Sub;
657           for (unsigned j = 0; j != NumElts; ++j)
658             if (DemandedElts[j])
659               DemandedSrcElts.setBit((j * Scale) + i);
660         }
661       }
662 
663       if (SDValue V = SimplifyMultipleUseDemandedBits(
664               Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
665         return DAG.getBitcast(DstVT, V);
666     }
667 
668     // TODO - bigendian once we have test coverage.
669     if ((NumSrcEltBits % NumDstEltBits) == 0 &&
670         DAG.getDataLayout().isLittleEndian()) {
671       unsigned Scale = NumSrcEltBits / NumDstEltBits;
672       unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
673       APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits);
674       APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts);
675       for (unsigned i = 0; i != NumElts; ++i)
676         if (DemandedElts[i]) {
677           unsigned Offset = (i % Scale) * NumDstEltBits;
678           DemandedSrcBits.insertBits(DemandedBits, Offset);
679           DemandedSrcElts.setBit(i / Scale);
680         }
681 
682       if (SDValue V = SimplifyMultipleUseDemandedBits(
683               Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
684         return DAG.getBitcast(DstVT, V);
685     }
686 
687     break;
688   }
689   case ISD::AND: {
690     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
691     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
692 
693     // If all of the demanded bits are known 1 on one side, return the other.
694     // These bits cannot contribute to the result of the 'and' in this
695     // context.
696     if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
697       return Op.getOperand(0);
698     if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
699       return Op.getOperand(1);
700     break;
701   }
702   case ISD::OR: {
703     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
704     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
705 
706     // If all of the demanded bits are known zero on one side, return the
707     // other.  These bits cannot contribute to the result of the 'or' in this
708     // context.
709     if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
710       return Op.getOperand(0);
711     if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
712       return Op.getOperand(1);
713     break;
714   }
715   case ISD::XOR: {
716     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
717     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
718 
719     // If all of the demanded bits are known zero on one side, return the
720     // other.
721     if (DemandedBits.isSubsetOf(RHSKnown.Zero))
722       return Op.getOperand(0);
723     if (DemandedBits.isSubsetOf(LHSKnown.Zero))
724       return Op.getOperand(1);
725     break;
726   }
727   case ISD::SHL: {
728     // If we are only demanding sign bits then we can use the shift source
729     // directly.
730     if (const APInt *MaxSA =
731             DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
732       SDValue Op0 = Op.getOperand(0);
733       unsigned ShAmt = MaxSA->getZExtValue();
734       unsigned NumSignBits =
735           DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
736       unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
737       if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
738         return Op0;
739     }
740     break;
741   }
742   case ISD::SETCC: {
743     SDValue Op0 = Op.getOperand(0);
744     SDValue Op1 = Op.getOperand(1);
745     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
746     // If (1) we only need the sign-bit, (2) the setcc operands are the same
747     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
748     // -1, we may be able to bypass the setcc.
749     if (DemandedBits.isSignMask() &&
750         Op0.getScalarValueSizeInBits() == BitWidth &&
751         getBooleanContents(Op0.getValueType()) ==
752             BooleanContent::ZeroOrNegativeOneBooleanContent) {
753       // If we're testing X < 0, then this compare isn't needed - just use X!
754       // FIXME: We're limiting to integer types here, but this should also work
755       // if we don't care about FP signed-zero. The use of SETLT with FP means
756       // that we don't care about NaNs.
757       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
758           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
759         return Op0;
760     }
761     break;
762   }
763   case ISD::SIGN_EXTEND_INREG: {
764     // If none of the extended bits are demanded, eliminate the sextinreg.
765     SDValue Op0 = Op.getOperand(0);
766     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
767     unsigned ExBits = ExVT.getScalarSizeInBits();
768     if (DemandedBits.getActiveBits() <= ExBits)
769       return Op0;
770     // If the input is already sign extended, just drop the extension.
771     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
772     if (NumSignBits >= (BitWidth - ExBits + 1))
773       return Op0;
774     break;
775   }
776   case ISD::INSERT_VECTOR_ELT: {
777     // If we don't demand the inserted element, return the base vector.
778     SDValue Vec = Op.getOperand(0);
779     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
780     EVT VecVT = Vec.getValueType();
781     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
782         !DemandedElts[CIdx->getZExtValue()])
783       return Vec;
784     break;
785   }
786   case ISD::INSERT_SUBVECTOR: {
787     // If we don't demand the inserted subvector, return the base vector.
788     SDValue Vec = Op.getOperand(0);
789     SDValue Sub = Op.getOperand(1);
790     uint64_t Idx = Op.getConstantOperandVal(2);
791     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
792     if (DemandedElts.extractBits(NumSubElts, Idx) == 0)
793       return Vec;
794     break;
795   }
796   case ISD::VECTOR_SHUFFLE: {
797     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
798 
799     // If all the demanded elts are from one operand and are inline,
800     // then we can use the operand directly.
801     bool AllUndef = true, IdentityLHS = true, IdentityRHS = true;
802     for (unsigned i = 0; i != NumElts; ++i) {
803       int M = ShuffleMask[i];
804       if (M < 0 || !DemandedElts[i])
805         continue;
806       AllUndef = false;
807       IdentityLHS &= (M == (int)i);
808       IdentityRHS &= ((M - NumElts) == i);
809     }
810 
811     if (AllUndef)
812       return DAG.getUNDEF(Op.getValueType());
813     if (IdentityLHS)
814       return Op.getOperand(0);
815     if (IdentityRHS)
816       return Op.getOperand(1);
817     break;
818   }
819   default:
820     if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
821       if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode(
822               Op, DemandedBits, DemandedElts, DAG, Depth))
823         return V;
824     break;
825   }
826   return SDValue();
827 }
828 
829 SDValue TargetLowering::SimplifyMultipleUseDemandedBits(
830     SDValue Op, const APInt &DemandedBits, SelectionDAG &DAG,
831     unsigned Depth) const {
832   EVT VT = Op.getValueType();
833   APInt DemandedElts = VT.isVector()
834                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
835                            : APInt(1, 1);
836   return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
837                                          Depth);
838 }
839 
840 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the
841 /// result of Op are ever used downstream. If we can use this information to
842 /// simplify Op, create a new simplified DAG node and return true, returning the
843 /// original and new nodes in Old and New. Otherwise, analyze the expression and
844 /// return a mask of Known bits for the expression (used to simplify the
845 /// caller).  The Known bits may only be accurate for those bits in the
846 /// OriginalDemandedBits and OriginalDemandedElts.
847 bool TargetLowering::SimplifyDemandedBits(
848     SDValue Op, const APInt &OriginalDemandedBits,
849     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
850     unsigned Depth, bool AssumeSingleUse) const {
851   unsigned BitWidth = OriginalDemandedBits.getBitWidth();
852   assert(Op.getScalarValueSizeInBits() == BitWidth &&
853          "Mask size mismatches value type size!");
854 
855   // Don't know anything.
856   Known = KnownBits(BitWidth);
857 
858   // TODO: We can probably do more work on calculating the known bits and
859   // simplifying the operations for scalable vectors, but for now we just
860   // bail out.
861   if (Op.getValueType().isScalableVector())
862     return false;
863 
864   unsigned NumElts = OriginalDemandedElts.getBitWidth();
865   assert((!Op.getValueType().isVector() ||
866           NumElts == Op.getValueType().getVectorNumElements()) &&
867          "Unexpected vector size");
868 
869   APInt DemandedBits = OriginalDemandedBits;
870   APInt DemandedElts = OriginalDemandedElts;
871   SDLoc dl(Op);
872   auto &DL = TLO.DAG.getDataLayout();
873 
874   // Undef operand.
875   if (Op.isUndef())
876     return false;
877 
878   if (Op.getOpcode() == ISD::Constant) {
879     // We know all of the bits for a constant!
880     Known.One = cast<ConstantSDNode>(Op)->getAPIntValue();
881     Known.Zero = ~Known.One;
882     return false;
883   }
884 
885   // Other users may use these bits.
886   EVT VT = Op.getValueType();
887   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) {
888     if (Depth != 0) {
889       // If not at the root, Just compute the Known bits to
890       // simplify things downstream.
891       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
892       return false;
893     }
894     // If this is the root being simplified, allow it to have multiple uses,
895     // just set the DemandedBits/Elts to all bits.
896     DemandedBits = APInt::getAllOnesValue(BitWidth);
897     DemandedElts = APInt::getAllOnesValue(NumElts);
898   } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
899     // Not demanding any bits/elts from Op.
900     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
901   } else if (Depth >= SelectionDAG::MaxRecursionDepth) {
902     // Limit search depth.
903     return false;
904   }
905 
906   KnownBits Known2;
907   switch (Op.getOpcode()) {
908   case ISD::TargetConstant:
909     llvm_unreachable("Can't simplify this node");
910   case ISD::SCALAR_TO_VECTOR: {
911     if (!DemandedElts[0])
912       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
913 
914     KnownBits SrcKnown;
915     SDValue Src = Op.getOperand(0);
916     unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
917     APInt SrcDemandedBits = DemandedBits.zextOrSelf(SrcBitWidth);
918     if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
919       return true;
920 
921     // Upper elements are undef, so only get the knownbits if we just demand
922     // the bottom element.
923     if (DemandedElts == 1)
924       Known = SrcKnown.anyextOrTrunc(BitWidth);
925     break;
926   }
927   case ISD::BUILD_VECTOR:
928     // Collect the known bits that are shared by every demanded element.
929     // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
930     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
931     return false; // Don't fall through, will infinitely loop.
932   case ISD::LOAD: {
933     LoadSDNode *LD = cast<LoadSDNode>(Op);
934     if (getTargetConstantFromLoad(LD)) {
935       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
936       return false; // Don't fall through, will infinitely loop.
937     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
938       // If this is a ZEXTLoad and we are looking at the loaded value.
939       EVT MemVT = LD->getMemoryVT();
940       unsigned MemBits = MemVT.getScalarSizeInBits();
941       Known.Zero.setBitsFrom(MemBits);
942       return false; // Don't fall through, will infinitely loop.
943     }
944     break;
945   }
946   case ISD::INSERT_VECTOR_ELT: {
947     SDValue Vec = Op.getOperand(0);
948     SDValue Scl = Op.getOperand(1);
949     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
950     EVT VecVT = Vec.getValueType();
951 
952     // If index isn't constant, assume we need all vector elements AND the
953     // inserted element.
954     APInt DemandedVecElts(DemandedElts);
955     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
956       unsigned Idx = CIdx->getZExtValue();
957       DemandedVecElts.clearBit(Idx);
958 
959       // Inserted element is not required.
960       if (!DemandedElts[Idx])
961         return TLO.CombineTo(Op, Vec);
962     }
963 
964     KnownBits KnownScl;
965     unsigned NumSclBits = Scl.getScalarValueSizeInBits();
966     APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits);
967     if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
968       return true;
969 
970     Known = KnownScl.anyextOrTrunc(BitWidth);
971 
972     KnownBits KnownVec;
973     if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO,
974                              Depth + 1))
975       return true;
976 
977     if (!!DemandedVecElts) {
978       Known.One &= KnownVec.One;
979       Known.Zero &= KnownVec.Zero;
980     }
981 
982     return false;
983   }
984   case ISD::INSERT_SUBVECTOR: {
985     // Demand any elements from the subvector and the remainder from the src its
986     // inserted into.
987     SDValue Src = Op.getOperand(0);
988     SDValue Sub = Op.getOperand(1);
989     uint64_t Idx = Op.getConstantOperandVal(2);
990     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
991     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
992     APInt DemandedSrcElts = DemandedElts;
993     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
994 
995     KnownBits KnownSub, KnownSrc;
996     if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO,
997                              Depth + 1))
998       return true;
999     if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO,
1000                              Depth + 1))
1001       return true;
1002 
1003     Known.Zero.setAllBits();
1004     Known.One.setAllBits();
1005     if (!!DemandedSubElts) {
1006       Known.One &= KnownSub.One;
1007       Known.Zero &= KnownSub.Zero;
1008     }
1009     if (!!DemandedSrcElts) {
1010       Known.One &= KnownSrc.One;
1011       Known.Zero &= KnownSrc.Zero;
1012     }
1013 
1014     // Attempt to avoid multi-use src if we don't need anything from it.
1015     if (!DemandedBits.isAllOnesValue() || !DemandedSubElts.isAllOnesValue() ||
1016         !DemandedSrcElts.isAllOnesValue()) {
1017       SDValue NewSub = SimplifyMultipleUseDemandedBits(
1018           Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1);
1019       SDValue NewSrc = SimplifyMultipleUseDemandedBits(
1020           Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1021       if (NewSub || NewSrc) {
1022         NewSub = NewSub ? NewSub : Sub;
1023         NewSrc = NewSrc ? NewSrc : Src;
1024         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub,
1025                                         Op.getOperand(2));
1026         return TLO.CombineTo(Op, NewOp);
1027       }
1028     }
1029     break;
1030   }
1031   case ISD::EXTRACT_SUBVECTOR: {
1032     // Offset the demanded elts by the subvector index.
1033     SDValue Src = Op.getOperand(0);
1034     uint64_t Idx = Op.getConstantOperandVal(1);
1035     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1036     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
1037 
1038     if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO,
1039                              Depth + 1))
1040       return true;
1041 
1042     // Attempt to avoid multi-use src if we don't need anything from it.
1043     if (!DemandedBits.isAllOnesValue() || !DemandedSrcElts.isAllOnesValue()) {
1044       SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
1045           Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1046       if (DemandedSrc) {
1047         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc,
1048                                         Op.getOperand(1));
1049         return TLO.CombineTo(Op, NewOp);
1050       }
1051     }
1052     break;
1053   }
1054   case ISD::CONCAT_VECTORS: {
1055     Known.Zero.setAllBits();
1056     Known.One.setAllBits();
1057     EVT SubVT = Op.getOperand(0).getValueType();
1058     unsigned NumSubVecs = Op.getNumOperands();
1059     unsigned NumSubElts = SubVT.getVectorNumElements();
1060     for (unsigned i = 0; i != NumSubVecs; ++i) {
1061       APInt DemandedSubElts =
1062           DemandedElts.extractBits(NumSubElts, i * NumSubElts);
1063       if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
1064                                Known2, TLO, Depth + 1))
1065         return true;
1066       // Known bits are shared by every demanded subvector element.
1067       if (!!DemandedSubElts) {
1068         Known.One &= Known2.One;
1069         Known.Zero &= Known2.Zero;
1070       }
1071     }
1072     break;
1073   }
1074   case ISD::VECTOR_SHUFFLE: {
1075     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1076 
1077     // Collect demanded elements from shuffle operands..
1078     APInt DemandedLHS(NumElts, 0);
1079     APInt DemandedRHS(NumElts, 0);
1080     for (unsigned i = 0; i != NumElts; ++i) {
1081       if (!DemandedElts[i])
1082         continue;
1083       int M = ShuffleMask[i];
1084       if (M < 0) {
1085         // For UNDEF elements, we don't know anything about the common state of
1086         // the shuffle result.
1087         DemandedLHS.clearAllBits();
1088         DemandedRHS.clearAllBits();
1089         break;
1090       }
1091       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
1092       if (M < (int)NumElts)
1093         DemandedLHS.setBit(M);
1094       else
1095         DemandedRHS.setBit(M - NumElts);
1096     }
1097 
1098     if (!!DemandedLHS || !!DemandedRHS) {
1099       SDValue Op0 = Op.getOperand(0);
1100       SDValue Op1 = Op.getOperand(1);
1101 
1102       Known.Zero.setAllBits();
1103       Known.One.setAllBits();
1104       if (!!DemandedLHS) {
1105         if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO,
1106                                  Depth + 1))
1107           return true;
1108         Known.One &= Known2.One;
1109         Known.Zero &= Known2.Zero;
1110       }
1111       if (!!DemandedRHS) {
1112         if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO,
1113                                  Depth + 1))
1114           return true;
1115         Known.One &= Known2.One;
1116         Known.Zero &= Known2.Zero;
1117       }
1118 
1119       // Attempt to avoid multi-use ops if we don't need anything from them.
1120       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1121           Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1);
1122       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1123           Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1);
1124       if (DemandedOp0 || DemandedOp1) {
1125         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1126         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1127         SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask);
1128         return TLO.CombineTo(Op, NewOp);
1129       }
1130     }
1131     break;
1132   }
1133   case ISD::AND: {
1134     SDValue Op0 = Op.getOperand(0);
1135     SDValue Op1 = Op.getOperand(1);
1136 
1137     // If the RHS is a constant, check to see if the LHS would be zero without
1138     // using the bits from the RHS.  Below, we use knowledge about the RHS to
1139     // simplify the LHS, here we're using information from the LHS to simplify
1140     // the RHS.
1141     if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) {
1142       // Do not increment Depth here; that can cause an infinite loop.
1143       KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
1144       // If the LHS already has zeros where RHSC does, this 'and' is dead.
1145       if ((LHSKnown.Zero & DemandedBits) ==
1146           (~RHSC->getAPIntValue() & DemandedBits))
1147         return TLO.CombineTo(Op, Op0);
1148 
1149       // If any of the set bits in the RHS are known zero on the LHS, shrink
1150       // the constant.
1151       if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits, TLO))
1152         return true;
1153 
1154       // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
1155       // constant, but if this 'and' is only clearing bits that were just set by
1156       // the xor, then this 'and' can be eliminated by shrinking the mask of
1157       // the xor. For example, for a 32-bit X:
1158       // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
1159       if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
1160           LHSKnown.One == ~RHSC->getAPIntValue()) {
1161         SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
1162         return TLO.CombineTo(Op, Xor);
1163       }
1164     }
1165 
1166     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1167                              Depth + 1))
1168       return true;
1169     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1170     if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
1171                              Known2, TLO, Depth + 1))
1172       return true;
1173     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1174 
1175     // Attempt to avoid multi-use ops if we don't need anything from them.
1176     if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
1177       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1178           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1179       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1180           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1181       if (DemandedOp0 || DemandedOp1) {
1182         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1183         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1184         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1185         return TLO.CombineTo(Op, NewOp);
1186       }
1187     }
1188 
1189     // If all of the demanded bits are known one on one side, return the other.
1190     // These bits cannot contribute to the result of the 'and'.
1191     if (DemandedBits.isSubsetOf(Known2.Zero | Known.One))
1192       return TLO.CombineTo(Op, Op0);
1193     if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
1194       return TLO.CombineTo(Op, Op1);
1195     // If all of the demanded bits in the inputs are known zeros, return zero.
1196     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1197       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
1198     // If the RHS is a constant, see if we can simplify it.
1199     if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, TLO))
1200       return true;
1201     // If the operation can be done in a smaller type, do so.
1202     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1203       return true;
1204 
1205     Known &= Known2;
1206     break;
1207   }
1208   case ISD::OR: {
1209     SDValue Op0 = Op.getOperand(0);
1210     SDValue Op1 = Op.getOperand(1);
1211 
1212     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1213                              Depth + 1))
1214       return true;
1215     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1216     if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
1217                              Known2, TLO, Depth + 1))
1218       return true;
1219     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1220 
1221     // Attempt to avoid multi-use ops if we don't need anything from them.
1222     if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
1223       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1224           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1225       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1226           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1227       if (DemandedOp0 || DemandedOp1) {
1228         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1229         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1230         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1231         return TLO.CombineTo(Op, NewOp);
1232       }
1233     }
1234 
1235     // If all of the demanded bits are known zero on one side, return the other.
1236     // These bits cannot contribute to the result of the 'or'.
1237     if (DemandedBits.isSubsetOf(Known2.One | Known.Zero))
1238       return TLO.CombineTo(Op, Op0);
1239     if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
1240       return TLO.CombineTo(Op, Op1);
1241     // If the RHS is a constant, see if we can simplify it.
1242     if (ShrinkDemandedConstant(Op, DemandedBits, TLO))
1243       return true;
1244     // If the operation can be done in a smaller type, do so.
1245     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1246       return true;
1247 
1248     Known |= Known2;
1249     break;
1250   }
1251   case ISD::XOR: {
1252     SDValue Op0 = Op.getOperand(0);
1253     SDValue Op1 = Op.getOperand(1);
1254 
1255     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1256                              Depth + 1))
1257       return true;
1258     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1259     if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
1260                              Depth + 1))
1261       return true;
1262     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1263 
1264     // Attempt to avoid multi-use ops if we don't need anything from them.
1265     if (!DemandedBits.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
1266       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1267           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1268       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1269           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1270       if (DemandedOp0 || DemandedOp1) {
1271         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1272         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1273         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1274         return TLO.CombineTo(Op, NewOp);
1275       }
1276     }
1277 
1278     // If all of the demanded bits are known zero on one side, return the other.
1279     // These bits cannot contribute to the result of the 'xor'.
1280     if (DemandedBits.isSubsetOf(Known.Zero))
1281       return TLO.CombineTo(Op, Op0);
1282     if (DemandedBits.isSubsetOf(Known2.Zero))
1283       return TLO.CombineTo(Op, Op1);
1284     // If the operation can be done in a smaller type, do so.
1285     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1286       return true;
1287 
1288     // If all of the unknown bits are known to be zero on one side or the other
1289     // (but not both) turn this into an *inclusive* or.
1290     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1291     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1292       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
1293 
1294     if (ConstantSDNode *C = isConstOrConstSplat(Op1)) {
1295       // If one side is a constant, and all of the known set bits on the other
1296       // side are also set in the constant, turn this into an AND, as we know
1297       // the bits will be cleared.
1298       //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1299       // NB: it is okay if more bits are known than are requested
1300       if (C->getAPIntValue() == Known2.One) {
1301         SDValue ANDC =
1302             TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
1303         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
1304       }
1305 
1306       // If the RHS is a constant, see if we can change it. Don't alter a -1
1307       // constant because that's a 'not' op, and that is better for combining
1308       // and codegen.
1309       if (!C->isAllOnesValue()) {
1310         if (DemandedBits.isSubsetOf(C->getAPIntValue())) {
1311           // We're flipping all demanded bits. Flip the undemanded bits too.
1312           SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
1313           return TLO.CombineTo(Op, New);
1314         }
1315         // If we can't turn this into a 'not', try to shrink the constant.
1316         if (ShrinkDemandedConstant(Op, DemandedBits, TLO))
1317           return true;
1318       }
1319     }
1320 
1321     Known ^= Known2;
1322     break;
1323   }
1324   case ISD::SELECT:
1325     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO,
1326                              Depth + 1))
1327       return true;
1328     if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO,
1329                              Depth + 1))
1330       return true;
1331     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1332     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1333 
1334     // If the operands are constants, see if we can simplify them.
1335     if (ShrinkDemandedConstant(Op, DemandedBits, TLO))
1336       return true;
1337 
1338     // Only known if known in both the LHS and RHS.
1339     Known.One &= Known2.One;
1340     Known.Zero &= Known2.Zero;
1341     break;
1342   case ISD::SELECT_CC:
1343     if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO,
1344                              Depth + 1))
1345       return true;
1346     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO,
1347                              Depth + 1))
1348       return true;
1349     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1350     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1351 
1352     // If the operands are constants, see if we can simplify them.
1353     if (ShrinkDemandedConstant(Op, DemandedBits, TLO))
1354       return true;
1355 
1356     // Only known if known in both the LHS and RHS.
1357     Known.One &= Known2.One;
1358     Known.Zero &= Known2.Zero;
1359     break;
1360   case ISD::SETCC: {
1361     SDValue Op0 = Op.getOperand(0);
1362     SDValue Op1 = Op.getOperand(1);
1363     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1364     // If (1) we only need the sign-bit, (2) the setcc operands are the same
1365     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
1366     // -1, we may be able to bypass the setcc.
1367     if (DemandedBits.isSignMask() &&
1368         Op0.getScalarValueSizeInBits() == BitWidth &&
1369         getBooleanContents(Op0.getValueType()) ==
1370             BooleanContent::ZeroOrNegativeOneBooleanContent) {
1371       // If we're testing X < 0, then this compare isn't needed - just use X!
1372       // FIXME: We're limiting to integer types here, but this should also work
1373       // if we don't care about FP signed-zero. The use of SETLT with FP means
1374       // that we don't care about NaNs.
1375       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
1376           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
1377         return TLO.CombineTo(Op, Op0);
1378 
1379       // TODO: Should we check for other forms of sign-bit comparisons?
1380       // Examples: X <= -1, X >= 0
1381     }
1382     if (getBooleanContents(Op0.getValueType()) ==
1383             TargetLowering::ZeroOrOneBooleanContent &&
1384         BitWidth > 1)
1385       Known.Zero.setBitsFrom(1);
1386     break;
1387   }
1388   case ISD::SHL: {
1389     SDValue Op0 = Op.getOperand(0);
1390     SDValue Op1 = Op.getOperand(1);
1391     EVT ShiftVT = Op1.getValueType();
1392 
1393     if (const APInt *SA =
1394             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1395       unsigned ShAmt = SA->getZExtValue();
1396       if (ShAmt == 0)
1397         return TLO.CombineTo(Op, Op0);
1398 
1399       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1400       // single shift.  We can do this if the bottom bits (which are shifted
1401       // out) are never demanded.
1402       // TODO - support non-uniform vector amounts.
1403       if (Op0.getOpcode() == ISD::SRL) {
1404         if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) {
1405           if (const APInt *SA2 =
1406                   TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) {
1407             unsigned C1 = SA2->getZExtValue();
1408             unsigned Opc = ISD::SHL;
1409             int Diff = ShAmt - C1;
1410             if (Diff < 0) {
1411               Diff = -Diff;
1412               Opc = ISD::SRL;
1413             }
1414             SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1415             return TLO.CombineTo(
1416                 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1417           }
1418         }
1419       }
1420 
1421       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1422       // are not demanded. This will likely allow the anyext to be folded away.
1423       // TODO - support non-uniform vector amounts.
1424       if (Op0.getOpcode() == ISD::ANY_EXTEND) {
1425         SDValue InnerOp = Op0.getOperand(0);
1426         EVT InnerVT = InnerOp.getValueType();
1427         unsigned InnerBits = InnerVT.getScalarSizeInBits();
1428         if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
1429             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
1430           EVT ShTy = getShiftAmountTy(InnerVT, DL);
1431           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
1432             ShTy = InnerVT;
1433           SDValue NarrowShl =
1434               TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
1435                               TLO.DAG.getConstant(ShAmt, dl, ShTy));
1436           return TLO.CombineTo(
1437               Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
1438         }
1439 
1440         // Repeat the SHL optimization above in cases where an extension
1441         // intervenes: (shl (anyext (shr x, c1)), c2) to
1442         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
1443         // aren't demanded (as above) and that the shifted upper c1 bits of
1444         // x aren't demanded.
1445         // TODO - support non-uniform vector amounts.
1446         if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL &&
1447             InnerOp.hasOneUse()) {
1448           if (const APInt *SA2 =
1449                   TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) {
1450             unsigned InnerShAmt = SA2->getZExtValue();
1451             if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
1452                 DemandedBits.getActiveBits() <=
1453                     (InnerBits - InnerShAmt + ShAmt) &&
1454                 DemandedBits.countTrailingZeros() >= ShAmt) {
1455               SDValue NewSA =
1456                   TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT);
1457               SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
1458                                                InnerOp.getOperand(0));
1459               return TLO.CombineTo(
1460                   Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
1461             }
1462           }
1463         }
1464       }
1465 
1466       APInt InDemandedMask = DemandedBits.lshr(ShAmt);
1467       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1468                                Depth + 1))
1469         return true;
1470       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1471       Known.Zero <<= ShAmt;
1472       Known.One <<= ShAmt;
1473       // low bits known zero.
1474       Known.Zero.setLowBits(ShAmt);
1475 
1476       // Try shrinking the operation as long as the shift amount will still be
1477       // in range.
1478       if ((ShAmt < DemandedBits.getActiveBits()) &&
1479           ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1480         return true;
1481     }
1482 
1483     // If we are only demanding sign bits then we can use the shift source
1484     // directly.
1485     if (const APInt *MaxSA =
1486             TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
1487       unsigned ShAmt = MaxSA->getZExtValue();
1488       unsigned NumSignBits =
1489           TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1490       unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
1491       if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
1492         return TLO.CombineTo(Op, Op0);
1493     }
1494     break;
1495   }
1496   case ISD::SRL: {
1497     SDValue Op0 = Op.getOperand(0);
1498     SDValue Op1 = Op.getOperand(1);
1499     EVT ShiftVT = Op1.getValueType();
1500 
1501     if (const APInt *SA =
1502             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1503       unsigned ShAmt = SA->getZExtValue();
1504       if (ShAmt == 0)
1505         return TLO.CombineTo(Op, Op0);
1506 
1507       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
1508       // single shift.  We can do this if the top bits (which are shifted out)
1509       // are never demanded.
1510       // TODO - support non-uniform vector amounts.
1511       if (Op0.getOpcode() == ISD::SHL) {
1512         if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
1513           if (const APInt *SA2 =
1514                   TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) {
1515             unsigned C1 = SA2->getZExtValue();
1516             unsigned Opc = ISD::SRL;
1517             int Diff = ShAmt - C1;
1518             if (Diff < 0) {
1519               Diff = -Diff;
1520               Opc = ISD::SHL;
1521             }
1522             SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1523             return TLO.CombineTo(
1524                 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1525           }
1526         }
1527       }
1528 
1529       APInt InDemandedMask = (DemandedBits << ShAmt);
1530 
1531       // If the shift is exact, then it does demand the low bits (and knows that
1532       // they are zero).
1533       if (Op->getFlags().hasExact())
1534         InDemandedMask.setLowBits(ShAmt);
1535 
1536       // Compute the new bits that are at the top now.
1537       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1538                                Depth + 1))
1539         return true;
1540       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1541       Known.Zero.lshrInPlace(ShAmt);
1542       Known.One.lshrInPlace(ShAmt);
1543       // High bits known zero.
1544       Known.Zero.setHighBits(ShAmt);
1545     }
1546     break;
1547   }
1548   case ISD::SRA: {
1549     SDValue Op0 = Op.getOperand(0);
1550     SDValue Op1 = Op.getOperand(1);
1551     EVT ShiftVT = Op1.getValueType();
1552 
1553     // If we only want bits that already match the signbit then we don't need
1554     // to shift.
1555     unsigned NumHiDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
1556     if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >=
1557         NumHiDemandedBits)
1558       return TLO.CombineTo(Op, Op0);
1559 
1560     // If this is an arithmetic shift right and only the low-bit is set, we can
1561     // always convert this into a logical shr, even if the shift amount is
1562     // variable.  The low bit of the shift cannot be an input sign bit unless
1563     // the shift amount is >= the size of the datatype, which is undefined.
1564     if (DemandedBits.isOneValue())
1565       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
1566 
1567     if (const APInt *SA =
1568             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1569       unsigned ShAmt = SA->getZExtValue();
1570       if (ShAmt == 0)
1571         return TLO.CombineTo(Op, Op0);
1572 
1573       APInt InDemandedMask = (DemandedBits << ShAmt);
1574 
1575       // If the shift is exact, then it does demand the low bits (and knows that
1576       // they are zero).
1577       if (Op->getFlags().hasExact())
1578         InDemandedMask.setLowBits(ShAmt);
1579 
1580       // If any of the demanded bits are produced by the sign extension, we also
1581       // demand the input sign bit.
1582       if (DemandedBits.countLeadingZeros() < ShAmt)
1583         InDemandedMask.setSignBit();
1584 
1585       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1586                                Depth + 1))
1587         return true;
1588       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1589       Known.Zero.lshrInPlace(ShAmt);
1590       Known.One.lshrInPlace(ShAmt);
1591 
1592       // If the input sign bit is known to be zero, or if none of the top bits
1593       // are demanded, turn this into an unsigned shift right.
1594       if (Known.Zero[BitWidth - ShAmt - 1] ||
1595           DemandedBits.countLeadingZeros() >= ShAmt) {
1596         SDNodeFlags Flags;
1597         Flags.setExact(Op->getFlags().hasExact());
1598         return TLO.CombineTo(
1599             Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
1600       }
1601 
1602       int Log2 = DemandedBits.exactLogBase2();
1603       if (Log2 >= 0) {
1604         // The bit must come from the sign.
1605         SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT);
1606         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
1607       }
1608 
1609       if (Known.One[BitWidth - ShAmt - 1])
1610         // New bits are known one.
1611         Known.One.setHighBits(ShAmt);
1612 
1613       // Attempt to avoid multi-use ops if we don't need anything from them.
1614       if (!InDemandedMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
1615         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1616             Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
1617         if (DemandedOp0) {
1618           SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1);
1619           return TLO.CombineTo(Op, NewOp);
1620         }
1621       }
1622     }
1623     break;
1624   }
1625   case ISD::FSHL:
1626   case ISD::FSHR: {
1627     SDValue Op0 = Op.getOperand(0);
1628     SDValue Op1 = Op.getOperand(1);
1629     SDValue Op2 = Op.getOperand(2);
1630     bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
1631 
1632     if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) {
1633       unsigned Amt = SA->getAPIntValue().urem(BitWidth);
1634 
1635       // For fshl, 0-shift returns the 1st arg.
1636       // For fshr, 0-shift returns the 2nd arg.
1637       if (Amt == 0) {
1638         if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
1639                                  Known, TLO, Depth + 1))
1640           return true;
1641         break;
1642       }
1643 
1644       // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
1645       // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
1646       APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
1647       APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
1648       if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
1649                                Depth + 1))
1650         return true;
1651       if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
1652                                Depth + 1))
1653         return true;
1654 
1655       Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt));
1656       Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt));
1657       Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
1658       Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
1659       Known.One |= Known2.One;
1660       Known.Zero |= Known2.Zero;
1661     }
1662 
1663     // For pow-2 bitwidths we only demand the bottom modulo amt bits.
1664     if (isPowerOf2_32(BitWidth)) {
1665       APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1);
1666       if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts,
1667                                Known2, TLO, Depth + 1))
1668         return true;
1669     }
1670     break;
1671   }
1672   case ISD::ROTL:
1673   case ISD::ROTR: {
1674     SDValue Op0 = Op.getOperand(0);
1675     SDValue Op1 = Op.getOperand(1);
1676 
1677     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
1678     if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1))
1679       return TLO.CombineTo(Op, Op0);
1680 
1681     // For pow-2 bitwidths we only demand the bottom modulo amt bits.
1682     if (isPowerOf2_32(BitWidth)) {
1683       APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1);
1684       if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO,
1685                                Depth + 1))
1686         return true;
1687     }
1688     break;
1689   }
1690   case ISD::BITREVERSE: {
1691     SDValue Src = Op.getOperand(0);
1692     APInt DemandedSrcBits = DemandedBits.reverseBits();
1693     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
1694                              Depth + 1))
1695       return true;
1696     Known.One = Known2.One.reverseBits();
1697     Known.Zero = Known2.Zero.reverseBits();
1698     break;
1699   }
1700   case ISD::BSWAP: {
1701     SDValue Src = Op.getOperand(0);
1702     APInt DemandedSrcBits = DemandedBits.byteSwap();
1703     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
1704                              Depth + 1))
1705       return true;
1706     Known.One = Known2.One.byteSwap();
1707     Known.Zero = Known2.Zero.byteSwap();
1708     break;
1709   }
1710   case ISD::SIGN_EXTEND_INREG: {
1711     SDValue Op0 = Op.getOperand(0);
1712     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1713     unsigned ExVTBits = ExVT.getScalarSizeInBits();
1714 
1715     // If we only care about the highest bit, don't bother shifting right.
1716     if (DemandedBits.isSignMask()) {
1717       unsigned NumSignBits =
1718           TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1719       bool AlreadySignExtended = NumSignBits >= BitWidth - ExVTBits + 1;
1720       // However if the input is already sign extended we expect the sign
1721       // extension to be dropped altogether later and do not simplify.
1722       if (!AlreadySignExtended) {
1723         // Compute the correct shift amount type, which must be getShiftAmountTy
1724         // for scalar types after legalization.
1725         EVT ShiftAmtTy = VT;
1726         if (TLO.LegalTypes() && !ShiftAmtTy.isVector())
1727           ShiftAmtTy = getShiftAmountTy(ShiftAmtTy, DL);
1728 
1729         SDValue ShiftAmt =
1730             TLO.DAG.getConstant(BitWidth - ExVTBits, dl, ShiftAmtTy);
1731         return TLO.CombineTo(Op,
1732                              TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
1733       }
1734     }
1735 
1736     // If none of the extended bits are demanded, eliminate the sextinreg.
1737     if (DemandedBits.getActiveBits() <= ExVTBits)
1738       return TLO.CombineTo(Op, Op0);
1739 
1740     APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
1741 
1742     // Since the sign extended bits are demanded, we know that the sign
1743     // bit is demanded.
1744     InputDemandedBits.setBit(ExVTBits - 1);
1745 
1746     if (SimplifyDemandedBits(Op0, InputDemandedBits, Known, TLO, Depth + 1))
1747       return true;
1748     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1749 
1750     // If the sign bit of the input is known set or clear, then we know the
1751     // top bits of the result.
1752 
1753     // If the input sign bit is known zero, convert this into a zero extension.
1754     if (Known.Zero[ExVTBits - 1])
1755       return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT));
1756 
1757     APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
1758     if (Known.One[ExVTBits - 1]) { // Input sign bit known set
1759       Known.One.setBitsFrom(ExVTBits);
1760       Known.Zero &= Mask;
1761     } else { // Input sign bit unknown
1762       Known.Zero &= Mask;
1763       Known.One &= Mask;
1764     }
1765     break;
1766   }
1767   case ISD::BUILD_PAIR: {
1768     EVT HalfVT = Op.getOperand(0).getValueType();
1769     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
1770 
1771     APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
1772     APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
1773 
1774     KnownBits KnownLo, KnownHi;
1775 
1776     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
1777       return true;
1778 
1779     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
1780       return true;
1781 
1782     Known.Zero = KnownLo.Zero.zext(BitWidth) |
1783                  KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth);
1784 
1785     Known.One = KnownLo.One.zext(BitWidth) |
1786                 KnownHi.One.zext(BitWidth).shl(HalfBitWidth);
1787     break;
1788   }
1789   case ISD::ZERO_EXTEND:
1790   case ISD::ZERO_EXTEND_VECTOR_INREG: {
1791     SDValue Src = Op.getOperand(0);
1792     EVT SrcVT = Src.getValueType();
1793     unsigned InBits = SrcVT.getScalarSizeInBits();
1794     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
1795     bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
1796 
1797     // If none of the top bits are demanded, convert this into an any_extend.
1798     if (DemandedBits.getActiveBits() <= InBits) {
1799       // If we only need the non-extended bits of the bottom element
1800       // then we can just bitcast to the result.
1801       if (IsVecInReg && DemandedElts == 1 &&
1802           VT.getSizeInBits() == SrcVT.getSizeInBits() &&
1803           TLO.DAG.getDataLayout().isLittleEndian())
1804         return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
1805 
1806       unsigned Opc =
1807           IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND;
1808       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
1809         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
1810     }
1811 
1812     APInt InDemandedBits = DemandedBits.trunc(InBits);
1813     APInt InDemandedElts = DemandedElts.zextOrSelf(InElts);
1814     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
1815                              Depth + 1))
1816       return true;
1817     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1818     assert(Known.getBitWidth() == InBits && "Src width has changed?");
1819     Known = Known.zext(BitWidth);
1820     break;
1821   }
1822   case ISD::SIGN_EXTEND:
1823   case ISD::SIGN_EXTEND_VECTOR_INREG: {
1824     SDValue Src = Op.getOperand(0);
1825     EVT SrcVT = Src.getValueType();
1826     unsigned InBits = SrcVT.getScalarSizeInBits();
1827     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
1828     bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
1829 
1830     // If none of the top bits are demanded, convert this into an any_extend.
1831     if (DemandedBits.getActiveBits() <= InBits) {
1832       // If we only need the non-extended bits of the bottom element
1833       // then we can just bitcast to the result.
1834       if (IsVecInReg && DemandedElts == 1 &&
1835           VT.getSizeInBits() == SrcVT.getSizeInBits() &&
1836           TLO.DAG.getDataLayout().isLittleEndian())
1837         return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
1838 
1839       unsigned Opc =
1840           IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND;
1841       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
1842         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
1843     }
1844 
1845     APInt InDemandedBits = DemandedBits.trunc(InBits);
1846     APInt InDemandedElts = DemandedElts.zextOrSelf(InElts);
1847 
1848     // Since some of the sign extended bits are demanded, we know that the sign
1849     // bit is demanded.
1850     InDemandedBits.setBit(InBits - 1);
1851 
1852     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
1853                              Depth + 1))
1854       return true;
1855     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1856     assert(Known.getBitWidth() == InBits && "Src width has changed?");
1857 
1858     // If the sign bit is known one, the top bits match.
1859     Known = Known.sext(BitWidth);
1860 
1861     // If the sign bit is known zero, convert this to a zero extend.
1862     if (Known.isNonNegative()) {
1863       unsigned Opc =
1864           IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND;
1865       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
1866         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
1867     }
1868     break;
1869   }
1870   case ISD::ANY_EXTEND:
1871   case ISD::ANY_EXTEND_VECTOR_INREG: {
1872     SDValue Src = Op.getOperand(0);
1873     EVT SrcVT = Src.getValueType();
1874     unsigned InBits = SrcVT.getScalarSizeInBits();
1875     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
1876     bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG;
1877 
1878     // If we only need the bottom element then we can just bitcast.
1879     // TODO: Handle ANY_EXTEND?
1880     if (IsVecInReg && DemandedElts == 1 &&
1881         VT.getSizeInBits() == SrcVT.getSizeInBits() &&
1882         TLO.DAG.getDataLayout().isLittleEndian())
1883       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
1884 
1885     APInt InDemandedBits = DemandedBits.trunc(InBits);
1886     APInt InDemandedElts = DemandedElts.zextOrSelf(InElts);
1887     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
1888                              Depth + 1))
1889       return true;
1890     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1891     assert(Known.getBitWidth() == InBits && "Src width has changed?");
1892     Known = Known.anyext(BitWidth);
1893 
1894     // Attempt to avoid multi-use ops if we don't need anything from them.
1895     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
1896             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
1897       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
1898     break;
1899   }
1900   case ISD::TRUNCATE: {
1901     SDValue Src = Op.getOperand(0);
1902 
1903     // Simplify the input, using demanded bit information, and compute the known
1904     // zero/one bits live out.
1905     unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
1906     APInt TruncMask = DemandedBits.zext(OperandBitWidth);
1907     if (SimplifyDemandedBits(Src, TruncMask, Known, TLO, Depth + 1))
1908       return true;
1909     Known = Known.trunc(BitWidth);
1910 
1911     // Attempt to avoid multi-use ops if we don't need anything from them.
1912     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
1913             Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1))
1914       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc));
1915 
1916     // If the input is only used by this truncate, see if we can shrink it based
1917     // on the known demanded bits.
1918     if (Src.getNode()->hasOneUse()) {
1919       switch (Src.getOpcode()) {
1920       default:
1921         break;
1922       case ISD::SRL:
1923         // Shrink SRL by a constant if none of the high bits shifted in are
1924         // demanded.
1925         if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
1926           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
1927           // undesirable.
1928           break;
1929 
1930         SDValue ShAmt = Src.getOperand(1);
1931         auto *ShAmtC = dyn_cast<ConstantSDNode>(ShAmt);
1932         if (!ShAmtC || ShAmtC->getAPIntValue().uge(BitWidth))
1933           break;
1934         uint64_t ShVal = ShAmtC->getZExtValue();
1935 
1936         APInt HighBits =
1937             APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
1938         HighBits.lshrInPlace(ShVal);
1939         HighBits = HighBits.trunc(BitWidth);
1940 
1941         if (!(HighBits & DemandedBits)) {
1942           // None of the shifted in bits are needed.  Add a truncate of the
1943           // shift input, then shift it.
1944           if (TLO.LegalTypes())
1945             ShAmt = TLO.DAG.getConstant(ShVal, dl, getShiftAmountTy(VT, DL));
1946           SDValue NewTrunc =
1947               TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
1948           return TLO.CombineTo(
1949               Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, ShAmt));
1950         }
1951         break;
1952       }
1953     }
1954 
1955     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1956     break;
1957   }
1958   case ISD::AssertZext: {
1959     // AssertZext demands all of the high bits, plus any of the low bits
1960     // demanded by its users.
1961     EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1962     APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits());
1963     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
1964                              TLO, Depth + 1))
1965       return true;
1966     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1967 
1968     Known.Zero |= ~InMask;
1969     break;
1970   }
1971   case ISD::EXTRACT_VECTOR_ELT: {
1972     SDValue Src = Op.getOperand(0);
1973     SDValue Idx = Op.getOperand(1);
1974     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1975     unsigned EltBitWidth = Src.getScalarValueSizeInBits();
1976 
1977     // Demand the bits from every vector element without a constant index.
1978     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
1979     if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
1980       if (CIdx->getAPIntValue().ult(NumSrcElts))
1981         DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
1982 
1983     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
1984     // anything about the extended bits.
1985     APInt DemandedSrcBits = DemandedBits;
1986     if (BitWidth > EltBitWidth)
1987       DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
1988 
1989     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
1990                              Depth + 1))
1991       return true;
1992 
1993     // Attempt to avoid multi-use ops if we don't need anything from them.
1994     if (!DemandedSrcBits.isAllOnesValue() ||
1995         !DemandedSrcElts.isAllOnesValue()) {
1996       if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
1997               Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
1998         SDValue NewOp =
1999             TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx);
2000         return TLO.CombineTo(Op, NewOp);
2001       }
2002     }
2003 
2004     Known = Known2;
2005     if (BitWidth > EltBitWidth)
2006       Known = Known.anyext(BitWidth);
2007     break;
2008   }
2009   case ISD::BITCAST: {
2010     SDValue Src = Op.getOperand(0);
2011     EVT SrcVT = Src.getValueType();
2012     unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
2013 
2014     // If this is an FP->Int bitcast and if the sign bit is the only
2015     // thing demanded, turn this into a FGETSIGN.
2016     if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
2017         DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
2018         SrcVT.isFloatingPoint()) {
2019       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT);
2020       bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
2021       if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 &&
2022           SrcVT != MVT::f128) {
2023         // Cannot eliminate/lower SHL for f128 yet.
2024         EVT Ty = OpVTLegal ? VT : MVT::i32;
2025         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
2026         // place.  We expect the SHL to be eliminated by other optimizations.
2027         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src);
2028         unsigned OpVTSizeInBits = Op.getValueSizeInBits();
2029         if (!OpVTLegal && OpVTSizeInBits > 32)
2030           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign);
2031         unsigned ShVal = Op.getValueSizeInBits() - 1;
2032         SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT);
2033         return TLO.CombineTo(Op,
2034                              TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
2035       }
2036     }
2037 
2038     // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
2039     // Demand the elt/bit if any of the original elts/bits are demanded.
2040     // TODO - bigendian once we have test coverage.
2041     if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0 &&
2042         TLO.DAG.getDataLayout().isLittleEndian()) {
2043       unsigned Scale = BitWidth / NumSrcEltBits;
2044       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2045       APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits);
2046       APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts);
2047       for (unsigned i = 0; i != Scale; ++i) {
2048         unsigned Offset = i * NumSrcEltBits;
2049         APInt Sub = DemandedBits.extractBits(NumSrcEltBits, Offset);
2050         if (!Sub.isNullValue()) {
2051           DemandedSrcBits |= Sub;
2052           for (unsigned j = 0; j != NumElts; ++j)
2053             if (DemandedElts[j])
2054               DemandedSrcElts.setBit((j * Scale) + i);
2055         }
2056       }
2057 
2058       APInt KnownSrcUndef, KnownSrcZero;
2059       if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2060                                      KnownSrcZero, TLO, Depth + 1))
2061         return true;
2062 
2063       KnownBits KnownSrcBits;
2064       if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2065                                KnownSrcBits, TLO, Depth + 1))
2066         return true;
2067     } else if ((NumSrcEltBits % BitWidth) == 0 &&
2068                TLO.DAG.getDataLayout().isLittleEndian()) {
2069       unsigned Scale = NumSrcEltBits / BitWidth;
2070       unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2071       APInt DemandedSrcBits = APInt::getNullValue(NumSrcEltBits);
2072       APInt DemandedSrcElts = APInt::getNullValue(NumSrcElts);
2073       for (unsigned i = 0; i != NumElts; ++i)
2074         if (DemandedElts[i]) {
2075           unsigned Offset = (i % Scale) * BitWidth;
2076           DemandedSrcBits.insertBits(DemandedBits, Offset);
2077           DemandedSrcElts.setBit(i / Scale);
2078         }
2079 
2080       if (SrcVT.isVector()) {
2081         APInt KnownSrcUndef, KnownSrcZero;
2082         if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2083                                        KnownSrcZero, TLO, Depth + 1))
2084           return true;
2085       }
2086 
2087       KnownBits KnownSrcBits;
2088       if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2089                                KnownSrcBits, TLO, Depth + 1))
2090         return true;
2091     }
2092 
2093     // If this is a bitcast, let computeKnownBits handle it.  Only do this on a
2094     // recursive call where Known may be useful to the caller.
2095     if (Depth > 0) {
2096       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2097       return false;
2098     }
2099     break;
2100   }
2101   case ISD::ADD:
2102   case ISD::MUL:
2103   case ISD::SUB: {
2104     // Add, Sub, and Mul don't demand any bits in positions beyond that
2105     // of the highest bit demanded of them.
2106     SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
2107     SDNodeFlags Flags = Op.getNode()->getFlags();
2108     unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros();
2109     APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2110     if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO,
2111                              Depth + 1) ||
2112         SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO,
2113                              Depth + 1) ||
2114         // See if the operation should be performed at a smaller bit width.
2115         ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) {
2116       if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
2117         // Disable the nsw and nuw flags. We can no longer guarantee that we
2118         // won't wrap after simplification.
2119         Flags.setNoSignedWrap(false);
2120         Flags.setNoUnsignedWrap(false);
2121         SDValue NewOp =
2122             TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
2123         return TLO.CombineTo(Op, NewOp);
2124       }
2125       return true;
2126     }
2127 
2128     // Attempt to avoid multi-use ops if we don't need anything from them.
2129     if (!LoMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
2130       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
2131           Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2132       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
2133           Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2134       if (DemandedOp0 || DemandedOp1) {
2135         Flags.setNoSignedWrap(false);
2136         Flags.setNoUnsignedWrap(false);
2137         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
2138         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
2139         SDValue NewOp =
2140             TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
2141         return TLO.CombineTo(Op, NewOp);
2142       }
2143     }
2144 
2145     // If we have a constant operand, we may be able to turn it into -1 if we
2146     // do not demand the high bits. This can make the constant smaller to
2147     // encode, allow more general folding, or match specialized instruction
2148     // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
2149     // is probably not useful (and could be detrimental).
2150     ConstantSDNode *C = isConstOrConstSplat(Op1);
2151     APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
2152     if (C && !C->isAllOnesValue() && !C->isOne() &&
2153         (C->getAPIntValue() | HighMask).isAllOnesValue()) {
2154       SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
2155       // Disable the nsw and nuw flags. We can no longer guarantee that we
2156       // won't wrap after simplification.
2157       Flags.setNoSignedWrap(false);
2158       Flags.setNoUnsignedWrap(false);
2159       SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags);
2160       return TLO.CombineTo(Op, NewOp);
2161     }
2162 
2163     LLVM_FALLTHROUGH;
2164   }
2165   default:
2166     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
2167       if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts,
2168                                             Known, TLO, Depth))
2169         return true;
2170       break;
2171     }
2172 
2173     // Just use computeKnownBits to compute output bits.
2174     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2175     break;
2176   }
2177 
2178   // If we know the value of all of the demanded bits, return this as a
2179   // constant.
2180   if (DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
2181     // Avoid folding to a constant if any OpaqueConstant is involved.
2182     const SDNode *N = Op.getNode();
2183     for (SDNodeIterator I = SDNodeIterator::begin(N),
2184                         E = SDNodeIterator::end(N);
2185          I != E; ++I) {
2186       SDNode *Op = *I;
2187       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
2188         if (C->isOpaque())
2189           return false;
2190     }
2191     // TODO: Handle float bits as well.
2192     if (VT.isInteger())
2193       return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
2194   }
2195 
2196   return false;
2197 }
2198 
2199 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op,
2200                                                 const APInt &DemandedElts,
2201                                                 APInt &KnownUndef,
2202                                                 APInt &KnownZero,
2203                                                 DAGCombinerInfo &DCI) const {
2204   SelectionDAG &DAG = DCI.DAG;
2205   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
2206                         !DCI.isBeforeLegalizeOps());
2207 
2208   bool Simplified =
2209       SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
2210   if (Simplified) {
2211     DCI.AddToWorklist(Op.getNode());
2212     DCI.CommitTargetLoweringOpt(TLO);
2213   }
2214 
2215   return Simplified;
2216 }
2217 
2218 /// Given a vector binary operation and known undefined elements for each input
2219 /// operand, compute whether each element of the output is undefined.
2220 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG,
2221                                          const APInt &UndefOp0,
2222                                          const APInt &UndefOp1) {
2223   EVT VT = BO.getValueType();
2224   assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() &&
2225          "Vector binop only");
2226 
2227   EVT EltVT = VT.getVectorElementType();
2228   unsigned NumElts = VT.getVectorNumElements();
2229   assert(UndefOp0.getBitWidth() == NumElts &&
2230          UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
2231 
2232   auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
2233                                    const APInt &UndefVals) {
2234     if (UndefVals[Index])
2235       return DAG.getUNDEF(EltVT);
2236 
2237     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2238       // Try hard to make sure that the getNode() call is not creating temporary
2239       // nodes. Ignore opaque integers because they do not constant fold.
2240       SDValue Elt = BV->getOperand(Index);
2241       auto *C = dyn_cast<ConstantSDNode>(Elt);
2242       if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
2243         return Elt;
2244     }
2245 
2246     return SDValue();
2247   };
2248 
2249   APInt KnownUndef = APInt::getNullValue(NumElts);
2250   for (unsigned i = 0; i != NumElts; ++i) {
2251     // If both inputs for this element are either constant or undef and match
2252     // the element type, compute the constant/undef result for this element of
2253     // the vector.
2254     // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
2255     // not handle FP constants. The code within getNode() should be refactored
2256     // to avoid the danger of creating a bogus temporary node here.
2257     SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
2258     SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
2259     if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
2260       if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
2261         KnownUndef.setBit(i);
2262   }
2263   return KnownUndef;
2264 }
2265 
2266 bool TargetLowering::SimplifyDemandedVectorElts(
2267     SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
2268     APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
2269     bool AssumeSingleUse) const {
2270   EVT VT = Op.getValueType();
2271   unsigned Opcode = Op.getOpcode();
2272   APInt DemandedElts = OriginalDemandedElts;
2273   unsigned NumElts = DemandedElts.getBitWidth();
2274   assert(VT.isVector() && "Expected vector op");
2275 
2276   KnownUndef = KnownZero = APInt::getNullValue(NumElts);
2277 
2278   // TODO: For now we assume we know nothing about scalable vectors.
2279   if (VT.isScalableVector())
2280     return false;
2281 
2282   assert(VT.getVectorNumElements() == NumElts &&
2283          "Mask size mismatches value type element count!");
2284 
2285   // Undef operand.
2286   if (Op.isUndef()) {
2287     KnownUndef.setAllBits();
2288     return false;
2289   }
2290 
2291   // If Op has other users, assume that all elements are needed.
2292   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse)
2293     DemandedElts.setAllBits();
2294 
2295   // Not demanding any elements from Op.
2296   if (DemandedElts == 0) {
2297     KnownUndef.setAllBits();
2298     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2299   }
2300 
2301   // Limit search depth.
2302   if (Depth >= SelectionDAG::MaxRecursionDepth)
2303     return false;
2304 
2305   SDLoc DL(Op);
2306   unsigned EltSizeInBits = VT.getScalarSizeInBits();
2307 
2308   // Helper for demanding the specified elements and all the bits of both binary
2309   // operands.
2310   auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) {
2311     unsigned NumBits0 = Op0.getScalarValueSizeInBits();
2312     unsigned NumBits1 = Op1.getScalarValueSizeInBits();
2313     APInt DemandedBits0 = APInt::getAllOnesValue(NumBits0);
2314     APInt DemandedBits1 = APInt::getAllOnesValue(NumBits1);
2315     SDValue NewOp0 = SimplifyMultipleUseDemandedBits(
2316         Op0, DemandedBits0, DemandedElts, TLO.DAG, Depth + 1);
2317     SDValue NewOp1 = SimplifyMultipleUseDemandedBits(
2318         Op1, DemandedBits1, DemandedElts, TLO.DAG, Depth + 1);
2319     if (NewOp0 || NewOp1) {
2320       SDValue NewOp = TLO.DAG.getNode(
2321           Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, NewOp1 ? NewOp1 : Op1);
2322       return TLO.CombineTo(Op, NewOp);
2323     }
2324     return false;
2325   };
2326 
2327   switch (Opcode) {
2328   case ISD::SCALAR_TO_VECTOR: {
2329     if (!DemandedElts[0]) {
2330       KnownUndef.setAllBits();
2331       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2332     }
2333     KnownUndef.setHighBits(NumElts - 1);
2334     break;
2335   }
2336   case ISD::BITCAST: {
2337     SDValue Src = Op.getOperand(0);
2338     EVT SrcVT = Src.getValueType();
2339 
2340     // We only handle vectors here.
2341     // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits?
2342     if (!SrcVT.isVector())
2343       break;
2344 
2345     // Fast handling of 'identity' bitcasts.
2346     unsigned NumSrcElts = SrcVT.getVectorNumElements();
2347     if (NumSrcElts == NumElts)
2348       return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
2349                                         KnownZero, TLO, Depth + 1);
2350 
2351     APInt SrcZero, SrcUndef;
2352     APInt SrcDemandedElts = APInt::getNullValue(NumSrcElts);
2353 
2354     // Bitcast from 'large element' src vector to 'small element' vector, we
2355     // must demand a source element if any DemandedElt maps to it.
2356     if ((NumElts % NumSrcElts) == 0) {
2357       unsigned Scale = NumElts / NumSrcElts;
2358       for (unsigned i = 0; i != NumElts; ++i)
2359         if (DemandedElts[i])
2360           SrcDemandedElts.setBit(i / Scale);
2361 
2362       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2363                                      TLO, Depth + 1))
2364         return true;
2365 
2366       // Try calling SimplifyDemandedBits, converting demanded elts to the bits
2367       // of the large element.
2368       // TODO - bigendian once we have test coverage.
2369       if (TLO.DAG.getDataLayout().isLittleEndian()) {
2370         unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
2371         APInt SrcDemandedBits = APInt::getNullValue(SrcEltSizeInBits);
2372         for (unsigned i = 0; i != NumElts; ++i)
2373           if (DemandedElts[i]) {
2374             unsigned Ofs = (i % Scale) * EltSizeInBits;
2375             SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
2376           }
2377 
2378         KnownBits Known;
2379         if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known,
2380                                  TLO, Depth + 1))
2381           return true;
2382       }
2383 
2384       // If the src element is zero/undef then all the output elements will be -
2385       // only demanded elements are guaranteed to be correct.
2386       for (unsigned i = 0; i != NumSrcElts; ++i) {
2387         if (SrcDemandedElts[i]) {
2388           if (SrcZero[i])
2389             KnownZero.setBits(i * Scale, (i + 1) * Scale);
2390           if (SrcUndef[i])
2391             KnownUndef.setBits(i * Scale, (i + 1) * Scale);
2392         }
2393       }
2394     }
2395 
2396     // Bitcast from 'small element' src vector to 'large element' vector, we
2397     // demand all smaller source elements covered by the larger demanded element
2398     // of this vector.
2399     if ((NumSrcElts % NumElts) == 0) {
2400       unsigned Scale = NumSrcElts / NumElts;
2401       for (unsigned i = 0; i != NumElts; ++i)
2402         if (DemandedElts[i])
2403           SrcDemandedElts.setBits(i * Scale, (i + 1) * Scale);
2404 
2405       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2406                                      TLO, Depth + 1))
2407         return true;
2408 
2409       // If all the src elements covering an output element are zero/undef, then
2410       // the output element will be as well, assuming it was demanded.
2411       for (unsigned i = 0; i != NumElts; ++i) {
2412         if (DemandedElts[i]) {
2413           if (SrcZero.extractBits(Scale, i * Scale).isAllOnesValue())
2414             KnownZero.setBit(i);
2415           if (SrcUndef.extractBits(Scale, i * Scale).isAllOnesValue())
2416             KnownUndef.setBit(i);
2417         }
2418       }
2419     }
2420     break;
2421   }
2422   case ISD::BUILD_VECTOR: {
2423     // Check all elements and simplify any unused elements with UNDEF.
2424     if (!DemandedElts.isAllOnesValue()) {
2425       // Don't simplify BROADCASTS.
2426       if (llvm::any_of(Op->op_values(),
2427                        [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
2428         SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end());
2429         bool Updated = false;
2430         for (unsigned i = 0; i != NumElts; ++i) {
2431           if (!DemandedElts[i] && !Ops[i].isUndef()) {
2432             Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
2433             KnownUndef.setBit(i);
2434             Updated = true;
2435           }
2436         }
2437         if (Updated)
2438           return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
2439       }
2440     }
2441     for (unsigned i = 0; i != NumElts; ++i) {
2442       SDValue SrcOp = Op.getOperand(i);
2443       if (SrcOp.isUndef()) {
2444         KnownUndef.setBit(i);
2445       } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
2446                  (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) {
2447         KnownZero.setBit(i);
2448       }
2449     }
2450     break;
2451   }
2452   case ISD::CONCAT_VECTORS: {
2453     EVT SubVT = Op.getOperand(0).getValueType();
2454     unsigned NumSubVecs = Op.getNumOperands();
2455     unsigned NumSubElts = SubVT.getVectorNumElements();
2456     for (unsigned i = 0; i != NumSubVecs; ++i) {
2457       SDValue SubOp = Op.getOperand(i);
2458       APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
2459       APInt SubUndef, SubZero;
2460       if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
2461                                      Depth + 1))
2462         return true;
2463       KnownUndef.insertBits(SubUndef, i * NumSubElts);
2464       KnownZero.insertBits(SubZero, i * NumSubElts);
2465     }
2466     break;
2467   }
2468   case ISD::INSERT_SUBVECTOR: {
2469     // Demand any elements from the subvector and the remainder from the src its
2470     // inserted into.
2471     SDValue Src = Op.getOperand(0);
2472     SDValue Sub = Op.getOperand(1);
2473     uint64_t Idx = Op.getConstantOperandVal(2);
2474     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2475     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2476     APInt DemandedSrcElts = DemandedElts;
2477     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
2478 
2479     APInt SubUndef, SubZero;
2480     if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
2481                                    Depth + 1))
2482       return true;
2483 
2484     // If none of the src operand elements are demanded, replace it with undef.
2485     if (!DemandedSrcElts && !Src.isUndef())
2486       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
2487                                                TLO.DAG.getUNDEF(VT), Sub,
2488                                                Op.getOperand(2)));
2489 
2490     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
2491                                    TLO, Depth + 1))
2492       return true;
2493     KnownUndef.insertBits(SubUndef, Idx);
2494     KnownZero.insertBits(SubZero, Idx);
2495 
2496     // Attempt to avoid multi-use ops if we don't need anything from them.
2497     if (!DemandedSrcElts.isAllOnesValue() ||
2498         !DemandedSubElts.isAllOnesValue()) {
2499       APInt DemandedBits = APInt::getAllOnesValue(VT.getScalarSizeInBits());
2500       SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2501           Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
2502       SDValue NewSub = SimplifyMultipleUseDemandedBits(
2503           Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1);
2504       if (NewSrc || NewSub) {
2505         NewSrc = NewSrc ? NewSrc : Src;
2506         NewSub = NewSub ? NewSub : Sub;
2507         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
2508                                         NewSub, Op.getOperand(2));
2509         return TLO.CombineTo(Op, NewOp);
2510       }
2511     }
2512     break;
2513   }
2514   case ISD::EXTRACT_SUBVECTOR: {
2515     // Offset the demanded elts by the subvector index.
2516     SDValue Src = Op.getOperand(0);
2517     uint64_t Idx = Op.getConstantOperandVal(1);
2518     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2519     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2520 
2521     APInt SrcUndef, SrcZero;
2522     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
2523                                    Depth + 1))
2524       return true;
2525     KnownUndef = SrcUndef.extractBits(NumElts, Idx);
2526     KnownZero = SrcZero.extractBits(NumElts, Idx);
2527 
2528     // Attempt to avoid multi-use ops if we don't need anything from them.
2529     if (!DemandedElts.isAllOnesValue()) {
2530       APInt DemandedBits = APInt::getAllOnesValue(VT.getScalarSizeInBits());
2531       SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2532           Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
2533       if (NewSrc) {
2534         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
2535                                         Op.getOperand(1));
2536         return TLO.CombineTo(Op, NewOp);
2537       }
2538     }
2539     break;
2540   }
2541   case ISD::INSERT_VECTOR_ELT: {
2542     SDValue Vec = Op.getOperand(0);
2543     SDValue Scl = Op.getOperand(1);
2544     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2545 
2546     // For a legal, constant insertion index, if we don't need this insertion
2547     // then strip it, else remove it from the demanded elts.
2548     if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
2549       unsigned Idx = CIdx->getZExtValue();
2550       if (!DemandedElts[Idx])
2551         return TLO.CombineTo(Op, Vec);
2552 
2553       APInt DemandedVecElts(DemandedElts);
2554       DemandedVecElts.clearBit(Idx);
2555       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
2556                                      KnownZero, TLO, Depth + 1))
2557         return true;
2558 
2559       KnownUndef.clearBit(Idx);
2560       if (Scl.isUndef())
2561         KnownUndef.setBit(Idx);
2562 
2563       KnownZero.clearBit(Idx);
2564       if (isNullConstant(Scl) || isNullFPConstant(Scl))
2565         KnownZero.setBit(Idx);
2566       break;
2567     }
2568 
2569     APInt VecUndef, VecZero;
2570     if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
2571                                    Depth + 1))
2572       return true;
2573     // Without knowing the insertion index we can't set KnownUndef/KnownZero.
2574     break;
2575   }
2576   case ISD::VSELECT: {
2577     // Try to transform the select condition based on the current demanded
2578     // elements.
2579     // TODO: If a condition element is undef, we can choose from one arm of the
2580     //       select (and if one arm is undef, then we can propagate that to the
2581     //       result).
2582     // TODO - add support for constant vselect masks (see IR version of this).
2583     APInt UnusedUndef, UnusedZero;
2584     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef,
2585                                    UnusedZero, TLO, Depth + 1))
2586       return true;
2587 
2588     // See if we can simplify either vselect operand.
2589     APInt DemandedLHS(DemandedElts);
2590     APInt DemandedRHS(DemandedElts);
2591     APInt UndefLHS, ZeroLHS;
2592     APInt UndefRHS, ZeroRHS;
2593     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS,
2594                                    ZeroLHS, TLO, Depth + 1))
2595       return true;
2596     if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS,
2597                                    ZeroRHS, TLO, Depth + 1))
2598       return true;
2599 
2600     KnownUndef = UndefLHS & UndefRHS;
2601     KnownZero = ZeroLHS & ZeroRHS;
2602     break;
2603   }
2604   case ISD::VECTOR_SHUFFLE: {
2605     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
2606 
2607     // Collect demanded elements from shuffle operands..
2608     APInt DemandedLHS(NumElts, 0);
2609     APInt DemandedRHS(NumElts, 0);
2610     for (unsigned i = 0; i != NumElts; ++i) {
2611       int M = ShuffleMask[i];
2612       if (M < 0 || !DemandedElts[i])
2613         continue;
2614       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
2615       if (M < (int)NumElts)
2616         DemandedLHS.setBit(M);
2617       else
2618         DemandedRHS.setBit(M - NumElts);
2619     }
2620 
2621     // See if we can simplify either shuffle operand.
2622     APInt UndefLHS, ZeroLHS;
2623     APInt UndefRHS, ZeroRHS;
2624     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS,
2625                                    ZeroLHS, TLO, Depth + 1))
2626       return true;
2627     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS,
2628                                    ZeroRHS, TLO, Depth + 1))
2629       return true;
2630 
2631     // Simplify mask using undef elements from LHS/RHS.
2632     bool Updated = false;
2633     bool IdentityLHS = true, IdentityRHS = true;
2634     SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end());
2635     for (unsigned i = 0; i != NumElts; ++i) {
2636       int &M = NewMask[i];
2637       if (M < 0)
2638         continue;
2639       if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
2640           (M >= (int)NumElts && UndefRHS[M - NumElts])) {
2641         Updated = true;
2642         M = -1;
2643       }
2644       IdentityLHS &= (M < 0) || (M == (int)i);
2645       IdentityRHS &= (M < 0) || ((M - NumElts) == i);
2646     }
2647 
2648     // Update legal shuffle masks based on demanded elements if it won't reduce
2649     // to Identity which can cause premature removal of the shuffle mask.
2650     if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
2651       SDValue LegalShuffle =
2652           buildLegalVectorShuffle(VT, DL, Op.getOperand(0), Op.getOperand(1),
2653                                   NewMask, TLO.DAG);
2654       if (LegalShuffle)
2655         return TLO.CombineTo(Op, LegalShuffle);
2656     }
2657 
2658     // Propagate undef/zero elements from LHS/RHS.
2659     for (unsigned i = 0; i != NumElts; ++i) {
2660       int M = ShuffleMask[i];
2661       if (M < 0) {
2662         KnownUndef.setBit(i);
2663       } else if (M < (int)NumElts) {
2664         if (UndefLHS[M])
2665           KnownUndef.setBit(i);
2666         if (ZeroLHS[M])
2667           KnownZero.setBit(i);
2668       } else {
2669         if (UndefRHS[M - NumElts])
2670           KnownUndef.setBit(i);
2671         if (ZeroRHS[M - NumElts])
2672           KnownZero.setBit(i);
2673       }
2674     }
2675     break;
2676   }
2677   case ISD::ANY_EXTEND_VECTOR_INREG:
2678   case ISD::SIGN_EXTEND_VECTOR_INREG:
2679   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2680     APInt SrcUndef, SrcZero;
2681     SDValue Src = Op.getOperand(0);
2682     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2683     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts);
2684     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
2685                                    Depth + 1))
2686       return true;
2687     KnownZero = SrcZero.zextOrTrunc(NumElts);
2688     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
2689 
2690     if (Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
2691         Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
2692         DemandedSrcElts == 1 && TLO.DAG.getDataLayout().isLittleEndian()) {
2693       // aext - if we just need the bottom element then we can bitcast.
2694       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2695     }
2696 
2697     if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
2698       // zext(undef) upper bits are guaranteed to be zero.
2699       if (DemandedElts.isSubsetOf(KnownUndef))
2700         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
2701       KnownUndef.clearAllBits();
2702     }
2703     break;
2704   }
2705 
2706   // TODO: There are more binop opcodes that could be handled here - MIN,
2707   // MAX, saturated math, etc.
2708   case ISD::OR:
2709   case ISD::XOR:
2710   case ISD::ADD:
2711   case ISD::SUB:
2712   case ISD::FADD:
2713   case ISD::FSUB:
2714   case ISD::FMUL:
2715   case ISD::FDIV:
2716   case ISD::FREM: {
2717     SDValue Op0 = Op.getOperand(0);
2718     SDValue Op1 = Op.getOperand(1);
2719 
2720     APInt UndefRHS, ZeroRHS;
2721     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
2722                                    Depth + 1))
2723       return true;
2724     APInt UndefLHS, ZeroLHS;
2725     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
2726                                    Depth + 1))
2727       return true;
2728 
2729     KnownZero = ZeroLHS & ZeroRHS;
2730     KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
2731 
2732     // Attempt to avoid multi-use ops if we don't need anything from them.
2733     // TODO - use KnownUndef to relax the demandedelts?
2734     if (!DemandedElts.isAllOnesValue())
2735       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
2736         return true;
2737     break;
2738   }
2739   case ISD::SHL:
2740   case ISD::SRL:
2741   case ISD::SRA:
2742   case ISD::ROTL:
2743   case ISD::ROTR: {
2744     SDValue Op0 = Op.getOperand(0);
2745     SDValue Op1 = Op.getOperand(1);
2746 
2747     APInt UndefRHS, ZeroRHS;
2748     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
2749                                    Depth + 1))
2750       return true;
2751     APInt UndefLHS, ZeroLHS;
2752     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
2753                                    Depth + 1))
2754       return true;
2755 
2756     KnownZero = ZeroLHS;
2757     KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
2758 
2759     // Attempt to avoid multi-use ops if we don't need anything from them.
2760     // TODO - use KnownUndef to relax the demandedelts?
2761     if (!DemandedElts.isAllOnesValue())
2762       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
2763         return true;
2764     break;
2765   }
2766   case ISD::MUL:
2767   case ISD::AND: {
2768     SDValue Op0 = Op.getOperand(0);
2769     SDValue Op1 = Op.getOperand(1);
2770 
2771     APInt SrcUndef, SrcZero;
2772     if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
2773                                    Depth + 1))
2774       return true;
2775     if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero,
2776                                    TLO, Depth + 1))
2777       return true;
2778 
2779     // If either side has a zero element, then the result element is zero, even
2780     // if the other is an UNDEF.
2781     // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
2782     // and then handle 'and' nodes with the rest of the binop opcodes.
2783     KnownZero |= SrcZero;
2784     KnownUndef &= SrcUndef;
2785     KnownUndef &= ~KnownZero;
2786 
2787     // Attempt to avoid multi-use ops if we don't need anything from them.
2788     // TODO - use KnownUndef to relax the demandedelts?
2789     if (!DemandedElts.isAllOnesValue())
2790       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
2791         return true;
2792     break;
2793   }
2794   case ISD::TRUNCATE:
2795   case ISD::SIGN_EXTEND:
2796   case ISD::ZERO_EXTEND:
2797     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
2798                                    KnownZero, TLO, Depth + 1))
2799       return true;
2800 
2801     if (Op.getOpcode() == ISD::ZERO_EXTEND) {
2802       // zext(undef) upper bits are guaranteed to be zero.
2803       if (DemandedElts.isSubsetOf(KnownUndef))
2804         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
2805       KnownUndef.clearAllBits();
2806     }
2807     break;
2808   default: {
2809     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
2810       if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
2811                                                   KnownZero, TLO, Depth))
2812         return true;
2813     } else {
2814       KnownBits Known;
2815       APInt DemandedBits = APInt::getAllOnesValue(EltSizeInBits);
2816       if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
2817                                TLO, Depth, AssumeSingleUse))
2818         return true;
2819     }
2820     break;
2821   }
2822   }
2823   assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
2824 
2825   // Constant fold all undef cases.
2826   // TODO: Handle zero cases as well.
2827   if (DemandedElts.isSubsetOf(KnownUndef))
2828     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2829 
2830   return false;
2831 }
2832 
2833 /// Determine which of the bits specified in Mask are known to be either zero or
2834 /// one and return them in the Known.
2835 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
2836                                                    KnownBits &Known,
2837                                                    const APInt &DemandedElts,
2838                                                    const SelectionDAG &DAG,
2839                                                    unsigned Depth) const {
2840   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2841           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2842           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2843           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2844          "Should use MaskedValueIsZero if you don't know whether Op"
2845          " is a target node!");
2846   Known.resetAll();
2847 }
2848 
2849 void TargetLowering::computeKnownBitsForTargetInstr(
2850     GISelKnownBits &Analysis, Register R, KnownBits &Known,
2851     const APInt &DemandedElts, const MachineRegisterInfo &MRI,
2852     unsigned Depth) const {
2853   Known.resetAll();
2854 }
2855 
2856 void TargetLowering::computeKnownBitsForFrameIndex(
2857   const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const {
2858   // The low bits are known zero if the pointer is aligned.
2859   Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx)));
2860 }
2861 
2862 Align TargetLowering::computeKnownAlignForTargetInstr(
2863   GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI,
2864   unsigned Depth) const {
2865   return Align(1);
2866 }
2867 
2868 /// This method can be implemented by targets that want to expose additional
2869 /// information about sign bits to the DAG Combiner.
2870 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
2871                                                          const APInt &,
2872                                                          const SelectionDAG &,
2873                                                          unsigned Depth) const {
2874   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2875           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2876           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2877           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2878          "Should use ComputeNumSignBits if you don't know whether Op"
2879          " is a target node!");
2880   return 1;
2881 }
2882 
2883 unsigned TargetLowering::computeNumSignBitsForTargetInstr(
2884   GISelKnownBits &Analysis, Register R, const APInt &DemandedElts,
2885   const MachineRegisterInfo &MRI, unsigned Depth) const {
2886   return 1;
2887 }
2888 
2889 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
2890     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
2891     TargetLoweringOpt &TLO, unsigned Depth) const {
2892   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2893           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2894           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2895           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2896          "Should use SimplifyDemandedVectorElts if you don't know whether Op"
2897          " is a target node!");
2898   return false;
2899 }
2900 
2901 bool TargetLowering::SimplifyDemandedBitsForTargetNode(
2902     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
2903     KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
2904   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2905           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2906           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2907           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2908          "Should use SimplifyDemandedBits if you don't know whether Op"
2909          " is a target node!");
2910   computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
2911   return false;
2912 }
2913 
2914 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
2915     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
2916     SelectionDAG &DAG, unsigned Depth) const {
2917   assert(
2918       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2919        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2920        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2921        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2922       "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
2923       " is a target node!");
2924   return SDValue();
2925 }
2926 
2927 SDValue
2928 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0,
2929                                         SDValue N1, MutableArrayRef<int> Mask,
2930                                         SelectionDAG &DAG) const {
2931   bool LegalMask = isShuffleMaskLegal(Mask, VT);
2932   if (!LegalMask) {
2933     std::swap(N0, N1);
2934     ShuffleVectorSDNode::commuteMask(Mask);
2935     LegalMask = isShuffleMaskLegal(Mask, VT);
2936   }
2937 
2938   if (!LegalMask)
2939     return SDValue();
2940 
2941   return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
2942 }
2943 
2944 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const {
2945   return nullptr;
2946 }
2947 
2948 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
2949                                                   const SelectionDAG &DAG,
2950                                                   bool SNaN,
2951                                                   unsigned Depth) const {
2952   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2953           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2954           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2955           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
2956          "Should use isKnownNeverNaN if you don't know whether Op"
2957          " is a target node!");
2958   return false;
2959 }
2960 
2961 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
2962 // work with truncating build vectors and vectors with elements of less than
2963 // 8 bits.
2964 bool TargetLowering::isConstTrueVal(const SDNode *N) const {
2965   if (!N)
2966     return false;
2967 
2968   APInt CVal;
2969   if (auto *CN = dyn_cast<ConstantSDNode>(N)) {
2970     CVal = CN->getAPIntValue();
2971   } else if (auto *BV = dyn_cast<BuildVectorSDNode>(N)) {
2972     auto *CN = BV->getConstantSplatNode();
2973     if (!CN)
2974       return false;
2975 
2976     // If this is a truncating build vector, truncate the splat value.
2977     // Otherwise, we may fail to match the expected values below.
2978     unsigned BVEltWidth = BV->getValueType(0).getScalarSizeInBits();
2979     CVal = CN->getAPIntValue();
2980     if (BVEltWidth < CVal.getBitWidth())
2981       CVal = CVal.trunc(BVEltWidth);
2982   } else {
2983     return false;
2984   }
2985 
2986   switch (getBooleanContents(N->getValueType(0))) {
2987   case UndefinedBooleanContent:
2988     return CVal[0];
2989   case ZeroOrOneBooleanContent:
2990     return CVal.isOneValue();
2991   case ZeroOrNegativeOneBooleanContent:
2992     return CVal.isAllOnesValue();
2993   }
2994 
2995   llvm_unreachable("Invalid boolean contents");
2996 }
2997 
2998 bool TargetLowering::isConstFalseVal(const SDNode *N) const {
2999   if (!N)
3000     return false;
3001 
3002   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
3003   if (!CN) {
3004     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
3005     if (!BV)
3006       return false;
3007 
3008     // Only interested in constant splats, we don't care about undef
3009     // elements in identifying boolean constants and getConstantSplatNode
3010     // returns NULL if all ops are undef;
3011     CN = BV->getConstantSplatNode();
3012     if (!CN)
3013       return false;
3014   }
3015 
3016   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
3017     return !CN->getAPIntValue()[0];
3018 
3019   return CN->isNullValue();
3020 }
3021 
3022 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
3023                                        bool SExt) const {
3024   if (VT == MVT::i1)
3025     return N->isOne();
3026 
3027   TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
3028   switch (Cnt) {
3029   case TargetLowering::ZeroOrOneBooleanContent:
3030     // An extended value of 1 is always true, unless its original type is i1,
3031     // in which case it will be sign extended to -1.
3032     return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
3033   case TargetLowering::UndefinedBooleanContent:
3034   case TargetLowering::ZeroOrNegativeOneBooleanContent:
3035     return N->isAllOnesValue() && SExt;
3036   }
3037   llvm_unreachable("Unexpected enumeration.");
3038 }
3039 
3040 /// This helper function of SimplifySetCC tries to optimize the comparison when
3041 /// either operand of the SetCC node is a bitwise-and instruction.
3042 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
3043                                          ISD::CondCode Cond, const SDLoc &DL,
3044                                          DAGCombinerInfo &DCI) const {
3045   // Match these patterns in any of their permutations:
3046   // (X & Y) == Y
3047   // (X & Y) != Y
3048   if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
3049     std::swap(N0, N1);
3050 
3051   EVT OpVT = N0.getValueType();
3052   if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
3053       (Cond != ISD::SETEQ && Cond != ISD::SETNE))
3054     return SDValue();
3055 
3056   SDValue X, Y;
3057   if (N0.getOperand(0) == N1) {
3058     X = N0.getOperand(1);
3059     Y = N0.getOperand(0);
3060   } else if (N0.getOperand(1) == N1) {
3061     X = N0.getOperand(0);
3062     Y = N0.getOperand(1);
3063   } else {
3064     return SDValue();
3065   }
3066 
3067   SelectionDAG &DAG = DCI.DAG;
3068   SDValue Zero = DAG.getConstant(0, DL, OpVT);
3069   if (DAG.isKnownToBeAPowerOfTwo(Y)) {
3070     // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
3071     // Note that where Y is variable and is known to have at most one bit set
3072     // (for example, if it is Z & 1) we cannot do this; the expressions are not
3073     // equivalent when Y == 0.
3074     assert(OpVT.isInteger());
3075     Cond = ISD::getSetCCInverse(Cond, OpVT);
3076     if (DCI.isBeforeLegalizeOps() ||
3077         isCondCodeLegal(Cond, N0.getSimpleValueType()))
3078       return DAG.getSetCC(DL, VT, N0, Zero, Cond);
3079   } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
3080     // If the target supports an 'and-not' or 'and-complement' logic operation,
3081     // try to use that to make a comparison operation more efficient.
3082     // But don't do this transform if the mask is a single bit because there are
3083     // more efficient ways to deal with that case (for example, 'bt' on x86 or
3084     // 'rlwinm' on PPC).
3085 
3086     // Bail out if the compare operand that we want to turn into a zero is
3087     // already a zero (otherwise, infinite loop).
3088     auto *YConst = dyn_cast<ConstantSDNode>(Y);
3089     if (YConst && YConst->isNullValue())
3090       return SDValue();
3091 
3092     // Transform this into: ~X & Y == 0.
3093     SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
3094     SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
3095     return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
3096   }
3097 
3098   return SDValue();
3099 }
3100 
3101 /// There are multiple IR patterns that could be checking whether certain
3102 /// truncation of a signed number would be lossy or not. The pattern which is
3103 /// best at IR level, may not lower optimally. Thus, we want to unfold it.
3104 /// We are looking for the following pattern: (KeptBits is a constant)
3105 ///   (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
3106 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
3107 /// KeptBits also can't be 1, that would have been folded to  %x dstcond 0
3108 /// We will unfold it into the natural trunc+sext pattern:
3109 ///   ((%x << C) a>> C) dstcond %x
3110 /// Where  C = bitwidth(x) - KeptBits  and  C u< bitwidth(x)
3111 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
3112     EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
3113     const SDLoc &DL) const {
3114   // We must be comparing with a constant.
3115   ConstantSDNode *C1;
3116   if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
3117     return SDValue();
3118 
3119   // N0 should be:  add %x, (1 << (KeptBits-1))
3120   if (N0->getOpcode() != ISD::ADD)
3121     return SDValue();
3122 
3123   // And we must be 'add'ing a constant.
3124   ConstantSDNode *C01;
3125   if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
3126     return SDValue();
3127 
3128   SDValue X = N0->getOperand(0);
3129   EVT XVT = X.getValueType();
3130 
3131   // Validate constants ...
3132 
3133   APInt I1 = C1->getAPIntValue();
3134 
3135   ISD::CondCode NewCond;
3136   if (Cond == ISD::CondCode::SETULT) {
3137     NewCond = ISD::CondCode::SETEQ;
3138   } else if (Cond == ISD::CondCode::SETULE) {
3139     NewCond = ISD::CondCode::SETEQ;
3140     // But need to 'canonicalize' the constant.
3141     I1 += 1;
3142   } else if (Cond == ISD::CondCode::SETUGT) {
3143     NewCond = ISD::CondCode::SETNE;
3144     // But need to 'canonicalize' the constant.
3145     I1 += 1;
3146   } else if (Cond == ISD::CondCode::SETUGE) {
3147     NewCond = ISD::CondCode::SETNE;
3148   } else
3149     return SDValue();
3150 
3151   APInt I01 = C01->getAPIntValue();
3152 
3153   auto checkConstants = [&I1, &I01]() -> bool {
3154     // Both of them must be power-of-two, and the constant from setcc is bigger.
3155     return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
3156   };
3157 
3158   if (checkConstants()) {
3159     // Great, e.g. got  icmp ult i16 (add i16 %x, 128), 256
3160   } else {
3161     // What if we invert constants? (and the target predicate)
3162     I1.negate();
3163     I01.negate();
3164     assert(XVT.isInteger());
3165     NewCond = getSetCCInverse(NewCond, XVT);
3166     if (!checkConstants())
3167       return SDValue();
3168     // Great, e.g. got  icmp uge i16 (add i16 %x, -128), -256
3169   }
3170 
3171   // They are power-of-two, so which bit is set?
3172   const unsigned KeptBits = I1.logBase2();
3173   const unsigned KeptBitsMinusOne = I01.logBase2();
3174 
3175   // Magic!
3176   if (KeptBits != (KeptBitsMinusOne + 1))
3177     return SDValue();
3178   assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
3179 
3180   // We don't want to do this in every single case.
3181   SelectionDAG &DAG = DCI.DAG;
3182   if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck(
3183           XVT, KeptBits))
3184     return SDValue();
3185 
3186   const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits;
3187   assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable");
3188 
3189   // Unfold into:  ((%x << C) a>> C) cond %x
3190   // Where 'cond' will be either 'eq' or 'ne'.
3191   SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT);
3192   SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt);
3193   SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt);
3194   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond);
3195 
3196   return T2;
3197 }
3198 
3199 // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
3200 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
3201     EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
3202     DAGCombinerInfo &DCI, const SDLoc &DL) const {
3203   assert(isConstOrConstSplat(N1C) &&
3204          isConstOrConstSplat(N1C)->getAPIntValue().isNullValue() &&
3205          "Should be a comparison with 0.");
3206   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3207          "Valid only for [in]equality comparisons.");
3208 
3209   unsigned NewShiftOpcode;
3210   SDValue X, C, Y;
3211 
3212   SelectionDAG &DAG = DCI.DAG;
3213   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3214 
3215   // Look for '(C l>>/<< Y)'.
3216   auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) {
3217     // The shift should be one-use.
3218     if (!V.hasOneUse())
3219       return false;
3220     unsigned OldShiftOpcode = V.getOpcode();
3221     switch (OldShiftOpcode) {
3222     case ISD::SHL:
3223       NewShiftOpcode = ISD::SRL;
3224       break;
3225     case ISD::SRL:
3226       NewShiftOpcode = ISD::SHL;
3227       break;
3228     default:
3229       return false; // must be a logical shift.
3230     }
3231     // We should be shifting a constant.
3232     // FIXME: best to use isConstantOrConstantVector().
3233     C = V.getOperand(0);
3234     ConstantSDNode *CC =
3235         isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
3236     if (!CC)
3237       return false;
3238     Y = V.getOperand(1);
3239 
3240     ConstantSDNode *XC =
3241         isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
3242     return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
3243         X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
3244   };
3245 
3246   // LHS of comparison should be an one-use 'and'.
3247   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
3248     return SDValue();
3249 
3250   X = N0.getOperand(0);
3251   SDValue Mask = N0.getOperand(1);
3252 
3253   // 'and' is commutative!
3254   if (!Match(Mask)) {
3255     std::swap(X, Mask);
3256     if (!Match(Mask))
3257       return SDValue();
3258   }
3259 
3260   EVT VT = X.getValueType();
3261 
3262   // Produce:
3263   // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
3264   SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
3265   SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
3266   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
3267   return T2;
3268 }
3269 
3270 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as
3271 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
3272 /// handle the commuted versions of these patterns.
3273 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
3274                                            ISD::CondCode Cond, const SDLoc &DL,
3275                                            DAGCombinerInfo &DCI) const {
3276   unsigned BOpcode = N0.getOpcode();
3277   assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
3278          "Unexpected binop");
3279   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
3280 
3281   // (X + Y) == X --> Y == 0
3282   // (X - Y) == X --> Y == 0
3283   // (X ^ Y) == X --> Y == 0
3284   SelectionDAG &DAG = DCI.DAG;
3285   EVT OpVT = N0.getValueType();
3286   SDValue X = N0.getOperand(0);
3287   SDValue Y = N0.getOperand(1);
3288   if (X == N1)
3289     return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
3290 
3291   if (Y != N1)
3292     return SDValue();
3293 
3294   // (X + Y) == Y --> X == 0
3295   // (X ^ Y) == Y --> X == 0
3296   if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
3297     return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
3298 
3299   // The shift would not be valid if the operands are boolean (i1).
3300   if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
3301     return SDValue();
3302 
3303   // (X - Y) == Y --> X == Y << 1
3304   EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(),
3305                                  !DCI.isBeforeLegalize());
3306   SDValue One = DAG.getConstant(1, DL, ShiftVT);
3307   SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
3308   if (!DCI.isCalledByLegalizer())
3309     DCI.AddToWorklist(YShl1.getNode());
3310   return DAG.getSetCC(DL, VT, X, YShl1, Cond);
3311 }
3312 
3313 /// Try to simplify a setcc built with the specified operands and cc. If it is
3314 /// unable to simplify it, return a null SDValue.
3315 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
3316                                       ISD::CondCode Cond, bool foldBooleans,
3317                                       DAGCombinerInfo &DCI,
3318                                       const SDLoc &dl) const {
3319   SelectionDAG &DAG = DCI.DAG;
3320   const DataLayout &Layout = DAG.getDataLayout();
3321   EVT OpVT = N0.getValueType();
3322 
3323   // Constant fold or commute setcc.
3324   if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
3325     return Fold;
3326 
3327   // Ensure that the constant occurs on the RHS and fold constant comparisons.
3328   // TODO: Handle non-splat vector constants. All undef causes trouble.
3329   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
3330   if (isConstOrConstSplat(N0) &&
3331       (DCI.isBeforeLegalizeOps() ||
3332        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
3333     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
3334 
3335   // If we have a subtract with the same 2 non-constant operands as this setcc
3336   // -- but in reverse order -- then try to commute the operands of this setcc
3337   // to match. A matching pair of setcc (cmp) and sub may be combined into 1
3338   // instruction on some targets.
3339   if (!isConstOrConstSplat(N0) && !isConstOrConstSplat(N1) &&
3340       (DCI.isBeforeLegalizeOps() ||
3341        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
3342       DAG.getNodeIfExists(ISD::SUB, DAG.getVTList(OpVT), { N1, N0 } ) &&
3343       !DAG.getNodeIfExists(ISD::SUB, DAG.getVTList(OpVT), { N0, N1 } ))
3344     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
3345 
3346   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
3347     const APInt &C1 = N1C->getAPIntValue();
3348 
3349     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
3350     // equality comparison, then we're just comparing whether X itself is
3351     // zero.
3352     if (N0.getOpcode() == ISD::SRL && (C1.isNullValue() || C1.isOneValue()) &&
3353         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
3354         N0.getOperand(1).getOpcode() == ISD::Constant) {
3355       const APInt &ShAmt = N0.getConstantOperandAPInt(1);
3356       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3357           ShAmt == Log2_32(N0.getValueSizeInBits())) {
3358         if ((C1 == 0) == (Cond == ISD::SETEQ)) {
3359           // (srl (ctlz x), 5) == 0  -> X != 0
3360           // (srl (ctlz x), 5) != 1  -> X != 0
3361           Cond = ISD::SETNE;
3362         } else {
3363           // (srl (ctlz x), 5) != 0  -> X == 0
3364           // (srl (ctlz x), 5) == 1  -> X == 0
3365           Cond = ISD::SETEQ;
3366         }
3367         SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
3368         return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0),
3369                             Zero, Cond);
3370       }
3371     }
3372 
3373     SDValue CTPOP = N0;
3374     // Look through truncs that don't change the value of a ctpop.
3375     if (N0.hasOneUse() && N0.getOpcode() == ISD::TRUNCATE)
3376       CTPOP = N0.getOperand(0);
3377 
3378     if (CTPOP.hasOneUse() && CTPOP.getOpcode() == ISD::CTPOP &&
3379         (N0 == CTPOP ||
3380          N0.getValueSizeInBits() > Log2_32_Ceil(CTPOP.getValueSizeInBits()))) {
3381       EVT CTVT = CTPOP.getValueType();
3382       SDValue CTOp = CTPOP.getOperand(0);
3383 
3384       // (ctpop x) u< 2 -> (x & x-1) == 0
3385       // (ctpop x) u> 1 -> (x & x-1) != 0
3386       if ((Cond == ISD::SETULT && C1 == 2) || (Cond == ISD::SETUGT && C1 == 1)){
3387         SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
3388         SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
3389         SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
3390         ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
3391         return DAG.getSetCC(dl, VT, And, DAG.getConstant(0, dl, CTVT), CC);
3392       }
3393 
3394       // If ctpop is not supported, expand a power-of-2 comparison based on it.
3395       if (C1 == 1 && !isOperationLegalOrCustom(ISD::CTPOP, CTVT) &&
3396           (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3397         // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0)
3398         // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0)
3399         SDValue Zero = DAG.getConstant(0, dl, CTVT);
3400         SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
3401         assert(CTVT.isInteger());
3402         ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, CTVT);
3403         SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
3404         SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
3405         SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond);
3406         SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
3407         unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR;
3408         return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS);
3409       }
3410     }
3411 
3412     // (zext x) == C --> x == (trunc C)
3413     // (sext x) == C --> x == (trunc C)
3414     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3415         DCI.isBeforeLegalize() && N0->hasOneUse()) {
3416       unsigned MinBits = N0.getValueSizeInBits();
3417       SDValue PreExt;
3418       bool Signed = false;
3419       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
3420         // ZExt
3421         MinBits = N0->getOperand(0).getValueSizeInBits();
3422         PreExt = N0->getOperand(0);
3423       } else if (N0->getOpcode() == ISD::AND) {
3424         // DAGCombine turns costly ZExts into ANDs
3425         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
3426           if ((C->getAPIntValue()+1).isPowerOf2()) {
3427             MinBits = C->getAPIntValue().countTrailingOnes();
3428             PreExt = N0->getOperand(0);
3429           }
3430       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
3431         // SExt
3432         MinBits = N0->getOperand(0).getValueSizeInBits();
3433         PreExt = N0->getOperand(0);
3434         Signed = true;
3435       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
3436         // ZEXTLOAD / SEXTLOAD
3437         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
3438           MinBits = LN0->getMemoryVT().getSizeInBits();
3439           PreExt = N0;
3440         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
3441           Signed = true;
3442           MinBits = LN0->getMemoryVT().getSizeInBits();
3443           PreExt = N0;
3444         }
3445       }
3446 
3447       // Figure out how many bits we need to preserve this constant.
3448       unsigned ReqdBits = Signed ?
3449         C1.getBitWidth() - C1.getNumSignBits() + 1 :
3450         C1.getActiveBits();
3451 
3452       // Make sure we're not losing bits from the constant.
3453       if (MinBits > 0 &&
3454           MinBits < C1.getBitWidth() &&
3455           MinBits >= ReqdBits) {
3456         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
3457         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
3458           // Will get folded away.
3459           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
3460           if (MinBits == 1 && C1 == 1)
3461             // Invert the condition.
3462             return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
3463                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3464           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
3465           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
3466         }
3467 
3468         // If truncating the setcc operands is not desirable, we can still
3469         // simplify the expression in some cases:
3470         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
3471         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
3472         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
3473         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
3474         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
3475         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
3476         SDValue TopSetCC = N0->getOperand(0);
3477         unsigned N0Opc = N0->getOpcode();
3478         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
3479         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
3480             TopSetCC.getOpcode() == ISD::SETCC &&
3481             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
3482             (isConstFalseVal(N1C) ||
3483              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
3484 
3485           bool Inverse = (N1C->isNullValue() && Cond == ISD::SETEQ) ||
3486                          (!N1C->isNullValue() && Cond == ISD::SETNE);
3487 
3488           if (!Inverse)
3489             return TopSetCC;
3490 
3491           ISD::CondCode InvCond = ISD::getSetCCInverse(
3492               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
3493               TopSetCC.getOperand(0).getValueType());
3494           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
3495                                       TopSetCC.getOperand(1),
3496                                       InvCond);
3497         }
3498       }
3499     }
3500 
3501     // If the LHS is '(and load, const)', the RHS is 0, the test is for
3502     // equality or unsigned, and all 1 bits of the const are in the same
3503     // partial word, see if we can shorten the load.
3504     if (DCI.isBeforeLegalize() &&
3505         !ISD::isSignedIntSetCC(Cond) &&
3506         N0.getOpcode() == ISD::AND && C1 == 0 &&
3507         N0.getNode()->hasOneUse() &&
3508         isa<LoadSDNode>(N0.getOperand(0)) &&
3509         N0.getOperand(0).getNode()->hasOneUse() &&
3510         isa<ConstantSDNode>(N0.getOperand(1))) {
3511       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
3512       APInt bestMask;
3513       unsigned bestWidth = 0, bestOffset = 0;
3514       if (Lod->isSimple() && Lod->isUnindexed()) {
3515         unsigned origWidth = N0.getValueSizeInBits();
3516         unsigned maskWidth = origWidth;
3517         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
3518         // 8 bits, but have to be careful...
3519         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
3520           origWidth = Lod->getMemoryVT().getSizeInBits();
3521         const APInt &Mask = N0.getConstantOperandAPInt(1);
3522         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
3523           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
3524           for (unsigned offset=0; offset<origWidth/width; offset++) {
3525             if (Mask.isSubsetOf(newMask)) {
3526               if (Layout.isLittleEndian())
3527                 bestOffset = (uint64_t)offset * (width/8);
3528               else
3529                 bestOffset = (origWidth/width - offset - 1) * (width/8);
3530               bestMask = Mask.lshr(offset * (width/8) * 8);
3531               bestWidth = width;
3532               break;
3533             }
3534             newMask <<= width;
3535           }
3536         }
3537       }
3538       if (bestWidth) {
3539         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
3540         if (newVT.isRound() &&
3541             shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) {
3542           SDValue Ptr = Lod->getBasePtr();
3543           if (bestOffset != 0)
3544             Ptr = DAG.getMemBasePlusOffset(Ptr, bestOffset, dl);
3545           unsigned NewAlign = MinAlign(Lod->getAlignment(), bestOffset);
3546           SDValue NewLoad = DAG.getLoad(
3547               newVT, dl, Lod->getChain(), Ptr,
3548               Lod->getPointerInfo().getWithOffset(bestOffset), NewAlign);
3549           return DAG.getSetCC(dl, VT,
3550                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
3551                                       DAG.getConstant(bestMask.trunc(bestWidth),
3552                                                       dl, newVT)),
3553                               DAG.getConstant(0LL, dl, newVT), Cond);
3554         }
3555       }
3556     }
3557 
3558     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
3559     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
3560       unsigned InSize = N0.getOperand(0).getValueSizeInBits();
3561 
3562       // If the comparison constant has bits in the upper part, the
3563       // zero-extended value could never match.
3564       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
3565                                               C1.getBitWidth() - InSize))) {
3566         switch (Cond) {
3567         case ISD::SETUGT:
3568         case ISD::SETUGE:
3569         case ISD::SETEQ:
3570           return DAG.getConstant(0, dl, VT);
3571         case ISD::SETULT:
3572         case ISD::SETULE:
3573         case ISD::SETNE:
3574           return DAG.getConstant(1, dl, VT);
3575         case ISD::SETGT:
3576         case ISD::SETGE:
3577           // True if the sign bit of C1 is set.
3578           return DAG.getConstant(C1.isNegative(), dl, VT);
3579         case ISD::SETLT:
3580         case ISD::SETLE:
3581           // True if the sign bit of C1 isn't set.
3582           return DAG.getConstant(C1.isNonNegative(), dl, VT);
3583         default:
3584           break;
3585         }
3586       }
3587 
3588       // Otherwise, we can perform the comparison with the low bits.
3589       switch (Cond) {
3590       case ISD::SETEQ:
3591       case ISD::SETNE:
3592       case ISD::SETUGT:
3593       case ISD::SETUGE:
3594       case ISD::SETULT:
3595       case ISD::SETULE: {
3596         EVT newVT = N0.getOperand(0).getValueType();
3597         if (DCI.isBeforeLegalizeOps() ||
3598             (isOperationLegal(ISD::SETCC, newVT) &&
3599              isCondCodeLegal(Cond, newVT.getSimpleVT()))) {
3600           EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
3601           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
3602 
3603           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
3604                                           NewConst, Cond);
3605           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
3606         }
3607         break;
3608       }
3609       default:
3610         break; // todo, be more careful with signed comparisons
3611       }
3612     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3613                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3614       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
3615       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
3616       EVT ExtDstTy = N0.getValueType();
3617       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
3618 
3619       // If the constant doesn't fit into the number of bits for the source of
3620       // the sign extension, it is impossible for both sides to be equal.
3621       if (C1.getMinSignedBits() > ExtSrcTyBits)
3622         return DAG.getConstant(Cond == ISD::SETNE, dl, VT);
3623 
3624       SDValue ZextOp;
3625       EVT Op0Ty = N0.getOperand(0).getValueType();
3626       if (Op0Ty == ExtSrcTy) {
3627         ZextOp = N0.getOperand(0);
3628       } else {
3629         APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
3630         ZextOp = DAG.getNode(ISD::AND, dl, Op0Ty, N0.getOperand(0),
3631                              DAG.getConstant(Imm, dl, Op0Ty));
3632       }
3633       if (!DCI.isCalledByLegalizer())
3634         DCI.AddToWorklist(ZextOp.getNode());
3635       // Otherwise, make this a use of a zext.
3636       return DAG.getSetCC(dl, VT, ZextOp,
3637                           DAG.getConstant(C1 & APInt::getLowBitsSet(
3638                                                               ExtDstTyBits,
3639                                                               ExtSrcTyBits),
3640                                           dl, ExtDstTy),
3641                           Cond);
3642     } else if ((N1C->isNullValue() || N1C->isOne()) &&
3643                 (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3644       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
3645       if (N0.getOpcode() == ISD::SETCC &&
3646           isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
3647           (N0.getValueType() == MVT::i1 ||
3648            getBooleanContents(N0.getOperand(0).getValueType()) ==
3649                        ZeroOrOneBooleanContent)) {
3650         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
3651         if (TrueWhenTrue)
3652           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
3653         // Invert the condition.
3654         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
3655         CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType());
3656         if (DCI.isBeforeLegalizeOps() ||
3657             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
3658           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
3659       }
3660 
3661       if ((N0.getOpcode() == ISD::XOR ||
3662            (N0.getOpcode() == ISD::AND &&
3663             N0.getOperand(0).getOpcode() == ISD::XOR &&
3664             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
3665           isa<ConstantSDNode>(N0.getOperand(1)) &&
3666           cast<ConstantSDNode>(N0.getOperand(1))->isOne()) {
3667         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
3668         // can only do this if the top bits are known zero.
3669         unsigned BitWidth = N0.getValueSizeInBits();
3670         if (DAG.MaskedValueIsZero(N0,
3671                                   APInt::getHighBitsSet(BitWidth,
3672                                                         BitWidth-1))) {
3673           // Okay, get the un-inverted input value.
3674           SDValue Val;
3675           if (N0.getOpcode() == ISD::XOR) {
3676             Val = N0.getOperand(0);
3677           } else {
3678             assert(N0.getOpcode() == ISD::AND &&
3679                     N0.getOperand(0).getOpcode() == ISD::XOR);
3680             // ((X^1)&1)^1 -> X & 1
3681             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
3682                               N0.getOperand(0).getOperand(0),
3683                               N0.getOperand(1));
3684           }
3685 
3686           return DAG.getSetCC(dl, VT, Val, N1,
3687                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3688         }
3689       } else if (N1C->isOne()) {
3690         SDValue Op0 = N0;
3691         if (Op0.getOpcode() == ISD::TRUNCATE)
3692           Op0 = Op0.getOperand(0);
3693 
3694         if ((Op0.getOpcode() == ISD::XOR) &&
3695             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
3696             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
3697           SDValue XorLHS = Op0.getOperand(0);
3698           SDValue XorRHS = Op0.getOperand(1);
3699           // Ensure that the input setccs return an i1 type or 0/1 value.
3700           if (Op0.getValueType() == MVT::i1 ||
3701               (getBooleanContents(XorLHS.getOperand(0).getValueType()) ==
3702                       ZeroOrOneBooleanContent &&
3703                getBooleanContents(XorRHS.getOperand(0).getValueType()) ==
3704                         ZeroOrOneBooleanContent)) {
3705             // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
3706             Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
3707             return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
3708           }
3709         }
3710         if (Op0.getOpcode() == ISD::AND &&
3711             isa<ConstantSDNode>(Op0.getOperand(1)) &&
3712             cast<ConstantSDNode>(Op0.getOperand(1))->isOne()) {
3713           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
3714           if (Op0.getValueType().bitsGT(VT))
3715             Op0 = DAG.getNode(ISD::AND, dl, VT,
3716                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
3717                           DAG.getConstant(1, dl, VT));
3718           else if (Op0.getValueType().bitsLT(VT))
3719             Op0 = DAG.getNode(ISD::AND, dl, VT,
3720                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
3721                         DAG.getConstant(1, dl, VT));
3722 
3723           return DAG.getSetCC(dl, VT, Op0,
3724                               DAG.getConstant(0, dl, Op0.getValueType()),
3725                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3726         }
3727         if (Op0.getOpcode() == ISD::AssertZext &&
3728             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
3729           return DAG.getSetCC(dl, VT, Op0,
3730                               DAG.getConstant(0, dl, Op0.getValueType()),
3731                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3732       }
3733     }
3734 
3735     // Given:
3736     //   icmp eq/ne (urem %x, %y), 0
3737     // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
3738     //   icmp eq/ne %x, 0
3739     if (N0.getOpcode() == ISD::UREM && N1C->isNullValue() &&
3740         (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3741       KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
3742       KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
3743       if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
3744         return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
3745     }
3746 
3747     if (SDValue V =
3748             optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
3749       return V;
3750   }
3751 
3752   // These simplifications apply to splat vectors as well.
3753   // TODO: Handle more splat vector cases.
3754   if (auto *N1C = isConstOrConstSplat(N1)) {
3755     const APInt &C1 = N1C->getAPIntValue();
3756 
3757     APInt MinVal, MaxVal;
3758     unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
3759     if (ISD::isSignedIntSetCC(Cond)) {
3760       MinVal = APInt::getSignedMinValue(OperandBitSize);
3761       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
3762     } else {
3763       MinVal = APInt::getMinValue(OperandBitSize);
3764       MaxVal = APInt::getMaxValue(OperandBitSize);
3765     }
3766 
3767     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
3768     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
3769       // X >= MIN --> true
3770       if (C1 == MinVal)
3771         return DAG.getBoolConstant(true, dl, VT, OpVT);
3772 
3773       if (!VT.isVector()) { // TODO: Support this for vectors.
3774         // X >= C0 --> X > (C0 - 1)
3775         APInt C = C1 - 1;
3776         ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
3777         if ((DCI.isBeforeLegalizeOps() ||
3778              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
3779             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
3780                                   isLegalICmpImmediate(C.getSExtValue())))) {
3781           return DAG.getSetCC(dl, VT, N0,
3782                               DAG.getConstant(C, dl, N1.getValueType()),
3783                               NewCC);
3784         }
3785       }
3786     }
3787 
3788     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
3789       // X <= MAX --> true
3790       if (C1 == MaxVal)
3791         return DAG.getBoolConstant(true, dl, VT, OpVT);
3792 
3793       // X <= C0 --> X < (C0 + 1)
3794       if (!VT.isVector()) { // TODO: Support this for vectors.
3795         APInt C = C1 + 1;
3796         ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
3797         if ((DCI.isBeforeLegalizeOps() ||
3798              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
3799             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
3800                                   isLegalICmpImmediate(C.getSExtValue())))) {
3801           return DAG.getSetCC(dl, VT, N0,
3802                               DAG.getConstant(C, dl, N1.getValueType()),
3803                               NewCC);
3804         }
3805       }
3806     }
3807 
3808     if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
3809       if (C1 == MinVal)
3810         return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
3811 
3812       // TODO: Support this for vectors after legalize ops.
3813       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
3814         // Canonicalize setlt X, Max --> setne X, Max
3815         if (C1 == MaxVal)
3816           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
3817 
3818         // If we have setult X, 1, turn it into seteq X, 0
3819         if (C1 == MinVal+1)
3820           return DAG.getSetCC(dl, VT, N0,
3821                               DAG.getConstant(MinVal, dl, N0.getValueType()),
3822                               ISD::SETEQ);
3823       }
3824     }
3825 
3826     if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
3827       if (C1 == MaxVal)
3828         return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
3829 
3830       // TODO: Support this for vectors after legalize ops.
3831       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
3832         // Canonicalize setgt X, Min --> setne X, Min
3833         if (C1 == MinVal)
3834           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
3835 
3836         // If we have setugt X, Max-1, turn it into seteq X, Max
3837         if (C1 == MaxVal-1)
3838           return DAG.getSetCC(dl, VT, N0,
3839                               DAG.getConstant(MaxVal, dl, N0.getValueType()),
3840                               ISD::SETEQ);
3841       }
3842     }
3843 
3844     if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
3845       // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
3846       if (C1.isNullValue())
3847         if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
3848                 VT, N0, N1, Cond, DCI, dl))
3849           return CC;
3850     }
3851 
3852     // If we have "setcc X, C0", check to see if we can shrink the immediate
3853     // by changing cc.
3854     // TODO: Support this for vectors after legalize ops.
3855     if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
3856       // SETUGT X, SINTMAX  -> SETLT X, 0
3857       if (Cond == ISD::SETUGT &&
3858           C1 == APInt::getSignedMaxValue(OperandBitSize))
3859         return DAG.getSetCC(dl, VT, N0,
3860                             DAG.getConstant(0, dl, N1.getValueType()),
3861                             ISD::SETLT);
3862 
3863       // SETULT X, SINTMIN  -> SETGT X, -1
3864       if (Cond == ISD::SETULT &&
3865           C1 == APInt::getSignedMinValue(OperandBitSize)) {
3866         SDValue ConstMinusOne =
3867             DAG.getConstant(APInt::getAllOnesValue(OperandBitSize), dl,
3868                             N1.getValueType());
3869         return DAG.getSetCC(dl, VT, N0, ConstMinusOne, ISD::SETGT);
3870       }
3871     }
3872   }
3873 
3874   // Back to non-vector simplifications.
3875   // TODO: Can we do these for vector splats?
3876   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
3877     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3878     const APInt &C1 = N1C->getAPIntValue();
3879     EVT ShValTy = N0.getValueType();
3880 
3881     // Fold bit comparisons when we can.
3882     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3883         (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
3884         N0.getOpcode() == ISD::AND) {
3885       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3886         EVT ShiftTy =
3887             getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
3888         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
3889           // Perform the xform if the AND RHS is a single bit.
3890           unsigned ShCt = AndRHS->getAPIntValue().logBase2();
3891           if (AndRHS->getAPIntValue().isPowerOf2() &&
3892               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
3893             return DAG.getNode(ISD::TRUNCATE, dl, VT,
3894                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
3895                                            DAG.getConstant(ShCt, dl, ShiftTy)));
3896           }
3897         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
3898           // (X & 8) == 8  -->  (X & 8) >> 3
3899           // Perform the xform if C1 is a single bit.
3900           unsigned ShCt = C1.logBase2();
3901           if (C1.isPowerOf2() &&
3902               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
3903             return DAG.getNode(ISD::TRUNCATE, dl, VT,
3904                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
3905                                            DAG.getConstant(ShCt, dl, ShiftTy)));
3906           }
3907         }
3908       }
3909     }
3910 
3911     if (C1.getMinSignedBits() <= 64 &&
3912         !isLegalICmpImmediate(C1.getSExtValue())) {
3913       EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
3914       // (X & -256) == 256 -> (X >> 8) == 1
3915       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3916           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
3917         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3918           const APInt &AndRHSC = AndRHS->getAPIntValue();
3919           if ((-AndRHSC).isPowerOf2() && (AndRHSC & C1) == C1) {
3920             unsigned ShiftBits = AndRHSC.countTrailingZeros();
3921             if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
3922               SDValue Shift =
3923                 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0),
3924                             DAG.getConstant(ShiftBits, dl, ShiftTy));
3925               SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy);
3926               return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
3927             }
3928           }
3929         }
3930       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
3931                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
3932         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
3933         // X <  0x100000000 -> (X >> 32) <  1
3934         // X >= 0x100000000 -> (X >> 32) >= 1
3935         // X <= 0x0ffffffff -> (X >> 32) <  1
3936         // X >  0x0ffffffff -> (X >> 32) >= 1
3937         unsigned ShiftBits;
3938         APInt NewC = C1;
3939         ISD::CondCode NewCond = Cond;
3940         if (AdjOne) {
3941           ShiftBits = C1.countTrailingOnes();
3942           NewC = NewC + 1;
3943           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3944         } else {
3945           ShiftBits = C1.countTrailingZeros();
3946         }
3947         NewC.lshrInPlace(ShiftBits);
3948         if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
3949             isLegalICmpImmediate(NewC.getSExtValue()) &&
3950             !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
3951           SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0,
3952                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
3953           SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
3954           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
3955         }
3956       }
3957     }
3958   }
3959 
3960   if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) {
3961     auto *CFP = cast<ConstantFPSDNode>(N1);
3962     assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
3963 
3964     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
3965     // constant if knowing that the operand is non-nan is enough.  We prefer to
3966     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
3967     // materialize 0.0.
3968     if (Cond == ISD::SETO || Cond == ISD::SETUO)
3969       return DAG.getSetCC(dl, VT, N0, N0, Cond);
3970 
3971     // setcc (fneg x), C -> setcc swap(pred) x, -C
3972     if (N0.getOpcode() == ISD::FNEG) {
3973       ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
3974       if (DCI.isBeforeLegalizeOps() ||
3975           isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
3976         SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
3977         return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
3978       }
3979     }
3980 
3981     // If the condition is not legal, see if we can find an equivalent one
3982     // which is legal.
3983     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
3984       // If the comparison was an awkward floating-point == or != and one of
3985       // the comparison operands is infinity or negative infinity, convert the
3986       // condition to a less-awkward <= or >=.
3987       if (CFP->getValueAPF().isInfinity()) {
3988         bool IsNegInf = CFP->getValueAPF().isNegative();
3989         ISD::CondCode NewCond = ISD::SETCC_INVALID;
3990         switch (Cond) {
3991         case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
3992         case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
3993         case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
3994         case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
3995         default: break;
3996         }
3997         if (NewCond != ISD::SETCC_INVALID &&
3998             isCondCodeLegal(NewCond, N0.getSimpleValueType()))
3999           return DAG.getSetCC(dl, VT, N0, N1, NewCond);
4000       }
4001     }
4002   }
4003 
4004   if (N0 == N1) {
4005     // The sext(setcc()) => setcc() optimization relies on the appropriate
4006     // constant being emitted.
4007     assert(!N0.getValueType().isInteger() &&
4008            "Integer types should be handled by FoldSetCC");
4009 
4010     bool EqTrue = ISD::isTrueWhenEqual(Cond);
4011     unsigned UOF = ISD::getUnorderedFlavor(Cond);
4012     if (UOF == 2) // FP operators that are undefined on NaNs.
4013       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
4014     if (UOF == unsigned(EqTrue))
4015       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
4016     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
4017     // if it is not already.
4018     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
4019     if (NewCond != Cond &&
4020         (DCI.isBeforeLegalizeOps() ||
4021                             isCondCodeLegal(NewCond, N0.getSimpleValueType())))
4022       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
4023   }
4024 
4025   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4026       N0.getValueType().isInteger()) {
4027     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
4028         N0.getOpcode() == ISD::XOR) {
4029       // Simplify (X+Y) == (X+Z) -->  Y == Z
4030       if (N0.getOpcode() == N1.getOpcode()) {
4031         if (N0.getOperand(0) == N1.getOperand(0))
4032           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
4033         if (N0.getOperand(1) == N1.getOperand(1))
4034           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
4035         if (isCommutativeBinOp(N0.getOpcode())) {
4036           // If X op Y == Y op X, try other combinations.
4037           if (N0.getOperand(0) == N1.getOperand(1))
4038             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
4039                                 Cond);
4040           if (N0.getOperand(1) == N1.getOperand(0))
4041             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
4042                                 Cond);
4043         }
4044       }
4045 
4046       // If RHS is a legal immediate value for a compare instruction, we need
4047       // to be careful about increasing register pressure needlessly.
4048       bool LegalRHSImm = false;
4049 
4050       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
4051         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4052           // Turn (X+C1) == C2 --> X == C2-C1
4053           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
4054             return DAG.getSetCC(dl, VT, N0.getOperand(0),
4055                                 DAG.getConstant(RHSC->getAPIntValue()-
4056                                                 LHSR->getAPIntValue(),
4057                                 dl, N0.getValueType()), Cond);
4058           }
4059 
4060           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
4061           if (N0.getOpcode() == ISD::XOR)
4062             // If we know that all of the inverted bits are zero, don't bother
4063             // performing the inversion.
4064             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
4065               return
4066                 DAG.getSetCC(dl, VT, N0.getOperand(0),
4067                              DAG.getConstant(LHSR->getAPIntValue() ^
4068                                                RHSC->getAPIntValue(),
4069                                              dl, N0.getValueType()),
4070                              Cond);
4071         }
4072 
4073         // Turn (C1-X) == C2 --> X == C1-C2
4074         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
4075           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
4076             return
4077               DAG.getSetCC(dl, VT, N0.getOperand(1),
4078                            DAG.getConstant(SUBC->getAPIntValue() -
4079                                              RHSC->getAPIntValue(),
4080                                            dl, N0.getValueType()),
4081                            Cond);
4082           }
4083         }
4084 
4085         // Could RHSC fold directly into a compare?
4086         if (RHSC->getValueType(0).getSizeInBits() <= 64)
4087           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
4088       }
4089 
4090       // (X+Y) == X --> Y == 0 and similar folds.
4091       // Don't do this if X is an immediate that can fold into a cmp
4092       // instruction and X+Y has other uses. It could be an induction variable
4093       // chain, and the transform would increase register pressure.
4094       if (!LegalRHSImm || N0.hasOneUse())
4095         if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
4096           return V;
4097     }
4098 
4099     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
4100         N1.getOpcode() == ISD::XOR)
4101       if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
4102         return V;
4103 
4104     if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
4105       return V;
4106   }
4107 
4108   // Fold remainder of division by a constant.
4109   if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
4110       N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4111     AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4112 
4113     // When division is cheap or optimizing for minimum size,
4114     // fall through to DIVREM creation by skipping this fold.
4115     if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttribute(Attribute::MinSize)) {
4116       if (N0.getOpcode() == ISD::UREM) {
4117         if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
4118           return Folded;
4119       } else if (N0.getOpcode() == ISD::SREM) {
4120         if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
4121           return Folded;
4122       }
4123     }
4124   }
4125 
4126   // Fold away ALL boolean setcc's.
4127   if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
4128     SDValue Temp;
4129     switch (Cond) {
4130     default: llvm_unreachable("Unknown integer setcc!");
4131     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
4132       Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
4133       N0 = DAG.getNOT(dl, Temp, OpVT);
4134       if (!DCI.isCalledByLegalizer())
4135         DCI.AddToWorklist(Temp.getNode());
4136       break;
4137     case ISD::SETNE:  // X != Y   -->  (X^Y)
4138       N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
4139       break;
4140     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
4141     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
4142       Temp = DAG.getNOT(dl, N0, OpVT);
4143       N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
4144       if (!DCI.isCalledByLegalizer())
4145         DCI.AddToWorklist(Temp.getNode());
4146       break;
4147     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
4148     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
4149       Temp = DAG.getNOT(dl, N1, OpVT);
4150       N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
4151       if (!DCI.isCalledByLegalizer())
4152         DCI.AddToWorklist(Temp.getNode());
4153       break;
4154     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
4155     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
4156       Temp = DAG.getNOT(dl, N0, OpVT);
4157       N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
4158       if (!DCI.isCalledByLegalizer())
4159         DCI.AddToWorklist(Temp.getNode());
4160       break;
4161     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
4162     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
4163       Temp = DAG.getNOT(dl, N1, OpVT);
4164       N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
4165       break;
4166     }
4167     if (VT.getScalarType() != MVT::i1) {
4168       if (!DCI.isCalledByLegalizer())
4169         DCI.AddToWorklist(N0.getNode());
4170       // FIXME: If running after legalize, we probably can't do this.
4171       ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT));
4172       N0 = DAG.getNode(ExtendCode, dl, VT, N0);
4173     }
4174     return N0;
4175   }
4176 
4177   // Could not fold it.
4178   return SDValue();
4179 }
4180 
4181 /// Returns true (and the GlobalValue and the offset) if the node is a
4182 /// GlobalAddress + offset.
4183 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA,
4184                                     int64_t &Offset) const {
4185 
4186   SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
4187 
4188   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
4189     GA = GASD->getGlobal();
4190     Offset += GASD->getOffset();
4191     return true;
4192   }
4193 
4194   if (N->getOpcode() == ISD::ADD) {
4195     SDValue N1 = N->getOperand(0);
4196     SDValue N2 = N->getOperand(1);
4197     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
4198       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
4199         Offset += V->getSExtValue();
4200         return true;
4201       }
4202     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
4203       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
4204         Offset += V->getSExtValue();
4205         return true;
4206       }
4207     }
4208   }
4209 
4210   return false;
4211 }
4212 
4213 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
4214                                           DAGCombinerInfo &DCI) const {
4215   // Default implementation: no optimization.
4216   return SDValue();
4217 }
4218 
4219 //===----------------------------------------------------------------------===//
4220 //  Inline Assembler Implementation Methods
4221 //===----------------------------------------------------------------------===//
4222 
4223 TargetLowering::ConstraintType
4224 TargetLowering::getConstraintType(StringRef Constraint) const {
4225   unsigned S = Constraint.size();
4226 
4227   if (S == 1) {
4228     switch (Constraint[0]) {
4229     default: break;
4230     case 'r':
4231       return C_RegisterClass;
4232     case 'm': // memory
4233     case 'o': // offsetable
4234     case 'V': // not offsetable
4235       return C_Memory;
4236     case 'n': // Simple Integer
4237     case 'E': // Floating Point Constant
4238     case 'F': // Floating Point Constant
4239       return C_Immediate;
4240     case 'i': // Simple Integer or Relocatable Constant
4241     case 's': // Relocatable Constant
4242     case 'p': // Address.
4243     case 'X': // Allow ANY value.
4244     case 'I': // Target registers.
4245     case 'J':
4246     case 'K':
4247     case 'L':
4248     case 'M':
4249     case 'N':
4250     case 'O':
4251     case 'P':
4252     case '<':
4253     case '>':
4254       return C_Other;
4255     }
4256   }
4257 
4258   if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
4259     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
4260       return C_Memory;
4261     return C_Register;
4262   }
4263   return C_Unknown;
4264 }
4265 
4266 /// Try to replace an X constraint, which matches anything, with another that
4267 /// has more specific requirements based on the type of the corresponding
4268 /// operand.
4269 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4270   if (ConstraintVT.isInteger())
4271     return "r";
4272   if (ConstraintVT.isFloatingPoint())
4273     return "f"; // works for many targets
4274   return nullptr;
4275 }
4276 
4277 SDValue TargetLowering::LowerAsmOutputForConstraint(
4278     SDValue &Chain, SDValue &Flag, SDLoc DL, const AsmOperandInfo &OpInfo,
4279     SelectionDAG &DAG) const {
4280   return SDValue();
4281 }
4282 
4283 /// Lower the specified operand into the Ops vector.
4284 /// If it is invalid, don't add anything to Ops.
4285 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
4286                                                   std::string &Constraint,
4287                                                   std::vector<SDValue> &Ops,
4288                                                   SelectionDAG &DAG) const {
4289 
4290   if (Constraint.length() > 1) return;
4291 
4292   char ConstraintLetter = Constraint[0];
4293   switch (ConstraintLetter) {
4294   default: break;
4295   case 'X':     // Allows any operand; labels (basic block) use this.
4296     if (Op.getOpcode() == ISD::BasicBlock ||
4297         Op.getOpcode() == ISD::TargetBlockAddress) {
4298       Ops.push_back(Op);
4299       return;
4300     }
4301     LLVM_FALLTHROUGH;
4302   case 'i':    // Simple Integer or Relocatable Constant
4303   case 'n':    // Simple Integer
4304   case 's': {  // Relocatable Constant
4305 
4306     GlobalAddressSDNode *GA;
4307     ConstantSDNode *C;
4308     BlockAddressSDNode *BA;
4309     uint64_t Offset = 0;
4310 
4311     // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
4312     // etc., since getelementpointer is variadic. We can't use
4313     // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
4314     // while in this case the GA may be furthest from the root node which is
4315     // likely an ISD::ADD.
4316     while (1) {
4317       if ((GA = dyn_cast<GlobalAddressSDNode>(Op)) && ConstraintLetter != 'n') {
4318         Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
4319                                                  GA->getValueType(0),
4320                                                  Offset + GA->getOffset()));
4321         return;
4322       } else if ((C = dyn_cast<ConstantSDNode>(Op)) &&
4323                  ConstraintLetter != 's') {
4324         // gcc prints these as sign extended.  Sign extend value to 64 bits
4325         // now; without this it would get ZExt'd later in
4326         // ScheduleDAGSDNodes::EmitNode, which is very generic.
4327         bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
4328         BooleanContent BCont = getBooleanContents(MVT::i64);
4329         ISD::NodeType ExtOpc = IsBool ? getExtendForContent(BCont)
4330                                       : ISD::SIGN_EXTEND;
4331         int64_t ExtVal = ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue()
4332                                                     : C->getSExtValue();
4333         Ops.push_back(DAG.getTargetConstant(Offset + ExtVal,
4334                                             SDLoc(C), MVT::i64));
4335         return;
4336       } else if ((BA = dyn_cast<BlockAddressSDNode>(Op)) &&
4337                  ConstraintLetter != 'n') {
4338         Ops.push_back(DAG.getTargetBlockAddress(
4339             BA->getBlockAddress(), BA->getValueType(0),
4340             Offset + BA->getOffset(), BA->getTargetFlags()));
4341         return;
4342       } else {
4343         const unsigned OpCode = Op.getOpcode();
4344         if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
4345           if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
4346             Op = Op.getOperand(1);
4347           // Subtraction is not commutative.
4348           else if (OpCode == ISD::ADD &&
4349                    (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
4350             Op = Op.getOperand(0);
4351           else
4352             return;
4353           Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
4354           continue;
4355         }
4356       }
4357       return;
4358     }
4359     break;
4360   }
4361   }
4362 }
4363 
4364 std::pair<unsigned, const TargetRegisterClass *>
4365 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
4366                                              StringRef Constraint,
4367                                              MVT VT) const {
4368   if (Constraint.empty() || Constraint[0] != '{')
4369     return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
4370   assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
4371 
4372   // Remove the braces from around the name.
4373   StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
4374 
4375   std::pair<unsigned, const TargetRegisterClass *> R =
4376       std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
4377 
4378   // Figure out which register class contains this reg.
4379   for (const TargetRegisterClass *RC : RI->regclasses()) {
4380     // If none of the value types for this register class are valid, we
4381     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
4382     if (!isLegalRC(*RI, *RC))
4383       continue;
4384 
4385     for (TargetRegisterClass::iterator I = RC->begin(), E = RC->end();
4386          I != E; ++I) {
4387       if (RegName.equals_lower(RI->getRegAsmName(*I))) {
4388         std::pair<unsigned, const TargetRegisterClass *> S =
4389             std::make_pair(*I, RC);
4390 
4391         // If this register class has the requested value type, return it,
4392         // otherwise keep searching and return the first class found
4393         // if no other is found which explicitly has the requested type.
4394         if (RI->isTypeLegalForClass(*RC, VT))
4395           return S;
4396         if (!R.second)
4397           R = S;
4398       }
4399     }
4400   }
4401 
4402   return R;
4403 }
4404 
4405 //===----------------------------------------------------------------------===//
4406 // Constraint Selection.
4407 
4408 /// Return true of this is an input operand that is a matching constraint like
4409 /// "4".
4410 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
4411   assert(!ConstraintCode.empty() && "No known constraint!");
4412   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
4413 }
4414 
4415 /// If this is an input matching constraint, this method returns the output
4416 /// operand it matches.
4417 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
4418   assert(!ConstraintCode.empty() && "No known constraint!");
4419   return atoi(ConstraintCode.c_str());
4420 }
4421 
4422 /// Split up the constraint string from the inline assembly value into the
4423 /// specific constraints and their prefixes, and also tie in the associated
4424 /// operand values.
4425 /// If this returns an empty vector, and if the constraint string itself
4426 /// isn't empty, there was an error parsing.
4427 TargetLowering::AsmOperandInfoVector
4428 TargetLowering::ParseConstraints(const DataLayout &DL,
4429                                  const TargetRegisterInfo *TRI,
4430                                  const CallBase &Call) const {
4431   /// Information about all of the constraints.
4432   AsmOperandInfoVector ConstraintOperands;
4433   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
4434   unsigned maCount = 0; // Largest number of multiple alternative constraints.
4435 
4436   // Do a prepass over the constraints, canonicalizing them, and building up the
4437   // ConstraintOperands list.
4438   unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4439   unsigned ResNo = 0; // ResNo - The result number of the next output.
4440 
4441   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
4442     ConstraintOperands.emplace_back(std::move(CI));
4443     AsmOperandInfo &OpInfo = ConstraintOperands.back();
4444 
4445     // Update multiple alternative constraint count.
4446     if (OpInfo.multipleAlternatives.size() > maCount)
4447       maCount = OpInfo.multipleAlternatives.size();
4448 
4449     OpInfo.ConstraintVT = MVT::Other;
4450 
4451     // Compute the value type for each operand.
4452     switch (OpInfo.Type) {
4453     case InlineAsm::isOutput:
4454       // Indirect outputs just consume an argument.
4455       if (OpInfo.isIndirect) {
4456         OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
4457         break;
4458       }
4459 
4460       // The return value of the call is this value.  As such, there is no
4461       // corresponding argument.
4462       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
4463       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
4464         OpInfo.ConstraintVT =
4465             getSimpleValueType(DL, STy->getElementType(ResNo));
4466       } else {
4467         assert(ResNo == 0 && "Asm only has one result!");
4468         OpInfo.ConstraintVT = getSimpleValueType(DL, Call.getType());
4469       }
4470       ++ResNo;
4471       break;
4472     case InlineAsm::isInput:
4473       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo++);
4474       break;
4475     case InlineAsm::isClobber:
4476       // Nothing to do.
4477       break;
4478     }
4479 
4480     if (OpInfo.CallOperandVal) {
4481       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
4482       if (OpInfo.isIndirect) {
4483         llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
4484         if (!PtrTy)
4485           report_fatal_error("Indirect operand for inline asm not a pointer!");
4486         OpTy = PtrTy->getElementType();
4487       }
4488 
4489       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
4490       if (StructType *STy = dyn_cast<StructType>(OpTy))
4491         if (STy->getNumElements() == 1)
4492           OpTy = STy->getElementType(0);
4493 
4494       // If OpTy is not a single value, it may be a struct/union that we
4495       // can tile with integers.
4496       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4497         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
4498         switch (BitSize) {
4499         default: break;
4500         case 1:
4501         case 8:
4502         case 16:
4503         case 32:
4504         case 64:
4505         case 128:
4506           OpInfo.ConstraintVT =
4507               MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
4508           break;
4509         }
4510       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
4511         unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
4512         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
4513       } else {
4514         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
4515       }
4516     }
4517   }
4518 
4519   // If we have multiple alternative constraints, select the best alternative.
4520   if (!ConstraintOperands.empty()) {
4521     if (maCount) {
4522       unsigned bestMAIndex = 0;
4523       int bestWeight = -1;
4524       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
4525       int weight = -1;
4526       unsigned maIndex;
4527       // Compute the sums of the weights for each alternative, keeping track
4528       // of the best (highest weight) one so far.
4529       for (maIndex = 0; maIndex < maCount; ++maIndex) {
4530         int weightSum = 0;
4531         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
4532              cIndex != eIndex; ++cIndex) {
4533           AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
4534           if (OpInfo.Type == InlineAsm::isClobber)
4535             continue;
4536 
4537           // If this is an output operand with a matching input operand,
4538           // look up the matching input. If their types mismatch, e.g. one
4539           // is an integer, the other is floating point, or their sizes are
4540           // different, flag it as an maCantMatch.
4541           if (OpInfo.hasMatchingInput()) {
4542             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4543             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
4544               if ((OpInfo.ConstraintVT.isInteger() !=
4545                    Input.ConstraintVT.isInteger()) ||
4546                   (OpInfo.ConstraintVT.getSizeInBits() !=
4547                    Input.ConstraintVT.getSizeInBits())) {
4548                 weightSum = -1; // Can't match.
4549                 break;
4550               }
4551             }
4552           }
4553           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
4554           if (weight == -1) {
4555             weightSum = -1;
4556             break;
4557           }
4558           weightSum += weight;
4559         }
4560         // Update best.
4561         if (weightSum > bestWeight) {
4562           bestWeight = weightSum;
4563           bestMAIndex = maIndex;
4564         }
4565       }
4566 
4567       // Now select chosen alternative in each constraint.
4568       for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
4569            cIndex != eIndex; ++cIndex) {
4570         AsmOperandInfo &cInfo = ConstraintOperands[cIndex];
4571         if (cInfo.Type == InlineAsm::isClobber)
4572           continue;
4573         cInfo.selectAlternative(bestMAIndex);
4574       }
4575     }
4576   }
4577 
4578   // Check and hook up tied operands, choose constraint code to use.
4579   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
4580        cIndex != eIndex; ++cIndex) {
4581     AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
4582 
4583     // If this is an output operand with a matching input operand, look up the
4584     // matching input. If their types mismatch, e.g. one is an integer, the
4585     // other is floating point, or their sizes are different, flag it as an
4586     // error.
4587     if (OpInfo.hasMatchingInput()) {
4588       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4589 
4590       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
4591         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
4592             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
4593                                          OpInfo.ConstraintVT);
4594         std::pair<unsigned, const TargetRegisterClass *> InputRC =
4595             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
4596                                          Input.ConstraintVT);
4597         if ((OpInfo.ConstraintVT.isInteger() !=
4598              Input.ConstraintVT.isInteger()) ||
4599             (MatchRC.second != InputRC.second)) {
4600           report_fatal_error("Unsupported asm: input constraint"
4601                              " with a matching output constraint of"
4602                              " incompatible type!");
4603         }
4604       }
4605     }
4606   }
4607 
4608   return ConstraintOperands;
4609 }
4610 
4611 /// Return an integer indicating how general CT is.
4612 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
4613   switch (CT) {
4614   case TargetLowering::C_Immediate:
4615   case TargetLowering::C_Other:
4616   case TargetLowering::C_Unknown:
4617     return 0;
4618   case TargetLowering::C_Register:
4619     return 1;
4620   case TargetLowering::C_RegisterClass:
4621     return 2;
4622   case TargetLowering::C_Memory:
4623     return 3;
4624   }
4625   llvm_unreachable("Invalid constraint type");
4626 }
4627 
4628 /// Examine constraint type and operand type and determine a weight value.
4629 /// This object must already have been set up with the operand type
4630 /// and the current alternative constraint selected.
4631 TargetLowering::ConstraintWeight
4632   TargetLowering::getMultipleConstraintMatchWeight(
4633     AsmOperandInfo &info, int maIndex) const {
4634   InlineAsm::ConstraintCodeVector *rCodes;
4635   if (maIndex >= (int)info.multipleAlternatives.size())
4636     rCodes = &info.Codes;
4637   else
4638     rCodes = &info.multipleAlternatives[maIndex].Codes;
4639   ConstraintWeight BestWeight = CW_Invalid;
4640 
4641   // Loop over the options, keeping track of the most general one.
4642   for (unsigned i = 0, e = rCodes->size(); i != e; ++i) {
4643     ConstraintWeight weight =
4644       getSingleConstraintMatchWeight(info, (*rCodes)[i].c_str());
4645     if (weight > BestWeight)
4646       BestWeight = weight;
4647   }
4648 
4649   return BestWeight;
4650 }
4651 
4652 /// Examine constraint type and operand type and determine a weight value.
4653 /// This object must already have been set up with the operand type
4654 /// and the current alternative constraint selected.
4655 TargetLowering::ConstraintWeight
4656   TargetLowering::getSingleConstraintMatchWeight(
4657     AsmOperandInfo &info, const char *constraint) const {
4658   ConstraintWeight weight = CW_Invalid;
4659   Value *CallOperandVal = info.CallOperandVal;
4660     // If we don't have a value, we can't do a match,
4661     // but allow it at the lowest weight.
4662   if (!CallOperandVal)
4663     return CW_Default;
4664   // Look at the constraint type.
4665   switch (*constraint) {
4666     case 'i': // immediate integer.
4667     case 'n': // immediate integer with a known value.
4668       if (isa<ConstantInt>(CallOperandVal))
4669         weight = CW_Constant;
4670       break;
4671     case 's': // non-explicit intregal immediate.
4672       if (isa<GlobalValue>(CallOperandVal))
4673         weight = CW_Constant;
4674       break;
4675     case 'E': // immediate float if host format.
4676     case 'F': // immediate float.
4677       if (isa<ConstantFP>(CallOperandVal))
4678         weight = CW_Constant;
4679       break;
4680     case '<': // memory operand with autodecrement.
4681     case '>': // memory operand with autoincrement.
4682     case 'm': // memory operand.
4683     case 'o': // offsettable memory operand
4684     case 'V': // non-offsettable memory operand
4685       weight = CW_Memory;
4686       break;
4687     case 'r': // general register.
4688     case 'g': // general register, memory operand or immediate integer.
4689               // note: Clang converts "g" to "imr".
4690       if (CallOperandVal->getType()->isIntegerTy())
4691         weight = CW_Register;
4692       break;
4693     case 'X': // any operand.
4694   default:
4695     weight = CW_Default;
4696     break;
4697   }
4698   return weight;
4699 }
4700 
4701 /// If there are multiple different constraints that we could pick for this
4702 /// operand (e.g. "imr") try to pick the 'best' one.
4703 /// This is somewhat tricky: constraints fall into four classes:
4704 ///    Other         -> immediates and magic values
4705 ///    Register      -> one specific register
4706 ///    RegisterClass -> a group of regs
4707 ///    Memory        -> memory
4708 /// Ideally, we would pick the most specific constraint possible: if we have
4709 /// something that fits into a register, we would pick it.  The problem here
4710 /// is that if we have something that could either be in a register or in
4711 /// memory that use of the register could cause selection of *other*
4712 /// operands to fail: they might only succeed if we pick memory.  Because of
4713 /// this the heuristic we use is:
4714 ///
4715 ///  1) If there is an 'other' constraint, and if the operand is valid for
4716 ///     that constraint, use it.  This makes us take advantage of 'i'
4717 ///     constraints when available.
4718 ///  2) Otherwise, pick the most general constraint present.  This prefers
4719 ///     'm' over 'r', for example.
4720 ///
4721 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
4722                              const TargetLowering &TLI,
4723                              SDValue Op, SelectionDAG *DAG) {
4724   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
4725   unsigned BestIdx = 0;
4726   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
4727   int BestGenerality = -1;
4728 
4729   // Loop over the options, keeping track of the most general one.
4730   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
4731     TargetLowering::ConstraintType CType =
4732       TLI.getConstraintType(OpInfo.Codes[i]);
4733 
4734     // Indirect 'other' or 'immediate' constraints are not allowed.
4735     if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
4736                                CType == TargetLowering::C_Register ||
4737                                CType == TargetLowering::C_RegisterClass))
4738       continue;
4739 
4740     // If this is an 'other' or 'immediate' constraint, see if the operand is
4741     // valid for it. For example, on X86 we might have an 'rI' constraint. If
4742     // the operand is an integer in the range [0..31] we want to use I (saving a
4743     // load of a register), otherwise we must use 'r'.
4744     if ((CType == TargetLowering::C_Other ||
4745          CType == TargetLowering::C_Immediate) && Op.getNode()) {
4746       assert(OpInfo.Codes[i].size() == 1 &&
4747              "Unhandled multi-letter 'other' constraint");
4748       std::vector<SDValue> ResultOps;
4749       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
4750                                        ResultOps, *DAG);
4751       if (!ResultOps.empty()) {
4752         BestType = CType;
4753         BestIdx = i;
4754         break;
4755       }
4756     }
4757 
4758     // Things with matching constraints can only be registers, per gcc
4759     // documentation.  This mainly affects "g" constraints.
4760     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
4761       continue;
4762 
4763     // This constraint letter is more general than the previous one, use it.
4764     int Generality = getConstraintGenerality(CType);
4765     if (Generality > BestGenerality) {
4766       BestType = CType;
4767       BestIdx = i;
4768       BestGenerality = Generality;
4769     }
4770   }
4771 
4772   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
4773   OpInfo.ConstraintType = BestType;
4774 }
4775 
4776 /// Determines the constraint code and constraint type to use for the specific
4777 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
4778 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
4779                                             SDValue Op,
4780                                             SelectionDAG *DAG) const {
4781   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
4782 
4783   // Single-letter constraints ('r') are very common.
4784   if (OpInfo.Codes.size() == 1) {
4785     OpInfo.ConstraintCode = OpInfo.Codes[0];
4786     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
4787   } else {
4788     ChooseConstraint(OpInfo, *this, Op, DAG);
4789   }
4790 
4791   // 'X' matches anything.
4792   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
4793     // Labels and constants are handled elsewhere ('X' is the only thing
4794     // that matches labels).  For Functions, the type here is the type of
4795     // the result, which is not what we want to look at; leave them alone.
4796     Value *v = OpInfo.CallOperandVal;
4797     if (isa<BasicBlock>(v) || isa<ConstantInt>(v) || isa<Function>(v)) {
4798       OpInfo.CallOperandVal = v;
4799       return;
4800     }
4801 
4802     if (Op.getNode() && Op.getOpcode() == ISD::TargetBlockAddress)
4803       return;
4804 
4805     // Otherwise, try to resolve it to something we know about by looking at
4806     // the actual operand type.
4807     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
4808       OpInfo.ConstraintCode = Repl;
4809       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
4810     }
4811   }
4812 }
4813 
4814 /// Given an exact SDIV by a constant, create a multiplication
4815 /// with the multiplicative inverse of the constant.
4816 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N,
4817                               const SDLoc &dl, SelectionDAG &DAG,
4818                               SmallVectorImpl<SDNode *> &Created) {
4819   SDValue Op0 = N->getOperand(0);
4820   SDValue Op1 = N->getOperand(1);
4821   EVT VT = N->getValueType(0);
4822   EVT SVT = VT.getScalarType();
4823   EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
4824   EVT ShSVT = ShVT.getScalarType();
4825 
4826   bool UseSRA = false;
4827   SmallVector<SDValue, 16> Shifts, Factors;
4828 
4829   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
4830     if (C->isNullValue())
4831       return false;
4832     APInt Divisor = C->getAPIntValue();
4833     unsigned Shift = Divisor.countTrailingZeros();
4834     if (Shift) {
4835       Divisor.ashrInPlace(Shift);
4836       UseSRA = true;
4837     }
4838     // Calculate the multiplicative inverse, using Newton's method.
4839     APInt t;
4840     APInt Factor = Divisor;
4841     while ((t = Divisor * Factor) != 1)
4842       Factor *= APInt(Divisor.getBitWidth(), 2) - t;
4843     Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
4844     Factors.push_back(DAG.getConstant(Factor, dl, SVT));
4845     return true;
4846   };
4847 
4848   // Collect all magic values from the build vector.
4849   if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
4850     return SDValue();
4851 
4852   SDValue Shift, Factor;
4853   if (VT.isVector()) {
4854     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
4855     Factor = DAG.getBuildVector(VT, dl, Factors);
4856   } else {
4857     Shift = Shifts[0];
4858     Factor = Factors[0];
4859   }
4860 
4861   SDValue Res = Op0;
4862 
4863   // Shift the value upfront if it is even, so the LSB is one.
4864   if (UseSRA) {
4865     // TODO: For UDIV use SRL instead of SRA.
4866     SDNodeFlags Flags;
4867     Flags.setExact(true);
4868     Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags);
4869     Created.push_back(Res.getNode());
4870   }
4871 
4872   return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
4873 }
4874 
4875 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
4876                               SelectionDAG &DAG,
4877                               SmallVectorImpl<SDNode *> &Created) const {
4878   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4879   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4880   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
4881     return SDValue(N, 0); // Lower SDIV as SDIV
4882   return SDValue();
4883 }
4884 
4885 /// Given an ISD::SDIV node expressing a divide by constant,
4886 /// return a DAG expression to select that will generate the same value by
4887 /// multiplying by a magic number.
4888 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
4889 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
4890                                   bool IsAfterLegalization,
4891                                   SmallVectorImpl<SDNode *> &Created) const {
4892   SDLoc dl(N);
4893   EVT VT = N->getValueType(0);
4894   EVT SVT = VT.getScalarType();
4895   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
4896   EVT ShSVT = ShVT.getScalarType();
4897   unsigned EltBits = VT.getScalarSizeInBits();
4898 
4899   // Check to see if we can do this.
4900   // FIXME: We should be more aggressive here.
4901   if (!isTypeLegal(VT))
4902     return SDValue();
4903 
4904   // If the sdiv has an 'exact' bit we can use a simpler lowering.
4905   if (N->getFlags().hasExact())
4906     return BuildExactSDIV(*this, N, dl, DAG, Created);
4907 
4908   SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
4909 
4910   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
4911     if (C->isNullValue())
4912       return false;
4913 
4914     const APInt &Divisor = C->getAPIntValue();
4915     APInt::ms magics = Divisor.magic();
4916     int NumeratorFactor = 0;
4917     int ShiftMask = -1;
4918 
4919     if (Divisor.isOneValue() || Divisor.isAllOnesValue()) {
4920       // If d is +1/-1, we just multiply the numerator by +1/-1.
4921       NumeratorFactor = Divisor.getSExtValue();
4922       magics.m = 0;
4923       magics.s = 0;
4924       ShiftMask = 0;
4925     } else if (Divisor.isStrictlyPositive() && magics.m.isNegative()) {
4926       // If d > 0 and m < 0, add the numerator.
4927       NumeratorFactor = 1;
4928     } else if (Divisor.isNegative() && magics.m.isStrictlyPositive()) {
4929       // If d < 0 and m > 0, subtract the numerator.
4930       NumeratorFactor = -1;
4931     }
4932 
4933     MagicFactors.push_back(DAG.getConstant(magics.m, dl, SVT));
4934     Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT));
4935     Shifts.push_back(DAG.getConstant(magics.s, dl, ShSVT));
4936     ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT));
4937     return true;
4938   };
4939 
4940   SDValue N0 = N->getOperand(0);
4941   SDValue N1 = N->getOperand(1);
4942 
4943   // Collect the shifts / magic values from each element.
4944   if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern))
4945     return SDValue();
4946 
4947   SDValue MagicFactor, Factor, Shift, ShiftMask;
4948   if (VT.isVector()) {
4949     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
4950     Factor = DAG.getBuildVector(VT, dl, Factors);
4951     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
4952     ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
4953   } else {
4954     MagicFactor = MagicFactors[0];
4955     Factor = Factors[0];
4956     Shift = Shifts[0];
4957     ShiftMask = ShiftMasks[0];
4958   }
4959 
4960   // Multiply the numerator (operand 0) by the magic value.
4961   // FIXME: We should support doing a MUL in a wider type.
4962   SDValue Q;
4963   if (IsAfterLegalization ? isOperationLegal(ISD::MULHS, VT)
4964                           : isOperationLegalOrCustom(ISD::MULHS, VT))
4965     Q = DAG.getNode(ISD::MULHS, dl, VT, N0, MagicFactor);
4966   else if (IsAfterLegalization ? isOperationLegal(ISD::SMUL_LOHI, VT)
4967                                : isOperationLegalOrCustom(ISD::SMUL_LOHI, VT)) {
4968     SDValue LoHi =
4969         DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), N0, MagicFactor);
4970     Q = SDValue(LoHi.getNode(), 1);
4971   } else
4972     return SDValue(); // No mulhs or equivalent.
4973   Created.push_back(Q.getNode());
4974 
4975   // (Optionally) Add/subtract the numerator using Factor.
4976   Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
4977   Created.push_back(Factor.getNode());
4978   Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
4979   Created.push_back(Q.getNode());
4980 
4981   // Shift right algebraic by shift value.
4982   Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
4983   Created.push_back(Q.getNode());
4984 
4985   // Extract the sign bit, mask it and add it to the quotient.
4986   SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
4987   SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
4988   Created.push_back(T.getNode());
4989   T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
4990   Created.push_back(T.getNode());
4991   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
4992 }
4993 
4994 /// Given an ISD::UDIV node expressing a divide by constant,
4995 /// return a DAG expression to select that will generate the same value by
4996 /// multiplying by a magic number.
4997 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
4998 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
4999                                   bool IsAfterLegalization,
5000                                   SmallVectorImpl<SDNode *> &Created) const {
5001   SDLoc dl(N);
5002   EVT VT = N->getValueType(0);
5003   EVT SVT = VT.getScalarType();
5004   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5005   EVT ShSVT = ShVT.getScalarType();
5006   unsigned EltBits = VT.getScalarSizeInBits();
5007 
5008   // Check to see if we can do this.
5009   // FIXME: We should be more aggressive here.
5010   if (!isTypeLegal(VT))
5011     return SDValue();
5012 
5013   bool UseNPQ = false;
5014   SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
5015 
5016   auto BuildUDIVPattern = [&](ConstantSDNode *C) {
5017     if (C->isNullValue())
5018       return false;
5019     // FIXME: We should use a narrower constant when the upper
5020     // bits are known to be zero.
5021     APInt Divisor = C->getAPIntValue();
5022     APInt::mu magics = Divisor.magicu();
5023     unsigned PreShift = 0, PostShift = 0;
5024 
5025     // If the divisor is even, we can avoid using the expensive fixup by
5026     // shifting the divided value upfront.
5027     if (magics.a != 0 && !Divisor[0]) {
5028       PreShift = Divisor.countTrailingZeros();
5029       // Get magic number for the shifted divisor.
5030       magics = Divisor.lshr(PreShift).magicu(PreShift);
5031       assert(magics.a == 0 && "Should use cheap fixup now");
5032     }
5033 
5034     APInt Magic = magics.m;
5035 
5036     unsigned SelNPQ;
5037     if (magics.a == 0 || Divisor.isOneValue()) {
5038       assert(magics.s < Divisor.getBitWidth() &&
5039              "We shouldn't generate an undefined shift!");
5040       PostShift = magics.s;
5041       SelNPQ = false;
5042     } else {
5043       PostShift = magics.s - 1;
5044       SelNPQ = true;
5045     }
5046 
5047     PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT));
5048     MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT));
5049     NPQFactors.push_back(
5050         DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
5051                                : APInt::getNullValue(EltBits),
5052                         dl, SVT));
5053     PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT));
5054     UseNPQ |= SelNPQ;
5055     return true;
5056   };
5057 
5058   SDValue N0 = N->getOperand(0);
5059   SDValue N1 = N->getOperand(1);
5060 
5061   // Collect the shifts/magic values from each element.
5062   if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern))
5063     return SDValue();
5064 
5065   SDValue PreShift, PostShift, MagicFactor, NPQFactor;
5066   if (VT.isVector()) {
5067     PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
5068     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
5069     NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
5070     PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
5071   } else {
5072     PreShift = PreShifts[0];
5073     MagicFactor = MagicFactors[0];
5074     PostShift = PostShifts[0];
5075   }
5076 
5077   SDValue Q = N0;
5078   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
5079   Created.push_back(Q.getNode());
5080 
5081   // FIXME: We should support doing a MUL in a wider type.
5082   auto GetMULHU = [&](SDValue X, SDValue Y) {
5083     if (IsAfterLegalization ? isOperationLegal(ISD::MULHU, VT)
5084                             : isOperationLegalOrCustom(ISD::MULHU, VT))
5085       return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
5086     if (IsAfterLegalization ? isOperationLegal(ISD::UMUL_LOHI, VT)
5087                             : isOperationLegalOrCustom(ISD::UMUL_LOHI, VT)) {
5088       SDValue LoHi =
5089           DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
5090       return SDValue(LoHi.getNode(), 1);
5091     }
5092     return SDValue(); // No mulhu or equivalent
5093   };
5094 
5095   // Multiply the numerator (operand 0) by the magic value.
5096   Q = GetMULHU(Q, MagicFactor);
5097   if (!Q)
5098     return SDValue();
5099 
5100   Created.push_back(Q.getNode());
5101 
5102   if (UseNPQ) {
5103     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
5104     Created.push_back(NPQ.getNode());
5105 
5106     // For vectors we might have a mix of non-NPQ/NPQ paths, so use
5107     // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
5108     if (VT.isVector())
5109       NPQ = GetMULHU(NPQ, NPQFactor);
5110     else
5111       NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
5112 
5113     Created.push_back(NPQ.getNode());
5114 
5115     Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
5116     Created.push_back(Q.getNode());
5117   }
5118 
5119   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
5120   Created.push_back(Q.getNode());
5121 
5122   SDValue One = DAG.getConstant(1, dl, VT);
5123   SDValue IsOne = DAG.getSetCC(dl, VT, N1, One, ISD::SETEQ);
5124   return DAG.getSelect(dl, VT, IsOne, N0, Q);
5125 }
5126 
5127 /// If all values in Values that *don't* match the predicate are same 'splat'
5128 /// value, then replace all values with that splat value.
5129 /// Else, if AlternativeReplacement was provided, then replace all values that
5130 /// do match predicate with AlternativeReplacement value.
5131 static void
5132 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values,
5133                           std::function<bool(SDValue)> Predicate,
5134                           SDValue AlternativeReplacement = SDValue()) {
5135   SDValue Replacement;
5136   // Is there a value for which the Predicate does *NOT* match? What is it?
5137   auto SplatValue = llvm::find_if_not(Values, Predicate);
5138   if (SplatValue != Values.end()) {
5139     // Does Values consist only of SplatValue's and values matching Predicate?
5140     if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
5141           return Value == *SplatValue || Predicate(Value);
5142         })) // Then we shall replace values matching predicate with SplatValue.
5143       Replacement = *SplatValue;
5144   }
5145   if (!Replacement) {
5146     // Oops, we did not find the "baseline" splat value.
5147     if (!AlternativeReplacement)
5148       return; // Nothing to do.
5149     // Let's replace with provided value then.
5150     Replacement = AlternativeReplacement;
5151   }
5152   std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
5153 }
5154 
5155 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
5156 /// where the divisor is constant and the comparison target is zero,
5157 /// return a DAG expression that will generate the same comparison result
5158 /// using only multiplications, additions and shifts/rotations.
5159 /// Ref: "Hacker's Delight" 10-17.
5160 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
5161                                         SDValue CompTargetNode,
5162                                         ISD::CondCode Cond,
5163                                         DAGCombinerInfo &DCI,
5164                                         const SDLoc &DL) const {
5165   SmallVector<SDNode *, 5> Built;
5166   if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
5167                                          DCI, DL, Built)) {
5168     for (SDNode *N : Built)
5169       DCI.AddToWorklist(N);
5170     return Folded;
5171   }
5172 
5173   return SDValue();
5174 }
5175 
5176 SDValue
5177 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
5178                                   SDValue CompTargetNode, ISD::CondCode Cond,
5179                                   DAGCombinerInfo &DCI, const SDLoc &DL,
5180                                   SmallVectorImpl<SDNode *> &Created) const {
5181   // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q)
5182   // - D must be constant, with D = D0 * 2^K where D0 is odd
5183   // - P is the multiplicative inverse of D0 modulo 2^W
5184   // - Q = floor(((2^W) - 1) / D)
5185   // where W is the width of the common type of N and D.
5186   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5187          "Only applicable for (in)equality comparisons.");
5188 
5189   SelectionDAG &DAG = DCI.DAG;
5190 
5191   EVT VT = REMNode.getValueType();
5192   EVT SVT = VT.getScalarType();
5193   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5194   EVT ShSVT = ShVT.getScalarType();
5195 
5196   // If MUL is unavailable, we cannot proceed in any case.
5197   if (!isOperationLegalOrCustom(ISD::MUL, VT))
5198     return SDValue();
5199 
5200   bool ComparingWithAllZeros = true;
5201   bool AllComparisonsWithNonZerosAreTautological = true;
5202   bool HadTautologicalLanes = false;
5203   bool AllLanesAreTautological = true;
5204   bool HadEvenDivisor = false;
5205   bool AllDivisorsArePowerOfTwo = true;
5206   bool HadTautologicalInvertedLanes = false;
5207   SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts;
5208 
5209   auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
5210     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
5211     if (CDiv->isNullValue())
5212       return false;
5213 
5214     const APInt &D = CDiv->getAPIntValue();
5215     const APInt &Cmp = CCmp->getAPIntValue();
5216 
5217     ComparingWithAllZeros &= Cmp.isNullValue();
5218 
5219     // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
5220     // if C2 is not less than C1, the comparison is always false.
5221     // But we will only be able to produce the comparison that will give the
5222     // opposive tautological answer. So this lane would need to be fixed up.
5223     bool TautologicalInvertedLane = D.ule(Cmp);
5224     HadTautologicalInvertedLanes |= TautologicalInvertedLane;
5225 
5226     // If all lanes are tautological (either all divisors are ones, or divisor
5227     // is not greater than the constant we are comparing with),
5228     // we will prefer to avoid the fold.
5229     bool TautologicalLane = D.isOneValue() || TautologicalInvertedLane;
5230     HadTautologicalLanes |= TautologicalLane;
5231     AllLanesAreTautological &= TautologicalLane;
5232 
5233     // If we are comparing with non-zero, we need'll need  to subtract said
5234     // comparison value from the LHS. But there is no point in doing that if
5235     // every lane where we are comparing with non-zero is tautological..
5236     if (!Cmp.isNullValue())
5237       AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
5238 
5239     // Decompose D into D0 * 2^K
5240     unsigned K = D.countTrailingZeros();
5241     assert((!D.isOneValue() || (K == 0)) && "For divisor '1' we won't rotate.");
5242     APInt D0 = D.lshr(K);
5243 
5244     // D is even if it has trailing zeros.
5245     HadEvenDivisor |= (K != 0);
5246     // D is a power-of-two if D0 is one.
5247     // If all divisors are power-of-two, we will prefer to avoid the fold.
5248     AllDivisorsArePowerOfTwo &= D0.isOneValue();
5249 
5250     // P = inv(D0, 2^W)
5251     // 2^W requires W + 1 bits, so we have to extend and then truncate.
5252     unsigned W = D.getBitWidth();
5253     APInt P = D0.zext(W + 1)
5254                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
5255                   .trunc(W);
5256     assert(!P.isNullValue() && "No multiplicative inverse!"); // unreachable
5257     assert((D0 * P).isOneValue() && "Multiplicative inverse sanity check.");
5258 
5259     // Q = floor((2^W - 1) u/ D)
5260     // R = ((2^W - 1) u% D)
5261     APInt Q, R;
5262     APInt::udivrem(APInt::getAllOnesValue(W), D, Q, R);
5263 
5264     // If we are comparing with zero, then that comparison constant is okay,
5265     // else it may need to be one less than that.
5266     if (Cmp.ugt(R))
5267       Q -= 1;
5268 
5269     assert(APInt::getAllOnesValue(ShSVT.getSizeInBits()).ugt(K) &&
5270            "We are expecting that K is always less than all-ones for ShSVT");
5271 
5272     // If the lane is tautological the result can be constant-folded.
5273     if (TautologicalLane) {
5274       // Set P and K amount to a bogus values so we can try to splat them.
5275       P = 0;
5276       K = -1;
5277       // And ensure that comparison constant is tautological,
5278       // it will always compare true/false.
5279       Q = -1;
5280     }
5281 
5282     PAmts.push_back(DAG.getConstant(P, DL, SVT));
5283     KAmts.push_back(
5284         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
5285     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
5286     return true;
5287   };
5288 
5289   SDValue N = REMNode.getOperand(0);
5290   SDValue D = REMNode.getOperand(1);
5291 
5292   // Collect the values from each element.
5293   if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
5294     return SDValue();
5295 
5296   // If all lanes are tautological, the result can be constant-folded.
5297   if (AllLanesAreTautological)
5298     return SDValue();
5299 
5300   // If this is a urem by a powers-of-two, avoid the fold since it can be
5301   // best implemented as a bit test.
5302   if (AllDivisorsArePowerOfTwo)
5303     return SDValue();
5304 
5305   SDValue PVal, KVal, QVal;
5306   if (VT.isVector()) {
5307     if (HadTautologicalLanes) {
5308       // Try to turn PAmts into a splat, since we don't care about the values
5309       // that are currently '0'. If we can't, just keep '0'`s.
5310       turnVectorIntoSplatVector(PAmts, isNullConstant);
5311       // Try to turn KAmts into a splat, since we don't care about the values
5312       // that are currently '-1'. If we can't, change them to '0'`s.
5313       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
5314                                 DAG.getConstant(0, DL, ShSVT));
5315     }
5316 
5317     PVal = DAG.getBuildVector(VT, DL, PAmts);
5318     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
5319     QVal = DAG.getBuildVector(VT, DL, QAmts);
5320   } else {
5321     PVal = PAmts[0];
5322     KVal = KAmts[0];
5323     QVal = QAmts[0];
5324   }
5325 
5326   if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
5327     if (!isOperationLegalOrCustom(ISD::SUB, VT))
5328       return SDValue(); // FIXME: Could/should use `ISD::ADD`?
5329     assert(CompTargetNode.getValueType() == N.getValueType() &&
5330            "Expecting that the types on LHS and RHS of comparisons match.");
5331     N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
5332   }
5333 
5334   // (mul N, P)
5335   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
5336   Created.push_back(Op0.getNode());
5337 
5338   // Rotate right only if any divisor was even. We avoid rotates for all-odd
5339   // divisors as a performance improvement, since rotating by 0 is a no-op.
5340   if (HadEvenDivisor) {
5341     // We need ROTR to do this.
5342     if (!isOperationLegalOrCustom(ISD::ROTR, VT))
5343       return SDValue();
5344     SDNodeFlags Flags;
5345     Flags.setExact(true);
5346     // UREM: (rotr (mul N, P), K)
5347     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal, Flags);
5348     Created.push_back(Op0.getNode());
5349   }
5350 
5351   // UREM: (setule/setugt (rotr (mul N, P), K), Q)
5352   SDValue NewCC =
5353       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
5354                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
5355   if (!HadTautologicalInvertedLanes)
5356     return NewCC;
5357 
5358   // If any lanes previously compared always-false, the NewCC will give
5359   // always-true result for them, so we need to fixup those lanes.
5360   // Or the other way around for inequality predicate.
5361   assert(VT.isVector() && "Can/should only get here for vectors.");
5362   Created.push_back(NewCC.getNode());
5363 
5364   // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
5365   // if C2 is not less than C1, the comparison is always false.
5366   // But we have produced the comparison that will give the
5367   // opposive tautological answer. So these lanes would need to be fixed up.
5368   SDValue TautologicalInvertedChannels =
5369       DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
5370   Created.push_back(TautologicalInvertedChannels.getNode());
5371 
5372   if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
5373     // If we have a vector select, let's replace the comparison results in the
5374     // affected lanes with the correct tautological result.
5375     SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
5376                                               DL, SETCCVT, SETCCVT);
5377     return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
5378                        Replacement, NewCC);
5379   }
5380 
5381   // Else, we can just invert the comparison result in the appropriate lanes.
5382   if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
5383     return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
5384                        TautologicalInvertedChannels);
5385 
5386   return SDValue(); // Don't know how to lower.
5387 }
5388 
5389 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
5390 /// where the divisor is constant and the comparison target is zero,
5391 /// return a DAG expression that will generate the same comparison result
5392 /// using only multiplications, additions and shifts/rotations.
5393 /// Ref: "Hacker's Delight" 10-17.
5394 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
5395                                         SDValue CompTargetNode,
5396                                         ISD::CondCode Cond,
5397                                         DAGCombinerInfo &DCI,
5398                                         const SDLoc &DL) const {
5399   SmallVector<SDNode *, 7> Built;
5400   if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
5401                                          DCI, DL, Built)) {
5402     assert(Built.size() <= 7 && "Max size prediction failed.");
5403     for (SDNode *N : Built)
5404       DCI.AddToWorklist(N);
5405     return Folded;
5406   }
5407 
5408   return SDValue();
5409 }
5410 
5411 SDValue
5412 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
5413                                   SDValue CompTargetNode, ISD::CondCode Cond,
5414                                   DAGCombinerInfo &DCI, const SDLoc &DL,
5415                                   SmallVectorImpl<SDNode *> &Created) const {
5416   // Fold:
5417   //   (seteq/ne (srem N, D), 0)
5418   // To:
5419   //   (setule/ugt (rotr (add (mul N, P), A), K), Q)
5420   //
5421   // - D must be constant, with D = D0 * 2^K where D0 is odd
5422   // - P is the multiplicative inverse of D0 modulo 2^W
5423   // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
5424   // - Q = floor((2 * A) / (2^K))
5425   // where W is the width of the common type of N and D.
5426   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5427          "Only applicable for (in)equality comparisons.");
5428 
5429   SelectionDAG &DAG = DCI.DAG;
5430 
5431   EVT VT = REMNode.getValueType();
5432   EVT SVT = VT.getScalarType();
5433   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5434   EVT ShSVT = ShVT.getScalarType();
5435 
5436   // If MUL is unavailable, we cannot proceed in any case.
5437   if (!isOperationLegalOrCustom(ISD::MUL, VT))
5438     return SDValue();
5439 
5440   // TODO: Could support comparing with non-zero too.
5441   ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
5442   if (!CompTarget || !CompTarget->isNullValue())
5443     return SDValue();
5444 
5445   bool HadIntMinDivisor = false;
5446   bool HadOneDivisor = false;
5447   bool AllDivisorsAreOnes = true;
5448   bool HadEvenDivisor = false;
5449   bool NeedToApplyOffset = false;
5450   bool AllDivisorsArePowerOfTwo = true;
5451   SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
5452 
5453   auto BuildSREMPattern = [&](ConstantSDNode *C) {
5454     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
5455     if (C->isNullValue())
5456       return false;
5457 
5458     // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
5459 
5460     // WARNING: this fold is only valid for positive divisors!
5461     APInt D = C->getAPIntValue();
5462     if (D.isNegative())
5463       D.negate(); //  `rem %X, -C` is equivalent to `rem %X, C`
5464 
5465     HadIntMinDivisor |= D.isMinSignedValue();
5466 
5467     // If all divisors are ones, we will prefer to avoid the fold.
5468     HadOneDivisor |= D.isOneValue();
5469     AllDivisorsAreOnes &= D.isOneValue();
5470 
5471     // Decompose D into D0 * 2^K
5472     unsigned K = D.countTrailingZeros();
5473     assert((!D.isOneValue() || (K == 0)) && "For divisor '1' we won't rotate.");
5474     APInt D0 = D.lshr(K);
5475 
5476     if (!D.isMinSignedValue()) {
5477       // D is even if it has trailing zeros; unless it's INT_MIN, in which case
5478       // we don't care about this lane in this fold, we'll special-handle it.
5479       HadEvenDivisor |= (K != 0);
5480     }
5481 
5482     // D is a power-of-two if D0 is one. This includes INT_MIN.
5483     // If all divisors are power-of-two, we will prefer to avoid the fold.
5484     AllDivisorsArePowerOfTwo &= D0.isOneValue();
5485 
5486     // P = inv(D0, 2^W)
5487     // 2^W requires W + 1 bits, so we have to extend and then truncate.
5488     unsigned W = D.getBitWidth();
5489     APInt P = D0.zext(W + 1)
5490                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
5491                   .trunc(W);
5492     assert(!P.isNullValue() && "No multiplicative inverse!"); // unreachable
5493     assert((D0 * P).isOneValue() && "Multiplicative inverse sanity check.");
5494 
5495     // A = floor((2^(W - 1) - 1) / D0) & -2^K
5496     APInt A = APInt::getSignedMaxValue(W).udiv(D0);
5497     A.clearLowBits(K);
5498 
5499     if (!D.isMinSignedValue()) {
5500       // If divisor INT_MIN, then we don't care about this lane in this fold,
5501       // we'll special-handle it.
5502       NeedToApplyOffset |= A != 0;
5503     }
5504 
5505     // Q = floor((2 * A) / (2^K))
5506     APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
5507 
5508     assert(APInt::getAllOnesValue(SVT.getSizeInBits()).ugt(A) &&
5509            "We are expecting that A is always less than all-ones for SVT");
5510     assert(APInt::getAllOnesValue(ShSVT.getSizeInBits()).ugt(K) &&
5511            "We are expecting that K is always less than all-ones for ShSVT");
5512 
5513     // If the divisor is 1 the result can be constant-folded. Likewise, we
5514     // don't care about INT_MIN lanes, those can be set to undef if appropriate.
5515     if (D.isOneValue()) {
5516       // Set P, A and K to a bogus values so we can try to splat them.
5517       P = 0;
5518       A = -1;
5519       K = -1;
5520 
5521       // x ?% 1 == 0  <-->  true  <-->  x u<= -1
5522       Q = -1;
5523     }
5524 
5525     PAmts.push_back(DAG.getConstant(P, DL, SVT));
5526     AAmts.push_back(DAG.getConstant(A, DL, SVT));
5527     KAmts.push_back(
5528         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
5529     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
5530     return true;
5531   };
5532 
5533   SDValue N = REMNode.getOperand(0);
5534   SDValue D = REMNode.getOperand(1);
5535 
5536   // Collect the values from each element.
5537   if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
5538     return SDValue();
5539 
5540   // If this is a srem by a one, avoid the fold since it can be constant-folded.
5541   if (AllDivisorsAreOnes)
5542     return SDValue();
5543 
5544   // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
5545   // since it can be best implemented as a bit test.
5546   if (AllDivisorsArePowerOfTwo)
5547     return SDValue();
5548 
5549   SDValue PVal, AVal, KVal, QVal;
5550   if (VT.isVector()) {
5551     if (HadOneDivisor) {
5552       // Try to turn PAmts into a splat, since we don't care about the values
5553       // that are currently '0'. If we can't, just keep '0'`s.
5554       turnVectorIntoSplatVector(PAmts, isNullConstant);
5555       // Try to turn AAmts into a splat, since we don't care about the
5556       // values that are currently '-1'. If we can't, change them to '0'`s.
5557       turnVectorIntoSplatVector(AAmts, isAllOnesConstant,
5558                                 DAG.getConstant(0, DL, SVT));
5559       // Try to turn KAmts into a splat, since we don't care about the values
5560       // that are currently '-1'. If we can't, change them to '0'`s.
5561       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
5562                                 DAG.getConstant(0, DL, ShSVT));
5563     }
5564 
5565     PVal = DAG.getBuildVector(VT, DL, PAmts);
5566     AVal = DAG.getBuildVector(VT, DL, AAmts);
5567     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
5568     QVal = DAG.getBuildVector(VT, DL, QAmts);
5569   } else {
5570     PVal = PAmts[0];
5571     AVal = AAmts[0];
5572     KVal = KAmts[0];
5573     QVal = QAmts[0];
5574   }
5575 
5576   // (mul N, P)
5577   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
5578   Created.push_back(Op0.getNode());
5579 
5580   if (NeedToApplyOffset) {
5581     // We need ADD to do this.
5582     if (!isOperationLegalOrCustom(ISD::ADD, VT))
5583       return SDValue();
5584 
5585     // (add (mul N, P), A)
5586     Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
5587     Created.push_back(Op0.getNode());
5588   }
5589 
5590   // Rotate right only if any divisor was even. We avoid rotates for all-odd
5591   // divisors as a performance improvement, since rotating by 0 is a no-op.
5592   if (HadEvenDivisor) {
5593     // We need ROTR to do this.
5594     if (!isOperationLegalOrCustom(ISD::ROTR, VT))
5595       return SDValue();
5596     SDNodeFlags Flags;
5597     Flags.setExact(true);
5598     // SREM: (rotr (add (mul N, P), A), K)
5599     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal, Flags);
5600     Created.push_back(Op0.getNode());
5601   }
5602 
5603   // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
5604   SDValue Fold =
5605       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
5606                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
5607 
5608   // If we didn't have lanes with INT_MIN divisor, then we're done.
5609   if (!HadIntMinDivisor)
5610     return Fold;
5611 
5612   // That fold is only valid for positive divisors. Which effectively means,
5613   // it is invalid for INT_MIN divisors. So if we have such a lane,
5614   // we must fix-up results for said lanes.
5615   assert(VT.isVector() && "Can/should only get here for vectors.");
5616 
5617   if (!isOperationLegalOrCustom(ISD::SETEQ, VT) ||
5618       !isOperationLegalOrCustom(ISD::AND, VT) ||
5619       !isOperationLegalOrCustom(Cond, VT) ||
5620       !isOperationLegalOrCustom(ISD::VSELECT, VT))
5621     return SDValue();
5622 
5623   Created.push_back(Fold.getNode());
5624 
5625   SDValue IntMin = DAG.getConstant(
5626       APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT);
5627   SDValue IntMax = DAG.getConstant(
5628       APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT);
5629   SDValue Zero =
5630       DAG.getConstant(APInt::getNullValue(SVT.getScalarSizeInBits()), DL, VT);
5631 
5632   // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded.
5633   SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ);
5634   Created.push_back(DivisorIsIntMin.getNode());
5635 
5636   // (N s% INT_MIN) ==/!= 0  <-->  (N & INT_MAX) ==/!= 0
5637   SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax);
5638   Created.push_back(Masked.getNode());
5639   SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond);
5640   Created.push_back(MaskedIsZero.getNode());
5641 
5642   // To produce final result we need to blend 2 vectors: 'SetCC' and
5643   // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick
5644   // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is
5645   // constant-folded, select can get lowered to a shuffle with constant mask.
5646   SDValue Blended =
5647       DAG.getNode(ISD::VSELECT, DL, VT, DivisorIsIntMin, MaskedIsZero, Fold);
5648 
5649   return Blended;
5650 }
5651 
5652 bool TargetLowering::
5653 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
5654   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
5655     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
5656                                 "be a constant integer");
5657     return true;
5658   }
5659 
5660   return false;
5661 }
5662 
5663 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
5664                                              bool LegalOps, bool OptForSize,
5665                                              NegatibleCost &Cost,
5666                                              unsigned Depth) const {
5667   // fneg is removable even if it has multiple uses.
5668   if (Op.getOpcode() == ISD::FNEG) {
5669     Cost = NegatibleCost::Cheaper;
5670     return Op.getOperand(0);
5671   }
5672 
5673   // Don't recurse exponentially.
5674   if (Depth > SelectionDAG::MaxRecursionDepth)
5675     return SDValue();
5676 
5677   // Pre-increment recursion depth for use in recursive calls.
5678   ++Depth;
5679   const SDNodeFlags Flags = Op->getFlags();
5680   const TargetOptions &Options = DAG.getTarget().Options;
5681   EVT VT = Op.getValueType();
5682   unsigned Opcode = Op.getOpcode();
5683 
5684   // Don't allow anything with multiple uses unless we know it is free.
5685   if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
5686     bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
5687                         isFPExtFree(VT, Op.getOperand(0).getValueType());
5688     if (!IsFreeExtend)
5689       return SDValue();
5690   }
5691 
5692   SDLoc DL(Op);
5693 
5694   switch (Opcode) {
5695   case ISD::ConstantFP: {
5696     // Don't invert constant FP values after legalization unless the target says
5697     // the negated constant is legal.
5698     bool IsOpLegal =
5699         isOperationLegal(ISD::ConstantFP, VT) ||
5700         isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
5701                      OptForSize);
5702 
5703     if (LegalOps && !IsOpLegal)
5704       break;
5705 
5706     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
5707     V.changeSign();
5708     SDValue CFP = DAG.getConstantFP(V, DL, VT);
5709 
5710     // If we already have the use of the negated floating constant, it is free
5711     // to negate it even it has multiple uses.
5712     if (!Op.hasOneUse() && CFP.use_empty())
5713       break;
5714     Cost = NegatibleCost::Neutral;
5715     return CFP;
5716   }
5717   case ISD::BUILD_VECTOR: {
5718     // Only permit BUILD_VECTOR of constants.
5719     if (llvm::any_of(Op->op_values(), [&](SDValue N) {
5720           return !N.isUndef() && !isa<ConstantFPSDNode>(N);
5721         }))
5722       break;
5723 
5724     bool IsOpLegal =
5725         (isOperationLegal(ISD::ConstantFP, VT) &&
5726          isOperationLegal(ISD::BUILD_VECTOR, VT)) ||
5727         llvm::all_of(Op->op_values(), [&](SDValue N) {
5728           return N.isUndef() ||
5729                  isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
5730                               OptForSize);
5731         });
5732 
5733     if (LegalOps && !IsOpLegal)
5734       break;
5735 
5736     SmallVector<SDValue, 4> Ops;
5737     for (SDValue C : Op->op_values()) {
5738       if (C.isUndef()) {
5739         Ops.push_back(C);
5740         continue;
5741       }
5742       APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
5743       V.changeSign();
5744       Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
5745     }
5746     Cost = NegatibleCost::Neutral;
5747     return DAG.getBuildVector(VT, DL, Ops);
5748   }
5749   case ISD::FADD: {
5750     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
5751       break;
5752 
5753     // After operation legalization, it might not be legal to create new FSUBs.
5754     if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
5755       break;
5756     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
5757 
5758     // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
5759     NegatibleCost CostX = NegatibleCost::Expensive;
5760     SDValue NegX =
5761         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
5762     // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
5763     NegatibleCost CostY = NegatibleCost::Expensive;
5764     SDValue NegY =
5765         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
5766 
5767     // Negate the X if its cost is less or equal than Y.
5768     if (NegX && (CostX <= CostY)) {
5769       Cost = CostX;
5770       return DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
5771     }
5772 
5773     // Negate the Y if it is not expensive.
5774     if (NegY) {
5775       Cost = CostY;
5776       return DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
5777     }
5778     break;
5779   }
5780   case ISD::FSUB: {
5781     // We can't turn -(A-B) into B-A when we honor signed zeros.
5782     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
5783       break;
5784 
5785     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
5786     // fold (fneg (fsub 0, Y)) -> Y
5787     if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
5788       if (C->isZero()) {
5789         Cost = NegatibleCost::Cheaper;
5790         return Y;
5791       }
5792 
5793     // fold (fneg (fsub X, Y)) -> (fsub Y, X)
5794     Cost = NegatibleCost::Neutral;
5795     return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
5796   }
5797   case ISD::FMUL:
5798   case ISD::FDIV: {
5799     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
5800 
5801     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
5802     NegatibleCost CostX = NegatibleCost::Expensive;
5803     SDValue NegX =
5804         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
5805     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
5806     NegatibleCost CostY = NegatibleCost::Expensive;
5807     SDValue NegY =
5808         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
5809 
5810     // Negate the X if its cost is less or equal than Y.
5811     if (NegX && (CostX <= CostY)) {
5812       Cost = CostX;
5813       return DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
5814     }
5815 
5816     // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
5817     if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
5818       if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
5819         break;
5820 
5821     // Negate the Y if it is not expensive.
5822     if (NegY) {
5823       Cost = CostY;
5824       return DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
5825     }
5826     break;
5827   }
5828   case ISD::FMA:
5829   case ISD::FMAD: {
5830     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
5831       break;
5832 
5833     SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
5834     NegatibleCost CostZ = NegatibleCost::Expensive;
5835     SDValue NegZ =
5836         getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
5837     // Give up if fail to negate the Z.
5838     if (!NegZ)
5839       break;
5840 
5841     // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
5842     NegatibleCost CostX = NegatibleCost::Expensive;
5843     SDValue NegX =
5844         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
5845     // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
5846     NegatibleCost CostY = NegatibleCost::Expensive;
5847     SDValue NegY =
5848         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
5849 
5850     // Negate the X if its cost is less or equal than Y.
5851     if (NegX && (CostX <= CostY)) {
5852       Cost = std::min(CostX, CostZ);
5853       return DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
5854     }
5855 
5856     // Negate the Y if it is not expensive.
5857     if (NegY) {
5858       Cost = std::min(CostY, CostZ);
5859       return DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
5860     }
5861     break;
5862   }
5863 
5864   case ISD::FP_EXTEND:
5865   case ISD::FSIN:
5866     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
5867                                             OptForSize, Cost, Depth))
5868       return DAG.getNode(Opcode, DL, VT, NegV);
5869     break;
5870   case ISD::FP_ROUND:
5871     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
5872                                             OptForSize, Cost, Depth))
5873       return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
5874     break;
5875   }
5876 
5877   return SDValue();
5878 }
5879 
5880 //===----------------------------------------------------------------------===//
5881 // Legalization Utilities
5882 //===----------------------------------------------------------------------===//
5883 
5884 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, SDLoc dl,
5885                                     SDValue LHS, SDValue RHS,
5886                                     SmallVectorImpl<SDValue> &Result,
5887                                     EVT HiLoVT, SelectionDAG &DAG,
5888                                     MulExpansionKind Kind, SDValue LL,
5889                                     SDValue LH, SDValue RL, SDValue RH) const {
5890   assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
5891          Opcode == ISD::SMUL_LOHI);
5892 
5893   bool HasMULHS = (Kind == MulExpansionKind::Always) ||
5894                   isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
5895   bool HasMULHU = (Kind == MulExpansionKind::Always) ||
5896                   isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
5897   bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
5898                       isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
5899   bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
5900                       isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
5901 
5902   if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
5903     return false;
5904 
5905   unsigned OuterBitSize = VT.getScalarSizeInBits();
5906   unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
5907   unsigned LHSSB = DAG.ComputeNumSignBits(LHS);
5908   unsigned RHSSB = DAG.ComputeNumSignBits(RHS);
5909 
5910   // LL, LH, RL, and RH must be either all NULL or all set to a value.
5911   assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
5912          (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
5913 
5914   SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
5915   auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
5916                           bool Signed) -> bool {
5917     if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
5918       Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
5919       Hi = SDValue(Lo.getNode(), 1);
5920       return true;
5921     }
5922     if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
5923       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
5924       Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
5925       return true;
5926     }
5927     return false;
5928   };
5929 
5930   SDValue Lo, Hi;
5931 
5932   if (!LL.getNode() && !RL.getNode() &&
5933       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
5934     LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
5935     RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
5936   }
5937 
5938   if (!LL.getNode())
5939     return false;
5940 
5941   APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
5942   if (DAG.MaskedValueIsZero(LHS, HighMask) &&
5943       DAG.MaskedValueIsZero(RHS, HighMask)) {
5944     // The inputs are both zero-extended.
5945     if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
5946       Result.push_back(Lo);
5947       Result.push_back(Hi);
5948       if (Opcode != ISD::MUL) {
5949         SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
5950         Result.push_back(Zero);
5951         Result.push_back(Zero);
5952       }
5953       return true;
5954     }
5955   }
5956 
5957   if (!VT.isVector() && Opcode == ISD::MUL && LHSSB > InnerBitSize &&
5958       RHSSB > InnerBitSize) {
5959     // The input values are both sign-extended.
5960     // TODO non-MUL case?
5961     if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
5962       Result.push_back(Lo);
5963       Result.push_back(Hi);
5964       return true;
5965     }
5966   }
5967 
5968   unsigned ShiftAmount = OuterBitSize - InnerBitSize;
5969   EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout());
5970   if (APInt::getMaxValue(ShiftAmountTy.getSizeInBits()).ult(ShiftAmount)) {
5971     // FIXME getShiftAmountTy does not always return a sensible result when VT
5972     // is an illegal type, and so the type may be too small to fit the shift
5973     // amount. Override it with i32. The shift will have to be legalized.
5974     ShiftAmountTy = MVT::i32;
5975   }
5976   SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy);
5977 
5978   if (!LH.getNode() && !RH.getNode() &&
5979       isOperationLegalOrCustom(ISD::SRL, VT) &&
5980       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
5981     LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
5982     LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
5983     RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
5984     RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
5985   }
5986 
5987   if (!LH.getNode())
5988     return false;
5989 
5990   if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
5991     return false;
5992 
5993   Result.push_back(Lo);
5994 
5995   if (Opcode == ISD::MUL) {
5996     RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
5997     LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
5998     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
5999     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
6000     Result.push_back(Hi);
6001     return true;
6002   }
6003 
6004   // Compute the full width result.
6005   auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
6006     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
6007     Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
6008     Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
6009     return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
6010   };
6011 
6012   SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
6013   if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
6014     return false;
6015 
6016   // This is effectively the add part of a multiply-add of half-sized operands,
6017   // so it cannot overflow.
6018   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
6019 
6020   if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
6021     return false;
6022 
6023   SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
6024   EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6025 
6026   bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
6027                   isOperationLegalOrCustom(ISD::ADDE, VT));
6028   if (UseGlue)
6029     Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
6030                        Merge(Lo, Hi));
6031   else
6032     Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next,
6033                        Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
6034 
6035   SDValue Carry = Next.getValue(1);
6036   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6037   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
6038 
6039   if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
6040     return false;
6041 
6042   if (UseGlue)
6043     Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
6044                      Carry);
6045   else
6046     Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
6047                      Zero, Carry);
6048 
6049   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
6050 
6051   if (Opcode == ISD::SMUL_LOHI) {
6052     SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
6053                                   DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
6054     Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
6055 
6056     NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
6057                           DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
6058     Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
6059   }
6060 
6061   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6062   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
6063   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6064   return true;
6065 }
6066 
6067 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
6068                                SelectionDAG &DAG, MulExpansionKind Kind,
6069                                SDValue LL, SDValue LH, SDValue RL,
6070                                SDValue RH) const {
6071   SmallVector<SDValue, 2> Result;
6072   bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), N,
6073                            N->getOperand(0), N->getOperand(1), Result, HiLoVT,
6074                            DAG, Kind, LL, LH, RL, RH);
6075   if (Ok) {
6076     assert(Result.size() == 2);
6077     Lo = Result[0];
6078     Hi = Result[1];
6079   }
6080   return Ok;
6081 }
6082 
6083 bool TargetLowering::expandFunnelShift(SDNode *Node, SDValue &Result,
6084                                        SelectionDAG &DAG) const {
6085   EVT VT = Node->getValueType(0);
6086 
6087   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
6088                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
6089                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
6090                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
6091     return false;
6092 
6093   // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
6094   // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
6095   SDValue X = Node->getOperand(0);
6096   SDValue Y = Node->getOperand(1);
6097   SDValue Z = Node->getOperand(2);
6098 
6099   unsigned EltSizeInBits = VT.getScalarSizeInBits();
6100   bool IsFSHL = Node->getOpcode() == ISD::FSHL;
6101   SDLoc DL(SDValue(Node, 0));
6102 
6103   EVT ShVT = Z.getValueType();
6104   SDValue Mask = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
6105   SDValue ShAmt, InvShAmt;
6106   if (isPowerOf2_32(EltSizeInBits)) {
6107     // Z % BW -> Z & (BW - 1)
6108     ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
6109     // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
6110     InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
6111   } else {
6112     SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
6113     ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
6114     InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
6115   }
6116 
6117   SDValue One = DAG.getConstant(1, DL, ShVT);
6118   SDValue ShX, ShY;
6119   if (IsFSHL) {
6120     ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
6121     SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
6122     ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
6123   } else {
6124     SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
6125     ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
6126     ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
6127   }
6128   Result = DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
6129   return true;
6130 }
6131 
6132 // TODO: Merge with expandFunnelShift.
6133 bool TargetLowering::expandROT(SDNode *Node, SDValue &Result,
6134                                SelectionDAG &DAG) const {
6135   EVT VT = Node->getValueType(0);
6136   unsigned EltSizeInBits = VT.getScalarSizeInBits();
6137   bool IsLeft = Node->getOpcode() == ISD::ROTL;
6138   SDValue Op0 = Node->getOperand(0);
6139   SDValue Op1 = Node->getOperand(1);
6140   SDLoc DL(SDValue(Node, 0));
6141 
6142   EVT ShVT = Op1.getValueType();
6143   SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
6144 
6145   // If a rotate in the other direction is legal, use it.
6146   unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
6147   if (isOperationLegal(RevRot, VT)) {
6148     SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, Op1);
6149     Result = DAG.getNode(RevRot, DL, VT, Op0, Sub);
6150     return true;
6151   }
6152 
6153   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
6154                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
6155                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
6156                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT) ||
6157                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT)))
6158     return false;
6159 
6160   // Otherwise,
6161   //   (rotl x, c) -> (or (shl x, (and c, w-1)), (srl x, (and w-c, w-1)))
6162   //   (rotr x, c) -> (or (srl x, (and c, w-1)), (shl x, (and w-c, w-1)))
6163   //
6164   assert(isPowerOf2_32(EltSizeInBits) && EltSizeInBits > 1 &&
6165          "Expecting the type bitwidth to be a power of 2");
6166   unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
6167   unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
6168   SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
6169   SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, Op1);
6170   SDValue And0 = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
6171   SDValue And1 = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
6172   Result = DAG.getNode(ISD::OR, DL, VT, DAG.getNode(ShOpc, DL, VT, Op0, And0),
6173                        DAG.getNode(HsOpc, DL, VT, Op0, And1));
6174   return true;
6175 }
6176 
6177 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
6178                                       SelectionDAG &DAG) const {
6179   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
6180   SDValue Src = Node->getOperand(OpNo);
6181   EVT SrcVT = Src.getValueType();
6182   EVT DstVT = Node->getValueType(0);
6183   SDLoc dl(SDValue(Node, 0));
6184 
6185   // FIXME: Only f32 to i64 conversions are supported.
6186   if (SrcVT != MVT::f32 || DstVT != MVT::i64)
6187     return false;
6188 
6189   if (Node->isStrictFPOpcode())
6190     // When a NaN is converted to an integer a trap is allowed. We can't
6191     // use this expansion here because it would eliminate that trap. Other
6192     // traps are also allowed and cannot be eliminated. See
6193     // IEEE 754-2008 sec 5.8.
6194     return false;
6195 
6196   // Expand f32 -> i64 conversion
6197   // This algorithm comes from compiler-rt's implementation of fixsfdi:
6198   // https://github.com/llvm/llvm-project/blob/master/compiler-rt/lib/builtins/fixsfdi.c
6199   unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
6200   EVT IntVT = SrcVT.changeTypeToInteger();
6201   EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
6202 
6203   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
6204   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
6205   SDValue Bias = DAG.getConstant(127, dl, IntVT);
6206   SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
6207   SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
6208   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
6209 
6210   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
6211 
6212   SDValue ExponentBits = DAG.getNode(
6213       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
6214       DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
6215   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
6216 
6217   SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
6218                              DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
6219                              DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
6220   Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
6221 
6222   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
6223                           DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
6224                           DAG.getConstant(0x00800000, dl, IntVT));
6225 
6226   R = DAG.getZExtOrTrunc(R, dl, DstVT);
6227 
6228   R = DAG.getSelectCC(
6229       dl, Exponent, ExponentLoBit,
6230       DAG.getNode(ISD::SHL, dl, DstVT, R,
6231                   DAG.getZExtOrTrunc(
6232                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
6233                       dl, IntShVT)),
6234       DAG.getNode(ISD::SRL, dl, DstVT, R,
6235                   DAG.getZExtOrTrunc(
6236                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
6237                       dl, IntShVT)),
6238       ISD::SETGT);
6239 
6240   SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
6241                             DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
6242 
6243   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
6244                            DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
6245   return true;
6246 }
6247 
6248 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result,
6249                                       SDValue &Chain,
6250                                       SelectionDAG &DAG) const {
6251   SDLoc dl(SDValue(Node, 0));
6252   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
6253   SDValue Src = Node->getOperand(OpNo);
6254 
6255   EVT SrcVT = Src.getValueType();
6256   EVT DstVT = Node->getValueType(0);
6257   EVT SetCCVT =
6258       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
6259   EVT DstSetCCVT =
6260       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
6261 
6262   // Only expand vector types if we have the appropriate vector bit operations.
6263   unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
6264                                                    ISD::FP_TO_SINT;
6265   if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
6266                            !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT)))
6267     return false;
6268 
6269   // If the maximum float value is smaller then the signed integer range,
6270   // the destination signmask can't be represented by the float, so we can
6271   // just use FP_TO_SINT directly.
6272   const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT);
6273   APFloat APF(APFSem, APInt::getNullValue(SrcVT.getScalarSizeInBits()));
6274   APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
6275   if (APFloat::opOverflow &
6276       APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
6277     if (Node->isStrictFPOpcode()) {
6278       Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
6279                            { Node->getOperand(0), Src });
6280       Chain = Result.getValue(1);
6281     } else
6282       Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
6283     return true;
6284   }
6285 
6286   SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
6287   SDValue Sel;
6288 
6289   if (Node->isStrictFPOpcode()) {
6290     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
6291                        Node->getOperand(0), /*IsSignaling*/ true);
6292     Chain = Sel.getValue(1);
6293   } else {
6294     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
6295   }
6296 
6297   bool Strict = Node->isStrictFPOpcode() ||
6298                 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
6299 
6300   if (Strict) {
6301     // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
6302     // signmask then offset (the result of which should be fully representable).
6303     // Sel = Src < 0x8000000000000000
6304     // FltOfs = select Sel, 0, 0x8000000000000000
6305     // IntOfs = select Sel, 0, 0x8000000000000000
6306     // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
6307 
6308     // TODO: Should any fast-math-flags be set for the FSUB?
6309     SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
6310                                    DAG.getConstantFP(0.0, dl, SrcVT), Cst);
6311     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
6312     SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
6313                                    DAG.getConstant(0, dl, DstVT),
6314                                    DAG.getConstant(SignMask, dl, DstVT));
6315     SDValue SInt;
6316     if (Node->isStrictFPOpcode()) {
6317       SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
6318                                 { Chain, Src, FltOfs });
6319       SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
6320                          { Val.getValue(1), Val });
6321       Chain = SInt.getValue(1);
6322     } else {
6323       SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
6324       SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
6325     }
6326     Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
6327   } else {
6328     // Expand based on maximum range of FP_TO_SINT:
6329     // True = fp_to_sint(Src)
6330     // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
6331     // Result = select (Src < 0x8000000000000000), True, False
6332 
6333     SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
6334     // TODO: Should any fast-math-flags be set for the FSUB?
6335     SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
6336                                 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
6337     False = DAG.getNode(ISD::XOR, dl, DstVT, False,
6338                         DAG.getConstant(SignMask, dl, DstVT));
6339     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
6340     Result = DAG.getSelect(dl, DstVT, Sel, True, False);
6341   }
6342   return true;
6343 }
6344 
6345 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result,
6346                                       SDValue &Chain,
6347                                       SelectionDAG &DAG) const {
6348   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
6349   SDValue Src = Node->getOperand(OpNo);
6350   EVT SrcVT = Src.getValueType();
6351   EVT DstVT = Node->getValueType(0);
6352 
6353   if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
6354     return false;
6355 
6356   // Only expand vector types if we have the appropriate vector bit operations.
6357   if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
6358                            !isOperationLegalOrCustom(ISD::FADD, DstVT) ||
6359                            !isOperationLegalOrCustom(ISD::FSUB, DstVT) ||
6360                            !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) ||
6361                            !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT)))
6362     return false;
6363 
6364   SDLoc dl(SDValue(Node, 0));
6365   EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout());
6366 
6367   // Implementation of unsigned i64 to f64 following the algorithm in
6368   // __floatundidf in compiler_rt. This implementation has the advantage
6369   // of performing rounding correctly, both in the default rounding mode
6370   // and in all alternate rounding modes.
6371   SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
6372   SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
6373       BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT);
6374   SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
6375   SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
6376   SDValue HiShift = DAG.getConstant(32, dl, ShiftVT);
6377 
6378   SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
6379   SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
6380   SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
6381   SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
6382   SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
6383   SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
6384   if (Node->isStrictFPOpcode()) {
6385     SDValue HiSub =
6386         DAG.getNode(ISD::STRICT_FSUB, dl, {DstVT, MVT::Other},
6387                     {Node->getOperand(0), HiFlt, TwoP84PlusTwoP52});
6388     Result = DAG.getNode(ISD::STRICT_FADD, dl, {DstVT, MVT::Other},
6389                          {HiSub.getValue(1), LoFlt, HiSub});
6390     Chain = Result.getValue(1);
6391   } else {
6392     SDValue HiSub =
6393         DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
6394     Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
6395   }
6396   return true;
6397 }
6398 
6399 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node,
6400                                               SelectionDAG &DAG) const {
6401   SDLoc dl(Node);
6402   unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ?
6403     ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
6404   EVT VT = Node->getValueType(0);
6405   if (isOperationLegalOrCustom(NewOp, VT)) {
6406     SDValue Quiet0 = Node->getOperand(0);
6407     SDValue Quiet1 = Node->getOperand(1);
6408 
6409     if (!Node->getFlags().hasNoNaNs()) {
6410       // Insert canonicalizes if it's possible we need to quiet to get correct
6411       // sNaN behavior.
6412       if (!DAG.isKnownNeverSNaN(Quiet0)) {
6413         Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
6414                              Node->getFlags());
6415       }
6416       if (!DAG.isKnownNeverSNaN(Quiet1)) {
6417         Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
6418                              Node->getFlags());
6419       }
6420     }
6421 
6422     return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
6423   }
6424 
6425   // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
6426   // instead if there are no NaNs.
6427   if (Node->getFlags().hasNoNaNs()) {
6428     unsigned IEEE2018Op =
6429         Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
6430     if (isOperationLegalOrCustom(IEEE2018Op, VT)) {
6431       return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
6432                          Node->getOperand(1), Node->getFlags());
6433     }
6434   }
6435 
6436   // If none of the above worked, but there are no NaNs, then expand to
6437   // a compare/select sequence.  This is required for correctness since
6438   // InstCombine might have canonicalized a fcmp+select sequence to a
6439   // FMINNUM/FMAXNUM node.  If we were to fall through to the default
6440   // expansion to libcall, we might introduce a link-time dependency
6441   // on libm into a file that originally did not have one.
6442   if (Node->getFlags().hasNoNaNs()) {
6443     ISD::CondCode Pred =
6444         Node->getOpcode() == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
6445     SDValue Op1 = Node->getOperand(0);
6446     SDValue Op2 = Node->getOperand(1);
6447     SDValue SelCC = DAG.getSelectCC(dl, Op1, Op2, Op1, Op2, Pred);
6448     // Copy FMF flags, but always set the no-signed-zeros flag
6449     // as this is implied by the FMINNUM/FMAXNUM semantics.
6450     SDNodeFlags Flags = Node->getFlags();
6451     Flags.setNoSignedZeros(true);
6452     SelCC->setFlags(Flags);
6453     return SelCC;
6454   }
6455 
6456   return SDValue();
6457 }
6458 
6459 bool TargetLowering::expandCTPOP(SDNode *Node, SDValue &Result,
6460                                  SelectionDAG &DAG) const {
6461   SDLoc dl(Node);
6462   EVT VT = Node->getValueType(0);
6463   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
6464   SDValue Op = Node->getOperand(0);
6465   unsigned Len = VT.getScalarSizeInBits();
6466   assert(VT.isInteger() && "CTPOP not implemented for this type.");
6467 
6468   // TODO: Add support for irregular type lengths.
6469   if (!(Len <= 128 && Len % 8 == 0))
6470     return false;
6471 
6472   // Only expand vector types if we have the appropriate vector bit operations.
6473   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::ADD, VT) ||
6474                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
6475                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
6476                         (Len != 8 && !isOperationLegalOrCustom(ISD::MUL, VT)) ||
6477                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT)))
6478     return false;
6479 
6480   // This is the "best" algorithm from
6481   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
6482   SDValue Mask55 =
6483       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
6484   SDValue Mask33 =
6485       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
6486   SDValue Mask0F =
6487       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
6488   SDValue Mask01 =
6489       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
6490 
6491   // v = v - ((v >> 1) & 0x55555555...)
6492   Op = DAG.getNode(ISD::SUB, dl, VT, Op,
6493                    DAG.getNode(ISD::AND, dl, VT,
6494                                DAG.getNode(ISD::SRL, dl, VT, Op,
6495                                            DAG.getConstant(1, dl, ShVT)),
6496                                Mask55));
6497   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
6498   Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
6499                    DAG.getNode(ISD::AND, dl, VT,
6500                                DAG.getNode(ISD::SRL, dl, VT, Op,
6501                                            DAG.getConstant(2, dl, ShVT)),
6502                                Mask33));
6503   // v = (v + (v >> 4)) & 0x0F0F0F0F...
6504   Op = DAG.getNode(ISD::AND, dl, VT,
6505                    DAG.getNode(ISD::ADD, dl, VT, Op,
6506                                DAG.getNode(ISD::SRL, dl, VT, Op,
6507                                            DAG.getConstant(4, dl, ShVT))),
6508                    Mask0F);
6509   // v = (v * 0x01010101...) >> (Len - 8)
6510   if (Len > 8)
6511     Op =
6512         DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
6513                     DAG.getConstant(Len - 8, dl, ShVT));
6514 
6515   Result = Op;
6516   return true;
6517 }
6518 
6519 bool TargetLowering::expandCTLZ(SDNode *Node, SDValue &Result,
6520                                 SelectionDAG &DAG) const {
6521   SDLoc dl(Node);
6522   EVT VT = Node->getValueType(0);
6523   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
6524   SDValue Op = Node->getOperand(0);
6525   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
6526 
6527   // If the non-ZERO_UNDEF version is supported we can use that instead.
6528   if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF &&
6529       isOperationLegalOrCustom(ISD::CTLZ, VT)) {
6530     Result = DAG.getNode(ISD::CTLZ, dl, VT, Op);
6531     return true;
6532   }
6533 
6534   // If the ZERO_UNDEF version is supported use that and handle the zero case.
6535   if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) {
6536     EVT SetCCVT =
6537         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6538     SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op);
6539     SDValue Zero = DAG.getConstant(0, dl, VT);
6540     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
6541     Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero,
6542                          DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
6543     return true;
6544   }
6545 
6546   // Only expand vector types if we have the appropriate vector bit operations.
6547   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
6548                         !isOperationLegalOrCustom(ISD::CTPOP, VT) ||
6549                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
6550                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
6551     return false;
6552 
6553   // for now, we do this:
6554   // x = x | (x >> 1);
6555   // x = x | (x >> 2);
6556   // ...
6557   // x = x | (x >>16);
6558   // x = x | (x >>32); // for 64-bit input
6559   // return popcount(~x);
6560   //
6561   // Ref: "Hacker's Delight" by Henry Warren
6562   for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) {
6563     SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
6564     Op = DAG.getNode(ISD::OR, dl, VT, Op,
6565                      DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
6566   }
6567   Op = DAG.getNOT(dl, Op, VT);
6568   Result = DAG.getNode(ISD::CTPOP, dl, VT, Op);
6569   return true;
6570 }
6571 
6572 bool TargetLowering::expandCTTZ(SDNode *Node, SDValue &Result,
6573                                 SelectionDAG &DAG) const {
6574   SDLoc dl(Node);
6575   EVT VT = Node->getValueType(0);
6576   SDValue Op = Node->getOperand(0);
6577   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
6578 
6579   // If the non-ZERO_UNDEF version is supported we can use that instead.
6580   if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
6581       isOperationLegalOrCustom(ISD::CTTZ, VT)) {
6582     Result = DAG.getNode(ISD::CTTZ, dl, VT, Op);
6583     return true;
6584   }
6585 
6586   // If the ZERO_UNDEF version is supported use that and handle the zero case.
6587   if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) {
6588     EVT SetCCVT =
6589         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6590     SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op);
6591     SDValue Zero = DAG.getConstant(0, dl, VT);
6592     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
6593     Result = DAG.getNode(ISD::SELECT, dl, VT, SrcIsZero,
6594                          DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
6595     return true;
6596   }
6597 
6598   // Only expand vector types if we have the appropriate vector bit operations.
6599   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
6600                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
6601                          !isOperationLegalOrCustom(ISD::CTLZ, VT)) ||
6602                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
6603                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
6604                         !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
6605     return false;
6606 
6607   // for now, we use: { return popcount(~x & (x - 1)); }
6608   // unless the target has ctlz but not ctpop, in which case we use:
6609   // { return 32 - nlz(~x & (x-1)); }
6610   // Ref: "Hacker's Delight" by Henry Warren
6611   SDValue Tmp = DAG.getNode(
6612       ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
6613       DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
6614 
6615   // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
6616   if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) {
6617     Result =
6618         DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
6619                     DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
6620     return true;
6621   }
6622 
6623   Result = DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
6624   return true;
6625 }
6626 
6627 bool TargetLowering::expandABS(SDNode *N, SDValue &Result,
6628                                SelectionDAG &DAG) const {
6629   SDLoc dl(N);
6630   EVT VT = N->getValueType(0);
6631   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
6632   SDValue Op = N->getOperand(0);
6633 
6634   // Only expand vector types if we have the appropriate vector operations.
6635   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SRA, VT) ||
6636                         !isOperationLegalOrCustom(ISD::ADD, VT) ||
6637                         !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
6638     return false;
6639 
6640   SDValue Shift =
6641       DAG.getNode(ISD::SRA, dl, VT, Op,
6642                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT));
6643   SDValue Add = DAG.getNode(ISD::ADD, dl, VT, Op, Shift);
6644   Result = DAG.getNode(ISD::XOR, dl, VT, Add, Shift);
6645   return true;
6646 }
6647 
6648 std::pair<SDValue, SDValue>
6649 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
6650                                     SelectionDAG &DAG) const {
6651   SDLoc SL(LD);
6652   SDValue Chain = LD->getChain();
6653   SDValue BasePTR = LD->getBasePtr();
6654   EVT SrcVT = LD->getMemoryVT();
6655   EVT DstVT = LD->getValueType(0);
6656   ISD::LoadExtType ExtType = LD->getExtensionType();
6657 
6658   unsigned NumElem = SrcVT.getVectorNumElements();
6659 
6660   EVT SrcEltVT = SrcVT.getScalarType();
6661   EVT DstEltVT = DstVT.getScalarType();
6662 
6663   // A vector must always be stored in memory as-is, i.e. without any padding
6664   // between the elements, since various code depend on it, e.g. in the
6665   // handling of a bitcast of a vector type to int, which may be done with a
6666   // vector store followed by an integer load. A vector that does not have
6667   // elements that are byte-sized must therefore be stored as an integer
6668   // built out of the extracted vector elements.
6669   if (!SrcEltVT.isByteSized()) {
6670     unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
6671     EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
6672 
6673     unsigned NumSrcBits = SrcVT.getSizeInBits();
6674     EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
6675 
6676     unsigned SrcEltBits = SrcEltVT.getSizeInBits();
6677     SDValue SrcEltBitMask = DAG.getConstant(
6678         APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
6679 
6680     // Load the whole vector and avoid masking off the top bits as it makes
6681     // the codegen worse.
6682     SDValue Load =
6683         DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR,
6684                        LD->getPointerInfo(), SrcIntVT, LD->getAlignment(),
6685                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
6686 
6687     SmallVector<SDValue, 8> Vals;
6688     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
6689       unsigned ShiftIntoIdx =
6690           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
6691       SDValue ShiftAmount =
6692           DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(),
6693                                      LoadVT, SL, /*LegalTypes=*/false);
6694       SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
6695       SDValue Elt =
6696           DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
6697       SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
6698 
6699       if (ExtType != ISD::NON_EXTLOAD) {
6700         unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
6701         Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
6702       }
6703 
6704       Vals.push_back(Scalar);
6705     }
6706 
6707     SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
6708     return std::make_pair(Value, Load.getValue(1));
6709   }
6710 
6711   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
6712   assert(SrcEltVT.isByteSized());
6713 
6714   SmallVector<SDValue, 8> Vals;
6715   SmallVector<SDValue, 8> LoadChains;
6716 
6717   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
6718     SDValue ScalarLoad =
6719         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
6720                        LD->getPointerInfo().getWithOffset(Idx * Stride),
6721                        SrcEltVT, MinAlign(LD->getAlignment(), Idx * Stride),
6722                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
6723 
6724     BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, Stride);
6725 
6726     Vals.push_back(ScalarLoad.getValue(0));
6727     LoadChains.push_back(ScalarLoad.getValue(1));
6728   }
6729 
6730   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
6731   SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
6732 
6733   return std::make_pair(Value, NewChain);
6734 }
6735 
6736 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
6737                                              SelectionDAG &DAG) const {
6738   SDLoc SL(ST);
6739 
6740   SDValue Chain = ST->getChain();
6741   SDValue BasePtr = ST->getBasePtr();
6742   SDValue Value = ST->getValue();
6743   EVT StVT = ST->getMemoryVT();
6744 
6745   // The type of the data we want to save
6746   EVT RegVT = Value.getValueType();
6747   EVT RegSclVT = RegVT.getScalarType();
6748 
6749   // The type of data as saved in memory.
6750   EVT MemSclVT = StVT.getScalarType();
6751 
6752   unsigned NumElem = StVT.getVectorNumElements();
6753 
6754   // A vector must always be stored in memory as-is, i.e. without any padding
6755   // between the elements, since various code depend on it, e.g. in the
6756   // handling of a bitcast of a vector type to int, which may be done with a
6757   // vector store followed by an integer load. A vector that does not have
6758   // elements that are byte-sized must therefore be stored as an integer
6759   // built out of the extracted vector elements.
6760   if (!MemSclVT.isByteSized()) {
6761     unsigned NumBits = StVT.getSizeInBits();
6762     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
6763 
6764     SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
6765 
6766     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
6767       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
6768                                 DAG.getVectorIdxConstant(Idx, SL));
6769       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
6770       SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
6771       unsigned ShiftIntoIdx =
6772           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
6773       SDValue ShiftAmount =
6774           DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
6775       SDValue ShiftedElt =
6776           DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
6777       CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
6778     }
6779 
6780     return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
6781                         ST->getAlignment(), ST->getMemOperand()->getFlags(),
6782                         ST->getAAInfo());
6783   }
6784 
6785   // Store Stride in bytes
6786   unsigned Stride = MemSclVT.getSizeInBits() / 8;
6787   assert(Stride && "Zero stride!");
6788   // Extract each of the elements from the original vector and save them into
6789   // memory individually.
6790   SmallVector<SDValue, 8> Stores;
6791   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
6792     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
6793                               DAG.getVectorIdxConstant(Idx, SL));
6794 
6795     SDValue Ptr = DAG.getObjectPtrOffset(SL, BasePtr, Idx * Stride);
6796 
6797     // This scalar TruncStore may be illegal, but we legalize it later.
6798     SDValue Store = DAG.getTruncStore(
6799         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
6800         MemSclVT, MinAlign(ST->getAlignment(), Idx * Stride),
6801         ST->getMemOperand()->getFlags(), ST->getAAInfo());
6802 
6803     Stores.push_back(Store);
6804   }
6805 
6806   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
6807 }
6808 
6809 std::pair<SDValue, SDValue>
6810 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
6811   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
6812          "unaligned indexed loads not implemented!");
6813   SDValue Chain = LD->getChain();
6814   SDValue Ptr = LD->getBasePtr();
6815   EVT VT = LD->getValueType(0);
6816   EVT LoadedVT = LD->getMemoryVT();
6817   SDLoc dl(LD);
6818   auto &MF = DAG.getMachineFunction();
6819 
6820   if (VT.isFloatingPoint() || VT.isVector()) {
6821     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
6822     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
6823       if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
6824           LoadedVT.isVector()) {
6825         // Scalarize the load and let the individual components be handled.
6826         return scalarizeVectorLoad(LD, DAG);
6827       }
6828 
6829       // Expand to a (misaligned) integer load of the same size,
6830       // then bitconvert to floating point or vector.
6831       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
6832                                     LD->getMemOperand());
6833       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
6834       if (LoadedVT != VT)
6835         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
6836                              ISD::ANY_EXTEND, dl, VT, Result);
6837 
6838       return std::make_pair(Result, newLoad.getValue(1));
6839     }
6840 
6841     // Copy the value to a (aligned) stack slot using (unaligned) integer
6842     // loads and stores, then do a (aligned) load from the stack slot.
6843     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
6844     unsigned LoadedBytes = LoadedVT.getStoreSize();
6845     unsigned RegBytes = RegVT.getSizeInBits() / 8;
6846     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
6847 
6848     // Make sure the stack slot is also aligned for the register type.
6849     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
6850     auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
6851     SmallVector<SDValue, 8> Stores;
6852     SDValue StackPtr = StackBase;
6853     unsigned Offset = 0;
6854 
6855     EVT PtrVT = Ptr.getValueType();
6856     EVT StackPtrVT = StackPtr.getValueType();
6857 
6858     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
6859     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
6860 
6861     // Do all but one copies using the full register width.
6862     for (unsigned i = 1; i < NumRegs; i++) {
6863       // Load one integer register's worth from the original location.
6864       SDValue Load = DAG.getLoad(
6865           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
6866           MinAlign(LD->getAlignment(), Offset), LD->getMemOperand()->getFlags(),
6867           LD->getAAInfo());
6868       // Follow the load with a store to the stack slot.  Remember the store.
6869       Stores.push_back(DAG.getStore(
6870           Load.getValue(1), dl, Load, StackPtr,
6871           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
6872       // Increment the pointers.
6873       Offset += RegBytes;
6874 
6875       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
6876       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
6877     }
6878 
6879     // The last copy may be partial.  Do an extending load.
6880     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
6881                                   8 * (LoadedBytes - Offset));
6882     SDValue Load =
6883         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
6884                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
6885                        MinAlign(LD->getAlignment(), Offset),
6886                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
6887     // Follow the load with a store to the stack slot.  Remember the store.
6888     // On big-endian machines this requires a truncating store to ensure
6889     // that the bits end up in the right place.
6890     Stores.push_back(DAG.getTruncStore(
6891         Load.getValue(1), dl, Load, StackPtr,
6892         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
6893 
6894     // The order of the stores doesn't matter - say it with a TokenFactor.
6895     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
6896 
6897     // Finally, perform the original load only redirected to the stack slot.
6898     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
6899                           MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
6900                           LoadedVT);
6901 
6902     // Callers expect a MERGE_VALUES node.
6903     return std::make_pair(Load, TF);
6904   }
6905 
6906   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
6907          "Unaligned load of unsupported type.");
6908 
6909   // Compute the new VT that is half the size of the old one.  This is an
6910   // integer MVT.
6911   unsigned NumBits = LoadedVT.getSizeInBits();
6912   EVT NewLoadedVT;
6913   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
6914   NumBits >>= 1;
6915 
6916   unsigned Alignment = LD->getAlignment();
6917   unsigned IncrementSize = NumBits / 8;
6918   ISD::LoadExtType HiExtType = LD->getExtensionType();
6919 
6920   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
6921   if (HiExtType == ISD::NON_EXTLOAD)
6922     HiExtType = ISD::ZEXTLOAD;
6923 
6924   // Load the value in two parts
6925   SDValue Lo, Hi;
6926   if (DAG.getDataLayout().isLittleEndian()) {
6927     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
6928                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
6929                         LD->getAAInfo());
6930 
6931     Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
6932     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
6933                         LD->getPointerInfo().getWithOffset(IncrementSize),
6934                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
6935                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
6936   } else {
6937     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
6938                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
6939                         LD->getAAInfo());
6940 
6941     Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
6942     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
6943                         LD->getPointerInfo().getWithOffset(IncrementSize),
6944                         NewLoadedVT, MinAlign(Alignment, IncrementSize),
6945                         LD->getMemOperand()->getFlags(), LD->getAAInfo());
6946   }
6947 
6948   // aggregate the two parts
6949   SDValue ShiftAmount =
6950       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
6951                                                     DAG.getDataLayout()));
6952   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
6953   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
6954 
6955   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
6956                              Hi.getValue(1));
6957 
6958   return std::make_pair(Result, TF);
6959 }
6960 
6961 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
6962                                              SelectionDAG &DAG) const {
6963   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
6964          "unaligned indexed stores not implemented!");
6965   SDValue Chain = ST->getChain();
6966   SDValue Ptr = ST->getBasePtr();
6967   SDValue Val = ST->getValue();
6968   EVT VT = Val.getValueType();
6969   int Alignment = ST->getAlignment();
6970   auto &MF = DAG.getMachineFunction();
6971   EVT StoreMemVT = ST->getMemoryVT();
6972 
6973   SDLoc dl(ST);
6974   if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
6975     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
6976     if (isTypeLegal(intVT)) {
6977       if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
6978           StoreMemVT.isVector()) {
6979         // Scalarize the store and let the individual components be handled.
6980         SDValue Result = scalarizeVectorStore(ST, DAG);
6981         return Result;
6982       }
6983       // Expand to a bitconvert of the value to the integer type of the
6984       // same size, then a (misaligned) int store.
6985       // FIXME: Does not handle truncating floating point stores!
6986       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
6987       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
6988                             Alignment, ST->getMemOperand()->getFlags());
6989       return Result;
6990     }
6991     // Do a (aligned) store to a stack slot, then copy from the stack slot
6992     // to the final destination using (unaligned) integer loads and stores.
6993     MVT RegVT = getRegisterType(
6994         *DAG.getContext(),
6995         EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
6996     EVT PtrVT = Ptr.getValueType();
6997     unsigned StoredBytes = StoreMemVT.getStoreSize();
6998     unsigned RegBytes = RegVT.getSizeInBits() / 8;
6999     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
7000 
7001     // Make sure the stack slot is also aligned for the register type.
7002     SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
7003     auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
7004 
7005     // Perform the original store, only redirected to the stack slot.
7006     SDValue Store = DAG.getTruncStore(
7007         Chain, dl, Val, StackPtr,
7008         MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
7009 
7010     EVT StackPtrVT = StackPtr.getValueType();
7011 
7012     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
7013     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
7014     SmallVector<SDValue, 8> Stores;
7015     unsigned Offset = 0;
7016 
7017     // Do all but one copies using the full register width.
7018     for (unsigned i = 1; i < NumRegs; i++) {
7019       // Load one integer register's worth from the stack slot.
7020       SDValue Load = DAG.getLoad(
7021           RegVT, dl, Store, StackPtr,
7022           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
7023       // Store it to the final location.  Remember the store.
7024       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
7025                                     ST->getPointerInfo().getWithOffset(Offset),
7026                                     MinAlign(ST->getAlignment(), Offset),
7027                                     ST->getMemOperand()->getFlags()));
7028       // Increment the pointers.
7029       Offset += RegBytes;
7030       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
7031       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
7032     }
7033 
7034     // The last store may be partial.  Do a truncating store.  On big-endian
7035     // machines this requires an extending load from the stack slot to ensure
7036     // that the bits are in the right place.
7037     EVT LoadMemVT =
7038         EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
7039 
7040     // Load from the stack slot.
7041     SDValue Load = DAG.getExtLoad(
7042         ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
7043         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
7044 
7045     Stores.push_back(
7046         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
7047                           ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
7048                           MinAlign(ST->getAlignment(), Offset),
7049                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
7050     // The order of the stores doesn't matter - say it with a TokenFactor.
7051     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7052     return Result;
7053   }
7054 
7055   assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
7056          "Unaligned store of unknown type.");
7057   // Get the half-size VT
7058   EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
7059   int NumBits = NewStoredVT.getSizeInBits();
7060   int IncrementSize = NumBits / 8;
7061 
7062   // Divide the stored value in two parts.
7063   SDValue ShiftAmount = DAG.getConstant(
7064       NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout()));
7065   SDValue Lo = Val;
7066   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
7067 
7068   // Store the two parts
7069   SDValue Store1, Store2;
7070   Store1 = DAG.getTruncStore(Chain, dl,
7071                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
7072                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
7073                              ST->getMemOperand()->getFlags());
7074 
7075   Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
7076   Alignment = MinAlign(Alignment, IncrementSize);
7077   Store2 = DAG.getTruncStore(
7078       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
7079       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
7080       ST->getMemOperand()->getFlags(), ST->getAAInfo());
7081 
7082   SDValue Result =
7083       DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
7084   return Result;
7085 }
7086 
7087 SDValue
7088 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
7089                                        const SDLoc &DL, EVT DataVT,
7090                                        SelectionDAG &DAG,
7091                                        bool IsCompressedMemory) const {
7092   SDValue Increment;
7093   EVT AddrVT = Addr.getValueType();
7094   EVT MaskVT = Mask.getValueType();
7095   assert(DataVT.getVectorNumElements() == MaskVT.getVectorNumElements() &&
7096          "Incompatible types of Data and Mask");
7097   if (IsCompressedMemory) {
7098     // Incrementing the pointer according to number of '1's in the mask.
7099     EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
7100     SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
7101     if (MaskIntVT.getSizeInBits() < 32) {
7102       MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
7103       MaskIntVT = MVT::i32;
7104     }
7105 
7106     // Count '1's with POPCNT.
7107     Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
7108     Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
7109     // Scale is an element size in bytes.
7110     SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
7111                                     AddrVT);
7112     Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
7113   } else
7114     Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT);
7115 
7116   return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
7117 }
7118 
7119 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG,
7120                                        SDValue Idx,
7121                                        EVT VecVT,
7122                                        const SDLoc &dl) {
7123   if (isa<ConstantSDNode>(Idx))
7124     return Idx;
7125 
7126   EVT IdxVT = Idx.getValueType();
7127   unsigned NElts = VecVT.getVectorNumElements();
7128   if (isPowerOf2_32(NElts)) {
7129     APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(),
7130                                      Log2_32(NElts));
7131     return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
7132                        DAG.getConstant(Imm, dl, IdxVT));
7133   }
7134 
7135   return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
7136                      DAG.getConstant(NElts - 1, dl, IdxVT));
7137 }
7138 
7139 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
7140                                                 SDValue VecPtr, EVT VecVT,
7141                                                 SDValue Index) const {
7142   SDLoc dl(Index);
7143   // Make sure the index type is big enough to compute in.
7144   Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
7145 
7146   EVT EltVT = VecVT.getVectorElementType();
7147 
7148   // Calculate the element offset and add it to the pointer.
7149   unsigned EltSize = EltVT.getSizeInBits() / 8; // FIXME: should be ABI size.
7150   assert(EltSize * 8 == EltVT.getSizeInBits() &&
7151          "Converting bits to bytes lost precision");
7152 
7153   Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl);
7154 
7155   EVT IdxVT = Index.getValueType();
7156 
7157   Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
7158                       DAG.getConstant(EltSize, dl, IdxVT));
7159   return DAG.getMemBasePlusOffset(VecPtr, Index, dl);
7160 }
7161 
7162 //===----------------------------------------------------------------------===//
7163 // Implementation of Emulated TLS Model
7164 //===----------------------------------------------------------------------===//
7165 
7166 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
7167                                                 SelectionDAG &DAG) const {
7168   // Access to address of TLS varialbe xyz is lowered to a function call:
7169   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
7170   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7171   PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
7172   SDLoc dl(GA);
7173 
7174   ArgListTy Args;
7175   ArgListEntry Entry;
7176   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
7177   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
7178   StringRef EmuTlsVarName(NameString);
7179   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
7180   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
7181   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
7182   Entry.Ty = VoidPtrType;
7183   Args.push_back(Entry);
7184 
7185   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
7186 
7187   TargetLowering::CallLoweringInfo CLI(DAG);
7188   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
7189   CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
7190   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7191 
7192   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
7193   // At last for X86 targets, maybe good for other targets too?
7194   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7195   MFI.setAdjustsStack(true); // Is this only for X86 target?
7196   MFI.setHasCalls(true);
7197 
7198   assert((GA->getOffset() == 0) &&
7199          "Emulated TLS must have zero offset in GlobalAddressSDNode");
7200   return CallResult.first;
7201 }
7202 
7203 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
7204                                                 SelectionDAG &DAG) const {
7205   assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
7206   if (!isCtlzFast())
7207     return SDValue();
7208   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7209   SDLoc dl(Op);
7210   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
7211     if (C->isNullValue() && CC == ISD::SETEQ) {
7212       EVT VT = Op.getOperand(0).getValueType();
7213       SDValue Zext = Op.getOperand(0);
7214       if (VT.bitsLT(MVT::i32)) {
7215         VT = MVT::i32;
7216         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
7217       }
7218       unsigned Log2b = Log2_32(VT.getSizeInBits());
7219       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
7220       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
7221                                 DAG.getConstant(Log2b, dl, MVT::i32));
7222       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
7223     }
7224   }
7225   return SDValue();
7226 }
7227 
7228 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const {
7229   unsigned Opcode = Node->getOpcode();
7230   SDValue LHS = Node->getOperand(0);
7231   SDValue RHS = Node->getOperand(1);
7232   EVT VT = LHS.getValueType();
7233   SDLoc dl(Node);
7234 
7235   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
7236   assert(VT.isInteger() && "Expected operands to be integers");
7237 
7238   // usub.sat(a, b) -> umax(a, b) - b
7239   if (Opcode == ISD::USUBSAT && isOperationLegalOrCustom(ISD::UMAX, VT)) {
7240     SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
7241     return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
7242   }
7243 
7244   if (Opcode == ISD::UADDSAT && isOperationLegalOrCustom(ISD::UMIN, VT)) {
7245     SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
7246     SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
7247     return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
7248   }
7249 
7250   unsigned OverflowOp;
7251   switch (Opcode) {
7252   case ISD::SADDSAT:
7253     OverflowOp = ISD::SADDO;
7254     break;
7255   case ISD::UADDSAT:
7256     OverflowOp = ISD::UADDO;
7257     break;
7258   case ISD::SSUBSAT:
7259     OverflowOp = ISD::SSUBO;
7260     break;
7261   case ISD::USUBSAT:
7262     OverflowOp = ISD::USUBO;
7263     break;
7264   default:
7265     llvm_unreachable("Expected method to receive signed or unsigned saturation "
7266                      "addition or subtraction node.");
7267   }
7268 
7269   unsigned BitWidth = LHS.getScalarValueSizeInBits();
7270   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7271   SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT),
7272                                LHS, RHS);
7273   SDValue SumDiff = Result.getValue(0);
7274   SDValue Overflow = Result.getValue(1);
7275   SDValue Zero = DAG.getConstant(0, dl, VT);
7276   SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
7277 
7278   if (Opcode == ISD::UADDSAT) {
7279     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
7280       // (LHS + RHS) | OverflowMask
7281       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
7282       return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
7283     }
7284     // Overflow ? 0xffff.... : (LHS + RHS)
7285     return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
7286   } else if (Opcode == ISD::USUBSAT) {
7287     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
7288       // (LHS - RHS) & ~OverflowMask
7289       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
7290       SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
7291       return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
7292     }
7293     // Overflow ? 0 : (LHS - RHS)
7294     return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
7295   } else {
7296     // SatMax -> Overflow && SumDiff < 0
7297     // SatMin -> Overflow && SumDiff >= 0
7298     APInt MinVal = APInt::getSignedMinValue(BitWidth);
7299     APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
7300     SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
7301     SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
7302     SDValue SumNeg = DAG.getSetCC(dl, BoolVT, SumDiff, Zero, ISD::SETLT);
7303     Result = DAG.getSelect(dl, VT, SumNeg, SatMax, SatMin);
7304     return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
7305   }
7306 }
7307 
7308 SDValue
7309 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const {
7310   assert((Node->getOpcode() == ISD::SMULFIX ||
7311           Node->getOpcode() == ISD::UMULFIX ||
7312           Node->getOpcode() == ISD::SMULFIXSAT ||
7313           Node->getOpcode() == ISD::UMULFIXSAT) &&
7314          "Expected a fixed point multiplication opcode");
7315 
7316   SDLoc dl(Node);
7317   SDValue LHS = Node->getOperand(0);
7318   SDValue RHS = Node->getOperand(1);
7319   EVT VT = LHS.getValueType();
7320   unsigned Scale = Node->getConstantOperandVal(2);
7321   bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
7322                      Node->getOpcode() == ISD::UMULFIXSAT);
7323   bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
7324                  Node->getOpcode() == ISD::SMULFIXSAT);
7325   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7326   unsigned VTSize = VT.getScalarSizeInBits();
7327 
7328   if (!Scale) {
7329     // [us]mul.fix(a, b, 0) -> mul(a, b)
7330     if (!Saturating) {
7331       if (isOperationLegalOrCustom(ISD::MUL, VT))
7332         return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
7333     } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
7334       SDValue Result =
7335           DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
7336       SDValue Product = Result.getValue(0);
7337       SDValue Overflow = Result.getValue(1);
7338       SDValue Zero = DAG.getConstant(0, dl, VT);
7339 
7340       APInt MinVal = APInt::getSignedMinValue(VTSize);
7341       APInt MaxVal = APInt::getSignedMaxValue(VTSize);
7342       SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
7343       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
7344       SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Product, Zero, ISD::SETLT);
7345       Result = DAG.getSelect(dl, VT, ProdNeg, SatMax, SatMin);
7346       return DAG.getSelect(dl, VT, Overflow, Result, Product);
7347     } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
7348       SDValue Result =
7349           DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
7350       SDValue Product = Result.getValue(0);
7351       SDValue Overflow = Result.getValue(1);
7352 
7353       APInt MaxVal = APInt::getMaxValue(VTSize);
7354       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
7355       return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
7356     }
7357   }
7358 
7359   assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
7360          "Expected scale to be less than the number of bits if signed or at "
7361          "most the number of bits if unsigned.");
7362   assert(LHS.getValueType() == RHS.getValueType() &&
7363          "Expected both operands to be the same type");
7364 
7365   // Get the upper and lower bits of the result.
7366   SDValue Lo, Hi;
7367   unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
7368   unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
7369   if (isOperationLegalOrCustom(LoHiOp, VT)) {
7370     SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
7371     Lo = Result.getValue(0);
7372     Hi = Result.getValue(1);
7373   } else if (isOperationLegalOrCustom(HiOp, VT)) {
7374     Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
7375     Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
7376   } else if (VT.isVector()) {
7377     return SDValue();
7378   } else {
7379     report_fatal_error("Unable to expand fixed point multiplication.");
7380   }
7381 
7382   if (Scale == VTSize)
7383     // Result is just the top half since we'd be shifting by the width of the
7384     // operand. Overflow impossible so this works for both UMULFIX and
7385     // UMULFIXSAT.
7386     return Hi;
7387 
7388   // The result will need to be shifted right by the scale since both operands
7389   // are scaled. The result is given to us in 2 halves, so we only want part of
7390   // both in the result.
7391   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
7392   SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
7393                                DAG.getConstant(Scale, dl, ShiftTy));
7394   if (!Saturating)
7395     return Result;
7396 
7397   if (!Signed) {
7398     // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
7399     // widened multiplication) aren't all zeroes.
7400 
7401     // Saturate to max if ((Hi >> Scale) != 0),
7402     // which is the same as if (Hi > ((1 << Scale) - 1))
7403     APInt MaxVal = APInt::getMaxValue(VTSize);
7404     SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale),
7405                                       dl, VT);
7406     Result = DAG.getSelectCC(dl, Hi, LowMask,
7407                              DAG.getConstant(MaxVal, dl, VT), Result,
7408                              ISD::SETUGT);
7409 
7410     return Result;
7411   }
7412 
7413   // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
7414   // widened multiplication) aren't all ones or all zeroes.
7415 
7416   SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
7417   SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
7418 
7419   if (Scale == 0) {
7420     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
7421                                DAG.getConstant(VTSize - 1, dl, ShiftTy));
7422     SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
7423     // Saturated to SatMin if wide product is negative, and SatMax if wide
7424     // product is positive ...
7425     SDValue Zero = DAG.getConstant(0, dl, VT);
7426     SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax,
7427                                                ISD::SETLT);
7428     // ... but only if we overflowed.
7429     return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
7430   }
7431 
7432   //  We handled Scale==0 above so all the bits to examine is in Hi.
7433 
7434   // Saturate to max if ((Hi >> (Scale - 1)) > 0),
7435   // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
7436   SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1),
7437                                     dl, VT);
7438   Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT);
7439   // Saturate to min if (Hi >> (Scale - 1)) < -1),
7440   // which is the same as if (HI < (-1 << (Scale - 1))
7441   SDValue HighMask =
7442       DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1),
7443                       dl, VT);
7444   Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT);
7445   return Result;
7446 }
7447 
7448 SDValue
7449 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl,
7450                                     SDValue LHS, SDValue RHS,
7451                                     unsigned Scale, SelectionDAG &DAG) const {
7452   assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
7453           Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
7454          "Expected a fixed point division opcode");
7455 
7456   EVT VT = LHS.getValueType();
7457   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
7458   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
7459   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7460 
7461   // If there is enough room in the type to upscale the LHS or downscale the
7462   // RHS before the division, we can perform it in this type without having to
7463   // resize. For signed operations, the LHS headroom is the number of
7464   // redundant sign bits, and for unsigned ones it is the number of zeroes.
7465   // The headroom for the RHS is the number of trailing zeroes.
7466   unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
7467                             : DAG.computeKnownBits(LHS).countMinLeadingZeros();
7468   unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
7469 
7470   // For signed saturating operations, we need to be able to detect true integer
7471   // division overflow; that is, when you have MIN / -EPS. However, this
7472   // is undefined behavior and if we emit divisions that could take such
7473   // values it may cause undesired behavior (arithmetic exceptions on x86, for
7474   // example).
7475   // Avoid this by requiring an extra bit so that we never get this case.
7476   // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
7477   // signed saturating division, we need to emit a whopping 32-bit division.
7478   if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
7479     return SDValue();
7480 
7481   unsigned LHSShift = std::min(LHSLead, Scale);
7482   unsigned RHSShift = Scale - LHSShift;
7483 
7484   // At this point, we know that if we shift the LHS up by LHSShift and the
7485   // RHS down by RHSShift, we can emit a regular division with a final scaling
7486   // factor of Scale.
7487 
7488   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
7489   if (LHSShift)
7490     LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
7491                       DAG.getConstant(LHSShift, dl, ShiftTy));
7492   if (RHSShift)
7493     RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
7494                       DAG.getConstant(RHSShift, dl, ShiftTy));
7495 
7496   SDValue Quot;
7497   if (Signed) {
7498     // For signed operations, if the resulting quotient is negative and the
7499     // remainder is nonzero, subtract 1 from the quotient to round towards
7500     // negative infinity.
7501     SDValue Rem;
7502     // FIXME: Ideally we would always produce an SDIVREM here, but if the
7503     // type isn't legal, SDIVREM cannot be expanded. There is no reason why
7504     // we couldn't just form a libcall, but the type legalizer doesn't do it.
7505     if (isTypeLegal(VT) &&
7506         isOperationLegalOrCustom(ISD::SDIVREM, VT)) {
7507       Quot = DAG.getNode(ISD::SDIVREM, dl,
7508                          DAG.getVTList(VT, VT),
7509                          LHS, RHS);
7510       Rem = Quot.getValue(1);
7511       Quot = Quot.getValue(0);
7512     } else {
7513       Quot = DAG.getNode(ISD::SDIV, dl, VT,
7514                          LHS, RHS);
7515       Rem = DAG.getNode(ISD::SREM, dl, VT,
7516                         LHS, RHS);
7517     }
7518     SDValue Zero = DAG.getConstant(0, dl, VT);
7519     SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
7520     SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
7521     SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
7522     SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
7523     SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
7524                                DAG.getConstant(1, dl, VT));
7525     Quot = DAG.getSelect(dl, VT,
7526                          DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
7527                          Sub1, Quot);
7528   } else
7529     Quot = DAG.getNode(ISD::UDIV, dl, VT,
7530                        LHS, RHS);
7531 
7532   return Quot;
7533 }
7534 
7535 void TargetLowering::expandUADDSUBO(
7536     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
7537   SDLoc dl(Node);
7538   SDValue LHS = Node->getOperand(0);
7539   SDValue RHS = Node->getOperand(1);
7540   bool IsAdd = Node->getOpcode() == ISD::UADDO;
7541 
7542   // If ADD/SUBCARRY is legal, use that instead.
7543   unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY;
7544   if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
7545     SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
7546     SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
7547                                     { LHS, RHS, CarryIn });
7548     Result = SDValue(NodeCarry.getNode(), 0);
7549     Overflow = SDValue(NodeCarry.getNode(), 1);
7550     return;
7551   }
7552 
7553   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
7554                             LHS.getValueType(), LHS, RHS);
7555 
7556   EVT ResultType = Node->getValueType(1);
7557   EVT SetCCType = getSetCCResultType(
7558       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
7559   ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
7560   SDValue SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
7561   Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
7562 }
7563 
7564 void TargetLowering::expandSADDSUBO(
7565     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
7566   SDLoc dl(Node);
7567   SDValue LHS = Node->getOperand(0);
7568   SDValue RHS = Node->getOperand(1);
7569   bool IsAdd = Node->getOpcode() == ISD::SADDO;
7570 
7571   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
7572                             LHS.getValueType(), LHS, RHS);
7573 
7574   EVT ResultType = Node->getValueType(1);
7575   EVT OType = getSetCCResultType(
7576       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
7577 
7578   // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
7579   unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
7580   if (isOperationLegalOrCustom(OpcSat, LHS.getValueType())) {
7581     SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
7582     SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
7583     Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
7584     return;
7585   }
7586 
7587   SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
7588 
7589   // For an addition, the result should be less than one of the operands (LHS)
7590   // if and only if the other operand (RHS) is negative, otherwise there will
7591   // be overflow.
7592   // For a subtraction, the result should be less than one of the operands
7593   // (LHS) if and only if the other operand (RHS) is (non-zero) positive,
7594   // otherwise there will be overflow.
7595   SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
7596   SDValue ConditionRHS =
7597       DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT);
7598 
7599   Overflow = DAG.getBoolExtOrTrunc(
7600       DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl,
7601       ResultType, ResultType);
7602 }
7603 
7604 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result,
7605                                 SDValue &Overflow, SelectionDAG &DAG) const {
7606   SDLoc dl(Node);
7607   EVT VT = Node->getValueType(0);
7608   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7609   SDValue LHS = Node->getOperand(0);
7610   SDValue RHS = Node->getOperand(1);
7611   bool isSigned = Node->getOpcode() == ISD::SMULO;
7612 
7613   // For power-of-two multiplications we can use a simpler shift expansion.
7614   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
7615     const APInt &C = RHSC->getAPIntValue();
7616     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
7617     if (C.isPowerOf2()) {
7618       // smulo(x, signed_min) is same as umulo(x, signed_min).
7619       bool UseArithShift = isSigned && !C.isMinSignedValue();
7620       EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout());
7621       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy);
7622       Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
7623       Overflow = DAG.getSetCC(dl, SetCCVT,
7624           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
7625                       dl, VT, Result, ShiftAmt),
7626           LHS, ISD::SETNE);
7627       return true;
7628     }
7629   }
7630 
7631   EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2);
7632   if (VT.isVector())
7633     WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT,
7634                               VT.getVectorNumElements());
7635 
7636   SDValue BottomHalf;
7637   SDValue TopHalf;
7638   static const unsigned Ops[2][3] =
7639       { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
7640         { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
7641   if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
7642     BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
7643     TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
7644   } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
7645     BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
7646                              RHS);
7647     TopHalf = BottomHalf.getValue(1);
7648   } else if (isTypeLegal(WideVT)) {
7649     LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
7650     RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
7651     SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
7652     BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
7653     SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl,
7654         getShiftAmountTy(WideVT, DAG.getDataLayout()));
7655     TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
7656                           DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
7657   } else {
7658     if (VT.isVector())
7659       return false;
7660 
7661     // We can fall back to a libcall with an illegal type for the MUL if we
7662     // have a libcall big enough.
7663     // Also, we can fall back to a division in some cases, but that's a big
7664     // performance hit in the general case.
7665     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
7666     if (WideVT == MVT::i16)
7667       LC = RTLIB::MUL_I16;
7668     else if (WideVT == MVT::i32)
7669       LC = RTLIB::MUL_I32;
7670     else if (WideVT == MVT::i64)
7671       LC = RTLIB::MUL_I64;
7672     else if (WideVT == MVT::i128)
7673       LC = RTLIB::MUL_I128;
7674     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
7675 
7676     SDValue HiLHS;
7677     SDValue HiRHS;
7678     if (isSigned) {
7679       // The high part is obtained by SRA'ing all but one of the bits of low
7680       // part.
7681       unsigned LoSize = VT.getSizeInBits();
7682       HiLHS =
7683           DAG.getNode(ISD::SRA, dl, VT, LHS,
7684                       DAG.getConstant(LoSize - 1, dl,
7685                                       getPointerTy(DAG.getDataLayout())));
7686       HiRHS =
7687           DAG.getNode(ISD::SRA, dl, VT, RHS,
7688                       DAG.getConstant(LoSize - 1, dl,
7689                                       getPointerTy(DAG.getDataLayout())));
7690     } else {
7691         HiLHS = DAG.getConstant(0, dl, VT);
7692         HiRHS = DAG.getConstant(0, dl, VT);
7693     }
7694 
7695     // Here we're passing the 2 arguments explicitly as 4 arguments that are
7696     // pre-lowered to the correct types. This all depends upon WideVT not
7697     // being a legal type for the architecture and thus has to be split to
7698     // two arguments.
7699     SDValue Ret;
7700     TargetLowering::MakeLibCallOptions CallOptions;
7701     CallOptions.setSExt(isSigned);
7702     CallOptions.setIsPostTypeLegalization(true);
7703     if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) {
7704       // Halves of WideVT are packed into registers in different order
7705       // depending on platform endianness. This is usually handled by
7706       // the C calling convention, but we can't defer to it in
7707       // the legalizer.
7708       SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
7709       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
7710     } else {
7711       SDValue Args[] = { HiLHS, LHS, HiRHS, RHS };
7712       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
7713     }
7714     assert(Ret.getOpcode() == ISD::MERGE_VALUES &&
7715            "Ret value is a collection of constituent nodes holding result.");
7716     if (DAG.getDataLayout().isLittleEndian()) {
7717       // Same as above.
7718       BottomHalf = Ret.getOperand(0);
7719       TopHalf = Ret.getOperand(1);
7720     } else {
7721       BottomHalf = Ret.getOperand(1);
7722       TopHalf = Ret.getOperand(0);
7723     }
7724   }
7725 
7726   Result = BottomHalf;
7727   if (isSigned) {
7728     SDValue ShiftAmt = DAG.getConstant(
7729         VT.getScalarSizeInBits() - 1, dl,
7730         getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout()));
7731     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
7732     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
7733   } else {
7734     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
7735                             DAG.getConstant(0, dl, VT), ISD::SETNE);
7736   }
7737 
7738   // Truncate the result if SetCC returns a larger type than needed.
7739   EVT RType = Node->getValueType(1);
7740   if (RType.getSizeInBits() < Overflow.getValueSizeInBits())
7741     Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
7742 
7743   assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
7744          "Unexpected result type for S/UMULO legalization");
7745   return true;
7746 }
7747 
7748 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const {
7749   SDLoc dl(Node);
7750   bool NoNaN = Node->getFlags().hasNoNaNs();
7751   unsigned BaseOpcode = 0;
7752   switch (Node->getOpcode()) {
7753   default: llvm_unreachable("Expected VECREDUCE opcode");
7754   case ISD::VECREDUCE_FADD: BaseOpcode = ISD::FADD; break;
7755   case ISD::VECREDUCE_FMUL: BaseOpcode = ISD::FMUL; break;
7756   case ISD::VECREDUCE_ADD:  BaseOpcode = ISD::ADD; break;
7757   case ISD::VECREDUCE_MUL:  BaseOpcode = ISD::MUL; break;
7758   case ISD::VECREDUCE_AND:  BaseOpcode = ISD::AND; break;
7759   case ISD::VECREDUCE_OR:   BaseOpcode = ISD::OR; break;
7760   case ISD::VECREDUCE_XOR:  BaseOpcode = ISD::XOR; break;
7761   case ISD::VECREDUCE_SMAX: BaseOpcode = ISD::SMAX; break;
7762   case ISD::VECREDUCE_SMIN: BaseOpcode = ISD::SMIN; break;
7763   case ISD::VECREDUCE_UMAX: BaseOpcode = ISD::UMAX; break;
7764   case ISD::VECREDUCE_UMIN: BaseOpcode = ISD::UMIN; break;
7765   case ISD::VECREDUCE_FMAX:
7766     BaseOpcode = NoNaN ? ISD::FMAXNUM : ISD::FMAXIMUM;
7767     break;
7768   case ISD::VECREDUCE_FMIN:
7769     BaseOpcode = NoNaN ? ISD::FMINNUM : ISD::FMINIMUM;
7770     break;
7771   }
7772 
7773   SDValue Op = Node->getOperand(0);
7774   EVT VT = Op.getValueType();
7775 
7776   // Try to use a shuffle reduction for power of two vectors.
7777   if (VT.isPow2VectorType()) {
7778     while (VT.getVectorNumElements() > 1) {
7779       EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
7780       if (!isOperationLegalOrCustom(BaseOpcode, HalfVT))
7781         break;
7782 
7783       SDValue Lo, Hi;
7784       std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
7785       Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi);
7786       VT = HalfVT;
7787     }
7788   }
7789 
7790   EVT EltVT = VT.getVectorElementType();
7791   unsigned NumElts = VT.getVectorNumElements();
7792 
7793   SmallVector<SDValue, 8> Ops;
7794   DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
7795 
7796   SDValue Res = Ops[0];
7797   for (unsigned i = 1; i < NumElts; i++)
7798     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags());
7799 
7800   // Result type may be wider than element type.
7801   if (EltVT != Node->getValueType(0))
7802     Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
7803   return Res;
7804 }
7805