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     // 'Quadratic Reciprocity': mul(x,x) -> 0 if we're only demanding bit[1]
2269     if (DemandedBits == 2 && Op.getOperand(0) == Op.getOperand(1))
2270       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
2271     LLVM_FALLTHROUGH;
2272   case ISD::ADD:
2273   case ISD::SUB: {
2274     // Add, Sub, and Mul don't demand any bits in positions beyond that
2275     // of the highest bit demanded of them.
2276     SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
2277     SDNodeFlags Flags = Op.getNode()->getFlags();
2278     unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros();
2279     APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2280     if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO,
2281                              Depth + 1) ||
2282         SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO,
2283                              Depth + 1) ||
2284         // See if the operation should be performed at a smaller bit width.
2285         ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) {
2286       if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
2287         // Disable the nsw and nuw flags. We can no longer guarantee that we
2288         // won't wrap after simplification.
2289         Flags.setNoSignedWrap(false);
2290         Flags.setNoUnsignedWrap(false);
2291         SDValue NewOp =
2292             TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
2293         return TLO.CombineTo(Op, NewOp);
2294       }
2295       return true;
2296     }
2297 
2298     // Attempt to avoid multi-use ops if we don't need anything from them.
2299     if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2300       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
2301           Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2302       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
2303           Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2304       if (DemandedOp0 || DemandedOp1) {
2305         Flags.setNoSignedWrap(false);
2306         Flags.setNoUnsignedWrap(false);
2307         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
2308         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
2309         SDValue NewOp =
2310             TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
2311         return TLO.CombineTo(Op, NewOp);
2312       }
2313     }
2314 
2315     // If we have a constant operand, we may be able to turn it into -1 if we
2316     // do not demand the high bits. This can make the constant smaller to
2317     // encode, allow more general folding, or match specialized instruction
2318     // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
2319     // is probably not useful (and could be detrimental).
2320     ConstantSDNode *C = isConstOrConstSplat(Op1);
2321     APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
2322     if (C && !C->isAllOnes() && !C->isOne() &&
2323         (C->getAPIntValue() | HighMask).isAllOnes()) {
2324       SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
2325       // Disable the nsw and nuw flags. We can no longer guarantee that we
2326       // won't wrap after simplification.
2327       Flags.setNoSignedWrap(false);
2328       Flags.setNoUnsignedWrap(false);
2329       SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags);
2330       return TLO.CombineTo(Op, NewOp);
2331     }
2332 
2333     LLVM_FALLTHROUGH;
2334   }
2335   default:
2336     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
2337       if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts,
2338                                             Known, TLO, Depth))
2339         return true;
2340       break;
2341     }
2342 
2343     // Just use computeKnownBits to compute output bits.
2344     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2345     break;
2346   }
2347 
2348   // If we know the value of all of the demanded bits, return this as a
2349   // constant.
2350   if (DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
2351     // Avoid folding to a constant if any OpaqueConstant is involved.
2352     const SDNode *N = Op.getNode();
2353     for (SDNode *Op :
2354          llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) {
2355       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
2356         if (C->isOpaque())
2357           return false;
2358     }
2359     if (VT.isInteger())
2360       return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
2361     if (VT.isFloatingPoint())
2362       return TLO.CombineTo(
2363           Op,
2364           TLO.DAG.getConstantFP(
2365               APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT));
2366   }
2367 
2368   return false;
2369 }
2370 
2371 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op,
2372                                                 const APInt &DemandedElts,
2373                                                 DAGCombinerInfo &DCI) const {
2374   SelectionDAG &DAG = DCI.DAG;
2375   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
2376                         !DCI.isBeforeLegalizeOps());
2377 
2378   APInt KnownUndef, KnownZero;
2379   bool Simplified =
2380       SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
2381   if (Simplified) {
2382     DCI.AddToWorklist(Op.getNode());
2383     DCI.CommitTargetLoweringOpt(TLO);
2384   }
2385 
2386   return Simplified;
2387 }
2388 
2389 /// Given a vector binary operation and known undefined elements for each input
2390 /// operand, compute whether each element of the output is undefined.
2391 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG,
2392                                          const APInt &UndefOp0,
2393                                          const APInt &UndefOp1) {
2394   EVT VT = BO.getValueType();
2395   assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() &&
2396          "Vector binop only");
2397 
2398   EVT EltVT = VT.getVectorElementType();
2399   unsigned NumElts = VT.getVectorNumElements();
2400   assert(UndefOp0.getBitWidth() == NumElts &&
2401          UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
2402 
2403   auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
2404                                    const APInt &UndefVals) {
2405     if (UndefVals[Index])
2406       return DAG.getUNDEF(EltVT);
2407 
2408     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2409       // Try hard to make sure that the getNode() call is not creating temporary
2410       // nodes. Ignore opaque integers because they do not constant fold.
2411       SDValue Elt = BV->getOperand(Index);
2412       auto *C = dyn_cast<ConstantSDNode>(Elt);
2413       if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
2414         return Elt;
2415     }
2416 
2417     return SDValue();
2418   };
2419 
2420   APInt KnownUndef = APInt::getZero(NumElts);
2421   for (unsigned i = 0; i != NumElts; ++i) {
2422     // If both inputs for this element are either constant or undef and match
2423     // the element type, compute the constant/undef result for this element of
2424     // the vector.
2425     // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
2426     // not handle FP constants. The code within getNode() should be refactored
2427     // to avoid the danger of creating a bogus temporary node here.
2428     SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
2429     SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
2430     if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
2431       if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
2432         KnownUndef.setBit(i);
2433   }
2434   return KnownUndef;
2435 }
2436 
2437 bool TargetLowering::SimplifyDemandedVectorElts(
2438     SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
2439     APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
2440     bool AssumeSingleUse) const {
2441   EVT VT = Op.getValueType();
2442   unsigned Opcode = Op.getOpcode();
2443   APInt DemandedElts = OriginalDemandedElts;
2444   unsigned NumElts = DemandedElts.getBitWidth();
2445   assert(VT.isVector() && "Expected vector op");
2446 
2447   KnownUndef = KnownZero = APInt::getZero(NumElts);
2448 
2449   // TODO: For now we assume we know nothing about scalable vectors.
2450   if (VT.isScalableVector())
2451     return false;
2452 
2453   assert(VT.getVectorNumElements() == NumElts &&
2454          "Mask size mismatches value type element count!");
2455 
2456   // Undef operand.
2457   if (Op.isUndef()) {
2458     KnownUndef.setAllBits();
2459     return false;
2460   }
2461 
2462   // If Op has other users, assume that all elements are needed.
2463   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse)
2464     DemandedElts.setAllBits();
2465 
2466   // Not demanding any elements from Op.
2467   if (DemandedElts == 0) {
2468     KnownUndef.setAllBits();
2469     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2470   }
2471 
2472   // Limit search depth.
2473   if (Depth >= SelectionDAG::MaxRecursionDepth)
2474     return false;
2475 
2476   SDLoc DL(Op);
2477   unsigned EltSizeInBits = VT.getScalarSizeInBits();
2478   bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
2479 
2480   // Helper for demanding the specified elements and all the bits of both binary
2481   // operands.
2482   auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) {
2483     SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts,
2484                                                            TLO.DAG, Depth + 1);
2485     SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts,
2486                                                            TLO.DAG, Depth + 1);
2487     if (NewOp0 || NewOp1) {
2488       SDValue NewOp = TLO.DAG.getNode(
2489           Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, NewOp1 ? NewOp1 : Op1);
2490       return TLO.CombineTo(Op, NewOp);
2491     }
2492     return false;
2493   };
2494 
2495   switch (Opcode) {
2496   case ISD::SCALAR_TO_VECTOR: {
2497     if (!DemandedElts[0]) {
2498       KnownUndef.setAllBits();
2499       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2500     }
2501     SDValue ScalarSrc = Op.getOperand(0);
2502     if (ScalarSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
2503       SDValue Src = ScalarSrc.getOperand(0);
2504       SDValue Idx = ScalarSrc.getOperand(1);
2505       EVT SrcVT = Src.getValueType();
2506 
2507       ElementCount SrcEltCnt = SrcVT.getVectorElementCount();
2508 
2509       if (SrcEltCnt.isScalable())
2510         return false;
2511 
2512       unsigned NumSrcElts = SrcEltCnt.getFixedValue();
2513       if (isNullConstant(Idx)) {
2514         APInt SrcDemandedElts = APInt::getOneBitSet(NumSrcElts, 0);
2515         APInt SrcUndef = KnownUndef.zextOrTrunc(NumSrcElts);
2516         APInt SrcZero = KnownZero.zextOrTrunc(NumSrcElts);
2517         if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2518                                        TLO, Depth + 1))
2519           return true;
2520       }
2521     }
2522     KnownUndef.setHighBits(NumElts - 1);
2523     break;
2524   }
2525   case ISD::BITCAST: {
2526     SDValue Src = Op.getOperand(0);
2527     EVT SrcVT = Src.getValueType();
2528 
2529     // We only handle vectors here.
2530     // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits?
2531     if (!SrcVT.isVector())
2532       break;
2533 
2534     // Fast handling of 'identity' bitcasts.
2535     unsigned NumSrcElts = SrcVT.getVectorNumElements();
2536     if (NumSrcElts == NumElts)
2537       return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
2538                                         KnownZero, TLO, Depth + 1);
2539 
2540     APInt SrcDemandedElts, SrcZero, SrcUndef;
2541 
2542     // Bitcast from 'large element' src vector to 'small element' vector, we
2543     // must demand a source element if any DemandedElt maps to it.
2544     if ((NumElts % NumSrcElts) == 0) {
2545       unsigned Scale = NumElts / NumSrcElts;
2546       SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2547       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2548                                      TLO, Depth + 1))
2549         return true;
2550 
2551       // Try calling SimplifyDemandedBits, converting demanded elts to the bits
2552       // of the large element.
2553       // TODO - bigendian once we have test coverage.
2554       if (IsLE) {
2555         unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
2556         APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits);
2557         for (unsigned i = 0; i != NumElts; ++i)
2558           if (DemandedElts[i]) {
2559             unsigned Ofs = (i % Scale) * EltSizeInBits;
2560             SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
2561           }
2562 
2563         KnownBits Known;
2564         if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known,
2565                                  TLO, Depth + 1))
2566           return true;
2567       }
2568 
2569       // If the src element is zero/undef then all the output elements will be -
2570       // only demanded elements are guaranteed to be correct.
2571       for (unsigned i = 0; i != NumSrcElts; ++i) {
2572         if (SrcDemandedElts[i]) {
2573           if (SrcZero[i])
2574             KnownZero.setBits(i * Scale, (i + 1) * Scale);
2575           if (SrcUndef[i])
2576             KnownUndef.setBits(i * Scale, (i + 1) * Scale);
2577         }
2578       }
2579     }
2580 
2581     // Bitcast from 'small element' src vector to 'large element' vector, we
2582     // demand all smaller source elements covered by the larger demanded element
2583     // of this vector.
2584     if ((NumSrcElts % NumElts) == 0) {
2585       unsigned Scale = NumSrcElts / NumElts;
2586       SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2587       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2588                                      TLO, Depth + 1))
2589         return true;
2590 
2591       // If all the src elements covering an output element are zero/undef, then
2592       // the output element will be as well, assuming it was demanded.
2593       for (unsigned i = 0; i != NumElts; ++i) {
2594         if (DemandedElts[i]) {
2595           if (SrcZero.extractBits(Scale, i * Scale).isAllOnes())
2596             KnownZero.setBit(i);
2597           if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes())
2598             KnownUndef.setBit(i);
2599         }
2600       }
2601     }
2602     break;
2603   }
2604   case ISD::BUILD_VECTOR: {
2605     // Check all elements and simplify any unused elements with UNDEF.
2606     if (!DemandedElts.isAllOnes()) {
2607       // Don't simplify BROADCASTS.
2608       if (llvm::any_of(Op->op_values(),
2609                        [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
2610         SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end());
2611         bool Updated = false;
2612         for (unsigned i = 0; i != NumElts; ++i) {
2613           if (!DemandedElts[i] && !Ops[i].isUndef()) {
2614             Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
2615             KnownUndef.setBit(i);
2616             Updated = true;
2617           }
2618         }
2619         if (Updated)
2620           return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
2621       }
2622     }
2623     for (unsigned i = 0; i != NumElts; ++i) {
2624       SDValue SrcOp = Op.getOperand(i);
2625       if (SrcOp.isUndef()) {
2626         KnownUndef.setBit(i);
2627       } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
2628                  (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) {
2629         KnownZero.setBit(i);
2630       }
2631     }
2632     break;
2633   }
2634   case ISD::CONCAT_VECTORS: {
2635     EVT SubVT = Op.getOperand(0).getValueType();
2636     unsigned NumSubVecs = Op.getNumOperands();
2637     unsigned NumSubElts = SubVT.getVectorNumElements();
2638     for (unsigned i = 0; i != NumSubVecs; ++i) {
2639       SDValue SubOp = Op.getOperand(i);
2640       APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
2641       APInt SubUndef, SubZero;
2642       if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
2643                                      Depth + 1))
2644         return true;
2645       KnownUndef.insertBits(SubUndef, i * NumSubElts);
2646       KnownZero.insertBits(SubZero, i * NumSubElts);
2647     }
2648     break;
2649   }
2650   case ISD::INSERT_SUBVECTOR: {
2651     // Demand any elements from the subvector and the remainder from the src its
2652     // inserted into.
2653     SDValue Src = Op.getOperand(0);
2654     SDValue Sub = Op.getOperand(1);
2655     uint64_t Idx = Op.getConstantOperandVal(2);
2656     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2657     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2658     APInt DemandedSrcElts = DemandedElts;
2659     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
2660 
2661     APInt SubUndef, SubZero;
2662     if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
2663                                    Depth + 1))
2664       return true;
2665 
2666     // If none of the src operand elements are demanded, replace it with undef.
2667     if (!DemandedSrcElts && !Src.isUndef())
2668       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
2669                                                TLO.DAG.getUNDEF(VT), Sub,
2670                                                Op.getOperand(2)));
2671 
2672     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
2673                                    TLO, Depth + 1))
2674       return true;
2675     KnownUndef.insertBits(SubUndef, Idx);
2676     KnownZero.insertBits(SubZero, Idx);
2677 
2678     // Attempt to avoid multi-use ops if we don't need anything from them.
2679     if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) {
2680       SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
2681           Src, DemandedSrcElts, TLO.DAG, Depth + 1);
2682       SDValue NewSub = SimplifyMultipleUseDemandedVectorElts(
2683           Sub, DemandedSubElts, TLO.DAG, Depth + 1);
2684       if (NewSrc || NewSub) {
2685         NewSrc = NewSrc ? NewSrc : Src;
2686         NewSub = NewSub ? NewSub : Sub;
2687         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
2688                                         NewSub, Op.getOperand(2));
2689         return TLO.CombineTo(Op, NewOp);
2690       }
2691     }
2692     break;
2693   }
2694   case ISD::EXTRACT_SUBVECTOR: {
2695     // Offset the demanded elts by the subvector index.
2696     SDValue Src = Op.getOperand(0);
2697     if (Src.getValueType().isScalableVector())
2698       break;
2699     uint64_t Idx = Op.getConstantOperandVal(1);
2700     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2701     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2702 
2703     APInt SrcUndef, SrcZero;
2704     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
2705                                    Depth + 1))
2706       return true;
2707     KnownUndef = SrcUndef.extractBits(NumElts, Idx);
2708     KnownZero = SrcZero.extractBits(NumElts, Idx);
2709 
2710     // Attempt to avoid multi-use ops if we don't need anything from them.
2711     if (!DemandedElts.isAllOnes()) {
2712       SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
2713           Src, DemandedSrcElts, TLO.DAG, Depth + 1);
2714       if (NewSrc) {
2715         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
2716                                         Op.getOperand(1));
2717         return TLO.CombineTo(Op, NewOp);
2718       }
2719     }
2720     break;
2721   }
2722   case ISD::INSERT_VECTOR_ELT: {
2723     SDValue Vec = Op.getOperand(0);
2724     SDValue Scl = Op.getOperand(1);
2725     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2726 
2727     // For a legal, constant insertion index, if we don't need this insertion
2728     // then strip it, else remove it from the demanded elts.
2729     if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
2730       unsigned Idx = CIdx->getZExtValue();
2731       if (!DemandedElts[Idx])
2732         return TLO.CombineTo(Op, Vec);
2733 
2734       APInt DemandedVecElts(DemandedElts);
2735       DemandedVecElts.clearBit(Idx);
2736       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
2737                                      KnownZero, TLO, Depth + 1))
2738         return true;
2739 
2740       KnownUndef.setBitVal(Idx, Scl.isUndef());
2741 
2742       KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl));
2743       break;
2744     }
2745 
2746     APInt VecUndef, VecZero;
2747     if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
2748                                    Depth + 1))
2749       return true;
2750     // Without knowing the insertion index we can't set KnownUndef/KnownZero.
2751     break;
2752   }
2753   case ISD::VSELECT: {
2754     // Try to transform the select condition based on the current demanded
2755     // elements.
2756     // TODO: If a condition element is undef, we can choose from one arm of the
2757     //       select (and if one arm is undef, then we can propagate that to the
2758     //       result).
2759     // TODO - add support for constant vselect masks (see IR version of this).
2760     APInt UnusedUndef, UnusedZero;
2761     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef,
2762                                    UnusedZero, TLO, Depth + 1))
2763       return true;
2764 
2765     // See if we can simplify either vselect operand.
2766     APInt DemandedLHS(DemandedElts);
2767     APInt DemandedRHS(DemandedElts);
2768     APInt UndefLHS, ZeroLHS;
2769     APInt UndefRHS, ZeroRHS;
2770     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS,
2771                                    ZeroLHS, TLO, Depth + 1))
2772       return true;
2773     if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS,
2774                                    ZeroRHS, TLO, Depth + 1))
2775       return true;
2776 
2777     KnownUndef = UndefLHS & UndefRHS;
2778     KnownZero = ZeroLHS & ZeroRHS;
2779     break;
2780   }
2781   case ISD::VECTOR_SHUFFLE: {
2782     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
2783 
2784     // Collect demanded elements from shuffle operands..
2785     APInt DemandedLHS(NumElts, 0);
2786     APInt DemandedRHS(NumElts, 0);
2787     for (unsigned i = 0; i != NumElts; ++i) {
2788       int M = ShuffleMask[i];
2789       if (M < 0 || !DemandedElts[i])
2790         continue;
2791       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
2792       if (M < (int)NumElts)
2793         DemandedLHS.setBit(M);
2794       else
2795         DemandedRHS.setBit(M - NumElts);
2796     }
2797 
2798     // See if we can simplify either shuffle operand.
2799     APInt UndefLHS, ZeroLHS;
2800     APInt UndefRHS, ZeroRHS;
2801     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS,
2802                                    ZeroLHS, TLO, Depth + 1))
2803       return true;
2804     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS,
2805                                    ZeroRHS, TLO, Depth + 1))
2806       return true;
2807 
2808     // Simplify mask using undef elements from LHS/RHS.
2809     bool Updated = false;
2810     bool IdentityLHS = true, IdentityRHS = true;
2811     SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end());
2812     for (unsigned i = 0; i != NumElts; ++i) {
2813       int &M = NewMask[i];
2814       if (M < 0)
2815         continue;
2816       if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
2817           (M >= (int)NumElts && UndefRHS[M - NumElts])) {
2818         Updated = true;
2819         M = -1;
2820       }
2821       IdentityLHS &= (M < 0) || (M == (int)i);
2822       IdentityRHS &= (M < 0) || ((M - NumElts) == i);
2823     }
2824 
2825     // Update legal shuffle masks based on demanded elements if it won't reduce
2826     // to Identity which can cause premature removal of the shuffle mask.
2827     if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
2828       SDValue LegalShuffle =
2829           buildLegalVectorShuffle(VT, DL, Op.getOperand(0), Op.getOperand(1),
2830                                   NewMask, TLO.DAG);
2831       if (LegalShuffle)
2832         return TLO.CombineTo(Op, LegalShuffle);
2833     }
2834 
2835     // Propagate undef/zero elements from LHS/RHS.
2836     for (unsigned i = 0; i != NumElts; ++i) {
2837       int M = ShuffleMask[i];
2838       if (M < 0) {
2839         KnownUndef.setBit(i);
2840       } else if (M < (int)NumElts) {
2841         if (UndefLHS[M])
2842           KnownUndef.setBit(i);
2843         if (ZeroLHS[M])
2844           KnownZero.setBit(i);
2845       } else {
2846         if (UndefRHS[M - NumElts])
2847           KnownUndef.setBit(i);
2848         if (ZeroRHS[M - NumElts])
2849           KnownZero.setBit(i);
2850       }
2851     }
2852     break;
2853   }
2854   case ISD::ANY_EXTEND_VECTOR_INREG:
2855   case ISD::SIGN_EXTEND_VECTOR_INREG:
2856   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2857     APInt SrcUndef, SrcZero;
2858     SDValue Src = Op.getOperand(0);
2859     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2860     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts);
2861     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
2862                                    Depth + 1))
2863       return true;
2864     KnownZero = SrcZero.zextOrTrunc(NumElts);
2865     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
2866 
2867     if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
2868         Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
2869         DemandedSrcElts == 1) {
2870       // aext - if we just need the bottom element then we can bitcast.
2871       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2872     }
2873 
2874     if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
2875       // zext(undef) upper bits are guaranteed to be zero.
2876       if (DemandedElts.isSubsetOf(KnownUndef))
2877         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
2878       KnownUndef.clearAllBits();
2879 
2880       // zext - if we just need the bottom element then we can mask:
2881       // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and.
2882       if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND &&
2883           Op->isOnlyUserOf(Src.getNode()) &&
2884           Op.getValueSizeInBits() == Src.getValueSizeInBits()) {
2885         SDLoc DL(Op);
2886         EVT SrcVT = Src.getValueType();
2887         EVT SrcSVT = SrcVT.getScalarType();
2888         SmallVector<SDValue> MaskElts;
2889         MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT));
2890         MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT));
2891         SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts);
2892         if (SDValue Fold = TLO.DAG.FoldConstantArithmetic(
2893                 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) {
2894           Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold);
2895           return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold));
2896         }
2897       }
2898     }
2899     break;
2900   }
2901 
2902   // TODO: There are more binop opcodes that could be handled here - MIN,
2903   // MAX, saturated math, etc.
2904   case ISD::ADD: {
2905     SDValue Op0 = Op.getOperand(0);
2906     SDValue Op1 = Op.getOperand(1);
2907     if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) {
2908       APInt UndefLHS, ZeroLHS;
2909       if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
2910                                      Depth + 1, /*AssumeSingleUse*/ true))
2911         return true;
2912     }
2913     LLVM_FALLTHROUGH;
2914   }
2915   case ISD::OR:
2916   case ISD::XOR:
2917   case ISD::SUB:
2918   case ISD::FADD:
2919   case ISD::FSUB:
2920   case ISD::FMUL:
2921   case ISD::FDIV:
2922   case ISD::FREM: {
2923     SDValue Op0 = Op.getOperand(0);
2924     SDValue Op1 = Op.getOperand(1);
2925 
2926     APInt UndefRHS, ZeroRHS;
2927     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
2928                                    Depth + 1))
2929       return true;
2930     APInt UndefLHS, ZeroLHS;
2931     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
2932                                    Depth + 1))
2933       return true;
2934 
2935     KnownZero = ZeroLHS & ZeroRHS;
2936     KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
2937 
2938     // Attempt to avoid multi-use ops if we don't need anything from them.
2939     // TODO - use KnownUndef to relax the demandedelts?
2940     if (!DemandedElts.isAllOnes())
2941       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
2942         return true;
2943     break;
2944   }
2945   case ISD::SHL:
2946   case ISD::SRL:
2947   case ISD::SRA:
2948   case ISD::ROTL:
2949   case ISD::ROTR: {
2950     SDValue Op0 = Op.getOperand(0);
2951     SDValue Op1 = Op.getOperand(1);
2952 
2953     APInt UndefRHS, ZeroRHS;
2954     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
2955                                    Depth + 1))
2956       return true;
2957     APInt UndefLHS, ZeroLHS;
2958     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
2959                                    Depth + 1))
2960       return true;
2961 
2962     KnownZero = ZeroLHS;
2963     KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
2964 
2965     // Attempt to avoid multi-use ops if we don't need anything from them.
2966     // TODO - use KnownUndef to relax the demandedelts?
2967     if (!DemandedElts.isAllOnes())
2968       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
2969         return true;
2970     break;
2971   }
2972   case ISD::MUL:
2973   case ISD::AND: {
2974     SDValue Op0 = Op.getOperand(0);
2975     SDValue Op1 = Op.getOperand(1);
2976 
2977     APInt SrcUndef, SrcZero;
2978     if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
2979                                    Depth + 1))
2980       return true;
2981     if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero,
2982                                    TLO, Depth + 1))
2983       return true;
2984 
2985     // If either side has a zero element, then the result element is zero, even
2986     // if the other is an UNDEF.
2987     // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
2988     // and then handle 'and' nodes with the rest of the binop opcodes.
2989     KnownZero |= SrcZero;
2990     KnownUndef &= SrcUndef;
2991     KnownUndef &= ~KnownZero;
2992 
2993     // Attempt to avoid multi-use ops if we don't need anything from them.
2994     // TODO - use KnownUndef to relax the demandedelts?
2995     if (!DemandedElts.isAllOnes())
2996       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
2997         return true;
2998     break;
2999   }
3000   case ISD::TRUNCATE:
3001   case ISD::SIGN_EXTEND:
3002   case ISD::ZERO_EXTEND:
3003     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
3004                                    KnownZero, TLO, Depth + 1))
3005       return true;
3006 
3007     if (Op.getOpcode() == ISD::ZERO_EXTEND) {
3008       // zext(undef) upper bits are guaranteed to be zero.
3009       if (DemandedElts.isSubsetOf(KnownUndef))
3010         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3011       KnownUndef.clearAllBits();
3012     }
3013     break;
3014   default: {
3015     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
3016       if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
3017                                                   KnownZero, TLO, Depth))
3018         return true;
3019     } else {
3020       KnownBits Known;
3021       APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
3022       if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
3023                                TLO, Depth, AssumeSingleUse))
3024         return true;
3025     }
3026     break;
3027   }
3028   }
3029   assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
3030 
3031   // Constant fold all undef cases.
3032   // TODO: Handle zero cases as well.
3033   if (DemandedElts.isSubsetOf(KnownUndef))
3034     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3035 
3036   return false;
3037 }
3038 
3039 /// Determine which of the bits specified in Mask are known to be either zero or
3040 /// one and return them in the Known.
3041 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
3042                                                    KnownBits &Known,
3043                                                    const APInt &DemandedElts,
3044                                                    const SelectionDAG &DAG,
3045                                                    unsigned Depth) const {
3046   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3047           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3048           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3049           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3050          "Should use MaskedValueIsZero if you don't know whether Op"
3051          " is a target node!");
3052   Known.resetAll();
3053 }
3054 
3055 void TargetLowering::computeKnownBitsForTargetInstr(
3056     GISelKnownBits &Analysis, Register R, KnownBits &Known,
3057     const APInt &DemandedElts, const MachineRegisterInfo &MRI,
3058     unsigned Depth) const {
3059   Known.resetAll();
3060 }
3061 
3062 void TargetLowering::computeKnownBitsForFrameIndex(
3063   const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const {
3064   // The low bits are known zero if the pointer is aligned.
3065   Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx)));
3066 }
3067 
3068 Align TargetLowering::computeKnownAlignForTargetInstr(
3069   GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI,
3070   unsigned Depth) const {
3071   return Align(1);
3072 }
3073 
3074 /// This method can be implemented by targets that want to expose additional
3075 /// information about sign bits to the DAG Combiner.
3076 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
3077                                                          const APInt &,
3078                                                          const SelectionDAG &,
3079                                                          unsigned Depth) const {
3080   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3081           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3082           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3083           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3084          "Should use ComputeNumSignBits if you don't know whether Op"
3085          " is a target node!");
3086   return 1;
3087 }
3088 
3089 unsigned TargetLowering::computeNumSignBitsForTargetInstr(
3090   GISelKnownBits &Analysis, Register R, const APInt &DemandedElts,
3091   const MachineRegisterInfo &MRI, unsigned Depth) const {
3092   return 1;
3093 }
3094 
3095 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
3096     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
3097     TargetLoweringOpt &TLO, 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 SimplifyDemandedVectorElts if you don't know whether Op"
3103          " is a target node!");
3104   return false;
3105 }
3106 
3107 bool TargetLowering::SimplifyDemandedBitsForTargetNode(
3108     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3109     KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
3110   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3111           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3112           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3113           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3114          "Should use SimplifyDemandedBits if you don't know whether Op"
3115          " is a target node!");
3116   computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
3117   return false;
3118 }
3119 
3120 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
3121     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3122     SelectionDAG &DAG, unsigned Depth) const {
3123   assert(
3124       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3125        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3126        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3127        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3128       "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
3129       " is a target node!");
3130   return SDValue();
3131 }
3132 
3133 SDValue
3134 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0,
3135                                         SDValue N1, MutableArrayRef<int> Mask,
3136                                         SelectionDAG &DAG) const {
3137   bool LegalMask = isShuffleMaskLegal(Mask, VT);
3138   if (!LegalMask) {
3139     std::swap(N0, N1);
3140     ShuffleVectorSDNode::commuteMask(Mask);
3141     LegalMask = isShuffleMaskLegal(Mask, VT);
3142   }
3143 
3144   if (!LegalMask)
3145     return SDValue();
3146 
3147   return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
3148 }
3149 
3150 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const {
3151   return nullptr;
3152 }
3153 
3154 bool TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode(
3155     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
3156     bool PoisonOnly, unsigned Depth) const {
3157   assert(
3158       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3159        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3160        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3161        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3162       "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op"
3163       " is a target node!");
3164   return false;
3165 }
3166 
3167 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
3168                                                   const SelectionDAG &DAG,
3169                                                   bool SNaN,
3170                                                   unsigned Depth) const {
3171   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3172           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3173           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3174           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3175          "Should use isKnownNeverNaN if you don't know whether Op"
3176          " is a target node!");
3177   return false;
3178 }
3179 
3180 bool TargetLowering::isSplatValueForTargetNode(SDValue Op,
3181                                                const APInt &DemandedElts,
3182                                                APInt &UndefElts,
3183                                                unsigned Depth) const {
3184   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3185           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3186           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3187           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3188          "Should use isSplatValue if you don't know whether Op"
3189          " is a target node!");
3190   return false;
3191 }
3192 
3193 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
3194 // work with truncating build vectors and vectors with elements of less than
3195 // 8 bits.
3196 bool TargetLowering::isConstTrueVal(SDValue N) const {
3197   if (!N)
3198     return false;
3199 
3200   unsigned EltWidth;
3201   APInt CVal;
3202   if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false,
3203                                                /*AllowTruncation=*/true)) {
3204     CVal = CN->getAPIntValue();
3205     EltWidth = N.getValueType().getScalarSizeInBits();
3206   } else
3207     return false;
3208 
3209   // If this is a truncating splat, truncate the splat value.
3210   // Otherwise, we may fail to match the expected values below.
3211   if (EltWidth < CVal.getBitWidth())
3212     CVal = CVal.trunc(EltWidth);
3213 
3214   switch (getBooleanContents(N.getValueType())) {
3215   case UndefinedBooleanContent:
3216     return CVal[0];
3217   case ZeroOrOneBooleanContent:
3218     return CVal.isOne();
3219   case ZeroOrNegativeOneBooleanContent:
3220     return CVal.isAllOnes();
3221   }
3222 
3223   llvm_unreachable("Invalid boolean contents");
3224 }
3225 
3226 bool TargetLowering::isConstFalseVal(SDValue N) const {
3227   if (!N)
3228     return false;
3229 
3230   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
3231   if (!CN) {
3232     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
3233     if (!BV)
3234       return false;
3235 
3236     // Only interested in constant splats, we don't care about undef
3237     // elements in identifying boolean constants and getConstantSplatNode
3238     // returns NULL if all ops are undef;
3239     CN = BV->getConstantSplatNode();
3240     if (!CN)
3241       return false;
3242   }
3243 
3244   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
3245     return !CN->getAPIntValue()[0];
3246 
3247   return CN->isZero();
3248 }
3249 
3250 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
3251                                        bool SExt) const {
3252   if (VT == MVT::i1)
3253     return N->isOne();
3254 
3255   TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
3256   switch (Cnt) {
3257   case TargetLowering::ZeroOrOneBooleanContent:
3258     // An extended value of 1 is always true, unless its original type is i1,
3259     // in which case it will be sign extended to -1.
3260     return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
3261   case TargetLowering::UndefinedBooleanContent:
3262   case TargetLowering::ZeroOrNegativeOneBooleanContent:
3263     return N->isAllOnes() && SExt;
3264   }
3265   llvm_unreachable("Unexpected enumeration.");
3266 }
3267 
3268 /// This helper function of SimplifySetCC tries to optimize the comparison when
3269 /// either operand of the SetCC node is a bitwise-and instruction.
3270 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
3271                                          ISD::CondCode Cond, const SDLoc &DL,
3272                                          DAGCombinerInfo &DCI) const {
3273   if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
3274     std::swap(N0, N1);
3275 
3276   SelectionDAG &DAG = DCI.DAG;
3277   EVT OpVT = N0.getValueType();
3278   if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
3279       (Cond != ISD::SETEQ && Cond != ISD::SETNE))
3280     return SDValue();
3281 
3282   // (X & Y) != 0 --> zextOrTrunc(X & Y)
3283   // iff everything but LSB is known zero:
3284   if (Cond == ISD::SETNE && isNullConstant(N1) &&
3285       (getBooleanContents(OpVT) == TargetLowering::UndefinedBooleanContent ||
3286        getBooleanContents(OpVT) == TargetLowering::ZeroOrOneBooleanContent)) {
3287     unsigned NumEltBits = OpVT.getScalarSizeInBits();
3288     APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1);
3289     if (DAG.MaskedValueIsZero(N0, UpperBits))
3290       return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT);
3291   }
3292 
3293   // Match these patterns in any of their permutations:
3294   // (X & Y) == Y
3295   // (X & Y) != Y
3296   SDValue X, Y;
3297   if (N0.getOperand(0) == N1) {
3298     X = N0.getOperand(1);
3299     Y = N0.getOperand(0);
3300   } else if (N0.getOperand(1) == N1) {
3301     X = N0.getOperand(0);
3302     Y = N0.getOperand(1);
3303   } else {
3304     return SDValue();
3305   }
3306 
3307   SDValue Zero = DAG.getConstant(0, DL, OpVT);
3308   if (DAG.isKnownToBeAPowerOfTwo(Y)) {
3309     // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
3310     // Note that where Y is variable and is known to have at most one bit set
3311     // (for example, if it is Z & 1) we cannot do this; the expressions are not
3312     // equivalent when Y == 0.
3313     assert(OpVT.isInteger());
3314     Cond = ISD::getSetCCInverse(Cond, OpVT);
3315     if (DCI.isBeforeLegalizeOps() ||
3316         isCondCodeLegal(Cond, N0.getSimpleValueType()))
3317       return DAG.getSetCC(DL, VT, N0, Zero, Cond);
3318   } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
3319     // If the target supports an 'and-not' or 'and-complement' logic operation,
3320     // try to use that to make a comparison operation more efficient.
3321     // But don't do this transform if the mask is a single bit because there are
3322     // more efficient ways to deal with that case (for example, 'bt' on x86 or
3323     // 'rlwinm' on PPC).
3324 
3325     // Bail out if the compare operand that we want to turn into a zero is
3326     // already a zero (otherwise, infinite loop).
3327     auto *YConst = dyn_cast<ConstantSDNode>(Y);
3328     if (YConst && YConst->isZero())
3329       return SDValue();
3330 
3331     // Transform this into: ~X & Y == 0.
3332     SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
3333     SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
3334     return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
3335   }
3336 
3337   return SDValue();
3338 }
3339 
3340 /// There are multiple IR patterns that could be checking whether certain
3341 /// truncation of a signed number would be lossy or not. The pattern which is
3342 /// best at IR level, may not lower optimally. Thus, we want to unfold it.
3343 /// We are looking for the following pattern: (KeptBits is a constant)
3344 ///   (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
3345 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
3346 /// KeptBits also can't be 1, that would have been folded to  %x dstcond 0
3347 /// We will unfold it into the natural trunc+sext pattern:
3348 ///   ((%x << C) a>> C) dstcond %x
3349 /// Where  C = bitwidth(x) - KeptBits  and  C u< bitwidth(x)
3350 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
3351     EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
3352     const SDLoc &DL) const {
3353   // We must be comparing with a constant.
3354   ConstantSDNode *C1;
3355   if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
3356     return SDValue();
3357 
3358   // N0 should be:  add %x, (1 << (KeptBits-1))
3359   if (N0->getOpcode() != ISD::ADD)
3360     return SDValue();
3361 
3362   // And we must be 'add'ing a constant.
3363   ConstantSDNode *C01;
3364   if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
3365     return SDValue();
3366 
3367   SDValue X = N0->getOperand(0);
3368   EVT XVT = X.getValueType();
3369 
3370   // Validate constants ...
3371 
3372   APInt I1 = C1->getAPIntValue();
3373 
3374   ISD::CondCode NewCond;
3375   if (Cond == ISD::CondCode::SETULT) {
3376     NewCond = ISD::CondCode::SETEQ;
3377   } else if (Cond == ISD::CondCode::SETULE) {
3378     NewCond = ISD::CondCode::SETEQ;
3379     // But need to 'canonicalize' the constant.
3380     I1 += 1;
3381   } else if (Cond == ISD::CondCode::SETUGT) {
3382     NewCond = ISD::CondCode::SETNE;
3383     // But need to 'canonicalize' the constant.
3384     I1 += 1;
3385   } else if (Cond == ISD::CondCode::SETUGE) {
3386     NewCond = ISD::CondCode::SETNE;
3387   } else
3388     return SDValue();
3389 
3390   APInt I01 = C01->getAPIntValue();
3391 
3392   auto checkConstants = [&I1, &I01]() -> bool {
3393     // Both of them must be power-of-two, and the constant from setcc is bigger.
3394     return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
3395   };
3396 
3397   if (checkConstants()) {
3398     // Great, e.g. got  icmp ult i16 (add i16 %x, 128), 256
3399   } else {
3400     // What if we invert constants? (and the target predicate)
3401     I1.negate();
3402     I01.negate();
3403     assert(XVT.isInteger());
3404     NewCond = getSetCCInverse(NewCond, XVT);
3405     if (!checkConstants())
3406       return SDValue();
3407     // Great, e.g. got  icmp uge i16 (add i16 %x, -128), -256
3408   }
3409 
3410   // They are power-of-two, so which bit is set?
3411   const unsigned KeptBits = I1.logBase2();
3412   const unsigned KeptBitsMinusOne = I01.logBase2();
3413 
3414   // Magic!
3415   if (KeptBits != (KeptBitsMinusOne + 1))
3416     return SDValue();
3417   assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
3418 
3419   // We don't want to do this in every single case.
3420   SelectionDAG &DAG = DCI.DAG;
3421   if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck(
3422           XVT, KeptBits))
3423     return SDValue();
3424 
3425   const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits;
3426   assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable");
3427 
3428   // Unfold into:  ((%x << C) a>> C) cond %x
3429   // Where 'cond' will be either 'eq' or 'ne'.
3430   SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT);
3431   SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt);
3432   SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt);
3433   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond);
3434 
3435   return T2;
3436 }
3437 
3438 // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
3439 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
3440     EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
3441     DAGCombinerInfo &DCI, const SDLoc &DL) const {
3442   assert(isConstOrConstSplat(N1C) &&
3443          isConstOrConstSplat(N1C)->getAPIntValue().isZero() &&
3444          "Should be a comparison with 0.");
3445   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3446          "Valid only for [in]equality comparisons.");
3447 
3448   unsigned NewShiftOpcode;
3449   SDValue X, C, Y;
3450 
3451   SelectionDAG &DAG = DCI.DAG;
3452   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3453 
3454   // Look for '(C l>>/<< Y)'.
3455   auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) {
3456     // The shift should be one-use.
3457     if (!V.hasOneUse())
3458       return false;
3459     unsigned OldShiftOpcode = V.getOpcode();
3460     switch (OldShiftOpcode) {
3461     case ISD::SHL:
3462       NewShiftOpcode = ISD::SRL;
3463       break;
3464     case ISD::SRL:
3465       NewShiftOpcode = ISD::SHL;
3466       break;
3467     default:
3468       return false; // must be a logical shift.
3469     }
3470     // We should be shifting a constant.
3471     // FIXME: best to use isConstantOrConstantVector().
3472     C = V.getOperand(0);
3473     ConstantSDNode *CC =
3474         isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
3475     if (!CC)
3476       return false;
3477     Y = V.getOperand(1);
3478 
3479     ConstantSDNode *XC =
3480         isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
3481     return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
3482         X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
3483   };
3484 
3485   // LHS of comparison should be an one-use 'and'.
3486   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
3487     return SDValue();
3488 
3489   X = N0.getOperand(0);
3490   SDValue Mask = N0.getOperand(1);
3491 
3492   // 'and' is commutative!
3493   if (!Match(Mask)) {
3494     std::swap(X, Mask);
3495     if (!Match(Mask))
3496       return SDValue();
3497   }
3498 
3499   EVT VT = X.getValueType();
3500 
3501   // Produce:
3502   // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
3503   SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
3504   SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
3505   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
3506   return T2;
3507 }
3508 
3509 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as
3510 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
3511 /// handle the commuted versions of these patterns.
3512 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
3513                                            ISD::CondCode Cond, const SDLoc &DL,
3514                                            DAGCombinerInfo &DCI) const {
3515   unsigned BOpcode = N0.getOpcode();
3516   assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
3517          "Unexpected binop");
3518   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
3519 
3520   // (X + Y) == X --> Y == 0
3521   // (X - Y) == X --> Y == 0
3522   // (X ^ Y) == X --> Y == 0
3523   SelectionDAG &DAG = DCI.DAG;
3524   EVT OpVT = N0.getValueType();
3525   SDValue X = N0.getOperand(0);
3526   SDValue Y = N0.getOperand(1);
3527   if (X == N1)
3528     return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
3529 
3530   if (Y != N1)
3531     return SDValue();
3532 
3533   // (X + Y) == Y --> X == 0
3534   // (X ^ Y) == Y --> X == 0
3535   if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
3536     return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
3537 
3538   // The shift would not be valid if the operands are boolean (i1).
3539   if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
3540     return SDValue();
3541 
3542   // (X - Y) == Y --> X == Y << 1
3543   EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(),
3544                                  !DCI.isBeforeLegalize());
3545   SDValue One = DAG.getConstant(1, DL, ShiftVT);
3546   SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
3547   if (!DCI.isCalledByLegalizer())
3548     DCI.AddToWorklist(YShl1.getNode());
3549   return DAG.getSetCC(DL, VT, X, YShl1, Cond);
3550 }
3551 
3552 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT,
3553                                       SDValue N0, const APInt &C1,
3554                                       ISD::CondCode Cond, const SDLoc &dl,
3555                                       SelectionDAG &DAG) {
3556   // Look through truncs that don't change the value of a ctpop.
3557   // FIXME: Add vector support? Need to be careful with setcc result type below.
3558   SDValue CTPOP = N0;
3559   if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
3560       N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits()))
3561     CTPOP = N0.getOperand(0);
3562 
3563   if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
3564     return SDValue();
3565 
3566   EVT CTVT = CTPOP.getValueType();
3567   SDValue CTOp = CTPOP.getOperand(0);
3568 
3569   // If this is a vector CTPOP, keep the CTPOP if it is legal.
3570   // TODO: Should we check if CTPOP is legal(or custom) for scalars?
3571   if (VT.isVector() && TLI.isOperationLegal(ISD::CTPOP, CTVT))
3572     return SDValue();
3573 
3574   // (ctpop x) u< 2 -> (x & x-1) == 0
3575   // (ctpop x) u> 1 -> (x & x-1) != 0
3576   if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
3577     unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
3578     if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
3579       return SDValue();
3580     if (C1 == 0 && (Cond == ISD::SETULT))
3581       return SDValue(); // This is handled elsewhere.
3582 
3583     unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
3584 
3585     SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
3586     SDValue Result = CTOp;
3587     for (unsigned i = 0; i < Passes; i++) {
3588       SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
3589       Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
3590     }
3591     ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
3592     return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
3593   }
3594 
3595   // If ctpop is not supported, expand a power-of-2 comparison based on it.
3596   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
3597     // For scalars, keep CTPOP if it is legal or custom.
3598     if (!VT.isVector() && TLI.isOperationLegalOrCustom(ISD::CTPOP, CTVT))
3599       return SDValue();
3600     // This is based on X86's custom lowering for CTPOP which produces more
3601     // instructions than the expansion here.
3602 
3603     // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0)
3604     // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0)
3605     SDValue Zero = DAG.getConstant(0, dl, CTVT);
3606     SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
3607     assert(CTVT.isInteger());
3608     ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, CTVT);
3609     SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
3610     SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
3611     SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond);
3612     SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
3613     unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR;
3614     return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS);
3615   }
3616 
3617   return SDValue();
3618 }
3619 
3620 /// Try to simplify a setcc built with the specified operands and cc. If it is
3621 /// unable to simplify it, return a null SDValue.
3622 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
3623                                       ISD::CondCode Cond, bool foldBooleans,
3624                                       DAGCombinerInfo &DCI,
3625                                       const SDLoc &dl) const {
3626   SelectionDAG &DAG = DCI.DAG;
3627   const DataLayout &Layout = DAG.getDataLayout();
3628   EVT OpVT = N0.getValueType();
3629 
3630   // Constant fold or commute setcc.
3631   if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
3632     return Fold;
3633 
3634   // Ensure that the constant occurs on the RHS and fold constant comparisons.
3635   // TODO: Handle non-splat vector constants. All undef causes trouble.
3636   // FIXME: We can't yet fold constant scalable vector splats, so avoid an
3637   // infinite loop here when we encounter one.
3638   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
3639   if (isConstOrConstSplat(N0) &&
3640       (!OpVT.isScalableVector() || !isConstOrConstSplat(N1)) &&
3641       (DCI.isBeforeLegalizeOps() ||
3642        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
3643     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
3644 
3645   // If we have a subtract with the same 2 non-constant operands as this setcc
3646   // -- but in reverse order -- then try to commute the operands of this setcc
3647   // to match. A matching pair of setcc (cmp) and sub may be combined into 1
3648   // instruction on some targets.
3649   if (!isConstOrConstSplat(N0) && !isConstOrConstSplat(N1) &&
3650       (DCI.isBeforeLegalizeOps() ||
3651        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
3652       DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
3653       !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
3654     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
3655 
3656   if (auto *N1C = isConstOrConstSplat(N1)) {
3657     const APInt &C1 = N1C->getAPIntValue();
3658 
3659     // Optimize some CTPOP cases.
3660     if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
3661       return V;
3662 
3663     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
3664     // equality comparison, then we're just comparing whether X itself is
3665     // zero.
3666     if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) &&
3667         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
3668         isPowerOf2_32(N0.getScalarValueSizeInBits())) {
3669       if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
3670         if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3671             ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
3672           if ((C1 == 0) == (Cond == ISD::SETEQ)) {
3673             // (srl (ctlz x), 5) == 0  -> X != 0
3674             // (srl (ctlz x), 5) != 1  -> X != 0
3675             Cond = ISD::SETNE;
3676           } else {
3677             // (srl (ctlz x), 5) != 0  -> X == 0
3678             // (srl (ctlz x), 5) == 1  -> X == 0
3679             Cond = ISD::SETEQ;
3680           }
3681           SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
3682           return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
3683                               Cond);
3684         }
3685       }
3686     }
3687   }
3688 
3689   // FIXME: Support vectors.
3690   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
3691     const APInt &C1 = N1C->getAPIntValue();
3692 
3693     // (zext x) == C --> x == (trunc C)
3694     // (sext x) == C --> x == (trunc C)
3695     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3696         DCI.isBeforeLegalize() && N0->hasOneUse()) {
3697       unsigned MinBits = N0.getValueSizeInBits();
3698       SDValue PreExt;
3699       bool Signed = false;
3700       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
3701         // ZExt
3702         MinBits = N0->getOperand(0).getValueSizeInBits();
3703         PreExt = N0->getOperand(0);
3704       } else if (N0->getOpcode() == ISD::AND) {
3705         // DAGCombine turns costly ZExts into ANDs
3706         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
3707           if ((C->getAPIntValue()+1).isPowerOf2()) {
3708             MinBits = C->getAPIntValue().countTrailingOnes();
3709             PreExt = N0->getOperand(0);
3710           }
3711       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
3712         // SExt
3713         MinBits = N0->getOperand(0).getValueSizeInBits();
3714         PreExt = N0->getOperand(0);
3715         Signed = true;
3716       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
3717         // ZEXTLOAD / SEXTLOAD
3718         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
3719           MinBits = LN0->getMemoryVT().getSizeInBits();
3720           PreExt = N0;
3721         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
3722           Signed = true;
3723           MinBits = LN0->getMemoryVT().getSizeInBits();
3724           PreExt = N0;
3725         }
3726       }
3727 
3728       // Figure out how many bits we need to preserve this constant.
3729       unsigned ReqdBits = Signed ? C1.getMinSignedBits() : C1.getActiveBits();
3730 
3731       // Make sure we're not losing bits from the constant.
3732       if (MinBits > 0 &&
3733           MinBits < C1.getBitWidth() &&
3734           MinBits >= ReqdBits) {
3735         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
3736         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
3737           // Will get folded away.
3738           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
3739           if (MinBits == 1 && C1 == 1)
3740             // Invert the condition.
3741             return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
3742                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3743           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
3744           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
3745         }
3746 
3747         // If truncating the setcc operands is not desirable, we can still
3748         // simplify the expression in some cases:
3749         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
3750         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
3751         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
3752         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
3753         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
3754         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
3755         SDValue TopSetCC = N0->getOperand(0);
3756         unsigned N0Opc = N0->getOpcode();
3757         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
3758         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
3759             TopSetCC.getOpcode() == ISD::SETCC &&
3760             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
3761             (isConstFalseVal(N1) ||
3762              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
3763 
3764           bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) ||
3765                          (!N1C->isZero() && Cond == ISD::SETNE);
3766 
3767           if (!Inverse)
3768             return TopSetCC;
3769 
3770           ISD::CondCode InvCond = ISD::getSetCCInverse(
3771               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
3772               TopSetCC.getOperand(0).getValueType());
3773           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
3774                                       TopSetCC.getOperand(1),
3775                                       InvCond);
3776         }
3777       }
3778     }
3779 
3780     // If the LHS is '(and load, const)', the RHS is 0, the test is for
3781     // equality or unsigned, and all 1 bits of the const are in the same
3782     // partial word, see if we can shorten the load.
3783     if (DCI.isBeforeLegalize() &&
3784         !ISD::isSignedIntSetCC(Cond) &&
3785         N0.getOpcode() == ISD::AND && C1 == 0 &&
3786         N0.getNode()->hasOneUse() &&
3787         isa<LoadSDNode>(N0.getOperand(0)) &&
3788         N0.getOperand(0).getNode()->hasOneUse() &&
3789         isa<ConstantSDNode>(N0.getOperand(1))) {
3790       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
3791       APInt bestMask;
3792       unsigned bestWidth = 0, bestOffset = 0;
3793       if (Lod->isSimple() && Lod->isUnindexed()) {
3794         unsigned origWidth = N0.getValueSizeInBits();
3795         unsigned maskWidth = origWidth;
3796         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
3797         // 8 bits, but have to be careful...
3798         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
3799           origWidth = Lod->getMemoryVT().getSizeInBits();
3800         const APInt &Mask = N0.getConstantOperandAPInt(1);
3801         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
3802           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
3803           for (unsigned offset=0; offset<origWidth/width; offset++) {
3804             if (Mask.isSubsetOf(newMask)) {
3805               if (Layout.isLittleEndian())
3806                 bestOffset = (uint64_t)offset * (width/8);
3807               else
3808                 bestOffset = (origWidth/width - offset - 1) * (width/8);
3809               bestMask = Mask.lshr(offset * (width/8) * 8);
3810               bestWidth = width;
3811               break;
3812             }
3813             newMask <<= width;
3814           }
3815         }
3816       }
3817       if (bestWidth) {
3818         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
3819         if (newVT.isRound() &&
3820             shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) {
3821           SDValue Ptr = Lod->getBasePtr();
3822           if (bestOffset != 0)
3823             Ptr =
3824                 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(bestOffset), dl);
3825           SDValue NewLoad =
3826               DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
3827                           Lod->getPointerInfo().getWithOffset(bestOffset),
3828                           Lod->getOriginalAlign());
3829           return DAG.getSetCC(dl, VT,
3830                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
3831                                       DAG.getConstant(bestMask.trunc(bestWidth),
3832                                                       dl, newVT)),
3833                               DAG.getConstant(0LL, dl, newVT), Cond);
3834         }
3835       }
3836     }
3837 
3838     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
3839     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
3840       unsigned InSize = N0.getOperand(0).getValueSizeInBits();
3841 
3842       // If the comparison constant has bits in the upper part, the
3843       // zero-extended value could never match.
3844       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
3845                                               C1.getBitWidth() - InSize))) {
3846         switch (Cond) {
3847         case ISD::SETUGT:
3848         case ISD::SETUGE:
3849         case ISD::SETEQ:
3850           return DAG.getConstant(0, dl, VT);
3851         case ISD::SETULT:
3852         case ISD::SETULE:
3853         case ISD::SETNE:
3854           return DAG.getConstant(1, dl, VT);
3855         case ISD::SETGT:
3856         case ISD::SETGE:
3857           // True if the sign bit of C1 is set.
3858           return DAG.getConstant(C1.isNegative(), dl, VT);
3859         case ISD::SETLT:
3860         case ISD::SETLE:
3861           // True if the sign bit of C1 isn't set.
3862           return DAG.getConstant(C1.isNonNegative(), dl, VT);
3863         default:
3864           break;
3865         }
3866       }
3867 
3868       // Otherwise, we can perform the comparison with the low bits.
3869       switch (Cond) {
3870       case ISD::SETEQ:
3871       case ISD::SETNE:
3872       case ISD::SETUGT:
3873       case ISD::SETUGE:
3874       case ISD::SETULT:
3875       case ISD::SETULE: {
3876         EVT newVT = N0.getOperand(0).getValueType();
3877         if (DCI.isBeforeLegalizeOps() ||
3878             (isOperationLegal(ISD::SETCC, newVT) &&
3879              isCondCodeLegal(Cond, newVT.getSimpleVT()))) {
3880           EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
3881           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
3882 
3883           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
3884                                           NewConst, Cond);
3885           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
3886         }
3887         break;
3888       }
3889       default:
3890         break; // todo, be more careful with signed comparisons
3891       }
3892     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3893                (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3894                !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(),
3895                                       OpVT)) {
3896       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
3897       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
3898       EVT ExtDstTy = N0.getValueType();
3899       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
3900 
3901       // If the constant doesn't fit into the number of bits for the source of
3902       // the sign extension, it is impossible for both sides to be equal.
3903       if (C1.getMinSignedBits() > ExtSrcTyBits)
3904         return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
3905 
3906       assert(ExtDstTy == N0.getOperand(0).getValueType() &&
3907              ExtDstTy != ExtSrcTy && "Unexpected types!");
3908       APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
3909       SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
3910                                    DAG.getConstant(Imm, dl, ExtDstTy));
3911       if (!DCI.isCalledByLegalizer())
3912         DCI.AddToWorklist(ZextOp.getNode());
3913       // Otherwise, make this a use of a zext.
3914       return DAG.getSetCC(dl, VT, ZextOp,
3915                           DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
3916     } else if ((N1C->isZero() || N1C->isOne()) &&
3917                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
3918       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
3919       if (N0.getOpcode() == ISD::SETCC &&
3920           isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
3921           (N0.getValueType() == MVT::i1 ||
3922            getBooleanContents(N0.getOperand(0).getValueType()) ==
3923                        ZeroOrOneBooleanContent)) {
3924         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
3925         if (TrueWhenTrue)
3926           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
3927         // Invert the condition.
3928         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
3929         CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType());
3930         if (DCI.isBeforeLegalizeOps() ||
3931             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
3932           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
3933       }
3934 
3935       if ((N0.getOpcode() == ISD::XOR ||
3936            (N0.getOpcode() == ISD::AND &&
3937             N0.getOperand(0).getOpcode() == ISD::XOR &&
3938             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
3939           isOneConstant(N0.getOperand(1))) {
3940         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
3941         // can only do this if the top bits are known zero.
3942         unsigned BitWidth = N0.getValueSizeInBits();
3943         if (DAG.MaskedValueIsZero(N0,
3944                                   APInt::getHighBitsSet(BitWidth,
3945                                                         BitWidth-1))) {
3946           // Okay, get the un-inverted input value.
3947           SDValue Val;
3948           if (N0.getOpcode() == ISD::XOR) {
3949             Val = N0.getOperand(0);
3950           } else {
3951             assert(N0.getOpcode() == ISD::AND &&
3952                     N0.getOperand(0).getOpcode() == ISD::XOR);
3953             // ((X^1)&1)^1 -> X & 1
3954             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
3955                               N0.getOperand(0).getOperand(0),
3956                               N0.getOperand(1));
3957           }
3958 
3959           return DAG.getSetCC(dl, VT, Val, N1,
3960                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3961         }
3962       } else if (N1C->isOne()) {
3963         SDValue Op0 = N0;
3964         if (Op0.getOpcode() == ISD::TRUNCATE)
3965           Op0 = Op0.getOperand(0);
3966 
3967         if ((Op0.getOpcode() == ISD::XOR) &&
3968             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
3969             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
3970           SDValue XorLHS = Op0.getOperand(0);
3971           SDValue XorRHS = Op0.getOperand(1);
3972           // Ensure that the input setccs return an i1 type or 0/1 value.
3973           if (Op0.getValueType() == MVT::i1 ||
3974               (getBooleanContents(XorLHS.getOperand(0).getValueType()) ==
3975                       ZeroOrOneBooleanContent &&
3976                getBooleanContents(XorRHS.getOperand(0).getValueType()) ==
3977                         ZeroOrOneBooleanContent)) {
3978             // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
3979             Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
3980             return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
3981           }
3982         }
3983         if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
3984           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
3985           if (Op0.getValueType().bitsGT(VT))
3986             Op0 = DAG.getNode(ISD::AND, dl, VT,
3987                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
3988                           DAG.getConstant(1, dl, VT));
3989           else if (Op0.getValueType().bitsLT(VT))
3990             Op0 = DAG.getNode(ISD::AND, dl, VT,
3991                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
3992                         DAG.getConstant(1, dl, VT));
3993 
3994           return DAG.getSetCC(dl, VT, Op0,
3995                               DAG.getConstant(0, dl, Op0.getValueType()),
3996                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
3997         }
3998         if (Op0.getOpcode() == ISD::AssertZext &&
3999             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
4000           return DAG.getSetCC(dl, VT, Op0,
4001                               DAG.getConstant(0, dl, Op0.getValueType()),
4002                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4003       }
4004     }
4005 
4006     // Given:
4007     //   icmp eq/ne (urem %x, %y), 0
4008     // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
4009     //   icmp eq/ne %x, 0
4010     if (N0.getOpcode() == ISD::UREM && N1C->isZero() &&
4011         (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4012       KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
4013       KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
4014       if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
4015         return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
4016     }
4017 
4018     // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0
4019     //  and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0
4020     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4021         N0.getOpcode() == ISD::SRA && isa<ConstantSDNode>(N0.getOperand(1)) &&
4022         N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 &&
4023         N1C && N1C->isAllOnes()) {
4024       return DAG.getSetCC(dl, VT, N0.getOperand(0),
4025                           DAG.getConstant(0, dl, OpVT),
4026                           Cond == ISD::SETEQ ? ISD::SETLT : ISD::SETGE);
4027     }
4028 
4029     if (SDValue V =
4030             optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
4031       return V;
4032   }
4033 
4034   // These simplifications apply to splat vectors as well.
4035   // TODO: Handle more splat vector cases.
4036   if (auto *N1C = isConstOrConstSplat(N1)) {
4037     const APInt &C1 = N1C->getAPIntValue();
4038 
4039     APInt MinVal, MaxVal;
4040     unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
4041     if (ISD::isSignedIntSetCC(Cond)) {
4042       MinVal = APInt::getSignedMinValue(OperandBitSize);
4043       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
4044     } else {
4045       MinVal = APInt::getMinValue(OperandBitSize);
4046       MaxVal = APInt::getMaxValue(OperandBitSize);
4047     }
4048 
4049     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
4050     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
4051       // X >= MIN --> true
4052       if (C1 == MinVal)
4053         return DAG.getBoolConstant(true, dl, VT, OpVT);
4054 
4055       if (!VT.isVector()) { // TODO: Support this for vectors.
4056         // X >= C0 --> X > (C0 - 1)
4057         APInt C = C1 - 1;
4058         ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
4059         if ((DCI.isBeforeLegalizeOps() ||
4060              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
4061             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
4062                                   isLegalICmpImmediate(C.getSExtValue())))) {
4063           return DAG.getSetCC(dl, VT, N0,
4064                               DAG.getConstant(C, dl, N1.getValueType()),
4065                               NewCC);
4066         }
4067       }
4068     }
4069 
4070     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
4071       // X <= MAX --> true
4072       if (C1 == MaxVal)
4073         return DAG.getBoolConstant(true, dl, VT, OpVT);
4074 
4075       // X <= C0 --> X < (C0 + 1)
4076       if (!VT.isVector()) { // TODO: Support this for vectors.
4077         APInt C = C1 + 1;
4078         ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
4079         if ((DCI.isBeforeLegalizeOps() ||
4080              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
4081             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
4082                                   isLegalICmpImmediate(C.getSExtValue())))) {
4083           return DAG.getSetCC(dl, VT, N0,
4084                               DAG.getConstant(C, dl, N1.getValueType()),
4085                               NewCC);
4086         }
4087       }
4088     }
4089 
4090     if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
4091       if (C1 == MinVal)
4092         return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
4093 
4094       // TODO: Support this for vectors after legalize ops.
4095       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4096         // Canonicalize setlt X, Max --> setne X, Max
4097         if (C1 == MaxVal)
4098           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
4099 
4100         // If we have setult X, 1, turn it into seteq X, 0
4101         if (C1 == MinVal+1)
4102           return DAG.getSetCC(dl, VT, N0,
4103                               DAG.getConstant(MinVal, dl, N0.getValueType()),
4104                               ISD::SETEQ);
4105       }
4106     }
4107 
4108     if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
4109       if (C1 == MaxVal)
4110         return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
4111 
4112       // TODO: Support this for vectors after legalize ops.
4113       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4114         // Canonicalize setgt X, Min --> setne X, Min
4115         if (C1 == MinVal)
4116           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
4117 
4118         // If we have setugt X, Max-1, turn it into seteq X, Max
4119         if (C1 == MaxVal-1)
4120           return DAG.getSetCC(dl, VT, N0,
4121                               DAG.getConstant(MaxVal, dl, N0.getValueType()),
4122                               ISD::SETEQ);
4123       }
4124     }
4125 
4126     if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
4127       // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
4128       if (C1.isZero())
4129         if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
4130                 VT, N0, N1, Cond, DCI, dl))
4131           return CC;
4132 
4133       // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
4134       // For example, when high 32-bits of i64 X are known clear:
4135       // all bits clear: (X | (Y<<32)) ==  0 --> (X | Y) ==  0
4136       // all bits set:   (X | (Y<<32)) == -1 --> (X & Y) == -1
4137       bool CmpZero = N1C->getAPIntValue().isZero();
4138       bool CmpNegOne = N1C->getAPIntValue().isAllOnes();
4139       if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
4140         // Match or(lo,shl(hi,bw/2)) pattern.
4141         auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
4142           unsigned EltBits = V.getScalarValueSizeInBits();
4143           if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
4144             return false;
4145           SDValue LHS = V.getOperand(0);
4146           SDValue RHS = V.getOperand(1);
4147           APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
4148           // Unshifted element must have zero upperbits.
4149           if (RHS.getOpcode() == ISD::SHL &&
4150               isa<ConstantSDNode>(RHS.getOperand(1)) &&
4151               RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
4152               DAG.MaskedValueIsZero(LHS, HiBits)) {
4153             Lo = LHS;
4154             Hi = RHS.getOperand(0);
4155             return true;
4156           }
4157           if (LHS.getOpcode() == ISD::SHL &&
4158               isa<ConstantSDNode>(LHS.getOperand(1)) &&
4159               LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
4160               DAG.MaskedValueIsZero(RHS, HiBits)) {
4161             Lo = RHS;
4162             Hi = LHS.getOperand(0);
4163             return true;
4164           }
4165           return false;
4166         };
4167 
4168         auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
4169           unsigned EltBits = N0.getScalarValueSizeInBits();
4170           unsigned HalfBits = EltBits / 2;
4171           APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
4172           SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
4173           SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
4174           SDValue NewN0 =
4175               DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
4176           SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
4177           return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
4178         };
4179 
4180         SDValue Lo, Hi;
4181         if (IsConcat(N0, Lo, Hi))
4182           return MergeConcat(Lo, Hi);
4183 
4184         if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
4185           SDValue Lo0, Lo1, Hi0, Hi1;
4186           if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
4187               IsConcat(N0.getOperand(1), Lo1, Hi1)) {
4188             return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
4189                                DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
4190           }
4191         }
4192       }
4193     }
4194 
4195     // If we have "setcc X, C0", check to see if we can shrink the immediate
4196     // by changing cc.
4197     // TODO: Support this for vectors after legalize ops.
4198     if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4199       // SETUGT X, SINTMAX  -> SETLT X, 0
4200       // SETUGE X, SINTMIN -> SETLT X, 0
4201       if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
4202           (Cond == ISD::SETUGE && C1.isMinSignedValue()))
4203         return DAG.getSetCC(dl, VT, N0,
4204                             DAG.getConstant(0, dl, N1.getValueType()),
4205                             ISD::SETLT);
4206 
4207       // SETULT X, SINTMIN  -> SETGT X, -1
4208       // SETULE X, SINTMAX  -> SETGT X, -1
4209       if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
4210           (Cond == ISD::SETULE && C1.isMaxSignedValue()))
4211         return DAG.getSetCC(dl, VT, N0,
4212                             DAG.getAllOnesConstant(dl, N1.getValueType()),
4213                             ISD::SETGT);
4214     }
4215   }
4216 
4217   // Back to non-vector simplifications.
4218   // TODO: Can we do these for vector splats?
4219   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
4220     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4221     const APInt &C1 = N1C->getAPIntValue();
4222     EVT ShValTy = N0.getValueType();
4223 
4224     // Fold bit comparisons when we can. This will result in an
4225     // incorrect value when boolean false is negative one, unless
4226     // the bitsize is 1 in which case the false value is the same
4227     // in practice regardless of the representation.
4228     if ((VT.getSizeInBits() == 1 ||
4229          getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) &&
4230         (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4231         (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
4232         N0.getOpcode() == ISD::AND) {
4233       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4234         EVT ShiftTy =
4235             getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
4236         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
4237           // Perform the xform if the AND RHS is a single bit.
4238           unsigned ShCt = AndRHS->getAPIntValue().logBase2();
4239           if (AndRHS->getAPIntValue().isPowerOf2() &&
4240               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
4241             return DAG.getNode(ISD::TRUNCATE, dl, VT,
4242                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4243                                            DAG.getConstant(ShCt, dl, ShiftTy)));
4244           }
4245         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
4246           // (X & 8) == 8  -->  (X & 8) >> 3
4247           // Perform the xform if C1 is a single bit.
4248           unsigned ShCt = C1.logBase2();
4249           if (C1.isPowerOf2() &&
4250               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
4251             return DAG.getNode(ISD::TRUNCATE, dl, VT,
4252                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4253                                            DAG.getConstant(ShCt, dl, ShiftTy)));
4254           }
4255         }
4256       }
4257     }
4258 
4259     if (C1.getMinSignedBits() <= 64 &&
4260         !isLegalICmpImmediate(C1.getSExtValue())) {
4261       EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
4262       // (X & -256) == 256 -> (X >> 8) == 1
4263       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4264           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
4265         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4266           const APInt &AndRHSC = AndRHS->getAPIntValue();
4267           if (AndRHSC.isNegatedPowerOf2() && (AndRHSC & C1) == C1) {
4268             unsigned ShiftBits = AndRHSC.countTrailingZeros();
4269             if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
4270               SDValue Shift =
4271                 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0),
4272                             DAG.getConstant(ShiftBits, dl, ShiftTy));
4273               SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy);
4274               return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
4275             }
4276           }
4277         }
4278       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
4279                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
4280         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
4281         // X <  0x100000000 -> (X >> 32) <  1
4282         // X >= 0x100000000 -> (X >> 32) >= 1
4283         // X <= 0x0ffffffff -> (X >> 32) <  1
4284         // X >  0x0ffffffff -> (X >> 32) >= 1
4285         unsigned ShiftBits;
4286         APInt NewC = C1;
4287         ISD::CondCode NewCond = Cond;
4288         if (AdjOne) {
4289           ShiftBits = C1.countTrailingOnes();
4290           NewC = NewC + 1;
4291           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4292         } else {
4293           ShiftBits = C1.countTrailingZeros();
4294         }
4295         NewC.lshrInPlace(ShiftBits);
4296         if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
4297             isLegalICmpImmediate(NewC.getSExtValue()) &&
4298             !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
4299           SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4300                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
4301           SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
4302           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
4303         }
4304       }
4305     }
4306   }
4307 
4308   if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) {
4309     auto *CFP = cast<ConstantFPSDNode>(N1);
4310     assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
4311 
4312     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
4313     // constant if knowing that the operand is non-nan is enough.  We prefer to
4314     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
4315     // materialize 0.0.
4316     if (Cond == ISD::SETO || Cond == ISD::SETUO)
4317       return DAG.getSetCC(dl, VT, N0, N0, Cond);
4318 
4319     // setcc (fneg x), C -> setcc swap(pred) x, -C
4320     if (N0.getOpcode() == ISD::FNEG) {
4321       ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
4322       if (DCI.isBeforeLegalizeOps() ||
4323           isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
4324         SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
4325         return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
4326       }
4327     }
4328 
4329     // If the condition is not legal, see if we can find an equivalent one
4330     // which is legal.
4331     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
4332       // If the comparison was an awkward floating-point == or != and one of
4333       // the comparison operands is infinity or negative infinity, convert the
4334       // condition to a less-awkward <= or >=.
4335       if (CFP->getValueAPF().isInfinity()) {
4336         bool IsNegInf = CFP->getValueAPF().isNegative();
4337         ISD::CondCode NewCond = ISD::SETCC_INVALID;
4338         switch (Cond) {
4339         case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
4340         case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
4341         case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
4342         case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
4343         default: break;
4344         }
4345         if (NewCond != ISD::SETCC_INVALID &&
4346             isCondCodeLegal(NewCond, N0.getSimpleValueType()))
4347           return DAG.getSetCC(dl, VT, N0, N1, NewCond);
4348       }
4349     }
4350   }
4351 
4352   if (N0 == N1) {
4353     // The sext(setcc()) => setcc() optimization relies on the appropriate
4354     // constant being emitted.
4355     assert(!N0.getValueType().isInteger() &&
4356            "Integer types should be handled by FoldSetCC");
4357 
4358     bool EqTrue = ISD::isTrueWhenEqual(Cond);
4359     unsigned UOF = ISD::getUnorderedFlavor(Cond);
4360     if (UOF == 2) // FP operators that are undefined on NaNs.
4361       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
4362     if (UOF == unsigned(EqTrue))
4363       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
4364     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
4365     // if it is not already.
4366     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
4367     if (NewCond != Cond &&
4368         (DCI.isBeforeLegalizeOps() ||
4369                             isCondCodeLegal(NewCond, N0.getSimpleValueType())))
4370       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
4371   }
4372 
4373   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4374       N0.getValueType().isInteger()) {
4375     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
4376         N0.getOpcode() == ISD::XOR) {
4377       // Simplify (X+Y) == (X+Z) -->  Y == Z
4378       if (N0.getOpcode() == N1.getOpcode()) {
4379         if (N0.getOperand(0) == N1.getOperand(0))
4380           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
4381         if (N0.getOperand(1) == N1.getOperand(1))
4382           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
4383         if (isCommutativeBinOp(N0.getOpcode())) {
4384           // If X op Y == Y op X, try other combinations.
4385           if (N0.getOperand(0) == N1.getOperand(1))
4386             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
4387                                 Cond);
4388           if (N0.getOperand(1) == N1.getOperand(0))
4389             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
4390                                 Cond);
4391         }
4392       }
4393 
4394       // If RHS is a legal immediate value for a compare instruction, we need
4395       // to be careful about increasing register pressure needlessly.
4396       bool LegalRHSImm = false;
4397 
4398       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
4399         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4400           // Turn (X+C1) == C2 --> X == C2-C1
4401           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse()) {
4402             return DAG.getSetCC(dl, VT, N0.getOperand(0),
4403                                 DAG.getConstant(RHSC->getAPIntValue()-
4404                                                 LHSR->getAPIntValue(),
4405                                 dl, N0.getValueType()), Cond);
4406           }
4407 
4408           // Turn (X^C1) == C2 into X == C1^C2 iff X&~C1 = 0.
4409           if (N0.getOpcode() == ISD::XOR)
4410             // If we know that all of the inverted bits are zero, don't bother
4411             // performing the inversion.
4412             if (DAG.MaskedValueIsZero(N0.getOperand(0), ~LHSR->getAPIntValue()))
4413               return
4414                 DAG.getSetCC(dl, VT, N0.getOperand(0),
4415                              DAG.getConstant(LHSR->getAPIntValue() ^
4416                                                RHSC->getAPIntValue(),
4417                                              dl, N0.getValueType()),
4418                              Cond);
4419         }
4420 
4421         // Turn (C1-X) == C2 --> X == C1-C2
4422         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
4423           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse()) {
4424             return
4425               DAG.getSetCC(dl, VT, N0.getOperand(1),
4426                            DAG.getConstant(SUBC->getAPIntValue() -
4427                                              RHSC->getAPIntValue(),
4428                                            dl, N0.getValueType()),
4429                            Cond);
4430           }
4431         }
4432 
4433         // Could RHSC fold directly into a compare?
4434         if (RHSC->getValueType(0).getSizeInBits() <= 64)
4435           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
4436       }
4437 
4438       // (X+Y) == X --> Y == 0 and similar folds.
4439       // Don't do this if X is an immediate that can fold into a cmp
4440       // instruction and X+Y has other uses. It could be an induction variable
4441       // chain, and the transform would increase register pressure.
4442       if (!LegalRHSImm || N0.hasOneUse())
4443         if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
4444           return V;
4445     }
4446 
4447     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
4448         N1.getOpcode() == ISD::XOR)
4449       if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
4450         return V;
4451 
4452     if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
4453       return V;
4454   }
4455 
4456   // Fold remainder of division by a constant.
4457   if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
4458       N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4459     AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4460 
4461     // When division is cheap or optimizing for minimum size,
4462     // fall through to DIVREM creation by skipping this fold.
4463     if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) {
4464       if (N0.getOpcode() == ISD::UREM) {
4465         if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
4466           return Folded;
4467       } else if (N0.getOpcode() == ISD::SREM) {
4468         if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
4469           return Folded;
4470       }
4471     }
4472   }
4473 
4474   // Fold away ALL boolean setcc's.
4475   if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
4476     SDValue Temp;
4477     switch (Cond) {
4478     default: llvm_unreachable("Unknown integer setcc!");
4479     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
4480       Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
4481       N0 = DAG.getNOT(dl, Temp, OpVT);
4482       if (!DCI.isCalledByLegalizer())
4483         DCI.AddToWorklist(Temp.getNode());
4484       break;
4485     case ISD::SETNE:  // X != Y   -->  (X^Y)
4486       N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
4487       break;
4488     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
4489     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
4490       Temp = DAG.getNOT(dl, N0, OpVT);
4491       N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
4492       if (!DCI.isCalledByLegalizer())
4493         DCI.AddToWorklist(Temp.getNode());
4494       break;
4495     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
4496     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
4497       Temp = DAG.getNOT(dl, N1, OpVT);
4498       N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
4499       if (!DCI.isCalledByLegalizer())
4500         DCI.AddToWorklist(Temp.getNode());
4501       break;
4502     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
4503     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
4504       Temp = DAG.getNOT(dl, N0, OpVT);
4505       N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
4506       if (!DCI.isCalledByLegalizer())
4507         DCI.AddToWorklist(Temp.getNode());
4508       break;
4509     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
4510     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
4511       Temp = DAG.getNOT(dl, N1, OpVT);
4512       N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
4513       break;
4514     }
4515     if (VT.getScalarType() != MVT::i1) {
4516       if (!DCI.isCalledByLegalizer())
4517         DCI.AddToWorklist(N0.getNode());
4518       // FIXME: If running after legalize, we probably can't do this.
4519       ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT));
4520       N0 = DAG.getNode(ExtendCode, dl, VT, N0);
4521     }
4522     return N0;
4523   }
4524 
4525   // Could not fold it.
4526   return SDValue();
4527 }
4528 
4529 /// Returns true (and the GlobalValue and the offset) if the node is a
4530 /// GlobalAddress + offset.
4531 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA,
4532                                     int64_t &Offset) const {
4533 
4534   SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
4535 
4536   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
4537     GA = GASD->getGlobal();
4538     Offset += GASD->getOffset();
4539     return true;
4540   }
4541 
4542   if (N->getOpcode() == ISD::ADD) {
4543     SDValue N1 = N->getOperand(0);
4544     SDValue N2 = N->getOperand(1);
4545     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
4546       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
4547         Offset += V->getSExtValue();
4548         return true;
4549       }
4550     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
4551       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
4552         Offset += V->getSExtValue();
4553         return true;
4554       }
4555     }
4556   }
4557 
4558   return false;
4559 }
4560 
4561 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
4562                                           DAGCombinerInfo &DCI) const {
4563   // Default implementation: no optimization.
4564   return SDValue();
4565 }
4566 
4567 //===----------------------------------------------------------------------===//
4568 //  Inline Assembler Implementation Methods
4569 //===----------------------------------------------------------------------===//
4570 
4571 TargetLowering::ConstraintType
4572 TargetLowering::getConstraintType(StringRef Constraint) const {
4573   unsigned S = Constraint.size();
4574 
4575   if (S == 1) {
4576     switch (Constraint[0]) {
4577     default: break;
4578     case 'r':
4579       return C_RegisterClass;
4580     case 'm': // memory
4581     case 'o': // offsetable
4582     case 'V': // not offsetable
4583       return C_Memory;
4584     case 'n': // Simple Integer
4585     case 'E': // Floating Point Constant
4586     case 'F': // Floating Point Constant
4587       return C_Immediate;
4588     case 'i': // Simple Integer or Relocatable Constant
4589     case 's': // Relocatable Constant
4590     case 'p': // Address.
4591     case 'X': // Allow ANY value.
4592     case 'I': // Target registers.
4593     case 'J':
4594     case 'K':
4595     case 'L':
4596     case 'M':
4597     case 'N':
4598     case 'O':
4599     case 'P':
4600     case '<':
4601     case '>':
4602       return C_Other;
4603     }
4604   }
4605 
4606   if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
4607     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
4608       return C_Memory;
4609     return C_Register;
4610   }
4611   return C_Unknown;
4612 }
4613 
4614 /// Try to replace an X constraint, which matches anything, with another that
4615 /// has more specific requirements based on the type of the corresponding
4616 /// operand.
4617 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4618   if (ConstraintVT.isInteger())
4619     return "r";
4620   if (ConstraintVT.isFloatingPoint())
4621     return "f"; // works for many targets
4622   return nullptr;
4623 }
4624 
4625 SDValue TargetLowering::LowerAsmOutputForConstraint(
4626     SDValue &Chain, SDValue &Flag, const SDLoc &DL,
4627     const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
4628   return SDValue();
4629 }
4630 
4631 /// Lower the specified operand into the Ops vector.
4632 /// If it is invalid, don't add anything to Ops.
4633 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
4634                                                   std::string &Constraint,
4635                                                   std::vector<SDValue> &Ops,
4636                                                   SelectionDAG &DAG) const {
4637 
4638   if (Constraint.length() > 1) return;
4639 
4640   char ConstraintLetter = Constraint[0];
4641   switch (ConstraintLetter) {
4642   default: break;
4643   case 'X':    // Allows any operand
4644   case 'i':    // Simple Integer or Relocatable Constant
4645   case 'n':    // Simple Integer
4646   case 's': {  // Relocatable Constant
4647 
4648     ConstantSDNode *C;
4649     uint64_t Offset = 0;
4650 
4651     // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
4652     // etc., since getelementpointer is variadic. We can't use
4653     // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
4654     // while in this case the GA may be furthest from the root node which is
4655     // likely an ISD::ADD.
4656     while (true) {
4657       if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
4658         // gcc prints these as sign extended.  Sign extend value to 64 bits
4659         // now; without this it would get ZExt'd later in
4660         // ScheduleDAGSDNodes::EmitNode, which is very generic.
4661         bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
4662         BooleanContent BCont = getBooleanContents(MVT::i64);
4663         ISD::NodeType ExtOpc =
4664             IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
4665         int64_t ExtVal =
4666             ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
4667         Ops.push_back(
4668             DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
4669         return;
4670       }
4671       if (ConstraintLetter != 'n') {
4672         if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
4673           Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
4674                                                    GA->getValueType(0),
4675                                                    Offset + GA->getOffset()));
4676           return;
4677         }
4678         if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
4679           Ops.push_back(DAG.getTargetBlockAddress(
4680               BA->getBlockAddress(), BA->getValueType(0),
4681               Offset + BA->getOffset(), BA->getTargetFlags()));
4682           return;
4683         }
4684         if (isa<BasicBlockSDNode>(Op)) {
4685           Ops.push_back(Op);
4686           return;
4687         }
4688       }
4689       const unsigned OpCode = Op.getOpcode();
4690       if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
4691         if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
4692           Op = Op.getOperand(1);
4693         // Subtraction is not commutative.
4694         else if (OpCode == ISD::ADD &&
4695                  (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
4696           Op = Op.getOperand(0);
4697         else
4698           return;
4699         Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
4700         continue;
4701       }
4702       return;
4703     }
4704     break;
4705   }
4706   }
4707 }
4708 
4709 std::pair<unsigned, const TargetRegisterClass *>
4710 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
4711                                              StringRef Constraint,
4712                                              MVT VT) const {
4713   if (Constraint.empty() || Constraint[0] != '{')
4714     return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
4715   assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
4716 
4717   // Remove the braces from around the name.
4718   StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
4719 
4720   std::pair<unsigned, const TargetRegisterClass *> R =
4721       std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
4722 
4723   // Figure out which register class contains this reg.
4724   for (const TargetRegisterClass *RC : RI->regclasses()) {
4725     // If none of the value types for this register class are valid, we
4726     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
4727     if (!isLegalRC(*RI, *RC))
4728       continue;
4729 
4730     for (const MCPhysReg &PR : *RC) {
4731       if (RegName.equals_insensitive(RI->getRegAsmName(PR))) {
4732         std::pair<unsigned, const TargetRegisterClass *> S =
4733             std::make_pair(PR, RC);
4734 
4735         // If this register class has the requested value type, return it,
4736         // otherwise keep searching and return the first class found
4737         // if no other is found which explicitly has the requested type.
4738         if (RI->isTypeLegalForClass(*RC, VT))
4739           return S;
4740         if (!R.second)
4741           R = S;
4742       }
4743     }
4744   }
4745 
4746   return R;
4747 }
4748 
4749 //===----------------------------------------------------------------------===//
4750 // Constraint Selection.
4751 
4752 /// Return true of this is an input operand that is a matching constraint like
4753 /// "4".
4754 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
4755   assert(!ConstraintCode.empty() && "No known constraint!");
4756   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
4757 }
4758 
4759 /// If this is an input matching constraint, this method returns the output
4760 /// operand it matches.
4761 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
4762   assert(!ConstraintCode.empty() && "No known constraint!");
4763   return atoi(ConstraintCode.c_str());
4764 }
4765 
4766 /// Split up the constraint string from the inline assembly value into the
4767 /// specific constraints and their prefixes, and also tie in the associated
4768 /// operand values.
4769 /// If this returns an empty vector, and if the constraint string itself
4770 /// isn't empty, there was an error parsing.
4771 TargetLowering::AsmOperandInfoVector
4772 TargetLowering::ParseConstraints(const DataLayout &DL,
4773                                  const TargetRegisterInfo *TRI,
4774                                  const CallBase &Call) const {
4775   /// Information about all of the constraints.
4776   AsmOperandInfoVector ConstraintOperands;
4777   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
4778   unsigned maCount = 0; // Largest number of multiple alternative constraints.
4779 
4780   // Do a prepass over the constraints, canonicalizing them, and building up the
4781   // ConstraintOperands list.
4782   unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4783   unsigned ResNo = 0; // ResNo - The result number of the next output.
4784 
4785   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
4786     ConstraintOperands.emplace_back(std::move(CI));
4787     AsmOperandInfo &OpInfo = ConstraintOperands.back();
4788 
4789     // Update multiple alternative constraint count.
4790     if (OpInfo.multipleAlternatives.size() > maCount)
4791       maCount = OpInfo.multipleAlternatives.size();
4792 
4793     OpInfo.ConstraintVT = MVT::Other;
4794 
4795     // Compute the value type for each operand.
4796     switch (OpInfo.Type) {
4797     case InlineAsm::isOutput:
4798       // Indirect outputs just consume an argument.
4799       if (OpInfo.isIndirect) {
4800         OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
4801         break;
4802       }
4803 
4804       // The return value of the call is this value.  As such, there is no
4805       // corresponding argument.
4806       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
4807       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
4808         OpInfo.ConstraintVT =
4809             getSimpleValueType(DL, STy->getElementType(ResNo));
4810       } else {
4811         assert(ResNo == 0 && "Asm only has one result!");
4812         OpInfo.ConstraintVT =
4813             getAsmOperandValueType(DL, Call.getType()).getSimpleVT();
4814       }
4815       ++ResNo;
4816       break;
4817     case InlineAsm::isInput:
4818       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
4819       break;
4820     case InlineAsm::isClobber:
4821       // Nothing to do.
4822       break;
4823     }
4824 
4825     if (OpInfo.CallOperandVal) {
4826       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
4827       if (OpInfo.isIndirect) {
4828         OpTy = Call.getAttributes().getParamElementType(ArgNo);
4829         assert(OpTy && "Indirect opernad must have elementtype attribute");
4830       }
4831 
4832       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
4833       if (StructType *STy = dyn_cast<StructType>(OpTy))
4834         if (STy->getNumElements() == 1)
4835           OpTy = STy->getElementType(0);
4836 
4837       // If OpTy is not a single value, it may be a struct/union that we
4838       // can tile with integers.
4839       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4840         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
4841         switch (BitSize) {
4842         default: break;
4843         case 1:
4844         case 8:
4845         case 16:
4846         case 32:
4847         case 64:
4848         case 128:
4849           OpInfo.ConstraintVT =
4850               MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
4851           break;
4852         }
4853       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
4854         unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
4855         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
4856       } else {
4857         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
4858       }
4859 
4860       ArgNo++;
4861     }
4862   }
4863 
4864   // If we have multiple alternative constraints, select the best alternative.
4865   if (!ConstraintOperands.empty()) {
4866     if (maCount) {
4867       unsigned bestMAIndex = 0;
4868       int bestWeight = -1;
4869       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
4870       int weight = -1;
4871       unsigned maIndex;
4872       // Compute the sums of the weights for each alternative, keeping track
4873       // of the best (highest weight) one so far.
4874       for (maIndex = 0; maIndex < maCount; ++maIndex) {
4875         int weightSum = 0;
4876         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
4877              cIndex != eIndex; ++cIndex) {
4878           AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
4879           if (OpInfo.Type == InlineAsm::isClobber)
4880             continue;
4881 
4882           // If this is an output operand with a matching input operand,
4883           // look up the matching input. If their types mismatch, e.g. one
4884           // is an integer, the other is floating point, or their sizes are
4885           // different, flag it as an maCantMatch.
4886           if (OpInfo.hasMatchingInput()) {
4887             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4888             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
4889               if ((OpInfo.ConstraintVT.isInteger() !=
4890                    Input.ConstraintVT.isInteger()) ||
4891                   (OpInfo.ConstraintVT.getSizeInBits() !=
4892                    Input.ConstraintVT.getSizeInBits())) {
4893                 weightSum = -1; // Can't match.
4894                 break;
4895               }
4896             }
4897           }
4898           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
4899           if (weight == -1) {
4900             weightSum = -1;
4901             break;
4902           }
4903           weightSum += weight;
4904         }
4905         // Update best.
4906         if (weightSum > bestWeight) {
4907           bestWeight = weightSum;
4908           bestMAIndex = maIndex;
4909         }
4910       }
4911 
4912       // Now select chosen alternative in each constraint.
4913       for (AsmOperandInfo &cInfo : ConstraintOperands)
4914         if (cInfo.Type != InlineAsm::isClobber)
4915           cInfo.selectAlternative(bestMAIndex);
4916     }
4917   }
4918 
4919   // Check and hook up tied operands, choose constraint code to use.
4920   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
4921        cIndex != eIndex; ++cIndex) {
4922     AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
4923 
4924     // If this is an output operand with a matching input operand, look up the
4925     // matching input. If their types mismatch, e.g. one is an integer, the
4926     // other is floating point, or their sizes are different, flag it as an
4927     // error.
4928     if (OpInfo.hasMatchingInput()) {
4929       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4930 
4931       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
4932         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
4933             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
4934                                          OpInfo.ConstraintVT);
4935         std::pair<unsigned, const TargetRegisterClass *> InputRC =
4936             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
4937                                          Input.ConstraintVT);
4938         if ((OpInfo.ConstraintVT.isInteger() !=
4939              Input.ConstraintVT.isInteger()) ||
4940             (MatchRC.second != InputRC.second)) {
4941           report_fatal_error("Unsupported asm: input constraint"
4942                              " with a matching output constraint of"
4943                              " incompatible type!");
4944         }
4945       }
4946     }
4947   }
4948 
4949   return ConstraintOperands;
4950 }
4951 
4952 /// Return an integer indicating how general CT is.
4953 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
4954   switch (CT) {
4955   case TargetLowering::C_Immediate:
4956   case TargetLowering::C_Other:
4957   case TargetLowering::C_Unknown:
4958     return 0;
4959   case TargetLowering::C_Register:
4960     return 1;
4961   case TargetLowering::C_RegisterClass:
4962     return 2;
4963   case TargetLowering::C_Memory:
4964     return 3;
4965   }
4966   llvm_unreachable("Invalid constraint type");
4967 }
4968 
4969 /// Examine constraint type and operand type and determine a weight value.
4970 /// This object must already have been set up with the operand type
4971 /// and the current alternative constraint selected.
4972 TargetLowering::ConstraintWeight
4973   TargetLowering::getMultipleConstraintMatchWeight(
4974     AsmOperandInfo &info, int maIndex) const {
4975   InlineAsm::ConstraintCodeVector *rCodes;
4976   if (maIndex >= (int)info.multipleAlternatives.size())
4977     rCodes = &info.Codes;
4978   else
4979     rCodes = &info.multipleAlternatives[maIndex].Codes;
4980   ConstraintWeight BestWeight = CW_Invalid;
4981 
4982   // Loop over the options, keeping track of the most general one.
4983   for (const std::string &rCode : *rCodes) {
4984     ConstraintWeight weight =
4985         getSingleConstraintMatchWeight(info, rCode.c_str());
4986     if (weight > BestWeight)
4987       BestWeight = weight;
4988   }
4989 
4990   return BestWeight;
4991 }
4992 
4993 /// Examine constraint type and operand type and determine a weight value.
4994 /// This object must already have been set up with the operand type
4995 /// and the current alternative constraint selected.
4996 TargetLowering::ConstraintWeight
4997   TargetLowering::getSingleConstraintMatchWeight(
4998     AsmOperandInfo &info, const char *constraint) const {
4999   ConstraintWeight weight = CW_Invalid;
5000   Value *CallOperandVal = info.CallOperandVal;
5001     // If we don't have a value, we can't do a match,
5002     // but allow it at the lowest weight.
5003   if (!CallOperandVal)
5004     return CW_Default;
5005   // Look at the constraint type.
5006   switch (*constraint) {
5007     case 'i': // immediate integer.
5008     case 'n': // immediate integer with a known value.
5009       if (isa<ConstantInt>(CallOperandVal))
5010         weight = CW_Constant;
5011       break;
5012     case 's': // non-explicit intregal immediate.
5013       if (isa<GlobalValue>(CallOperandVal))
5014         weight = CW_Constant;
5015       break;
5016     case 'E': // immediate float if host format.
5017     case 'F': // immediate float.
5018       if (isa<ConstantFP>(CallOperandVal))
5019         weight = CW_Constant;
5020       break;
5021     case '<': // memory operand with autodecrement.
5022     case '>': // memory operand with autoincrement.
5023     case 'm': // memory operand.
5024     case 'o': // offsettable memory operand
5025     case 'V': // non-offsettable memory operand
5026       weight = CW_Memory;
5027       break;
5028     case 'r': // general register.
5029     case 'g': // general register, memory operand or immediate integer.
5030               // note: Clang converts "g" to "imr".
5031       if (CallOperandVal->getType()->isIntegerTy())
5032         weight = CW_Register;
5033       break;
5034     case 'X': // any operand.
5035   default:
5036     weight = CW_Default;
5037     break;
5038   }
5039   return weight;
5040 }
5041 
5042 /// If there are multiple different constraints that we could pick for this
5043 /// operand (e.g. "imr") try to pick the 'best' one.
5044 /// This is somewhat tricky: constraints fall into four classes:
5045 ///    Other         -> immediates and magic values
5046 ///    Register      -> one specific register
5047 ///    RegisterClass -> a group of regs
5048 ///    Memory        -> memory
5049 /// Ideally, we would pick the most specific constraint possible: if we have
5050 /// something that fits into a register, we would pick it.  The problem here
5051 /// is that if we have something that could either be in a register or in
5052 /// memory that use of the register could cause selection of *other*
5053 /// operands to fail: they might only succeed if we pick memory.  Because of
5054 /// this the heuristic we use is:
5055 ///
5056 ///  1) If there is an 'other' constraint, and if the operand is valid for
5057 ///     that constraint, use it.  This makes us take advantage of 'i'
5058 ///     constraints when available.
5059 ///  2) Otherwise, pick the most general constraint present.  This prefers
5060 ///     'm' over 'r', for example.
5061 ///
5062 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
5063                              const TargetLowering &TLI,
5064                              SDValue Op, SelectionDAG *DAG) {
5065   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
5066   unsigned BestIdx = 0;
5067   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
5068   int BestGenerality = -1;
5069 
5070   // Loop over the options, keeping track of the most general one.
5071   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
5072     TargetLowering::ConstraintType CType =
5073       TLI.getConstraintType(OpInfo.Codes[i]);
5074 
5075     // Indirect 'other' or 'immediate' constraints are not allowed.
5076     if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
5077                                CType == TargetLowering::C_Register ||
5078                                CType == TargetLowering::C_RegisterClass))
5079       continue;
5080 
5081     // If this is an 'other' or 'immediate' constraint, see if the operand is
5082     // valid for it. For example, on X86 we might have an 'rI' constraint. If
5083     // the operand is an integer in the range [0..31] we want to use I (saving a
5084     // load of a register), otherwise we must use 'r'.
5085     if ((CType == TargetLowering::C_Other ||
5086          CType == TargetLowering::C_Immediate) && Op.getNode()) {
5087       assert(OpInfo.Codes[i].size() == 1 &&
5088              "Unhandled multi-letter 'other' constraint");
5089       std::vector<SDValue> ResultOps;
5090       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
5091                                        ResultOps, *DAG);
5092       if (!ResultOps.empty()) {
5093         BestType = CType;
5094         BestIdx = i;
5095         break;
5096       }
5097     }
5098 
5099     // Things with matching constraints can only be registers, per gcc
5100     // documentation.  This mainly affects "g" constraints.
5101     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
5102       continue;
5103 
5104     // This constraint letter is more general than the previous one, use it.
5105     int Generality = getConstraintGenerality(CType);
5106     if (Generality > BestGenerality) {
5107       BestType = CType;
5108       BestIdx = i;
5109       BestGenerality = Generality;
5110     }
5111   }
5112 
5113   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
5114   OpInfo.ConstraintType = BestType;
5115 }
5116 
5117 /// Determines the constraint code and constraint type to use for the specific
5118 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
5119 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
5120                                             SDValue Op,
5121                                             SelectionDAG *DAG) const {
5122   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
5123 
5124   // Single-letter constraints ('r') are very common.
5125   if (OpInfo.Codes.size() == 1) {
5126     OpInfo.ConstraintCode = OpInfo.Codes[0];
5127     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
5128   } else {
5129     ChooseConstraint(OpInfo, *this, Op, DAG);
5130   }
5131 
5132   // 'X' matches anything.
5133   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
5134     // Constants are handled elsewhere.  For Functions, the type here is the
5135     // type of the result, which is not what we want to look at; leave them
5136     // alone.
5137     Value *v = OpInfo.CallOperandVal;
5138     if (isa<ConstantInt>(v) || isa<Function>(v)) {
5139       return;
5140     }
5141 
5142     if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) {
5143       OpInfo.ConstraintCode = "i";
5144       return;
5145     }
5146 
5147     // Otherwise, try to resolve it to something we know about by looking at
5148     // the actual operand type.
5149     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
5150       OpInfo.ConstraintCode = Repl;
5151       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
5152     }
5153   }
5154 }
5155 
5156 /// Given an exact SDIV by a constant, create a multiplication
5157 /// with the multiplicative inverse of the constant.
5158 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N,
5159                               const SDLoc &dl, SelectionDAG &DAG,
5160                               SmallVectorImpl<SDNode *> &Created) {
5161   SDValue Op0 = N->getOperand(0);
5162   SDValue Op1 = N->getOperand(1);
5163   EVT VT = N->getValueType(0);
5164   EVT SVT = VT.getScalarType();
5165   EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
5166   EVT ShSVT = ShVT.getScalarType();
5167 
5168   bool UseSRA = false;
5169   SmallVector<SDValue, 16> Shifts, Factors;
5170 
5171   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
5172     if (C->isZero())
5173       return false;
5174     APInt Divisor = C->getAPIntValue();
5175     unsigned Shift = Divisor.countTrailingZeros();
5176     if (Shift) {
5177       Divisor.ashrInPlace(Shift);
5178       UseSRA = true;
5179     }
5180     // Calculate the multiplicative inverse, using Newton's method.
5181     APInt t;
5182     APInt Factor = Divisor;
5183     while ((t = Divisor * Factor) != 1)
5184       Factor *= APInt(Divisor.getBitWidth(), 2) - t;
5185     Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
5186     Factors.push_back(DAG.getConstant(Factor, dl, SVT));
5187     return true;
5188   };
5189 
5190   // Collect all magic values from the build vector.
5191   if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
5192     return SDValue();
5193 
5194   SDValue Shift, Factor;
5195   if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
5196     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
5197     Factor = DAG.getBuildVector(VT, dl, Factors);
5198   } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
5199     assert(Shifts.size() == 1 && Factors.size() == 1 &&
5200            "Expected matchUnaryPredicate to return one element for scalable "
5201            "vectors");
5202     Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
5203     Factor = DAG.getSplatVector(VT, dl, Factors[0]);
5204   } else {
5205     assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
5206     Shift = Shifts[0];
5207     Factor = Factors[0];
5208   }
5209 
5210   SDValue Res = Op0;
5211 
5212   // Shift the value upfront if it is even, so the LSB is one.
5213   if (UseSRA) {
5214     // TODO: For UDIV use SRL instead of SRA.
5215     SDNodeFlags Flags;
5216     Flags.setExact(true);
5217     Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags);
5218     Created.push_back(Res.getNode());
5219   }
5220 
5221   return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
5222 }
5223 
5224 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
5225                               SelectionDAG &DAG,
5226                               SmallVectorImpl<SDNode *> &Created) const {
5227   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5228   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5229   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
5230     return SDValue(N, 0); // Lower SDIV as SDIV
5231   return SDValue();
5232 }
5233 
5234 /// Given an ISD::SDIV node expressing a divide by constant,
5235 /// return a DAG expression to select that will generate the same value by
5236 /// multiplying by a magic number.
5237 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
5238 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
5239                                   bool IsAfterLegalization,
5240                                   SmallVectorImpl<SDNode *> &Created) const {
5241   SDLoc dl(N);
5242   EVT VT = N->getValueType(0);
5243   EVT SVT = VT.getScalarType();
5244   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5245   EVT ShSVT = ShVT.getScalarType();
5246   unsigned EltBits = VT.getScalarSizeInBits();
5247   EVT MulVT;
5248 
5249   // Check to see if we can do this.
5250   // FIXME: We should be more aggressive here.
5251   if (!isTypeLegal(VT)) {
5252     // Limit this to simple scalars for now.
5253     if (VT.isVector() || !VT.isSimple())
5254       return SDValue();
5255 
5256     // If this type will be promoted to a large enough type with a legal
5257     // multiply operation, we can go ahead and do this transform.
5258     if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger)
5259       return SDValue();
5260 
5261     MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
5262     if (MulVT.getSizeInBits() < (2 * EltBits) ||
5263         !isOperationLegal(ISD::MUL, MulVT))
5264       return SDValue();
5265   }
5266 
5267   // If the sdiv has an 'exact' bit we can use a simpler lowering.
5268   if (N->getFlags().hasExact())
5269     return BuildExactSDIV(*this, N, dl, DAG, Created);
5270 
5271   SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
5272 
5273   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
5274     if (C->isZero())
5275       return false;
5276 
5277     const APInt &Divisor = C->getAPIntValue();
5278     SignedDivisionByConstantInfo magics = SignedDivisionByConstantInfo::get(Divisor);
5279     int NumeratorFactor = 0;
5280     int ShiftMask = -1;
5281 
5282     if (Divisor.isOne() || Divisor.isAllOnes()) {
5283       // If d is +1/-1, we just multiply the numerator by +1/-1.
5284       NumeratorFactor = Divisor.getSExtValue();
5285       magics.Magic = 0;
5286       magics.ShiftAmount = 0;
5287       ShiftMask = 0;
5288     } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) {
5289       // If d > 0 and m < 0, add the numerator.
5290       NumeratorFactor = 1;
5291     } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) {
5292       // If d < 0 and m > 0, subtract the numerator.
5293       NumeratorFactor = -1;
5294     }
5295 
5296     MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT));
5297     Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT));
5298     Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT));
5299     ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT));
5300     return true;
5301   };
5302 
5303   SDValue N0 = N->getOperand(0);
5304   SDValue N1 = N->getOperand(1);
5305 
5306   // Collect the shifts / magic values from each element.
5307   if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern))
5308     return SDValue();
5309 
5310   SDValue MagicFactor, Factor, Shift, ShiftMask;
5311   if (N1.getOpcode() == ISD::BUILD_VECTOR) {
5312     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
5313     Factor = DAG.getBuildVector(VT, dl, Factors);
5314     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
5315     ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
5316   } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
5317     assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
5318            Shifts.size() == 1 && ShiftMasks.size() == 1 &&
5319            "Expected matchUnaryPredicate to return one element for scalable "
5320            "vectors");
5321     MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
5322     Factor = DAG.getSplatVector(VT, dl, Factors[0]);
5323     Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
5324     ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
5325   } else {
5326     assert(isa<ConstantSDNode>(N1) && "Expected a constant");
5327     MagicFactor = MagicFactors[0];
5328     Factor = Factors[0];
5329     Shift = Shifts[0];
5330     ShiftMask = ShiftMasks[0];
5331   }
5332 
5333   // Multiply the numerator (operand 0) by the magic value.
5334   // FIXME: We should support doing a MUL in a wider type.
5335   auto GetMULHS = [&](SDValue X, SDValue Y) {
5336     // If the type isn't legal, use a wider mul of the the type calculated
5337     // earlier.
5338     if (!isTypeLegal(VT)) {
5339       X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
5340       Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
5341       Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
5342       Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
5343                       DAG.getShiftAmountConstant(EltBits, MulVT, dl));
5344       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
5345     }
5346 
5347     if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization))
5348       return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
5349     if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) {
5350       SDValue LoHi =
5351           DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
5352       return SDValue(LoHi.getNode(), 1);
5353     }
5354     return SDValue();
5355   };
5356 
5357   SDValue Q = GetMULHS(N0, MagicFactor);
5358   if (!Q)
5359     return SDValue();
5360 
5361   Created.push_back(Q.getNode());
5362 
5363   // (Optionally) Add/subtract the numerator using Factor.
5364   Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
5365   Created.push_back(Factor.getNode());
5366   Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
5367   Created.push_back(Q.getNode());
5368 
5369   // Shift right algebraic by shift value.
5370   Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
5371   Created.push_back(Q.getNode());
5372 
5373   // Extract the sign bit, mask it and add it to the quotient.
5374   SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
5375   SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
5376   Created.push_back(T.getNode());
5377   T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
5378   Created.push_back(T.getNode());
5379   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
5380 }
5381 
5382 /// Given an ISD::UDIV node expressing a divide by constant,
5383 /// return a DAG expression to select that will generate the same value by
5384 /// multiplying by a magic number.
5385 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
5386 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
5387                                   bool IsAfterLegalization,
5388                                   SmallVectorImpl<SDNode *> &Created) const {
5389   SDLoc dl(N);
5390   EVT VT = N->getValueType(0);
5391   EVT SVT = VT.getScalarType();
5392   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5393   EVT ShSVT = ShVT.getScalarType();
5394   unsigned EltBits = VT.getScalarSizeInBits();
5395   EVT MulVT;
5396 
5397   // Check to see if we can do this.
5398   // FIXME: We should be more aggressive here.
5399   if (!isTypeLegal(VT)) {
5400     // Limit this to simple scalars for now.
5401     if (VT.isVector() || !VT.isSimple())
5402       return SDValue();
5403 
5404     // If this type will be promoted to a large enough type with a legal
5405     // multiply operation, we can go ahead and do this transform.
5406     if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger)
5407       return SDValue();
5408 
5409     MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
5410     if (MulVT.getSizeInBits() < (2 * EltBits) ||
5411         !isOperationLegal(ISD::MUL, MulVT))
5412       return SDValue();
5413   }
5414 
5415   bool UseNPQ = false;
5416   SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
5417 
5418   auto BuildUDIVPattern = [&](ConstantSDNode *C) {
5419     if (C->isZero())
5420       return false;
5421     // FIXME: We should use a narrower constant when the upper
5422     // bits are known to be zero.
5423     const APInt& Divisor = C->getAPIntValue();
5424     UnsignedDivisonByConstantInfo magics = UnsignedDivisonByConstantInfo::get(Divisor);
5425     unsigned PreShift = 0, PostShift = 0;
5426 
5427     // If the divisor is even, we can avoid using the expensive fixup by
5428     // shifting the divided value upfront.
5429     if (magics.IsAdd != 0 && !Divisor[0]) {
5430       PreShift = Divisor.countTrailingZeros();
5431       // Get magic number for the shifted divisor.
5432       magics = UnsignedDivisonByConstantInfo::get(Divisor.lshr(PreShift), PreShift);
5433       assert(magics.IsAdd == 0 && "Should use cheap fixup now");
5434     }
5435 
5436     APInt Magic = magics.Magic;
5437 
5438     unsigned SelNPQ;
5439     if (magics.IsAdd == 0 || Divisor.isOne()) {
5440       assert(magics.ShiftAmount < Divisor.getBitWidth() &&
5441              "We shouldn't generate an undefined shift!");
5442       PostShift = magics.ShiftAmount;
5443       SelNPQ = false;
5444     } else {
5445       PostShift = magics.ShiftAmount - 1;
5446       SelNPQ = true;
5447     }
5448 
5449     PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT));
5450     MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT));
5451     NPQFactors.push_back(
5452         DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
5453                                : APInt::getZero(EltBits),
5454                         dl, SVT));
5455     PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT));
5456     UseNPQ |= SelNPQ;
5457     return true;
5458   };
5459 
5460   SDValue N0 = N->getOperand(0);
5461   SDValue N1 = N->getOperand(1);
5462 
5463   // Collect the shifts/magic values from each element.
5464   if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern))
5465     return SDValue();
5466 
5467   SDValue PreShift, PostShift, MagicFactor, NPQFactor;
5468   if (N1.getOpcode() == ISD::BUILD_VECTOR) {
5469     PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
5470     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
5471     NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
5472     PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
5473   } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
5474     assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
5475            NPQFactors.size() == 1 && PostShifts.size() == 1 &&
5476            "Expected matchUnaryPredicate to return one for scalable vectors");
5477     PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
5478     MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
5479     NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
5480     PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
5481   } else {
5482     assert(isa<ConstantSDNode>(N1) && "Expected a constant");
5483     PreShift = PreShifts[0];
5484     MagicFactor = MagicFactors[0];
5485     PostShift = PostShifts[0];
5486   }
5487 
5488   SDValue Q = N0;
5489   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
5490   Created.push_back(Q.getNode());
5491 
5492   // FIXME: We should support doing a MUL in a wider type.
5493   auto GetMULHU = [&](SDValue X, SDValue Y) {
5494     // If the type isn't legal, use a wider mul of the the type calculated
5495     // earlier.
5496     if (!isTypeLegal(VT)) {
5497       X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
5498       Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
5499       Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
5500       Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
5501                       DAG.getShiftAmountConstant(EltBits, MulVT, dl));
5502       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
5503     }
5504 
5505     if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization))
5506       return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
5507     if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) {
5508       SDValue LoHi =
5509           DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
5510       return SDValue(LoHi.getNode(), 1);
5511     }
5512     return SDValue(); // No mulhu or equivalent
5513   };
5514 
5515   // Multiply the numerator (operand 0) by the magic value.
5516   Q = GetMULHU(Q, MagicFactor);
5517   if (!Q)
5518     return SDValue();
5519 
5520   Created.push_back(Q.getNode());
5521 
5522   if (UseNPQ) {
5523     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
5524     Created.push_back(NPQ.getNode());
5525 
5526     // For vectors we might have a mix of non-NPQ/NPQ paths, so use
5527     // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
5528     if (VT.isVector())
5529       NPQ = GetMULHU(NPQ, NPQFactor);
5530     else
5531       NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
5532 
5533     Created.push_back(NPQ.getNode());
5534 
5535     Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
5536     Created.push_back(Q.getNode());
5537   }
5538 
5539   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
5540   Created.push_back(Q.getNode());
5541 
5542   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
5543 
5544   SDValue One = DAG.getConstant(1, dl, VT);
5545   SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
5546   return DAG.getSelect(dl, VT, IsOne, N0, Q);
5547 }
5548 
5549 /// If all values in Values that *don't* match the predicate are same 'splat'
5550 /// value, then replace all values with that splat value.
5551 /// Else, if AlternativeReplacement was provided, then replace all values that
5552 /// do match predicate with AlternativeReplacement value.
5553 static void
5554 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values,
5555                           std::function<bool(SDValue)> Predicate,
5556                           SDValue AlternativeReplacement = SDValue()) {
5557   SDValue Replacement;
5558   // Is there a value for which the Predicate does *NOT* match? What is it?
5559   auto SplatValue = llvm::find_if_not(Values, Predicate);
5560   if (SplatValue != Values.end()) {
5561     // Does Values consist only of SplatValue's and values matching Predicate?
5562     if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
5563           return Value == *SplatValue || Predicate(Value);
5564         })) // Then we shall replace values matching predicate with SplatValue.
5565       Replacement = *SplatValue;
5566   }
5567   if (!Replacement) {
5568     // Oops, we did not find the "baseline" splat value.
5569     if (!AlternativeReplacement)
5570       return; // Nothing to do.
5571     // Let's replace with provided value then.
5572     Replacement = AlternativeReplacement;
5573   }
5574   std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
5575 }
5576 
5577 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
5578 /// where the divisor is constant and the comparison target is zero,
5579 /// return a DAG expression that will generate the same comparison result
5580 /// using only multiplications, additions and shifts/rotations.
5581 /// Ref: "Hacker's Delight" 10-17.
5582 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
5583                                         SDValue CompTargetNode,
5584                                         ISD::CondCode Cond,
5585                                         DAGCombinerInfo &DCI,
5586                                         const SDLoc &DL) const {
5587   SmallVector<SDNode *, 5> Built;
5588   if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
5589                                          DCI, DL, Built)) {
5590     for (SDNode *N : Built)
5591       DCI.AddToWorklist(N);
5592     return Folded;
5593   }
5594 
5595   return SDValue();
5596 }
5597 
5598 SDValue
5599 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
5600                                   SDValue CompTargetNode, ISD::CondCode Cond,
5601                                   DAGCombinerInfo &DCI, const SDLoc &DL,
5602                                   SmallVectorImpl<SDNode *> &Created) const {
5603   // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q)
5604   // - D must be constant, with D = D0 * 2^K where D0 is odd
5605   // - P is the multiplicative inverse of D0 modulo 2^W
5606   // - Q = floor(((2^W) - 1) / D)
5607   // where W is the width of the common type of N and D.
5608   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5609          "Only applicable for (in)equality comparisons.");
5610 
5611   SelectionDAG &DAG = DCI.DAG;
5612 
5613   EVT VT = REMNode.getValueType();
5614   EVT SVT = VT.getScalarType();
5615   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize());
5616   EVT ShSVT = ShVT.getScalarType();
5617 
5618   // If MUL is unavailable, we cannot proceed in any case.
5619   if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
5620     return SDValue();
5621 
5622   bool ComparingWithAllZeros = true;
5623   bool AllComparisonsWithNonZerosAreTautological = true;
5624   bool HadTautologicalLanes = false;
5625   bool AllLanesAreTautological = true;
5626   bool HadEvenDivisor = false;
5627   bool AllDivisorsArePowerOfTwo = true;
5628   bool HadTautologicalInvertedLanes = false;
5629   SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts;
5630 
5631   auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
5632     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
5633     if (CDiv->isZero())
5634       return false;
5635 
5636     const APInt &D = CDiv->getAPIntValue();
5637     const APInt &Cmp = CCmp->getAPIntValue();
5638 
5639     ComparingWithAllZeros &= Cmp.isZero();
5640 
5641     // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
5642     // if C2 is not less than C1, the comparison is always false.
5643     // But we will only be able to produce the comparison that will give the
5644     // opposive tautological answer. So this lane would need to be fixed up.
5645     bool TautologicalInvertedLane = D.ule(Cmp);
5646     HadTautologicalInvertedLanes |= TautologicalInvertedLane;
5647 
5648     // If all lanes are tautological (either all divisors are ones, or divisor
5649     // is not greater than the constant we are comparing with),
5650     // we will prefer to avoid the fold.
5651     bool TautologicalLane = D.isOne() || TautologicalInvertedLane;
5652     HadTautologicalLanes |= TautologicalLane;
5653     AllLanesAreTautological &= TautologicalLane;
5654 
5655     // If we are comparing with non-zero, we need'll need  to subtract said
5656     // comparison value from the LHS. But there is no point in doing that if
5657     // every lane where we are comparing with non-zero is tautological..
5658     if (!Cmp.isZero())
5659       AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
5660 
5661     // Decompose D into D0 * 2^K
5662     unsigned K = D.countTrailingZeros();
5663     assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
5664     APInt D0 = D.lshr(K);
5665 
5666     // D is even if it has trailing zeros.
5667     HadEvenDivisor |= (K != 0);
5668     // D is a power-of-two if D0 is one.
5669     // If all divisors are power-of-two, we will prefer to avoid the fold.
5670     AllDivisorsArePowerOfTwo &= D0.isOne();
5671 
5672     // P = inv(D0, 2^W)
5673     // 2^W requires W + 1 bits, so we have to extend and then truncate.
5674     unsigned W = D.getBitWidth();
5675     APInt P = D0.zext(W + 1)
5676                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
5677                   .trunc(W);
5678     assert(!P.isZero() && "No multiplicative inverse!"); // unreachable
5679     assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
5680 
5681     // Q = floor((2^W - 1) u/ D)
5682     // R = ((2^W - 1) u% D)
5683     APInt Q, R;
5684     APInt::udivrem(APInt::getAllOnes(W), D, Q, R);
5685 
5686     // If we are comparing with zero, then that comparison constant is okay,
5687     // else it may need to be one less than that.
5688     if (Cmp.ugt(R))
5689       Q -= 1;
5690 
5691     assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) &&
5692            "We are expecting that K is always less than all-ones for ShSVT");
5693 
5694     // If the lane is tautological the result can be constant-folded.
5695     if (TautologicalLane) {
5696       // Set P and K amount to a bogus values so we can try to splat them.
5697       P = 0;
5698       K = -1;
5699       // And ensure that comparison constant is tautological,
5700       // it will always compare true/false.
5701       Q = -1;
5702     }
5703 
5704     PAmts.push_back(DAG.getConstant(P, DL, SVT));
5705     KAmts.push_back(
5706         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
5707     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
5708     return true;
5709   };
5710 
5711   SDValue N = REMNode.getOperand(0);
5712   SDValue D = REMNode.getOperand(1);
5713 
5714   // Collect the values from each element.
5715   if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
5716     return SDValue();
5717 
5718   // If all lanes are tautological, the result can be constant-folded.
5719   if (AllLanesAreTautological)
5720     return SDValue();
5721 
5722   // If this is a urem by a powers-of-two, avoid the fold since it can be
5723   // best implemented as a bit test.
5724   if (AllDivisorsArePowerOfTwo)
5725     return SDValue();
5726 
5727   SDValue PVal, KVal, QVal;
5728   if (D.getOpcode() == ISD::BUILD_VECTOR) {
5729     if (HadTautologicalLanes) {
5730       // Try to turn PAmts into a splat, since we don't care about the values
5731       // that are currently '0'. If we can't, just keep '0'`s.
5732       turnVectorIntoSplatVector(PAmts, isNullConstant);
5733       // Try to turn KAmts into a splat, since we don't care about the values
5734       // that are currently '-1'. If we can't, change them to '0'`s.
5735       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
5736                                 DAG.getConstant(0, DL, ShSVT));
5737     }
5738 
5739     PVal = DAG.getBuildVector(VT, DL, PAmts);
5740     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
5741     QVal = DAG.getBuildVector(VT, DL, QAmts);
5742   } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
5743     assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 &&
5744            "Expected matchBinaryPredicate to return one element for "
5745            "SPLAT_VECTORs");
5746     PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
5747     KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
5748     QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
5749   } else {
5750     PVal = PAmts[0];
5751     KVal = KAmts[0];
5752     QVal = QAmts[0];
5753   }
5754 
5755   if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
5756     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
5757       return SDValue(); // FIXME: Could/should use `ISD::ADD`?
5758     assert(CompTargetNode.getValueType() == N.getValueType() &&
5759            "Expecting that the types on LHS and RHS of comparisons match.");
5760     N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
5761   }
5762 
5763   // (mul N, P)
5764   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
5765   Created.push_back(Op0.getNode());
5766 
5767   // Rotate right only if any divisor was even. We avoid rotates for all-odd
5768   // divisors as a performance improvement, since rotating by 0 is a no-op.
5769   if (HadEvenDivisor) {
5770     // We need ROTR to do this.
5771     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
5772       return SDValue();
5773     // UREM: (rotr (mul N, P), K)
5774     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
5775     Created.push_back(Op0.getNode());
5776   }
5777 
5778   // UREM: (setule/setugt (rotr (mul N, P), K), Q)
5779   SDValue NewCC =
5780       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
5781                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
5782   if (!HadTautologicalInvertedLanes)
5783     return NewCC;
5784 
5785   // If any lanes previously compared always-false, the NewCC will give
5786   // always-true result for them, so we need to fixup those lanes.
5787   // Or the other way around for inequality predicate.
5788   assert(VT.isVector() && "Can/should only get here for vectors.");
5789   Created.push_back(NewCC.getNode());
5790 
5791   // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
5792   // if C2 is not less than C1, the comparison is always false.
5793   // But we have produced the comparison that will give the
5794   // opposive tautological answer. So these lanes would need to be fixed up.
5795   SDValue TautologicalInvertedChannels =
5796       DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
5797   Created.push_back(TautologicalInvertedChannels.getNode());
5798 
5799   // NOTE: we avoid letting illegal types through even if we're before legalize
5800   // ops – legalization has a hard time producing good code for this.
5801   if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
5802     // If we have a vector select, let's replace the comparison results in the
5803     // affected lanes with the correct tautological result.
5804     SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
5805                                               DL, SETCCVT, SETCCVT);
5806     return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
5807                        Replacement, NewCC);
5808   }
5809 
5810   // Else, we can just invert the comparison result in the appropriate lanes.
5811   //
5812   // NOTE: see the note above VSELECT above.
5813   if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
5814     return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
5815                        TautologicalInvertedChannels);
5816 
5817   return SDValue(); // Don't know how to lower.
5818 }
5819 
5820 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
5821 /// where the divisor is constant and the comparison target is zero,
5822 /// return a DAG expression that will generate the same comparison result
5823 /// using only multiplications, additions and shifts/rotations.
5824 /// Ref: "Hacker's Delight" 10-17.
5825 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
5826                                         SDValue CompTargetNode,
5827                                         ISD::CondCode Cond,
5828                                         DAGCombinerInfo &DCI,
5829                                         const SDLoc &DL) const {
5830   SmallVector<SDNode *, 7> Built;
5831   if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
5832                                          DCI, DL, Built)) {
5833     assert(Built.size() <= 7 && "Max size prediction failed.");
5834     for (SDNode *N : Built)
5835       DCI.AddToWorklist(N);
5836     return Folded;
5837   }
5838 
5839   return SDValue();
5840 }
5841 
5842 SDValue
5843 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
5844                                   SDValue CompTargetNode, ISD::CondCode Cond,
5845                                   DAGCombinerInfo &DCI, const SDLoc &DL,
5846                                   SmallVectorImpl<SDNode *> &Created) const {
5847   // Fold:
5848   //   (seteq/ne (srem N, D), 0)
5849   // To:
5850   //   (setule/ugt (rotr (add (mul N, P), A), K), Q)
5851   //
5852   // - D must be constant, with D = D0 * 2^K where D0 is odd
5853   // - P is the multiplicative inverse of D0 modulo 2^W
5854   // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
5855   // - Q = floor((2 * A) / (2^K))
5856   // where W is the width of the common type of N and D.
5857   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5858          "Only applicable for (in)equality comparisons.");
5859 
5860   SelectionDAG &DAG = DCI.DAG;
5861 
5862   EVT VT = REMNode.getValueType();
5863   EVT SVT = VT.getScalarType();
5864   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize());
5865   EVT ShSVT = ShVT.getScalarType();
5866 
5867   // If we are after ops legalization, and MUL is unavailable, we can not
5868   // proceed.
5869   if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
5870     return SDValue();
5871 
5872   // TODO: Could support comparing with non-zero too.
5873   ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
5874   if (!CompTarget || !CompTarget->isZero())
5875     return SDValue();
5876 
5877   bool HadIntMinDivisor = false;
5878   bool HadOneDivisor = false;
5879   bool AllDivisorsAreOnes = true;
5880   bool HadEvenDivisor = false;
5881   bool NeedToApplyOffset = false;
5882   bool AllDivisorsArePowerOfTwo = true;
5883   SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
5884 
5885   auto BuildSREMPattern = [&](ConstantSDNode *C) {
5886     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
5887     if (C->isZero())
5888       return false;
5889 
5890     // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
5891 
5892     // WARNING: this fold is only valid for positive divisors!
5893     APInt D = C->getAPIntValue();
5894     if (D.isNegative())
5895       D.negate(); //  `rem %X, -C` is equivalent to `rem %X, C`
5896 
5897     HadIntMinDivisor |= D.isMinSignedValue();
5898 
5899     // If all divisors are ones, we will prefer to avoid the fold.
5900     HadOneDivisor |= D.isOne();
5901     AllDivisorsAreOnes &= D.isOne();
5902 
5903     // Decompose D into D0 * 2^K
5904     unsigned K = D.countTrailingZeros();
5905     assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
5906     APInt D0 = D.lshr(K);
5907 
5908     if (!D.isMinSignedValue()) {
5909       // D is even if it has trailing zeros; unless it's INT_MIN, in which case
5910       // we don't care about this lane in this fold, we'll special-handle it.
5911       HadEvenDivisor |= (K != 0);
5912     }
5913 
5914     // D is a power-of-two if D0 is one. This includes INT_MIN.
5915     // If all divisors are power-of-two, we will prefer to avoid the fold.
5916     AllDivisorsArePowerOfTwo &= D0.isOne();
5917 
5918     // P = inv(D0, 2^W)
5919     // 2^W requires W + 1 bits, so we have to extend and then truncate.
5920     unsigned W = D.getBitWidth();
5921     APInt P = D0.zext(W + 1)
5922                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
5923                   .trunc(W);
5924     assert(!P.isZero() && "No multiplicative inverse!"); // unreachable
5925     assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
5926 
5927     // A = floor((2^(W - 1) - 1) / D0) & -2^K
5928     APInt A = APInt::getSignedMaxValue(W).udiv(D0);
5929     A.clearLowBits(K);
5930 
5931     if (!D.isMinSignedValue()) {
5932       // If divisor INT_MIN, then we don't care about this lane in this fold,
5933       // we'll special-handle it.
5934       NeedToApplyOffset |= A != 0;
5935     }
5936 
5937     // Q = floor((2 * A) / (2^K))
5938     APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
5939 
5940     assert(APInt::getAllOnes(SVT.getSizeInBits()).ugt(A) &&
5941            "We are expecting that A is always less than all-ones for SVT");
5942     assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) &&
5943            "We are expecting that K is always less than all-ones for ShSVT");
5944 
5945     // If the divisor is 1 the result can be constant-folded. Likewise, we
5946     // don't care about INT_MIN lanes, those can be set to undef if appropriate.
5947     if (D.isOne()) {
5948       // Set P, A and K to a bogus values so we can try to splat them.
5949       P = 0;
5950       A = -1;
5951       K = -1;
5952 
5953       // x ?% 1 == 0  <-->  true  <-->  x u<= -1
5954       Q = -1;
5955     }
5956 
5957     PAmts.push_back(DAG.getConstant(P, DL, SVT));
5958     AAmts.push_back(DAG.getConstant(A, DL, SVT));
5959     KAmts.push_back(
5960         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
5961     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
5962     return true;
5963   };
5964 
5965   SDValue N = REMNode.getOperand(0);
5966   SDValue D = REMNode.getOperand(1);
5967 
5968   // Collect the values from each element.
5969   if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
5970     return SDValue();
5971 
5972   // If this is a srem by a one, avoid the fold since it can be constant-folded.
5973   if (AllDivisorsAreOnes)
5974     return SDValue();
5975 
5976   // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
5977   // since it can be best implemented as a bit test.
5978   if (AllDivisorsArePowerOfTwo)
5979     return SDValue();
5980 
5981   SDValue PVal, AVal, KVal, QVal;
5982   if (D.getOpcode() == ISD::BUILD_VECTOR) {
5983     if (HadOneDivisor) {
5984       // Try to turn PAmts into a splat, since we don't care about the values
5985       // that are currently '0'. If we can't, just keep '0'`s.
5986       turnVectorIntoSplatVector(PAmts, isNullConstant);
5987       // Try to turn AAmts into a splat, since we don't care about the
5988       // values that are currently '-1'. If we can't, change them to '0'`s.
5989       turnVectorIntoSplatVector(AAmts, isAllOnesConstant,
5990                                 DAG.getConstant(0, DL, SVT));
5991       // Try to turn KAmts into a splat, since we don't care about the values
5992       // that are currently '-1'. If we can't, change them to '0'`s.
5993       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
5994                                 DAG.getConstant(0, DL, ShSVT));
5995     }
5996 
5997     PVal = DAG.getBuildVector(VT, DL, PAmts);
5998     AVal = DAG.getBuildVector(VT, DL, AAmts);
5999     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
6000     QVal = DAG.getBuildVector(VT, DL, QAmts);
6001   } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
6002     assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
6003            QAmts.size() == 1 &&
6004            "Expected matchUnaryPredicate to return one element for scalable "
6005            "vectors");
6006     PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
6007     AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
6008     KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
6009     QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
6010   } else {
6011     assert(isa<ConstantSDNode>(D) && "Expected a constant");
6012     PVal = PAmts[0];
6013     AVal = AAmts[0];
6014     KVal = KAmts[0];
6015     QVal = QAmts[0];
6016   }
6017 
6018   // (mul N, P)
6019   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
6020   Created.push_back(Op0.getNode());
6021 
6022   if (NeedToApplyOffset) {
6023     // We need ADD to do this.
6024     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
6025       return SDValue();
6026 
6027     // (add (mul N, P), A)
6028     Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
6029     Created.push_back(Op0.getNode());
6030   }
6031 
6032   // Rotate right only if any divisor was even. We avoid rotates for all-odd
6033   // divisors as a performance improvement, since rotating by 0 is a no-op.
6034   if (HadEvenDivisor) {
6035     // We need ROTR to do this.
6036     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
6037       return SDValue();
6038     // SREM: (rotr (add (mul N, P), A), K)
6039     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
6040     Created.push_back(Op0.getNode());
6041   }
6042 
6043   // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
6044   SDValue Fold =
6045       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
6046                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
6047 
6048   // If we didn't have lanes with INT_MIN divisor, then we're done.
6049   if (!HadIntMinDivisor)
6050     return Fold;
6051 
6052   // That fold is only valid for positive divisors. Which effectively means,
6053   // it is invalid for INT_MIN divisors. So if we have such a lane,
6054   // we must fix-up results for said lanes.
6055   assert(VT.isVector() && "Can/should only get here for vectors.");
6056 
6057   // NOTE: we avoid letting illegal types through even if we're before legalize
6058   // ops – legalization has a hard time producing good code for the code that
6059   // follows.
6060   if (!isOperationLegalOrCustom(ISD::SETEQ, VT) ||
6061       !isOperationLegalOrCustom(ISD::AND, VT) ||
6062       !isOperationLegalOrCustom(Cond, VT) ||
6063       !isOperationLegalOrCustom(ISD::VSELECT, SETCCVT))
6064     return SDValue();
6065 
6066   Created.push_back(Fold.getNode());
6067 
6068   SDValue IntMin = DAG.getConstant(
6069       APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT);
6070   SDValue IntMax = DAG.getConstant(
6071       APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT);
6072   SDValue Zero =
6073       DAG.getConstant(APInt::getZero(SVT.getScalarSizeInBits()), DL, VT);
6074 
6075   // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded.
6076   SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ);
6077   Created.push_back(DivisorIsIntMin.getNode());
6078 
6079   // (N s% INT_MIN) ==/!= 0  <-->  (N & INT_MAX) ==/!= 0
6080   SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax);
6081   Created.push_back(Masked.getNode());
6082   SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond);
6083   Created.push_back(MaskedIsZero.getNode());
6084 
6085   // To produce final result we need to blend 2 vectors: 'SetCC' and
6086   // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick
6087   // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is
6088   // constant-folded, select can get lowered to a shuffle with constant mask.
6089   SDValue Blended = DAG.getNode(ISD::VSELECT, DL, SETCCVT, DivisorIsIntMin,
6090                                 MaskedIsZero, Fold);
6091 
6092   return Blended;
6093 }
6094 
6095 bool TargetLowering::
6096 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
6097   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
6098     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
6099                                 "be a constant integer");
6100     return true;
6101   }
6102 
6103   return false;
6104 }
6105 
6106 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
6107                                          const DenormalMode &Mode) const {
6108   SDLoc DL(Op);
6109   EVT VT = Op.getValueType();
6110   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6111   SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
6112   // Testing it with denormal inputs to avoid wrong estimate.
6113   if (Mode.Input == DenormalMode::IEEE) {
6114     // This is specifically a check for the handling of denormal inputs,
6115     // not the result.
6116 
6117     // Test = fabs(X) < SmallestNormal
6118     const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
6119     APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
6120     SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
6121     SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op);
6122     return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT);
6123   }
6124   // Test = X == 0.0
6125   return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
6126 }
6127 
6128 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
6129                                              bool LegalOps, bool OptForSize,
6130                                              NegatibleCost &Cost,
6131                                              unsigned Depth) const {
6132   // fneg is removable even if it has multiple uses.
6133   if (Op.getOpcode() == ISD::FNEG) {
6134     Cost = NegatibleCost::Cheaper;
6135     return Op.getOperand(0);
6136   }
6137 
6138   // Don't recurse exponentially.
6139   if (Depth > SelectionDAG::MaxRecursionDepth)
6140     return SDValue();
6141 
6142   // Pre-increment recursion depth for use in recursive calls.
6143   ++Depth;
6144   const SDNodeFlags Flags = Op->getFlags();
6145   const TargetOptions &Options = DAG.getTarget().Options;
6146   EVT VT = Op.getValueType();
6147   unsigned Opcode = Op.getOpcode();
6148 
6149   // Don't allow anything with multiple uses unless we know it is free.
6150   if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
6151     bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
6152                         isFPExtFree(VT, Op.getOperand(0).getValueType());
6153     if (!IsFreeExtend)
6154       return SDValue();
6155   }
6156 
6157   auto RemoveDeadNode = [&](SDValue N) {
6158     if (N && N.getNode()->use_empty())
6159       DAG.RemoveDeadNode(N.getNode());
6160   };
6161 
6162   SDLoc DL(Op);
6163 
6164   // Because getNegatedExpression can delete nodes we need a handle to keep
6165   // temporary nodes alive in case the recursion manages to create an identical
6166   // node.
6167   std::list<HandleSDNode> Handles;
6168 
6169   switch (Opcode) {
6170   case ISD::ConstantFP: {
6171     // Don't invert constant FP values after legalization unless the target says
6172     // the negated constant is legal.
6173     bool IsOpLegal =
6174         isOperationLegal(ISD::ConstantFP, VT) ||
6175         isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
6176                      OptForSize);
6177 
6178     if (LegalOps && !IsOpLegal)
6179       break;
6180 
6181     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
6182     V.changeSign();
6183     SDValue CFP = DAG.getConstantFP(V, DL, VT);
6184 
6185     // If we already have the use of the negated floating constant, it is free
6186     // to negate it even it has multiple uses.
6187     if (!Op.hasOneUse() && CFP.use_empty())
6188       break;
6189     Cost = NegatibleCost::Neutral;
6190     return CFP;
6191   }
6192   case ISD::BUILD_VECTOR: {
6193     // Only permit BUILD_VECTOR of constants.
6194     if (llvm::any_of(Op->op_values(), [&](SDValue N) {
6195           return !N.isUndef() && !isa<ConstantFPSDNode>(N);
6196         }))
6197       break;
6198 
6199     bool IsOpLegal =
6200         (isOperationLegal(ISD::ConstantFP, VT) &&
6201          isOperationLegal(ISD::BUILD_VECTOR, VT)) ||
6202         llvm::all_of(Op->op_values(), [&](SDValue N) {
6203           return N.isUndef() ||
6204                  isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
6205                               OptForSize);
6206         });
6207 
6208     if (LegalOps && !IsOpLegal)
6209       break;
6210 
6211     SmallVector<SDValue, 4> Ops;
6212     for (SDValue C : Op->op_values()) {
6213       if (C.isUndef()) {
6214         Ops.push_back(C);
6215         continue;
6216       }
6217       APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
6218       V.changeSign();
6219       Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
6220     }
6221     Cost = NegatibleCost::Neutral;
6222     return DAG.getBuildVector(VT, DL, Ops);
6223   }
6224   case ISD::FADD: {
6225     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6226       break;
6227 
6228     // After operation legalization, it might not be legal to create new FSUBs.
6229     if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
6230       break;
6231     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6232 
6233     // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
6234     NegatibleCost CostX = NegatibleCost::Expensive;
6235     SDValue NegX =
6236         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6237     // Prevent this node from being deleted by the next call.
6238     if (NegX)
6239       Handles.emplace_back(NegX);
6240 
6241     // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
6242     NegatibleCost CostY = NegatibleCost::Expensive;
6243     SDValue NegY =
6244         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6245 
6246     // We're done with the handles.
6247     Handles.clear();
6248 
6249     // Negate the X if its cost is less or equal than Y.
6250     if (NegX && (CostX <= CostY)) {
6251       Cost = CostX;
6252       SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
6253       if (NegY != N)
6254         RemoveDeadNode(NegY);
6255       return N;
6256     }
6257 
6258     // Negate the Y if it is not expensive.
6259     if (NegY) {
6260       Cost = CostY;
6261       SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
6262       if (NegX != N)
6263         RemoveDeadNode(NegX);
6264       return N;
6265     }
6266     break;
6267   }
6268   case ISD::FSUB: {
6269     // We can't turn -(A-B) into B-A when we honor signed zeros.
6270     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6271       break;
6272 
6273     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6274     // fold (fneg (fsub 0, Y)) -> Y
6275     if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
6276       if (C->isZero()) {
6277         Cost = NegatibleCost::Cheaper;
6278         return Y;
6279       }
6280 
6281     // fold (fneg (fsub X, Y)) -> (fsub Y, X)
6282     Cost = NegatibleCost::Neutral;
6283     return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
6284   }
6285   case ISD::FMUL:
6286   case ISD::FDIV: {
6287     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6288 
6289     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
6290     NegatibleCost CostX = NegatibleCost::Expensive;
6291     SDValue NegX =
6292         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6293     // Prevent this node from being deleted by the next call.
6294     if (NegX)
6295       Handles.emplace_back(NegX);
6296 
6297     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
6298     NegatibleCost CostY = NegatibleCost::Expensive;
6299     SDValue NegY =
6300         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6301 
6302     // We're done with the handles.
6303     Handles.clear();
6304 
6305     // Negate the X if its cost is less or equal than Y.
6306     if (NegX && (CostX <= CostY)) {
6307       Cost = CostX;
6308       SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
6309       if (NegY != N)
6310         RemoveDeadNode(NegY);
6311       return N;
6312     }
6313 
6314     // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
6315     if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
6316       if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
6317         break;
6318 
6319     // Negate the Y if it is not expensive.
6320     if (NegY) {
6321       Cost = CostY;
6322       SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
6323       if (NegX != N)
6324         RemoveDeadNode(NegX);
6325       return N;
6326     }
6327     break;
6328   }
6329   case ISD::FMA:
6330   case ISD::FMAD: {
6331     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6332       break;
6333 
6334     SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
6335     NegatibleCost CostZ = NegatibleCost::Expensive;
6336     SDValue NegZ =
6337         getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
6338     // Give up if fail to negate the Z.
6339     if (!NegZ)
6340       break;
6341 
6342     // Prevent this node from being deleted by the next two calls.
6343     Handles.emplace_back(NegZ);
6344 
6345     // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
6346     NegatibleCost CostX = NegatibleCost::Expensive;
6347     SDValue NegX =
6348         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6349     // Prevent this node from being deleted by the next call.
6350     if (NegX)
6351       Handles.emplace_back(NegX);
6352 
6353     // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
6354     NegatibleCost CostY = NegatibleCost::Expensive;
6355     SDValue NegY =
6356         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6357 
6358     // We're done with the handles.
6359     Handles.clear();
6360 
6361     // Negate the X if its cost is less or equal than Y.
6362     if (NegX && (CostX <= CostY)) {
6363       Cost = std::min(CostX, CostZ);
6364       SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
6365       if (NegY != N)
6366         RemoveDeadNode(NegY);
6367       return N;
6368     }
6369 
6370     // Negate the Y if it is not expensive.
6371     if (NegY) {
6372       Cost = std::min(CostY, CostZ);
6373       SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
6374       if (NegX != N)
6375         RemoveDeadNode(NegX);
6376       return N;
6377     }
6378     break;
6379   }
6380 
6381   case ISD::FP_EXTEND:
6382   case ISD::FSIN:
6383     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
6384                                             OptForSize, Cost, Depth))
6385       return DAG.getNode(Opcode, DL, VT, NegV);
6386     break;
6387   case ISD::FP_ROUND:
6388     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
6389                                             OptForSize, Cost, Depth))
6390       return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
6391     break;
6392   }
6393 
6394   return SDValue();
6395 }
6396 
6397 //===----------------------------------------------------------------------===//
6398 // Legalization Utilities
6399 //===----------------------------------------------------------------------===//
6400 
6401 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
6402                                     SDValue LHS, SDValue RHS,
6403                                     SmallVectorImpl<SDValue> &Result,
6404                                     EVT HiLoVT, SelectionDAG &DAG,
6405                                     MulExpansionKind Kind, SDValue LL,
6406                                     SDValue LH, SDValue RL, SDValue RH) const {
6407   assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
6408          Opcode == ISD::SMUL_LOHI);
6409 
6410   bool HasMULHS = (Kind == MulExpansionKind::Always) ||
6411                   isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
6412   bool HasMULHU = (Kind == MulExpansionKind::Always) ||
6413                   isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
6414   bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
6415                       isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
6416   bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
6417                       isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
6418 
6419   if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
6420     return false;
6421 
6422   unsigned OuterBitSize = VT.getScalarSizeInBits();
6423   unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
6424 
6425   // LL, LH, RL, and RH must be either all NULL or all set to a value.
6426   assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
6427          (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
6428 
6429   SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
6430   auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
6431                           bool Signed) -> bool {
6432     if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
6433       Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
6434       Hi = SDValue(Lo.getNode(), 1);
6435       return true;
6436     }
6437     if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
6438       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
6439       Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
6440       return true;
6441     }
6442     return false;
6443   };
6444 
6445   SDValue Lo, Hi;
6446 
6447   if (!LL.getNode() && !RL.getNode() &&
6448       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
6449     LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
6450     RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
6451   }
6452 
6453   if (!LL.getNode())
6454     return false;
6455 
6456   APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
6457   if (DAG.MaskedValueIsZero(LHS, HighMask) &&
6458       DAG.MaskedValueIsZero(RHS, HighMask)) {
6459     // The inputs are both zero-extended.
6460     if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
6461       Result.push_back(Lo);
6462       Result.push_back(Hi);
6463       if (Opcode != ISD::MUL) {
6464         SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
6465         Result.push_back(Zero);
6466         Result.push_back(Zero);
6467       }
6468       return true;
6469     }
6470   }
6471 
6472   if (!VT.isVector() && Opcode == ISD::MUL &&
6473       DAG.ComputeNumSignBits(LHS) > InnerBitSize &&
6474       DAG.ComputeNumSignBits(RHS) > InnerBitSize) {
6475     // The input values are both sign-extended.
6476     // TODO non-MUL case?
6477     if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
6478       Result.push_back(Lo);
6479       Result.push_back(Hi);
6480       return true;
6481     }
6482   }
6483 
6484   unsigned ShiftAmount = OuterBitSize - InnerBitSize;
6485   EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout());
6486   SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy);
6487 
6488   if (!LH.getNode() && !RH.getNode() &&
6489       isOperationLegalOrCustom(ISD::SRL, VT) &&
6490       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
6491     LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
6492     LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
6493     RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
6494     RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
6495   }
6496 
6497   if (!LH.getNode())
6498     return false;
6499 
6500   if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
6501     return false;
6502 
6503   Result.push_back(Lo);
6504 
6505   if (Opcode == ISD::MUL) {
6506     RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
6507     LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
6508     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
6509     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
6510     Result.push_back(Hi);
6511     return true;
6512   }
6513 
6514   // Compute the full width result.
6515   auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
6516     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
6517     Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
6518     Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
6519     return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
6520   };
6521 
6522   SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
6523   if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
6524     return false;
6525 
6526   // This is effectively the add part of a multiply-add of half-sized operands,
6527   // so it cannot overflow.
6528   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
6529 
6530   if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
6531     return false;
6532 
6533   SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
6534   EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6535 
6536   bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
6537                   isOperationLegalOrCustom(ISD::ADDE, VT));
6538   if (UseGlue)
6539     Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
6540                        Merge(Lo, Hi));
6541   else
6542     Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next,
6543                        Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
6544 
6545   SDValue Carry = Next.getValue(1);
6546   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6547   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
6548 
6549   if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
6550     return false;
6551 
6552   if (UseGlue)
6553     Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
6554                      Carry);
6555   else
6556     Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
6557                      Zero, Carry);
6558 
6559   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
6560 
6561   if (Opcode == ISD::SMUL_LOHI) {
6562     SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
6563                                   DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
6564     Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
6565 
6566     NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
6567                           DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
6568     Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
6569   }
6570 
6571   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6572   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
6573   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6574   return true;
6575 }
6576 
6577 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
6578                                SelectionDAG &DAG, MulExpansionKind Kind,
6579                                SDValue LL, SDValue LH, SDValue RL,
6580                                SDValue RH) const {
6581   SmallVector<SDValue, 2> Result;
6582   bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
6583                            N->getOperand(0), N->getOperand(1), Result, HiLoVT,
6584                            DAG, Kind, LL, LH, RL, RH);
6585   if (Ok) {
6586     assert(Result.size() == 2);
6587     Lo = Result[0];
6588     Hi = Result[1];
6589   }
6590   return Ok;
6591 }
6592 
6593 // Check that (every element of) Z is undef or not an exact multiple of BW.
6594 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
6595   return ISD::matchUnaryPredicate(
6596       Z,
6597       [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
6598       true);
6599 }
6600 
6601 SDValue TargetLowering::expandFunnelShift(SDNode *Node,
6602                                           SelectionDAG &DAG) const {
6603   EVT VT = Node->getValueType(0);
6604 
6605   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
6606                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
6607                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
6608                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
6609     return SDValue();
6610 
6611   SDValue X = Node->getOperand(0);
6612   SDValue Y = Node->getOperand(1);
6613   SDValue Z = Node->getOperand(2);
6614 
6615   unsigned BW = VT.getScalarSizeInBits();
6616   bool IsFSHL = Node->getOpcode() == ISD::FSHL;
6617   SDLoc DL(SDValue(Node, 0));
6618 
6619   EVT ShVT = Z.getValueType();
6620 
6621   // If a funnel shift in the other direction is more supported, use it.
6622   unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
6623   if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
6624       isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
6625     if (isNonZeroModBitWidthOrUndef(Z, BW)) {
6626       // fshl X, Y, Z -> fshr X, Y, -Z
6627       // fshr X, Y, Z -> fshl X, Y, -Z
6628       SDValue Zero = DAG.getConstant(0, DL, ShVT);
6629       Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z);
6630     } else {
6631       // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
6632       // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
6633       SDValue One = DAG.getConstant(1, DL, ShVT);
6634       if (IsFSHL) {
6635         Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
6636         X = DAG.getNode(ISD::SRL, DL, VT, X, One);
6637       } else {
6638         X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
6639         Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
6640       }
6641       Z = DAG.getNOT(DL, Z, ShVT);
6642     }
6643     return DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
6644   }
6645 
6646   SDValue ShX, ShY;
6647   SDValue ShAmt, InvShAmt;
6648   if (isNonZeroModBitWidthOrUndef(Z, BW)) {
6649     // fshl: X << C | Y >> (BW - C)
6650     // fshr: X << (BW - C) | Y >> C
6651     // where C = Z % BW is not zero
6652     SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
6653     ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
6654     InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
6655     ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
6656     ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
6657   } else {
6658     // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
6659     // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
6660     SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
6661     if (isPowerOf2_32(BW)) {
6662       // Z % BW -> Z & (BW - 1)
6663       ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
6664       // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
6665       InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
6666     } else {
6667       SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
6668       ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
6669       InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
6670     }
6671 
6672     SDValue One = DAG.getConstant(1, DL, ShVT);
6673     if (IsFSHL) {
6674       ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
6675       SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
6676       ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
6677     } else {
6678       SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
6679       ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
6680       ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
6681     }
6682   }
6683   return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
6684 }
6685 
6686 // TODO: Merge with expandFunnelShift.
6687 SDValue TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps,
6688                                   SelectionDAG &DAG) const {
6689   EVT VT = Node->getValueType(0);
6690   unsigned EltSizeInBits = VT.getScalarSizeInBits();
6691   bool IsLeft = Node->getOpcode() == ISD::ROTL;
6692   SDValue Op0 = Node->getOperand(0);
6693   SDValue Op1 = Node->getOperand(1);
6694   SDLoc DL(SDValue(Node, 0));
6695 
6696   EVT ShVT = Op1.getValueType();
6697   SDValue Zero = DAG.getConstant(0, DL, ShVT);
6698 
6699   // If a rotate in the other direction is more supported, use it.
6700   unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
6701   if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
6702       isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
6703     SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
6704     return DAG.getNode(RevRot, DL, VT, Op0, Sub);
6705   }
6706 
6707   if (!AllowVectorOps && VT.isVector() &&
6708       (!isOperationLegalOrCustom(ISD::SHL, VT) ||
6709        !isOperationLegalOrCustom(ISD::SRL, VT) ||
6710        !isOperationLegalOrCustom(ISD::SUB, VT) ||
6711        !isOperationLegalOrCustomOrPromote(ISD::OR, VT) ||
6712        !isOperationLegalOrCustomOrPromote(ISD::AND, VT)))
6713     return SDValue();
6714 
6715   unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
6716   unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
6717   SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
6718   SDValue ShVal;
6719   SDValue HsVal;
6720   if (isPowerOf2_32(EltSizeInBits)) {
6721     // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
6722     // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
6723     SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
6724     SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
6725     ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
6726     SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
6727     HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
6728   } else {
6729     // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
6730     // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
6731     SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
6732     SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
6733     ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
6734     SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
6735     SDValue One = DAG.getConstant(1, DL, ShVT);
6736     HsVal =
6737         DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
6738   }
6739   return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
6740 }
6741 
6742 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi,
6743                                       SelectionDAG &DAG) const {
6744   assert(Node->getNumOperands() == 3 && "Not a double-shift!");
6745   EVT VT = Node->getValueType(0);
6746   unsigned VTBits = VT.getScalarSizeInBits();
6747   assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
6748 
6749   bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
6750   bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
6751   SDValue ShOpLo = Node->getOperand(0);
6752   SDValue ShOpHi = Node->getOperand(1);
6753   SDValue ShAmt = Node->getOperand(2);
6754   EVT ShAmtVT = ShAmt.getValueType();
6755   EVT ShAmtCCVT =
6756       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
6757   SDLoc dl(Node);
6758 
6759   // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
6760   // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
6761   // away during isel.
6762   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
6763                                   DAG.getConstant(VTBits - 1, dl, ShAmtVT));
6764   SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
6765                                      DAG.getConstant(VTBits - 1, dl, ShAmtVT))
6766                        : DAG.getConstant(0, dl, VT);
6767 
6768   SDValue Tmp2, Tmp3;
6769   if (IsSHL) {
6770     Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
6771     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
6772   } else {
6773     Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
6774     Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
6775   }
6776 
6777   // If the shift amount is larger or equal than the width of a part we don't
6778   // use the result from the FSHL/FSHR. Insert a test and select the appropriate
6779   // values for large shift amounts.
6780   SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
6781                                 DAG.getConstant(VTBits, dl, ShAmtVT));
6782   SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
6783                               DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
6784 
6785   if (IsSHL) {
6786     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
6787     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
6788   } else {
6789     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
6790     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
6791   }
6792 }
6793 
6794 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
6795                                       SelectionDAG &DAG) const {
6796   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
6797   SDValue Src = Node->getOperand(OpNo);
6798   EVT SrcVT = Src.getValueType();
6799   EVT DstVT = Node->getValueType(0);
6800   SDLoc dl(SDValue(Node, 0));
6801 
6802   // FIXME: Only f32 to i64 conversions are supported.
6803   if (SrcVT != MVT::f32 || DstVT != MVT::i64)
6804     return false;
6805 
6806   if (Node->isStrictFPOpcode())
6807     // When a NaN is converted to an integer a trap is allowed. We can't
6808     // use this expansion here because it would eliminate that trap. Other
6809     // traps are also allowed and cannot be eliminated. See
6810     // IEEE 754-2008 sec 5.8.
6811     return false;
6812 
6813   // Expand f32 -> i64 conversion
6814   // This algorithm comes from compiler-rt's implementation of fixsfdi:
6815   // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
6816   unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
6817   EVT IntVT = SrcVT.changeTypeToInteger();
6818   EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
6819 
6820   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
6821   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
6822   SDValue Bias = DAG.getConstant(127, dl, IntVT);
6823   SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
6824   SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
6825   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
6826 
6827   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
6828 
6829   SDValue ExponentBits = DAG.getNode(
6830       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
6831       DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
6832   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
6833 
6834   SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
6835                              DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
6836                              DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
6837   Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
6838 
6839   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
6840                           DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
6841                           DAG.getConstant(0x00800000, dl, IntVT));
6842 
6843   R = DAG.getZExtOrTrunc(R, dl, DstVT);
6844 
6845   R = DAG.getSelectCC(
6846       dl, Exponent, ExponentLoBit,
6847       DAG.getNode(ISD::SHL, dl, DstVT, R,
6848                   DAG.getZExtOrTrunc(
6849                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
6850                       dl, IntShVT)),
6851       DAG.getNode(ISD::SRL, dl, DstVT, R,
6852                   DAG.getZExtOrTrunc(
6853                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
6854                       dl, IntShVT)),
6855       ISD::SETGT);
6856 
6857   SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
6858                             DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
6859 
6860   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
6861                            DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
6862   return true;
6863 }
6864 
6865 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result,
6866                                       SDValue &Chain,
6867                                       SelectionDAG &DAG) const {
6868   SDLoc dl(SDValue(Node, 0));
6869   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
6870   SDValue Src = Node->getOperand(OpNo);
6871 
6872   EVT SrcVT = Src.getValueType();
6873   EVT DstVT = Node->getValueType(0);
6874   EVT SetCCVT =
6875       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
6876   EVT DstSetCCVT =
6877       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
6878 
6879   // Only expand vector types if we have the appropriate vector bit operations.
6880   unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
6881                                                    ISD::FP_TO_SINT;
6882   if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
6883                            !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT)))
6884     return false;
6885 
6886   // If the maximum float value is smaller then the signed integer range,
6887   // the destination signmask can't be represented by the float, so we can
6888   // just use FP_TO_SINT directly.
6889   const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT);
6890   APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
6891   APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
6892   if (APFloat::opOverflow &
6893       APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
6894     if (Node->isStrictFPOpcode()) {
6895       Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
6896                            { Node->getOperand(0), Src });
6897       Chain = Result.getValue(1);
6898     } else
6899       Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
6900     return true;
6901   }
6902 
6903   // Don't expand it if there isn't cheap fsub instruction.
6904   if (!isOperationLegalOrCustom(
6905           Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
6906     return false;
6907 
6908   SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
6909   SDValue Sel;
6910 
6911   if (Node->isStrictFPOpcode()) {
6912     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
6913                        Node->getOperand(0), /*IsSignaling*/ true);
6914     Chain = Sel.getValue(1);
6915   } else {
6916     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
6917   }
6918 
6919   bool Strict = Node->isStrictFPOpcode() ||
6920                 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
6921 
6922   if (Strict) {
6923     // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
6924     // signmask then offset (the result of which should be fully representable).
6925     // Sel = Src < 0x8000000000000000
6926     // FltOfs = select Sel, 0, 0x8000000000000000
6927     // IntOfs = select Sel, 0, 0x8000000000000000
6928     // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
6929 
6930     // TODO: Should any fast-math-flags be set for the FSUB?
6931     SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
6932                                    DAG.getConstantFP(0.0, dl, SrcVT), Cst);
6933     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
6934     SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
6935                                    DAG.getConstant(0, dl, DstVT),
6936                                    DAG.getConstant(SignMask, dl, DstVT));
6937     SDValue SInt;
6938     if (Node->isStrictFPOpcode()) {
6939       SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
6940                                 { Chain, Src, FltOfs });
6941       SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
6942                          { Val.getValue(1), Val });
6943       Chain = SInt.getValue(1);
6944     } else {
6945       SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
6946       SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
6947     }
6948     Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
6949   } else {
6950     // Expand based on maximum range of FP_TO_SINT:
6951     // True = fp_to_sint(Src)
6952     // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
6953     // Result = select (Src < 0x8000000000000000), True, False
6954 
6955     SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
6956     // TODO: Should any fast-math-flags be set for the FSUB?
6957     SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
6958                                 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
6959     False = DAG.getNode(ISD::XOR, dl, DstVT, False,
6960                         DAG.getConstant(SignMask, dl, DstVT));
6961     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
6962     Result = DAG.getSelect(dl, DstVT, Sel, True, False);
6963   }
6964   return true;
6965 }
6966 
6967 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result,
6968                                       SDValue &Chain,
6969                                       SelectionDAG &DAG) const {
6970   // This transform is not correct for converting 0 when rounding mode is set
6971   // to round toward negative infinity which will produce -0.0. So disable under
6972   // strictfp.
6973   if (Node->isStrictFPOpcode())
6974     return false;
6975 
6976   SDValue Src = Node->getOperand(0);
6977   EVT SrcVT = Src.getValueType();
6978   EVT DstVT = Node->getValueType(0);
6979 
6980   if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
6981     return false;
6982 
6983   // Only expand vector types if we have the appropriate vector bit operations.
6984   if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
6985                            !isOperationLegalOrCustom(ISD::FADD, DstVT) ||
6986                            !isOperationLegalOrCustom(ISD::FSUB, DstVT) ||
6987                            !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) ||
6988                            !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT)))
6989     return false;
6990 
6991   SDLoc dl(SDValue(Node, 0));
6992   EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout());
6993 
6994   // Implementation of unsigned i64 to f64 following the algorithm in
6995   // __floatundidf in compiler_rt.  This implementation performs rounding
6996   // correctly in all rounding modes with the exception of converting 0
6997   // when rounding toward negative infinity. In that case the fsub will produce
6998   // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect.
6999   SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
7000   SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
7001       BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT);
7002   SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
7003   SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
7004   SDValue HiShift = DAG.getConstant(32, dl, ShiftVT);
7005 
7006   SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
7007   SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
7008   SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
7009   SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
7010   SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
7011   SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
7012   SDValue HiSub =
7013       DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
7014   Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
7015   return true;
7016 }
7017 
7018 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node,
7019                                               SelectionDAG &DAG) const {
7020   SDLoc dl(Node);
7021   unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ?
7022     ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
7023   EVT VT = Node->getValueType(0);
7024 
7025   if (VT.isScalableVector())
7026     report_fatal_error(
7027         "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
7028 
7029   if (isOperationLegalOrCustom(NewOp, VT)) {
7030     SDValue Quiet0 = Node->getOperand(0);
7031     SDValue Quiet1 = Node->getOperand(1);
7032 
7033     if (!Node->getFlags().hasNoNaNs()) {
7034       // Insert canonicalizes if it's possible we need to quiet to get correct
7035       // sNaN behavior.
7036       if (!DAG.isKnownNeverSNaN(Quiet0)) {
7037         Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
7038                              Node->getFlags());
7039       }
7040       if (!DAG.isKnownNeverSNaN(Quiet1)) {
7041         Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
7042                              Node->getFlags());
7043       }
7044     }
7045 
7046     return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
7047   }
7048 
7049   // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
7050   // instead if there are no NaNs.
7051   if (Node->getFlags().hasNoNaNs()) {
7052     unsigned IEEE2018Op =
7053         Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
7054     if (isOperationLegalOrCustom(IEEE2018Op, VT)) {
7055       return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
7056                          Node->getOperand(1), Node->getFlags());
7057     }
7058   }
7059 
7060   // If none of the above worked, but there are no NaNs, then expand to
7061   // a compare/select sequence.  This is required for correctness since
7062   // InstCombine might have canonicalized a fcmp+select sequence to a
7063   // FMINNUM/FMAXNUM node.  If we were to fall through to the default
7064   // expansion to libcall, we might introduce a link-time dependency
7065   // on libm into a file that originally did not have one.
7066   if (Node->getFlags().hasNoNaNs()) {
7067     ISD::CondCode Pred =
7068         Node->getOpcode() == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
7069     SDValue Op1 = Node->getOperand(0);
7070     SDValue Op2 = Node->getOperand(1);
7071     SDValue SelCC = DAG.getSelectCC(dl, Op1, Op2, Op1, Op2, Pred);
7072     // Copy FMF flags, but always set the no-signed-zeros flag
7073     // as this is implied by the FMINNUM/FMAXNUM semantics.
7074     SDNodeFlags Flags = Node->getFlags();
7075     Flags.setNoSignedZeros(true);
7076     SelCC->setFlags(Flags);
7077     return SelCC;
7078   }
7079 
7080   return SDValue();
7081 }
7082 
7083 // Only expand vector types if we have the appropriate vector bit operations.
7084 static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) {
7085   assert(VT.isVector() && "Expected vector type");
7086   unsigned Len = VT.getScalarSizeInBits();
7087   return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
7088          TLI.isOperationLegalOrCustom(ISD::SUB, VT) &&
7089          TLI.isOperationLegalOrCustom(ISD::SRL, VT) &&
7090          (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
7091          TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT);
7092 }
7093 
7094 SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &DAG) const {
7095   SDLoc dl(Node);
7096   EVT VT = Node->getValueType(0);
7097   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7098   SDValue Op = Node->getOperand(0);
7099   unsigned Len = VT.getScalarSizeInBits();
7100   assert(VT.isInteger() && "CTPOP not implemented for this type.");
7101 
7102   // TODO: Add support for irregular type lengths.
7103   if (!(Len <= 128 && Len % 8 == 0))
7104     return SDValue();
7105 
7106   // Only expand vector types if we have the appropriate vector bit operations.
7107   if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
7108     return SDValue();
7109 
7110   // This is the "best" algorithm from
7111   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
7112   SDValue Mask55 =
7113       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
7114   SDValue Mask33 =
7115       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
7116   SDValue Mask0F =
7117       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
7118   SDValue Mask01 =
7119       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
7120 
7121   // v = v - ((v >> 1) & 0x55555555...)
7122   Op = DAG.getNode(ISD::SUB, dl, VT, Op,
7123                    DAG.getNode(ISD::AND, dl, VT,
7124                                DAG.getNode(ISD::SRL, dl, VT, Op,
7125                                            DAG.getConstant(1, dl, ShVT)),
7126                                Mask55));
7127   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
7128   Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
7129                    DAG.getNode(ISD::AND, dl, VT,
7130                                DAG.getNode(ISD::SRL, dl, VT, Op,
7131                                            DAG.getConstant(2, dl, ShVT)),
7132                                Mask33));
7133   // v = (v + (v >> 4)) & 0x0F0F0F0F...
7134   Op = DAG.getNode(ISD::AND, dl, VT,
7135                    DAG.getNode(ISD::ADD, dl, VT, Op,
7136                                DAG.getNode(ISD::SRL, dl, VT, Op,
7137                                            DAG.getConstant(4, dl, ShVT))),
7138                    Mask0F);
7139   // v = (v * 0x01010101...) >> (Len - 8)
7140   if (Len > 8)
7141     Op =
7142         DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
7143                     DAG.getConstant(Len - 8, dl, ShVT));
7144 
7145   return Op;
7146 }
7147 
7148 SDValue TargetLowering::expandCTLZ(SDNode *Node, SelectionDAG &DAG) const {
7149   SDLoc dl(Node);
7150   EVT VT = Node->getValueType(0);
7151   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7152   SDValue Op = Node->getOperand(0);
7153   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
7154 
7155   // If the non-ZERO_UNDEF version is supported we can use that instead.
7156   if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF &&
7157       isOperationLegalOrCustom(ISD::CTLZ, VT))
7158     return DAG.getNode(ISD::CTLZ, dl, VT, Op);
7159 
7160   // If the ZERO_UNDEF version is supported use that and handle the zero case.
7161   if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) {
7162     EVT SetCCVT =
7163         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7164     SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op);
7165     SDValue Zero = DAG.getConstant(0, dl, VT);
7166     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
7167     return DAG.getSelect(dl, VT, SrcIsZero,
7168                          DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
7169   }
7170 
7171   // Only expand vector types if we have the appropriate vector bit operations.
7172   // This includes the operations needed to expand CTPOP if it isn't supported.
7173   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
7174                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
7175                          !canExpandVectorCTPOP(*this, VT)) ||
7176                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
7177                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
7178     return SDValue();
7179 
7180   // for now, we do this:
7181   // x = x | (x >> 1);
7182   // x = x | (x >> 2);
7183   // ...
7184   // x = x | (x >>16);
7185   // x = x | (x >>32); // for 64-bit input
7186   // return popcount(~x);
7187   //
7188   // Ref: "Hacker's Delight" by Henry Warren
7189   for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) {
7190     SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
7191     Op = DAG.getNode(ISD::OR, dl, VT, Op,
7192                      DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
7193   }
7194   Op = DAG.getNOT(dl, Op, VT);
7195   return DAG.getNode(ISD::CTPOP, dl, VT, Op);
7196 }
7197 
7198 SDValue TargetLowering::expandCTTZ(SDNode *Node, SelectionDAG &DAG) const {
7199   SDLoc dl(Node);
7200   EVT VT = Node->getValueType(0);
7201   SDValue Op = Node->getOperand(0);
7202   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
7203 
7204   // If the non-ZERO_UNDEF version is supported we can use that instead.
7205   if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
7206       isOperationLegalOrCustom(ISD::CTTZ, VT))
7207     return DAG.getNode(ISD::CTTZ, dl, VT, Op);
7208 
7209   // If the ZERO_UNDEF version is supported use that and handle the zero case.
7210   if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) {
7211     EVT SetCCVT =
7212         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7213     SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op);
7214     SDValue Zero = DAG.getConstant(0, dl, VT);
7215     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
7216     return DAG.getSelect(dl, VT, SrcIsZero,
7217                          DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
7218   }
7219 
7220   // Only expand vector types if we have the appropriate vector bit operations.
7221   // This includes the operations needed to expand CTPOP if it isn't supported.
7222   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
7223                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
7224                          !isOperationLegalOrCustom(ISD::CTLZ, VT) &&
7225                          !canExpandVectorCTPOP(*this, VT)) ||
7226                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
7227                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
7228                         !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
7229     return SDValue();
7230 
7231   // for now, we use: { return popcount(~x & (x - 1)); }
7232   // unless the target has ctlz but not ctpop, in which case we use:
7233   // { return 32 - nlz(~x & (x-1)); }
7234   // Ref: "Hacker's Delight" by Henry Warren
7235   SDValue Tmp = DAG.getNode(
7236       ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
7237       DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
7238 
7239   // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
7240   if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) {
7241     return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
7242                        DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
7243   }
7244 
7245   return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
7246 }
7247 
7248 SDValue TargetLowering::expandABS(SDNode *N, SelectionDAG &DAG,
7249                                   bool IsNegative) const {
7250   SDLoc dl(N);
7251   EVT VT = N->getValueType(0);
7252   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7253   SDValue Op = N->getOperand(0);
7254 
7255   // abs(x) -> smax(x,sub(0,x))
7256   if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
7257       isOperationLegal(ISD::SMAX, VT)) {
7258     SDValue Zero = DAG.getConstant(0, dl, VT);
7259     return DAG.getNode(ISD::SMAX, dl, VT, Op,
7260                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7261   }
7262 
7263   // abs(x) -> umin(x,sub(0,x))
7264   if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
7265       isOperationLegal(ISD::UMIN, VT)) {
7266     SDValue Zero = DAG.getConstant(0, dl, VT);
7267     return DAG.getNode(ISD::UMIN, dl, VT, Op,
7268                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7269   }
7270 
7271   // 0 - abs(x) -> smin(x, sub(0,x))
7272   if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
7273       isOperationLegal(ISD::SMIN, VT)) {
7274     SDValue Zero = DAG.getConstant(0, dl, VT);
7275     return DAG.getNode(ISD::SMIN, dl, VT, Op,
7276                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7277   }
7278 
7279   // Only expand vector types if we have the appropriate vector operations.
7280   if (VT.isVector() &&
7281       (!isOperationLegalOrCustom(ISD::SRA, VT) ||
7282        (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
7283        (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
7284        !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
7285     return SDValue();
7286 
7287   SDValue Shift =
7288       DAG.getNode(ISD::SRA, dl, VT, Op,
7289                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT));
7290   if (!IsNegative) {
7291     SDValue Add = DAG.getNode(ISD::ADD, dl, VT, Op, Shift);
7292     return DAG.getNode(ISD::XOR, dl, VT, Add, Shift);
7293   }
7294 
7295   // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
7296   SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
7297   return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
7298 }
7299 
7300 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const {
7301   SDLoc dl(N);
7302   EVT VT = N->getValueType(0);
7303   SDValue Op = N->getOperand(0);
7304 
7305   if (!VT.isSimple())
7306     return SDValue();
7307 
7308   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
7309   SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
7310   switch (VT.getSimpleVT().getScalarType().SimpleTy) {
7311   default:
7312     return SDValue();
7313   case MVT::i16:
7314     // Use a rotate by 8. This can be further expanded if necessary.
7315     return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7316   case MVT::i32:
7317     Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7318     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7319     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7320     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7321     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
7322                        DAG.getConstant(0xFF0000, dl, VT));
7323     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
7324     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
7325     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
7326     return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
7327   case MVT::i64:
7328     Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
7329     Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
7330     Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7331     Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7332     Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7333     Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7334     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
7335     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
7336     Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7,
7337                        DAG.getConstant(255ULL<<48, dl, VT));
7338     Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6,
7339                        DAG.getConstant(255ULL<<40, dl, VT));
7340     Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5,
7341                        DAG.getConstant(255ULL<<32, dl, VT));
7342     Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
7343                        DAG.getConstant(255ULL<<24, dl, VT));
7344     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
7345                        DAG.getConstant(255ULL<<16, dl, VT));
7346     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
7347                        DAG.getConstant(255ULL<<8 , dl, VT));
7348     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
7349     Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
7350     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
7351     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
7352     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
7353     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
7354     return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
7355   }
7356 }
7357 
7358 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const {
7359   SDLoc dl(N);
7360   EVT VT = N->getValueType(0);
7361   SDValue Op = N->getOperand(0);
7362   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
7363   unsigned Sz = VT.getScalarSizeInBits();
7364 
7365   SDValue Tmp, Tmp2, Tmp3;
7366 
7367   // If we can, perform BSWAP first and then the mask+swap the i4, then i2
7368   // and finally the i1 pairs.
7369   // TODO: We can easily support i4/i2 legal types if any target ever does.
7370   if (Sz >= 8 && isPowerOf2_32(Sz)) {
7371     // Create the masks - repeating the pattern every byte.
7372     APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
7373     APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
7374     APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
7375 
7376     // BSWAP if the type is wider than a single byte.
7377     Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
7378 
7379     // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
7380     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
7381     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
7382     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
7383     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
7384     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7385 
7386     // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
7387     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
7388     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
7389     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
7390     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
7391     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7392 
7393     // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
7394     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
7395     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
7396     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
7397     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
7398     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
7399     return Tmp;
7400   }
7401 
7402   Tmp = DAG.getConstant(0, dl, VT);
7403   for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
7404     if (I < J)
7405       Tmp2 =
7406           DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
7407     else
7408       Tmp2 =
7409           DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
7410 
7411     APInt Shift(Sz, 1);
7412     Shift <<= J;
7413     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
7414     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
7415   }
7416 
7417   return Tmp;
7418 }
7419 
7420 std::pair<SDValue, SDValue>
7421 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
7422                                     SelectionDAG &DAG) const {
7423   SDLoc SL(LD);
7424   SDValue Chain = LD->getChain();
7425   SDValue BasePTR = LD->getBasePtr();
7426   EVT SrcVT = LD->getMemoryVT();
7427   EVT DstVT = LD->getValueType(0);
7428   ISD::LoadExtType ExtType = LD->getExtensionType();
7429 
7430   if (SrcVT.isScalableVector())
7431     report_fatal_error("Cannot scalarize scalable vector loads");
7432 
7433   unsigned NumElem = SrcVT.getVectorNumElements();
7434 
7435   EVT SrcEltVT = SrcVT.getScalarType();
7436   EVT DstEltVT = DstVT.getScalarType();
7437 
7438   // A vector must always be stored in memory as-is, i.e. without any padding
7439   // between the elements, since various code depend on it, e.g. in the
7440   // handling of a bitcast of a vector type to int, which may be done with a
7441   // vector store followed by an integer load. A vector that does not have
7442   // elements that are byte-sized must therefore be stored as an integer
7443   // built out of the extracted vector elements.
7444   if (!SrcEltVT.isByteSized()) {
7445     unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
7446     EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
7447 
7448     unsigned NumSrcBits = SrcVT.getSizeInBits();
7449     EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
7450 
7451     unsigned SrcEltBits = SrcEltVT.getSizeInBits();
7452     SDValue SrcEltBitMask = DAG.getConstant(
7453         APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
7454 
7455     // Load the whole vector and avoid masking off the top bits as it makes
7456     // the codegen worse.
7457     SDValue Load =
7458         DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR,
7459                        LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(),
7460                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
7461 
7462     SmallVector<SDValue, 8> Vals;
7463     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
7464       unsigned ShiftIntoIdx =
7465           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
7466       SDValue ShiftAmount =
7467           DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(),
7468                                      LoadVT, SL, /*LegalTypes=*/false);
7469       SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
7470       SDValue Elt =
7471           DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
7472       SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
7473 
7474       if (ExtType != ISD::NON_EXTLOAD) {
7475         unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
7476         Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
7477       }
7478 
7479       Vals.push_back(Scalar);
7480     }
7481 
7482     SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
7483     return std::make_pair(Value, Load.getValue(1));
7484   }
7485 
7486   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
7487   assert(SrcEltVT.isByteSized());
7488 
7489   SmallVector<SDValue, 8> Vals;
7490   SmallVector<SDValue, 8> LoadChains;
7491 
7492   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
7493     SDValue ScalarLoad =
7494         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
7495                        LD->getPointerInfo().getWithOffset(Idx * Stride),
7496                        SrcEltVT, LD->getOriginalAlign(),
7497                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
7498 
7499     BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::Fixed(Stride));
7500 
7501     Vals.push_back(ScalarLoad.getValue(0));
7502     LoadChains.push_back(ScalarLoad.getValue(1));
7503   }
7504 
7505   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
7506   SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
7507 
7508   return std::make_pair(Value, NewChain);
7509 }
7510 
7511 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
7512                                              SelectionDAG &DAG) const {
7513   SDLoc SL(ST);
7514 
7515   SDValue Chain = ST->getChain();
7516   SDValue BasePtr = ST->getBasePtr();
7517   SDValue Value = ST->getValue();
7518   EVT StVT = ST->getMemoryVT();
7519 
7520   if (StVT.isScalableVector())
7521     report_fatal_error("Cannot scalarize scalable vector stores");
7522 
7523   // The type of the data we want to save
7524   EVT RegVT = Value.getValueType();
7525   EVT RegSclVT = RegVT.getScalarType();
7526 
7527   // The type of data as saved in memory.
7528   EVT MemSclVT = StVT.getScalarType();
7529 
7530   unsigned NumElem = StVT.getVectorNumElements();
7531 
7532   // A vector must always be stored in memory as-is, i.e. without any padding
7533   // between the elements, since various code depend on it, e.g. in the
7534   // handling of a bitcast of a vector type to int, which may be done with a
7535   // vector store followed by an integer load. A vector that does not have
7536   // elements that are byte-sized must therefore be stored as an integer
7537   // built out of the extracted vector elements.
7538   if (!MemSclVT.isByteSized()) {
7539     unsigned NumBits = StVT.getSizeInBits();
7540     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
7541 
7542     SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
7543 
7544     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
7545       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
7546                                 DAG.getVectorIdxConstant(Idx, SL));
7547       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
7548       SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
7549       unsigned ShiftIntoIdx =
7550           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
7551       SDValue ShiftAmount =
7552           DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
7553       SDValue ShiftedElt =
7554           DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
7555       CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
7556     }
7557 
7558     return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
7559                         ST->getOriginalAlign(), ST->getMemOperand()->getFlags(),
7560                         ST->getAAInfo());
7561   }
7562 
7563   // Store Stride in bytes
7564   unsigned Stride = MemSclVT.getSizeInBits() / 8;
7565   assert(Stride && "Zero stride!");
7566   // Extract each of the elements from the original vector and save them into
7567   // memory individually.
7568   SmallVector<SDValue, 8> Stores;
7569   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
7570     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
7571                               DAG.getVectorIdxConstant(Idx, SL));
7572 
7573     SDValue Ptr =
7574         DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Idx * Stride));
7575 
7576     // This scalar TruncStore may be illegal, but we legalize it later.
7577     SDValue Store = DAG.getTruncStore(
7578         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
7579         MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(),
7580         ST->getAAInfo());
7581 
7582     Stores.push_back(Store);
7583   }
7584 
7585   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
7586 }
7587 
7588 std::pair<SDValue, SDValue>
7589 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
7590   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
7591          "unaligned indexed loads not implemented!");
7592   SDValue Chain = LD->getChain();
7593   SDValue Ptr = LD->getBasePtr();
7594   EVT VT = LD->getValueType(0);
7595   EVT LoadedVT = LD->getMemoryVT();
7596   SDLoc dl(LD);
7597   auto &MF = DAG.getMachineFunction();
7598 
7599   if (VT.isFloatingPoint() || VT.isVector()) {
7600     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
7601     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
7602       if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
7603           LoadedVT.isVector()) {
7604         // Scalarize the load and let the individual components be handled.
7605         return scalarizeVectorLoad(LD, DAG);
7606       }
7607 
7608       // Expand to a (misaligned) integer load of the same size,
7609       // then bitconvert to floating point or vector.
7610       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
7611                                     LD->getMemOperand());
7612       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
7613       if (LoadedVT != VT)
7614         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
7615                              ISD::ANY_EXTEND, dl, VT, Result);
7616 
7617       return std::make_pair(Result, newLoad.getValue(1));
7618     }
7619 
7620     // Copy the value to a (aligned) stack slot using (unaligned) integer
7621     // loads and stores, then do a (aligned) load from the stack slot.
7622     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
7623     unsigned LoadedBytes = LoadedVT.getStoreSize();
7624     unsigned RegBytes = RegVT.getSizeInBits() / 8;
7625     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
7626 
7627     // Make sure the stack slot is also aligned for the register type.
7628     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
7629     auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
7630     SmallVector<SDValue, 8> Stores;
7631     SDValue StackPtr = StackBase;
7632     unsigned Offset = 0;
7633 
7634     EVT PtrVT = Ptr.getValueType();
7635     EVT StackPtrVT = StackPtr.getValueType();
7636 
7637     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
7638     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
7639 
7640     // Do all but one copies using the full register width.
7641     for (unsigned i = 1; i < NumRegs; i++) {
7642       // Load one integer register's worth from the original location.
7643       SDValue Load = DAG.getLoad(
7644           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
7645           LD->getOriginalAlign(), LD->getMemOperand()->getFlags(),
7646           LD->getAAInfo());
7647       // Follow the load with a store to the stack slot.  Remember the store.
7648       Stores.push_back(DAG.getStore(
7649           Load.getValue(1), dl, Load, StackPtr,
7650           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
7651       // Increment the pointers.
7652       Offset += RegBytes;
7653 
7654       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
7655       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
7656     }
7657 
7658     // The last copy may be partial.  Do an extending load.
7659     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
7660                                   8 * (LoadedBytes - Offset));
7661     SDValue Load =
7662         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
7663                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
7664                        LD->getOriginalAlign(), LD->getMemOperand()->getFlags(),
7665                        LD->getAAInfo());
7666     // Follow the load with a store to the stack slot.  Remember the store.
7667     // On big-endian machines this requires a truncating store to ensure
7668     // that the bits end up in the right place.
7669     Stores.push_back(DAG.getTruncStore(
7670         Load.getValue(1), dl, Load, StackPtr,
7671         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
7672 
7673     // The order of the stores doesn't matter - say it with a TokenFactor.
7674     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7675 
7676     // Finally, perform the original load only redirected to the stack slot.
7677     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
7678                           MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
7679                           LoadedVT);
7680 
7681     // Callers expect a MERGE_VALUES node.
7682     return std::make_pair(Load, TF);
7683   }
7684 
7685   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
7686          "Unaligned load of unsupported type.");
7687 
7688   // Compute the new VT that is half the size of the old one.  This is an
7689   // integer MVT.
7690   unsigned NumBits = LoadedVT.getSizeInBits();
7691   EVT NewLoadedVT;
7692   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
7693   NumBits >>= 1;
7694 
7695   Align Alignment = LD->getOriginalAlign();
7696   unsigned IncrementSize = NumBits / 8;
7697   ISD::LoadExtType HiExtType = LD->getExtensionType();
7698 
7699   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
7700   if (HiExtType == ISD::NON_EXTLOAD)
7701     HiExtType = ISD::ZEXTLOAD;
7702 
7703   // Load the value in two parts
7704   SDValue Lo, Hi;
7705   if (DAG.getDataLayout().isLittleEndian()) {
7706     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
7707                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
7708                         LD->getAAInfo());
7709 
7710     Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
7711     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
7712                         LD->getPointerInfo().getWithOffset(IncrementSize),
7713                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
7714                         LD->getAAInfo());
7715   } else {
7716     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
7717                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
7718                         LD->getAAInfo());
7719 
7720     Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
7721     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
7722                         LD->getPointerInfo().getWithOffset(IncrementSize),
7723                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
7724                         LD->getAAInfo());
7725   }
7726 
7727   // aggregate the two parts
7728   SDValue ShiftAmount =
7729       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
7730                                                     DAG.getDataLayout()));
7731   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
7732   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
7733 
7734   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
7735                              Hi.getValue(1));
7736 
7737   return std::make_pair(Result, TF);
7738 }
7739 
7740 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
7741                                              SelectionDAG &DAG) const {
7742   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
7743          "unaligned indexed stores not implemented!");
7744   SDValue Chain = ST->getChain();
7745   SDValue Ptr = ST->getBasePtr();
7746   SDValue Val = ST->getValue();
7747   EVT VT = Val.getValueType();
7748   Align Alignment = ST->getOriginalAlign();
7749   auto &MF = DAG.getMachineFunction();
7750   EVT StoreMemVT = ST->getMemoryVT();
7751 
7752   SDLoc dl(ST);
7753   if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
7754     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7755     if (isTypeLegal(intVT)) {
7756       if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
7757           StoreMemVT.isVector()) {
7758         // Scalarize the store and let the individual components be handled.
7759         SDValue Result = scalarizeVectorStore(ST, DAG);
7760         return Result;
7761       }
7762       // Expand to a bitconvert of the value to the integer type of the
7763       // same size, then a (misaligned) int store.
7764       // FIXME: Does not handle truncating floating point stores!
7765       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
7766       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
7767                             Alignment, ST->getMemOperand()->getFlags());
7768       return Result;
7769     }
7770     // Do a (aligned) store to a stack slot, then copy from the stack slot
7771     // to the final destination using (unaligned) integer loads and stores.
7772     MVT RegVT = getRegisterType(
7773         *DAG.getContext(),
7774         EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
7775     EVT PtrVT = Ptr.getValueType();
7776     unsigned StoredBytes = StoreMemVT.getStoreSize();
7777     unsigned RegBytes = RegVT.getSizeInBits() / 8;
7778     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
7779 
7780     // Make sure the stack slot is also aligned for the register type.
7781     SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
7782     auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
7783 
7784     // Perform the original store, only redirected to the stack slot.
7785     SDValue Store = DAG.getTruncStore(
7786         Chain, dl, Val, StackPtr,
7787         MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
7788 
7789     EVT StackPtrVT = StackPtr.getValueType();
7790 
7791     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
7792     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
7793     SmallVector<SDValue, 8> Stores;
7794     unsigned Offset = 0;
7795 
7796     // Do all but one copies using the full register width.
7797     for (unsigned i = 1; i < NumRegs; i++) {
7798       // Load one integer register's worth from the stack slot.
7799       SDValue Load = DAG.getLoad(
7800           RegVT, dl, Store, StackPtr,
7801           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
7802       // Store it to the final location.  Remember the store.
7803       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
7804                                     ST->getPointerInfo().getWithOffset(Offset),
7805                                     ST->getOriginalAlign(),
7806                                     ST->getMemOperand()->getFlags()));
7807       // Increment the pointers.
7808       Offset += RegBytes;
7809       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
7810       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
7811     }
7812 
7813     // The last store may be partial.  Do a truncating store.  On big-endian
7814     // machines this requires an extending load from the stack slot to ensure
7815     // that the bits are in the right place.
7816     EVT LoadMemVT =
7817         EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
7818 
7819     // Load from the stack slot.
7820     SDValue Load = DAG.getExtLoad(
7821         ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
7822         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
7823 
7824     Stores.push_back(
7825         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
7826                           ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
7827                           ST->getOriginalAlign(),
7828                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
7829     // The order of the stores doesn't matter - say it with a TokenFactor.
7830     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
7831     return Result;
7832   }
7833 
7834   assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
7835          "Unaligned store of unknown type.");
7836   // Get the half-size VT
7837   EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
7838   unsigned NumBits = NewStoredVT.getFixedSizeInBits();
7839   unsigned IncrementSize = NumBits / 8;
7840 
7841   // Divide the stored value in two parts.
7842   SDValue ShiftAmount = DAG.getConstant(
7843       NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout()));
7844   SDValue Lo = Val;
7845   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
7846 
7847   // Store the two parts
7848   SDValue Store1, Store2;
7849   Store1 = DAG.getTruncStore(Chain, dl,
7850                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
7851                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
7852                              ST->getMemOperand()->getFlags());
7853 
7854   Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
7855   Store2 = DAG.getTruncStore(
7856       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
7857       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
7858       ST->getMemOperand()->getFlags(), ST->getAAInfo());
7859 
7860   SDValue Result =
7861       DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
7862   return Result;
7863 }
7864 
7865 SDValue
7866 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
7867                                        const SDLoc &DL, EVT DataVT,
7868                                        SelectionDAG &DAG,
7869                                        bool IsCompressedMemory) const {
7870   SDValue Increment;
7871   EVT AddrVT = Addr.getValueType();
7872   EVT MaskVT = Mask.getValueType();
7873   assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
7874          "Incompatible types of Data and Mask");
7875   if (IsCompressedMemory) {
7876     if (DataVT.isScalableVector())
7877       report_fatal_error(
7878           "Cannot currently handle compressed memory with scalable vectors");
7879     // Incrementing the pointer according to number of '1's in the mask.
7880     EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
7881     SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
7882     if (MaskIntVT.getSizeInBits() < 32) {
7883       MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
7884       MaskIntVT = MVT::i32;
7885     }
7886 
7887     // Count '1's with POPCNT.
7888     Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
7889     Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
7890     // Scale is an element size in bytes.
7891     SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
7892                                     AddrVT);
7893     Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
7894   } else if (DataVT.isScalableVector()) {
7895     Increment = DAG.getVScale(DL, AddrVT,
7896                               APInt(AddrVT.getFixedSizeInBits(),
7897                                     DataVT.getStoreSize().getKnownMinSize()));
7898   } else
7899     Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT);
7900 
7901   return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
7902 }
7903 
7904 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx,
7905                                        EVT VecVT, const SDLoc &dl,
7906                                        ElementCount SubEC) {
7907   assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
7908          "Cannot index a scalable vector within a fixed-width vector");
7909 
7910   unsigned NElts = VecVT.getVectorMinNumElements();
7911   unsigned NumSubElts = SubEC.getKnownMinValue();
7912   EVT IdxVT = Idx.getValueType();
7913 
7914   if (VecVT.isScalableVector() && !SubEC.isScalable()) {
7915     // If this is a constant index and we know the value plus the number of the
7916     // elements in the subvector minus one is less than the minimum number of
7917     // elements then it's safe to return Idx.
7918     if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx))
7919       if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts)
7920         return Idx;
7921     SDValue VS =
7922         DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts));
7923     unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT;
7924     SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS,
7925                               DAG.getConstant(NumSubElts, dl, IdxVT));
7926     return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub);
7927   }
7928   if (isPowerOf2_32(NElts) && NumSubElts == 1) {
7929     APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts));
7930     return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
7931                        DAG.getConstant(Imm, dl, IdxVT));
7932   }
7933   unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0;
7934   return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
7935                      DAG.getConstant(MaxIndex, dl, IdxVT));
7936 }
7937 
7938 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
7939                                                 SDValue VecPtr, EVT VecVT,
7940                                                 SDValue Index) const {
7941   return getVectorSubVecPointer(
7942       DAG, VecPtr, VecVT,
7943       EVT::getVectorVT(*DAG.getContext(), VecVT.getVectorElementType(), 1),
7944       Index);
7945 }
7946 
7947 SDValue TargetLowering::getVectorSubVecPointer(SelectionDAG &DAG,
7948                                                SDValue VecPtr, EVT VecVT,
7949                                                EVT SubVecVT,
7950                                                SDValue Index) const {
7951   SDLoc dl(Index);
7952   // Make sure the index type is big enough to compute in.
7953   Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
7954 
7955   EVT EltVT = VecVT.getVectorElementType();
7956 
7957   // Calculate the element offset and add it to the pointer.
7958   unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
7959   assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
7960          "Converting bits to bytes lost precision");
7961   assert(SubVecVT.getVectorElementType() == EltVT &&
7962          "Sub-vector must be a vector with matching element type");
7963   Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
7964                                   SubVecVT.getVectorElementCount());
7965 
7966   EVT IdxVT = Index.getValueType();
7967   if (SubVecVT.isScalableVector())
7968     Index =
7969         DAG.getNode(ISD::MUL, dl, IdxVT, Index,
7970                     DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1)));
7971 
7972   Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
7973                       DAG.getConstant(EltSize, dl, IdxVT));
7974   return DAG.getMemBasePlusOffset(VecPtr, Index, dl);
7975 }
7976 
7977 //===----------------------------------------------------------------------===//
7978 // Implementation of Emulated TLS Model
7979 //===----------------------------------------------------------------------===//
7980 
7981 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
7982                                                 SelectionDAG &DAG) const {
7983   // Access to address of TLS varialbe xyz is lowered to a function call:
7984   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
7985   EVT PtrVT = getPointerTy(DAG.getDataLayout());
7986   PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
7987   SDLoc dl(GA);
7988 
7989   ArgListTy Args;
7990   ArgListEntry Entry;
7991   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
7992   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
7993   StringRef EmuTlsVarName(NameString);
7994   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
7995   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
7996   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
7997   Entry.Ty = VoidPtrType;
7998   Args.push_back(Entry);
7999 
8000   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
8001 
8002   TargetLowering::CallLoweringInfo CLI(DAG);
8003   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
8004   CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
8005   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8006 
8007   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8008   // At last for X86 targets, maybe good for other targets too?
8009   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8010   MFI.setAdjustsStack(true); // Is this only for X86 target?
8011   MFI.setHasCalls(true);
8012 
8013   assert((GA->getOffset() == 0) &&
8014          "Emulated TLS must have zero offset in GlobalAddressSDNode");
8015   return CallResult.first;
8016 }
8017 
8018 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
8019                                                 SelectionDAG &DAG) const {
8020   assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
8021   if (!isCtlzFast())
8022     return SDValue();
8023   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8024   SDLoc dl(Op);
8025   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8026     if (C->isZero() && CC == ISD::SETEQ) {
8027       EVT VT = Op.getOperand(0).getValueType();
8028       SDValue Zext = Op.getOperand(0);
8029       if (VT.bitsLT(MVT::i32)) {
8030         VT = MVT::i32;
8031         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
8032       }
8033       unsigned Log2b = Log2_32(VT.getSizeInBits());
8034       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
8035       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
8036                                 DAG.getConstant(Log2b, dl, MVT::i32));
8037       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
8038     }
8039   }
8040   return SDValue();
8041 }
8042 
8043 // Convert redundant addressing modes (e.g. scaling is redundant
8044 // when accessing bytes).
8045 ISD::MemIndexType
8046 TargetLowering::getCanonicalIndexType(ISD::MemIndexType IndexType, EVT MemVT,
8047                                       SDValue Offsets) const {
8048   bool IsScaledIndex =
8049       (IndexType == ISD::SIGNED_SCALED) || (IndexType == ISD::UNSIGNED_SCALED);
8050   bool IsSignedIndex =
8051       (IndexType == ISD::SIGNED_SCALED) || (IndexType == ISD::SIGNED_UNSCALED);
8052 
8053   // Scaling is unimportant for bytes, canonicalize to unscaled.
8054   if (IsScaledIndex && MemVT.getScalarType() == MVT::i8)
8055     return IsSignedIndex ? ISD::SIGNED_UNSCALED : ISD::UNSIGNED_UNSCALED;
8056 
8057   return IndexType;
8058 }
8059 
8060 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const {
8061   SDValue Op0 = Node->getOperand(0);
8062   SDValue Op1 = Node->getOperand(1);
8063   EVT VT = Op0.getValueType();
8064   unsigned Opcode = Node->getOpcode();
8065   SDLoc DL(Node);
8066 
8067   // umin(x,y) -> sub(x,usubsat(x,y))
8068   if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
8069       isOperationLegal(ISD::USUBSAT, VT)) {
8070     return DAG.getNode(ISD::SUB, DL, VT, Op0,
8071                        DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
8072   }
8073 
8074   // umax(x,y) -> add(x,usubsat(y,x))
8075   if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
8076       isOperationLegal(ISD::USUBSAT, VT)) {
8077     return DAG.getNode(ISD::ADD, DL, VT, Op0,
8078                        DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
8079   }
8080 
8081   // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
8082   ISD::CondCode CC;
8083   switch (Opcode) {
8084   default: llvm_unreachable("How did we get here?");
8085   case ISD::SMAX: CC = ISD::SETGT; break;
8086   case ISD::SMIN: CC = ISD::SETLT; break;
8087   case ISD::UMAX: CC = ISD::SETUGT; break;
8088   case ISD::UMIN: CC = ISD::SETULT; break;
8089   }
8090 
8091   // FIXME: Should really try to split the vector in case it's legal on a
8092   // subvector.
8093   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
8094     return DAG.UnrollVectorOp(Node);
8095 
8096   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8097   SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
8098   return DAG.getSelect(DL, VT, Cond, Op0, Op1);
8099 }
8100 
8101 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const {
8102   unsigned Opcode = Node->getOpcode();
8103   SDValue LHS = Node->getOperand(0);
8104   SDValue RHS = Node->getOperand(1);
8105   EVT VT = LHS.getValueType();
8106   SDLoc dl(Node);
8107 
8108   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
8109   assert(VT.isInteger() && "Expected operands to be integers");
8110 
8111   // usub.sat(a, b) -> umax(a, b) - b
8112   if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
8113     SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
8114     return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
8115   }
8116 
8117   // uadd.sat(a, b) -> umin(a, ~b) + b
8118   if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
8119     SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
8120     SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
8121     return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
8122   }
8123 
8124   unsigned OverflowOp;
8125   switch (Opcode) {
8126   case ISD::SADDSAT:
8127     OverflowOp = ISD::SADDO;
8128     break;
8129   case ISD::UADDSAT:
8130     OverflowOp = ISD::UADDO;
8131     break;
8132   case ISD::SSUBSAT:
8133     OverflowOp = ISD::SSUBO;
8134     break;
8135   case ISD::USUBSAT:
8136     OverflowOp = ISD::USUBO;
8137     break;
8138   default:
8139     llvm_unreachable("Expected method to receive signed or unsigned saturation "
8140                      "addition or subtraction node.");
8141   }
8142 
8143   // FIXME: Should really try to split the vector in case it's legal on a
8144   // subvector.
8145   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
8146     return DAG.UnrollVectorOp(Node);
8147 
8148   unsigned BitWidth = LHS.getScalarValueSizeInBits();
8149   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8150   SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8151   SDValue SumDiff = Result.getValue(0);
8152   SDValue Overflow = Result.getValue(1);
8153   SDValue Zero = DAG.getConstant(0, dl, VT);
8154   SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
8155 
8156   if (Opcode == ISD::UADDSAT) {
8157     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
8158       // (LHS + RHS) | OverflowMask
8159       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
8160       return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
8161     }
8162     // Overflow ? 0xffff.... : (LHS + RHS)
8163     return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
8164   }
8165 
8166   if (Opcode == ISD::USUBSAT) {
8167     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
8168       // (LHS - RHS) & ~OverflowMask
8169       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
8170       SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
8171       return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
8172     }
8173     // Overflow ? 0 : (LHS - RHS)
8174     return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
8175   }
8176 
8177   // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
8178   APInt MinVal = APInt::getSignedMinValue(BitWidth);
8179   SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
8180   SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
8181                               DAG.getConstant(BitWidth - 1, dl, VT));
8182   Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
8183   return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
8184 }
8185 
8186 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const {
8187   unsigned Opcode = Node->getOpcode();
8188   bool IsSigned = Opcode == ISD::SSHLSAT;
8189   SDValue LHS = Node->getOperand(0);
8190   SDValue RHS = Node->getOperand(1);
8191   EVT VT = LHS.getValueType();
8192   SDLoc dl(Node);
8193 
8194   assert((Node->getOpcode() == ISD::SSHLSAT ||
8195           Node->getOpcode() == ISD::USHLSAT) &&
8196           "Expected a SHLSAT opcode");
8197   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
8198   assert(VT.isInteger() && "Expected operands to be integers");
8199 
8200   // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
8201 
8202   unsigned BW = VT.getScalarSizeInBits();
8203   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
8204   SDValue Orig =
8205       DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
8206 
8207   SDValue SatVal;
8208   if (IsSigned) {
8209     SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
8210     SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
8211     SatVal = DAG.getSelectCC(dl, LHS, DAG.getConstant(0, dl, VT),
8212                              SatMin, SatMax, ISD::SETLT);
8213   } else {
8214     SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
8215   }
8216   Result = DAG.getSelectCC(dl, LHS, Orig, SatVal, Result, ISD::SETNE);
8217 
8218   return Result;
8219 }
8220 
8221 SDValue
8222 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const {
8223   assert((Node->getOpcode() == ISD::SMULFIX ||
8224           Node->getOpcode() == ISD::UMULFIX ||
8225           Node->getOpcode() == ISD::SMULFIXSAT ||
8226           Node->getOpcode() == ISD::UMULFIXSAT) &&
8227          "Expected a fixed point multiplication opcode");
8228 
8229   SDLoc dl(Node);
8230   SDValue LHS = Node->getOperand(0);
8231   SDValue RHS = Node->getOperand(1);
8232   EVT VT = LHS.getValueType();
8233   unsigned Scale = Node->getConstantOperandVal(2);
8234   bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
8235                      Node->getOpcode() == ISD::UMULFIXSAT);
8236   bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
8237                  Node->getOpcode() == ISD::SMULFIXSAT);
8238   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8239   unsigned VTSize = VT.getScalarSizeInBits();
8240 
8241   if (!Scale) {
8242     // [us]mul.fix(a, b, 0) -> mul(a, b)
8243     if (!Saturating) {
8244       if (isOperationLegalOrCustom(ISD::MUL, VT))
8245         return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
8246     } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
8247       SDValue Result =
8248           DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8249       SDValue Product = Result.getValue(0);
8250       SDValue Overflow = Result.getValue(1);
8251       SDValue Zero = DAG.getConstant(0, dl, VT);
8252 
8253       APInt MinVal = APInt::getSignedMinValue(VTSize);
8254       APInt MaxVal = APInt::getSignedMaxValue(VTSize);
8255       SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
8256       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
8257       // Xor the inputs, if resulting sign bit is 0 the product will be
8258       // positive, else negative.
8259       SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
8260       SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
8261       Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
8262       return DAG.getSelect(dl, VT, Overflow, Result, Product);
8263     } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
8264       SDValue Result =
8265           DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8266       SDValue Product = Result.getValue(0);
8267       SDValue Overflow = Result.getValue(1);
8268 
8269       APInt MaxVal = APInt::getMaxValue(VTSize);
8270       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
8271       return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
8272     }
8273   }
8274 
8275   assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
8276          "Expected scale to be less than the number of bits if signed or at "
8277          "most the number of bits if unsigned.");
8278   assert(LHS.getValueType() == RHS.getValueType() &&
8279          "Expected both operands to be the same type");
8280 
8281   // Get the upper and lower bits of the result.
8282   SDValue Lo, Hi;
8283   unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
8284   unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
8285   if (isOperationLegalOrCustom(LoHiOp, VT)) {
8286     SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
8287     Lo = Result.getValue(0);
8288     Hi = Result.getValue(1);
8289   } else if (isOperationLegalOrCustom(HiOp, VT)) {
8290     Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
8291     Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
8292   } else if (VT.isVector()) {
8293     return SDValue();
8294   } else {
8295     report_fatal_error("Unable to expand fixed point multiplication.");
8296   }
8297 
8298   if (Scale == VTSize)
8299     // Result is just the top half since we'd be shifting by the width of the
8300     // operand. Overflow impossible so this works for both UMULFIX and
8301     // UMULFIXSAT.
8302     return Hi;
8303 
8304   // The result will need to be shifted right by the scale since both operands
8305   // are scaled. The result is given to us in 2 halves, so we only want part of
8306   // both in the result.
8307   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
8308   SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
8309                                DAG.getConstant(Scale, dl, ShiftTy));
8310   if (!Saturating)
8311     return Result;
8312 
8313   if (!Signed) {
8314     // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
8315     // widened multiplication) aren't all zeroes.
8316 
8317     // Saturate to max if ((Hi >> Scale) != 0),
8318     // which is the same as if (Hi > ((1 << Scale) - 1))
8319     APInt MaxVal = APInt::getMaxValue(VTSize);
8320     SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale),
8321                                       dl, VT);
8322     Result = DAG.getSelectCC(dl, Hi, LowMask,
8323                              DAG.getConstant(MaxVal, dl, VT), Result,
8324                              ISD::SETUGT);
8325 
8326     return Result;
8327   }
8328 
8329   // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
8330   // widened multiplication) aren't all ones or all zeroes.
8331 
8332   SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
8333   SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
8334 
8335   if (Scale == 0) {
8336     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
8337                                DAG.getConstant(VTSize - 1, dl, ShiftTy));
8338     SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
8339     // Saturated to SatMin if wide product is negative, and SatMax if wide
8340     // product is positive ...
8341     SDValue Zero = DAG.getConstant(0, dl, VT);
8342     SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax,
8343                                                ISD::SETLT);
8344     // ... but only if we overflowed.
8345     return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
8346   }
8347 
8348   //  We handled Scale==0 above so all the bits to examine is in Hi.
8349 
8350   // Saturate to max if ((Hi >> (Scale - 1)) > 0),
8351   // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
8352   SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1),
8353                                     dl, VT);
8354   Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT);
8355   // Saturate to min if (Hi >> (Scale - 1)) < -1),
8356   // which is the same as if (HI < (-1 << (Scale - 1))
8357   SDValue HighMask =
8358       DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1),
8359                       dl, VT);
8360   Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT);
8361   return Result;
8362 }
8363 
8364 SDValue
8365 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl,
8366                                     SDValue LHS, SDValue RHS,
8367                                     unsigned Scale, SelectionDAG &DAG) const {
8368   assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
8369           Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
8370          "Expected a fixed point division opcode");
8371 
8372   EVT VT = LHS.getValueType();
8373   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
8374   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
8375   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8376 
8377   // If there is enough room in the type to upscale the LHS or downscale the
8378   // RHS before the division, we can perform it in this type without having to
8379   // resize. For signed operations, the LHS headroom is the number of
8380   // redundant sign bits, and for unsigned ones it is the number of zeroes.
8381   // The headroom for the RHS is the number of trailing zeroes.
8382   unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
8383                             : DAG.computeKnownBits(LHS).countMinLeadingZeros();
8384   unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
8385 
8386   // For signed saturating operations, we need to be able to detect true integer
8387   // division overflow; that is, when you have MIN / -EPS. However, this
8388   // is undefined behavior and if we emit divisions that could take such
8389   // values it may cause undesired behavior (arithmetic exceptions on x86, for
8390   // example).
8391   // Avoid this by requiring an extra bit so that we never get this case.
8392   // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
8393   // signed saturating division, we need to emit a whopping 32-bit division.
8394   if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
8395     return SDValue();
8396 
8397   unsigned LHSShift = std::min(LHSLead, Scale);
8398   unsigned RHSShift = Scale - LHSShift;
8399 
8400   // At this point, we know that if we shift the LHS up by LHSShift and the
8401   // RHS down by RHSShift, we can emit a regular division with a final scaling
8402   // factor of Scale.
8403 
8404   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
8405   if (LHSShift)
8406     LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
8407                       DAG.getConstant(LHSShift, dl, ShiftTy));
8408   if (RHSShift)
8409     RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
8410                       DAG.getConstant(RHSShift, dl, ShiftTy));
8411 
8412   SDValue Quot;
8413   if (Signed) {
8414     // For signed operations, if the resulting quotient is negative and the
8415     // remainder is nonzero, subtract 1 from the quotient to round towards
8416     // negative infinity.
8417     SDValue Rem;
8418     // FIXME: Ideally we would always produce an SDIVREM here, but if the
8419     // type isn't legal, SDIVREM cannot be expanded. There is no reason why
8420     // we couldn't just form a libcall, but the type legalizer doesn't do it.
8421     if (isTypeLegal(VT) &&
8422         isOperationLegalOrCustom(ISD::SDIVREM, VT)) {
8423       Quot = DAG.getNode(ISD::SDIVREM, dl,
8424                          DAG.getVTList(VT, VT),
8425                          LHS, RHS);
8426       Rem = Quot.getValue(1);
8427       Quot = Quot.getValue(0);
8428     } else {
8429       Quot = DAG.getNode(ISD::SDIV, dl, VT,
8430                          LHS, RHS);
8431       Rem = DAG.getNode(ISD::SREM, dl, VT,
8432                         LHS, RHS);
8433     }
8434     SDValue Zero = DAG.getConstant(0, dl, VT);
8435     SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
8436     SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
8437     SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
8438     SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
8439     SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
8440                                DAG.getConstant(1, dl, VT));
8441     Quot = DAG.getSelect(dl, VT,
8442                          DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
8443                          Sub1, Quot);
8444   } else
8445     Quot = DAG.getNode(ISD::UDIV, dl, VT,
8446                        LHS, RHS);
8447 
8448   return Quot;
8449 }
8450 
8451 void TargetLowering::expandUADDSUBO(
8452     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
8453   SDLoc dl(Node);
8454   SDValue LHS = Node->getOperand(0);
8455   SDValue RHS = Node->getOperand(1);
8456   bool IsAdd = Node->getOpcode() == ISD::UADDO;
8457 
8458   // If ADD/SUBCARRY is legal, use that instead.
8459   unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY;
8460   if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
8461     SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
8462     SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
8463                                     { LHS, RHS, CarryIn });
8464     Result = SDValue(NodeCarry.getNode(), 0);
8465     Overflow = SDValue(NodeCarry.getNode(), 1);
8466     return;
8467   }
8468 
8469   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
8470                             LHS.getValueType(), LHS, RHS);
8471 
8472   EVT ResultType = Node->getValueType(1);
8473   EVT SetCCType = getSetCCResultType(
8474       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
8475   ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
8476   SDValue SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
8477   Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
8478 }
8479 
8480 void TargetLowering::expandSADDSUBO(
8481     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
8482   SDLoc dl(Node);
8483   SDValue LHS = Node->getOperand(0);
8484   SDValue RHS = Node->getOperand(1);
8485   bool IsAdd = Node->getOpcode() == ISD::SADDO;
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 OType = getSetCCResultType(
8492       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
8493 
8494   // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
8495   unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
8496   if (isOperationLegal(OpcSat, LHS.getValueType())) {
8497     SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
8498     SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
8499     Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
8500     return;
8501   }
8502 
8503   SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
8504 
8505   // For an addition, the result should be less than one of the operands (LHS)
8506   // if and only if the other operand (RHS) is negative, otherwise there will
8507   // be overflow.
8508   // For a subtraction, the result should be less than one of the operands
8509   // (LHS) if and only if the other operand (RHS) is (non-zero) positive,
8510   // otherwise there will be overflow.
8511   SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
8512   SDValue ConditionRHS =
8513       DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT);
8514 
8515   Overflow = DAG.getBoolExtOrTrunc(
8516       DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl,
8517       ResultType, ResultType);
8518 }
8519 
8520 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result,
8521                                 SDValue &Overflow, SelectionDAG &DAG) const {
8522   SDLoc dl(Node);
8523   EVT VT = Node->getValueType(0);
8524   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8525   SDValue LHS = Node->getOperand(0);
8526   SDValue RHS = Node->getOperand(1);
8527   bool isSigned = Node->getOpcode() == ISD::SMULO;
8528 
8529   // For power-of-two multiplications we can use a simpler shift expansion.
8530   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
8531     const APInt &C = RHSC->getAPIntValue();
8532     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
8533     if (C.isPowerOf2()) {
8534       // smulo(x, signed_min) is same as umulo(x, signed_min).
8535       bool UseArithShift = isSigned && !C.isMinSignedValue();
8536       EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout());
8537       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy);
8538       Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
8539       Overflow = DAG.getSetCC(dl, SetCCVT,
8540           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
8541                       dl, VT, Result, ShiftAmt),
8542           LHS, ISD::SETNE);
8543       return true;
8544     }
8545   }
8546 
8547   EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2);
8548   if (VT.isVector())
8549     WideVT =
8550         EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount());
8551 
8552   SDValue BottomHalf;
8553   SDValue TopHalf;
8554   static const unsigned Ops[2][3] =
8555       { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
8556         { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
8557   if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
8558     BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
8559     TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
8560   } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
8561     BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
8562                              RHS);
8563     TopHalf = BottomHalf.getValue(1);
8564   } else if (isTypeLegal(WideVT)) {
8565     LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
8566     RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
8567     SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
8568     BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
8569     SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl,
8570         getShiftAmountTy(WideVT, DAG.getDataLayout()));
8571     TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
8572                           DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
8573   } else {
8574     if (VT.isVector())
8575       return false;
8576 
8577     // We can fall back to a libcall with an illegal type for the MUL if we
8578     // have a libcall big enough.
8579     // Also, we can fall back to a division in some cases, but that's a big
8580     // performance hit in the general case.
8581     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
8582     if (WideVT == MVT::i16)
8583       LC = RTLIB::MUL_I16;
8584     else if (WideVT == MVT::i32)
8585       LC = RTLIB::MUL_I32;
8586     else if (WideVT == MVT::i64)
8587       LC = RTLIB::MUL_I64;
8588     else if (WideVT == MVT::i128)
8589       LC = RTLIB::MUL_I128;
8590     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
8591 
8592     SDValue HiLHS;
8593     SDValue HiRHS;
8594     if (isSigned) {
8595       // The high part is obtained by SRA'ing all but one of the bits of low
8596       // part.
8597       unsigned LoSize = VT.getFixedSizeInBits();
8598       HiLHS =
8599           DAG.getNode(ISD::SRA, dl, VT, LHS,
8600                       DAG.getConstant(LoSize - 1, dl,
8601                                       getPointerTy(DAG.getDataLayout())));
8602       HiRHS =
8603           DAG.getNode(ISD::SRA, dl, VT, RHS,
8604                       DAG.getConstant(LoSize - 1, dl,
8605                                       getPointerTy(DAG.getDataLayout())));
8606     } else {
8607         HiLHS = DAG.getConstant(0, dl, VT);
8608         HiRHS = DAG.getConstant(0, dl, VT);
8609     }
8610 
8611     // Here we're passing the 2 arguments explicitly as 4 arguments that are
8612     // pre-lowered to the correct types. This all depends upon WideVT not
8613     // being a legal type for the architecture and thus has to be split to
8614     // two arguments.
8615     SDValue Ret;
8616     TargetLowering::MakeLibCallOptions CallOptions;
8617     CallOptions.setSExt(isSigned);
8618     CallOptions.setIsPostTypeLegalization(true);
8619     if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) {
8620       // Halves of WideVT are packed into registers in different order
8621       // depending on platform endianness. This is usually handled by
8622       // the C calling convention, but we can't defer to it in
8623       // the legalizer.
8624       SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
8625       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
8626     } else {
8627       SDValue Args[] = { HiLHS, LHS, HiRHS, RHS };
8628       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
8629     }
8630     assert(Ret.getOpcode() == ISD::MERGE_VALUES &&
8631            "Ret value is a collection of constituent nodes holding result.");
8632     if (DAG.getDataLayout().isLittleEndian()) {
8633       // Same as above.
8634       BottomHalf = Ret.getOperand(0);
8635       TopHalf = Ret.getOperand(1);
8636     } else {
8637       BottomHalf = Ret.getOperand(1);
8638       TopHalf = Ret.getOperand(0);
8639     }
8640   }
8641 
8642   Result = BottomHalf;
8643   if (isSigned) {
8644     SDValue ShiftAmt = DAG.getConstant(
8645         VT.getScalarSizeInBits() - 1, dl,
8646         getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout()));
8647     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
8648     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
8649   } else {
8650     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
8651                             DAG.getConstant(0, dl, VT), ISD::SETNE);
8652   }
8653 
8654   // Truncate the result if SetCC returns a larger type than needed.
8655   EVT RType = Node->getValueType(1);
8656   if (RType.bitsLT(Overflow.getValueType()))
8657     Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
8658 
8659   assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
8660          "Unexpected result type for S/UMULO legalization");
8661   return true;
8662 }
8663 
8664 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const {
8665   SDLoc dl(Node);
8666   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
8667   SDValue Op = Node->getOperand(0);
8668   EVT VT = Op.getValueType();
8669 
8670   if (VT.isScalableVector())
8671     report_fatal_error(
8672         "Expanding reductions for scalable vectors is undefined.");
8673 
8674   // Try to use a shuffle reduction for power of two vectors.
8675   if (VT.isPow2VectorType()) {
8676     while (VT.getVectorNumElements() > 1) {
8677       EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
8678       if (!isOperationLegalOrCustom(BaseOpcode, HalfVT))
8679         break;
8680 
8681       SDValue Lo, Hi;
8682       std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
8683       Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi);
8684       VT = HalfVT;
8685     }
8686   }
8687 
8688   EVT EltVT = VT.getVectorElementType();
8689   unsigned NumElts = VT.getVectorNumElements();
8690 
8691   SmallVector<SDValue, 8> Ops;
8692   DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
8693 
8694   SDValue Res = Ops[0];
8695   for (unsigned i = 1; i < NumElts; i++)
8696     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags());
8697 
8698   // Result type may be wider than element type.
8699   if (EltVT != Node->getValueType(0))
8700     Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
8701   return Res;
8702 }
8703 
8704 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const {
8705   SDLoc dl(Node);
8706   SDValue AccOp = Node->getOperand(0);
8707   SDValue VecOp = Node->getOperand(1);
8708   SDNodeFlags Flags = Node->getFlags();
8709 
8710   EVT VT = VecOp.getValueType();
8711   EVT EltVT = VT.getVectorElementType();
8712 
8713   if (VT.isScalableVector())
8714     report_fatal_error(
8715         "Expanding reductions for scalable vectors is undefined.");
8716 
8717   unsigned NumElts = VT.getVectorNumElements();
8718 
8719   SmallVector<SDValue, 8> Ops;
8720   DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
8721 
8722   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
8723 
8724   SDValue Res = AccOp;
8725   for (unsigned i = 0; i < NumElts; i++)
8726     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
8727 
8728   return Res;
8729 }
8730 
8731 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result,
8732                                SelectionDAG &DAG) const {
8733   EVT VT = Node->getValueType(0);
8734   SDLoc dl(Node);
8735   bool isSigned = Node->getOpcode() == ISD::SREM;
8736   unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
8737   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
8738   SDValue Dividend = Node->getOperand(0);
8739   SDValue Divisor = Node->getOperand(1);
8740   if (isOperationLegalOrCustom(DivRemOpc, VT)) {
8741     SDVTList VTs = DAG.getVTList(VT, VT);
8742     Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
8743     return true;
8744   }
8745   if (isOperationLegalOrCustom(DivOpc, VT)) {
8746     // X % Y -> X-X/Y*Y
8747     SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
8748     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
8749     Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
8750     return true;
8751   }
8752   return false;
8753 }
8754 
8755 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node,
8756                                             SelectionDAG &DAG) const {
8757   bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
8758   SDLoc dl(SDValue(Node, 0));
8759   SDValue Src = Node->getOperand(0);
8760 
8761   // DstVT is the result type, while SatVT is the size to which we saturate
8762   EVT SrcVT = Src.getValueType();
8763   EVT DstVT = Node->getValueType(0);
8764 
8765   EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
8766   unsigned SatWidth = SatVT.getScalarSizeInBits();
8767   unsigned DstWidth = DstVT.getScalarSizeInBits();
8768   assert(SatWidth <= DstWidth &&
8769          "Expected saturation width smaller than result width");
8770 
8771   // Determine minimum and maximum integer values and their corresponding
8772   // floating-point values.
8773   APInt MinInt, MaxInt;
8774   if (IsSigned) {
8775     MinInt = APInt::getSignedMinValue(SatWidth).sextOrSelf(DstWidth);
8776     MaxInt = APInt::getSignedMaxValue(SatWidth).sextOrSelf(DstWidth);
8777   } else {
8778     MinInt = APInt::getMinValue(SatWidth).zextOrSelf(DstWidth);
8779     MaxInt = APInt::getMaxValue(SatWidth).zextOrSelf(DstWidth);
8780   }
8781 
8782   // We cannot risk emitting FP_TO_XINT nodes with a source VT of f16, as
8783   // libcall emission cannot handle this. Large result types will fail.
8784   if (SrcVT == MVT::f16) {
8785     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
8786     SrcVT = Src.getValueType();
8787   }
8788 
8789   APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT));
8790   APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT));
8791 
8792   APFloat::opStatus MinStatus =
8793       MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
8794   APFloat::opStatus MaxStatus =
8795       MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
8796   bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
8797                              !(MaxStatus & APFloat::opStatus::opInexact);
8798 
8799   SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
8800   SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
8801 
8802   // If the integer bounds are exactly representable as floats and min/max are
8803   // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
8804   // of comparisons and selects.
8805   bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) &&
8806                      isOperationLegal(ISD::FMAXNUM, SrcVT);
8807   if (AreExactFloatBounds && MinMaxLegal) {
8808     SDValue Clamped = Src;
8809 
8810     // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat.
8811     Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode);
8812     // Clamp by MaxFloat from above. NaN cannot occur.
8813     Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode);
8814     // Convert clamped value to integer.
8815     SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
8816                                   dl, DstVT, Clamped);
8817 
8818     // In the unsigned case we're done, because we mapped NaN to MinFloat,
8819     // which will cast to zero.
8820     if (!IsSigned)
8821       return FpToInt;
8822 
8823     // Otherwise, select 0 if Src is NaN.
8824     SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
8825     return DAG.getSelectCC(dl, Src, Src, ZeroInt, FpToInt,
8826                            ISD::CondCode::SETUO);
8827   }
8828 
8829   SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
8830   SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
8831 
8832   // Result of direct conversion. The assumption here is that the operation is
8833   // non-trapping and it's fine to apply it to an out-of-range value if we
8834   // select it away later.
8835   SDValue FpToInt =
8836       DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
8837 
8838   SDValue Select = FpToInt;
8839 
8840   // If Src ULT MinFloat, select MinInt. In particular, this also selects
8841   // MinInt if Src is NaN.
8842   Select = DAG.getSelectCC(dl, Src, MinFloatNode, MinIntNode, Select,
8843                            ISD::CondCode::SETULT);
8844   // If Src OGT MaxFloat, select MaxInt.
8845   Select = DAG.getSelectCC(dl, Src, MaxFloatNode, MaxIntNode, Select,
8846                            ISD::CondCode::SETOGT);
8847 
8848   // In the unsigned case we are done, because we mapped NaN to MinInt, which
8849   // is already zero.
8850   if (!IsSigned)
8851     return Select;
8852 
8853   // Otherwise, select 0 if Src is NaN.
8854   SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
8855   return DAG.getSelectCC(dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO);
8856 }
8857 
8858 SDValue TargetLowering::expandVectorSplice(SDNode *Node,
8859                                            SelectionDAG &DAG) const {
8860   assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!");
8861   assert(Node->getValueType(0).isScalableVector() &&
8862          "Fixed length vector types expected to use SHUFFLE_VECTOR!");
8863 
8864   EVT VT = Node->getValueType(0);
8865   SDValue V1 = Node->getOperand(0);
8866   SDValue V2 = Node->getOperand(1);
8867   int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue();
8868   SDLoc DL(Node);
8869 
8870   // Expand through memory thusly:
8871   //  Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
8872   //  Store V1, Ptr
8873   //  Store V2, Ptr + sizeof(V1)
8874   //  If (Imm < 0)
8875   //    TrailingElts = -Imm
8876   //    Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt))
8877   //  else
8878   //    Ptr = Ptr + (Imm * sizeof(VT.Elt))
8879   //  Res = Load Ptr
8880 
8881   Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
8882 
8883   EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
8884                                VT.getVectorElementCount() * 2);
8885   SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
8886   EVT PtrVT = StackPtr.getValueType();
8887   auto &MF = DAG.getMachineFunction();
8888   auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
8889   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
8890 
8891   // Store the lo part of CONCAT_VECTORS(V1, V2)
8892   SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo);
8893   // Store the hi part of CONCAT_VECTORS(V1, V2)
8894   SDValue OffsetToV2 = DAG.getVScale(
8895       DL, PtrVT,
8896       APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize()));
8897   SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2);
8898   SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo);
8899 
8900   if (Imm >= 0) {
8901     // Load back the required element. getVectorElementPointer takes care of
8902     // clamping the index if it's out-of-bounds.
8903     StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2));
8904     // Load the spliced result
8905     return DAG.getLoad(VT, DL, StoreV2, StackPtr,
8906                        MachinePointerInfo::getUnknownStack(MF));
8907   }
8908 
8909   uint64_t TrailingElts = -Imm;
8910 
8911   // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2.
8912   TypeSize EltByteSize = VT.getVectorElementType().getStoreSize();
8913   SDValue TrailingBytes =
8914       DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT);
8915 
8916   if (TrailingElts > VT.getVectorMinNumElements()) {
8917     SDValue VLBytes = DAG.getVScale(
8918         DL, PtrVT,
8919         APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize()));
8920     TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes);
8921   }
8922 
8923   // Calculate the start address of the spliced result.
8924   StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
8925 
8926   // Load the spliced result
8927   return DAG.getLoad(VT, DL, StoreV2, StackPtr2,
8928                      MachinePointerInfo::getUnknownStack(MF));
8929 }
8930 
8931 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT,
8932                                            SDValue &LHS, SDValue &RHS,
8933                                            SDValue &CC, bool &NeedInvert,
8934                                            const SDLoc &dl, SDValue &Chain,
8935                                            bool IsSignaling) const {
8936   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8937   MVT OpVT = LHS.getSimpleValueType();
8938   ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
8939   NeedInvert = false;
8940   switch (TLI.getCondCodeAction(CCCode, OpVT)) {
8941   default:
8942     llvm_unreachable("Unknown condition code action!");
8943   case TargetLowering::Legal:
8944     // Nothing to do.
8945     break;
8946   case TargetLowering::Expand: {
8947     ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode);
8948     if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
8949       std::swap(LHS, RHS);
8950       CC = DAG.getCondCode(InvCC);
8951       return true;
8952     }
8953     // Swapping operands didn't work. Try inverting the condition.
8954     bool NeedSwap = false;
8955     InvCC = getSetCCInverse(CCCode, OpVT);
8956     if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
8957       // If inverting the condition is not enough, try swapping operands
8958       // on top of it.
8959       InvCC = ISD::getSetCCSwappedOperands(InvCC);
8960       NeedSwap = true;
8961     }
8962     if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
8963       CC = DAG.getCondCode(InvCC);
8964       NeedInvert = true;
8965       if (NeedSwap)
8966         std::swap(LHS, RHS);
8967       return true;
8968     }
8969 
8970     ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
8971     unsigned Opc = 0;
8972     switch (CCCode) {
8973     default:
8974       llvm_unreachable("Don't know how to expand this condition!");
8975     case ISD::SETUO:
8976       if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) {
8977         CC1 = ISD::SETUNE;
8978         CC2 = ISD::SETUNE;
8979         Opc = ISD::OR;
8980         break;
8981       }
8982       assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) &&
8983              "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
8984       NeedInvert = true;
8985       LLVM_FALLTHROUGH;
8986     case ISD::SETO:
8987       assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) &&
8988              "If SETO is expanded, SETOEQ must be legal!");
8989       CC1 = ISD::SETOEQ;
8990       CC2 = ISD::SETOEQ;
8991       Opc = ISD::AND;
8992       break;
8993     case ISD::SETONE:
8994     case ISD::SETUEQ:
8995       // If the SETUO or SETO CC isn't legal, we might be able to use
8996       // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
8997       // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
8998       // the operands.
8999       CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
9000       if (!TLI.isCondCodeLegal(CC2, OpVT) &&
9001           (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) ||
9002            TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) {
9003         CC1 = ISD::SETOGT;
9004         CC2 = ISD::SETOLT;
9005         Opc = ISD::OR;
9006         NeedInvert = ((unsigned)CCCode & 0x8U);
9007         break;
9008       }
9009       LLVM_FALLTHROUGH;
9010     case ISD::SETOEQ:
9011     case ISD::SETOGT:
9012     case ISD::SETOGE:
9013     case ISD::SETOLT:
9014     case ISD::SETOLE:
9015     case ISD::SETUNE:
9016     case ISD::SETUGT:
9017     case ISD::SETUGE:
9018     case ISD::SETULT:
9019     case ISD::SETULE:
9020       // If we are floating point, assign and break, otherwise fall through.
9021       if (!OpVT.isInteger()) {
9022         // We can use the 4th bit to tell if we are the unordered
9023         // or ordered version of the opcode.
9024         CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
9025         Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
9026         CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
9027         break;
9028       }
9029       // Fallthrough if we are unsigned integer.
9030       LLVM_FALLTHROUGH;
9031     case ISD::SETLE:
9032     case ISD::SETGT:
9033     case ISD::SETGE:
9034     case ISD::SETLT:
9035     case ISD::SETNE:
9036     case ISD::SETEQ:
9037       // If all combinations of inverting the condition and swapping operands
9038       // didn't work then we have no means to expand the condition.
9039       llvm_unreachable("Don't know how to expand this condition!");
9040     }
9041 
9042     SDValue SetCC1, SetCC2;
9043     if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
9044       // If we aren't the ordered or unorder operation,
9045       // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
9046       SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
9047       SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
9048     } else {
9049       // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
9050       SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
9051       SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
9052     }
9053     if (Chain)
9054       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
9055                           SetCC2.getValue(1));
9056     LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
9057     RHS = SDValue();
9058     CC = SDValue();
9059     return true;
9060   }
9061   }
9062   return false;
9063 }
9064