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