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