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