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/CodeGenCommonISel.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineJumpTableInfo.h"
20 #include "llvm/CodeGen/MachineRegisterInfo.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/CodeGen/TargetRegisterInfo.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/GlobalVariable.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/Support/DivisionByConstantInfo.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/KnownBits.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include <cctype>
35 using namespace llvm;
36 
37 /// NOTE: The TargetMachine owns TLOF.
38 TargetLowering::TargetLowering(const TargetMachine &tm)
39     : TargetLoweringBase(tm) {}
40 
41 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
42   return nullptr;
43 }
44 
45 bool TargetLowering::isPositionIndependent() const {
46   return getTargetMachine().isPositionIndependent();
47 }
48 
49 /// Check whether a given call node is in tail position within its function. If
50 /// so, it sets Chain to the input chain of the tail call.
51 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
52                                           SDValue &Chain) const {
53   const Function &F = DAG.getMachineFunction().getFunction();
54 
55   // First, check if tail calls have been disabled in this function.
56   if (F.getFnAttribute("disable-tail-calls").getValueAsBool())
57     return false;
58 
59   // Conservatively require the attributes of the call to match those of
60   // the return. Ignore following attributes because they don't affect the
61   // call sequence.
62   AttrBuilder CallerAttrs(F.getContext(), F.getAttributes().getRetAttrs());
63   for (const auto &Attr : {Attribute::Alignment, Attribute::Dereferenceable,
64                            Attribute::DereferenceableOrNull, Attribute::NoAlias,
65                            Attribute::NonNull, Attribute::NoUndef})
66     CallerAttrs.removeAttribute(Attr);
67 
68   if (CallerAttrs.hasAttributes())
69     return false;
70 
71   // It's not safe to eliminate the sign / zero extension of the return value.
72   if (CallerAttrs.contains(Attribute::ZExt) ||
73       CallerAttrs.contains(Attribute::SExt))
74     return false;
75 
76   // Check if the only use is a function return node.
77   return isUsedByReturnOnly(Node, Chain);
78 }
79 
80 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
81     const uint32_t *CallerPreservedMask,
82     const SmallVectorImpl<CCValAssign> &ArgLocs,
83     const SmallVectorImpl<SDValue> &OutVals) const {
84   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
85     const CCValAssign &ArgLoc = ArgLocs[I];
86     if (!ArgLoc.isRegLoc())
87       continue;
88     MCRegister Reg = ArgLoc.getLocReg();
89     // Only look at callee saved registers.
90     if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
91       continue;
92     // Check that we pass the value used for the caller.
93     // (We look for a CopyFromReg reading a virtual register that is used
94     //  for the function live-in value of register Reg)
95     SDValue Value = OutVals[I];
96     if (Value->getOpcode() == ISD::AssertZext)
97       Value = Value.getOperand(0);
98     if (Value->getOpcode() != ISD::CopyFromReg)
99       return false;
100     Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
101     if (MRI.getLiveInPhysReg(ArgReg) != Reg)
102       return false;
103   }
104   return true;
105 }
106 
107 /// Set CallLoweringInfo attribute flags based on a call instruction
108 /// and called function attributes.
109 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase *Call,
110                                                      unsigned ArgIdx) {
111   IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt);
112   IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt);
113   IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg);
114   IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet);
115   IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest);
116   IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal);
117   IsPreallocated = Call->paramHasAttr(ArgIdx, Attribute::Preallocated);
118   IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca);
119   IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned);
120   IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf);
121   IsSwiftAsync = Call->paramHasAttr(ArgIdx, Attribute::SwiftAsync);
122   IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError);
123   Alignment = Call->getParamStackAlign(ArgIdx);
124   IndirectType = nullptr;
125   assert(IsByVal + IsPreallocated + IsInAlloca + IsSRet <= 1 &&
126          "multiple ABI attributes?");
127   if (IsByVal) {
128     IndirectType = Call->getParamByValType(ArgIdx);
129     if (!Alignment)
130       Alignment = Call->getParamAlign(ArgIdx);
131   }
132   if (IsPreallocated)
133     IndirectType = Call->getParamPreallocatedType(ArgIdx);
134   if (IsInAlloca)
135     IndirectType = Call->getParamInAllocaType(ArgIdx);
136   if (IsSRet)
137     IndirectType = Call->getParamStructRetType(ArgIdx);
138 }
139 
140 /// Generate a libcall taking the given operands as arguments and returning a
141 /// result of type RetVT.
142 std::pair<SDValue, SDValue>
143 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
144                             ArrayRef<SDValue> Ops,
145                             MakeLibCallOptions CallOptions,
146                             const SDLoc &dl,
147                             SDValue InChain) const {
148   if (!InChain)
149     InChain = DAG.getEntryNode();
150 
151   TargetLowering::ArgListTy Args;
152   Args.reserve(Ops.size());
153 
154   TargetLowering::ArgListEntry Entry;
155   for (unsigned i = 0; i < Ops.size(); ++i) {
156     SDValue NewOp = Ops[i];
157     Entry.Node = NewOp;
158     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
159     Entry.IsSExt = shouldSignExtendTypeInLibCall(NewOp.getValueType(),
160                                                  CallOptions.IsSExt);
161     Entry.IsZExt = !Entry.IsSExt;
162 
163     if (CallOptions.IsSoften &&
164         !shouldExtendTypeInLibCall(CallOptions.OpsVTBeforeSoften[i])) {
165       Entry.IsSExt = Entry.IsZExt = false;
166     }
167     Args.push_back(Entry);
168   }
169 
170   if (LC == RTLIB::UNKNOWN_LIBCALL)
171     report_fatal_error("Unsupported library call operation!");
172   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
173                                          getPointerTy(DAG.getDataLayout()));
174 
175   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
176   TargetLowering::CallLoweringInfo CLI(DAG);
177   bool signExtend = shouldSignExtendTypeInLibCall(RetVT, CallOptions.IsSExt);
178   bool zeroExtend = !signExtend;
179 
180   if (CallOptions.IsSoften &&
181       !shouldExtendTypeInLibCall(CallOptions.RetVTBeforeSoften)) {
182     signExtend = zeroExtend = false;
183   }
184 
185   CLI.setDebugLoc(dl)
186       .setChain(InChain)
187       .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
188       .setNoReturn(CallOptions.DoesNotReturn)
189       .setDiscardResult(!CallOptions.IsReturnValueUsed)
190       .setIsPostTypeLegalization(CallOptions.IsPostTypeLegalization)
191       .setSExtResult(signExtend)
192       .setZExtResult(zeroExtend);
193   return LowerCallTo(CLI);
194 }
195 
196 bool TargetLowering::findOptimalMemOpLowering(
197     std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS,
198     unsigned SrcAS, const AttributeList &FuncAttributes) const {
199   if (Limit != ~unsigned(0) && Op.isMemcpyWithFixedDstAlign() &&
200       Op.getSrcAlign() < Op.getDstAlign())
201     return false;
202 
203   EVT VT = getOptimalMemOpType(Op, FuncAttributes);
204 
205   if (VT == MVT::Other) {
206     // Use the largest integer type whose alignment constraints are satisfied.
207     // We only need to check DstAlign here as SrcAlign is always greater or
208     // equal to DstAlign (or zero).
209     VT = MVT::i64;
210     if (Op.isFixedDstAlign())
211       while (Op.getDstAlign() < (VT.getSizeInBits() / 8) &&
212              !allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign()))
213         VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
214     assert(VT.isInteger());
215 
216     // Find the largest legal integer type.
217     MVT LVT = MVT::i64;
218     while (!isTypeLegal(LVT))
219       LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
220     assert(LVT.isInteger());
221 
222     // If the type we've chosen is larger than the largest legal integer type
223     // then use that instead.
224     if (VT.bitsGT(LVT))
225       VT = LVT;
226   }
227 
228   unsigned NumMemOps = 0;
229   uint64_t Size = Op.size();
230   while (Size) {
231     unsigned VTSize = VT.getSizeInBits() / 8;
232     while (VTSize > Size) {
233       // For now, only use non-vector load / store's for the left-over pieces.
234       EVT NewVT = VT;
235       unsigned NewVTSize;
236 
237       bool Found = false;
238       if (VT.isVector() || VT.isFloatingPoint()) {
239         NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
240         if (isOperationLegalOrCustom(ISD::STORE, NewVT) &&
241             isSafeMemOpType(NewVT.getSimpleVT()))
242           Found = true;
243         else if (NewVT == MVT::i64 &&
244                  isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
245                  isSafeMemOpType(MVT::f64)) {
246           // i64 is usually not legal on 32-bit targets, but f64 may be.
247           NewVT = MVT::f64;
248           Found = true;
249         }
250       }
251 
252       if (!Found) {
253         do {
254           NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
255           if (NewVT == MVT::i8)
256             break;
257         } while (!isSafeMemOpType(NewVT.getSimpleVT()));
258       }
259       NewVTSize = NewVT.getSizeInBits() / 8;
260 
261       // If the new VT cannot cover all of the remaining bits, then consider
262       // issuing a (or a pair of) unaligned and overlapping load / store.
263       bool Fast;
264       if (NumMemOps && Op.allowOverlap() && NewVTSize < Size &&
265           allowsMisalignedMemoryAccesses(
266               VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1),
267               MachineMemOperand::MONone, &Fast) &&
268           Fast)
269         VTSize = Size;
270       else {
271         VT = NewVT;
272         VTSize = NewVTSize;
273       }
274     }
275 
276     if (++NumMemOps > Limit)
277       return false;
278 
279     MemOps.push_back(VT);
280     Size -= VTSize;
281   }
282 
283   return true;
284 }
285 
286 /// Soften the operands of a comparison. This code is shared among BR_CC,
287 /// SELECT_CC, and SETCC handlers.
288 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
289                                          SDValue &NewLHS, SDValue &NewRHS,
290                                          ISD::CondCode &CCCode,
291                                          const SDLoc &dl, const SDValue OldLHS,
292                                          const SDValue OldRHS) const {
293   SDValue Chain;
294   return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS,
295                              OldRHS, Chain);
296 }
297 
298 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
299                                          SDValue &NewLHS, SDValue &NewRHS,
300                                          ISD::CondCode &CCCode,
301                                          const SDLoc &dl, const SDValue OldLHS,
302                                          const SDValue OldRHS,
303                                          SDValue &Chain,
304                                          bool IsSignaling) const {
305   // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc
306   // not supporting it. We can update this code when libgcc provides such
307   // functions.
308 
309   assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
310          && "Unsupported setcc type!");
311 
312   // Expand into one or more soft-fp libcall(s).
313   RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
314   bool ShouldInvertCC = false;
315   switch (CCCode) {
316   case ISD::SETEQ:
317   case ISD::SETOEQ:
318     LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
319           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
320           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
321     break;
322   case ISD::SETNE:
323   case ISD::SETUNE:
324     LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
325           (VT == MVT::f64) ? RTLIB::UNE_F64 :
326           (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
327     break;
328   case ISD::SETGE:
329   case ISD::SETOGE:
330     LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
331           (VT == MVT::f64) ? RTLIB::OGE_F64 :
332           (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
333     break;
334   case ISD::SETLT:
335   case ISD::SETOLT:
336     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
337           (VT == MVT::f64) ? RTLIB::OLT_F64 :
338           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
339     break;
340   case ISD::SETLE:
341   case ISD::SETOLE:
342     LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
343           (VT == MVT::f64) ? RTLIB::OLE_F64 :
344           (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
345     break;
346   case ISD::SETGT:
347   case ISD::SETOGT:
348     LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
349           (VT == MVT::f64) ? RTLIB::OGT_F64 :
350           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
351     break;
352   case ISD::SETO:
353     ShouldInvertCC = true;
354     LLVM_FALLTHROUGH;
355   case ISD::SETUO:
356     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
357           (VT == MVT::f64) ? RTLIB::UO_F64 :
358           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
359     break;
360   case ISD::SETONE:
361     // SETONE = O && UNE
362     ShouldInvertCC = true;
363     LLVM_FALLTHROUGH;
364   case ISD::SETUEQ:
365     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
366           (VT == MVT::f64) ? RTLIB::UO_F64 :
367           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
368     LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
369           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
370           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
371     break;
372   default:
373     // Invert CC for unordered comparisons
374     ShouldInvertCC = true;
375     switch (CCCode) {
376     case ISD::SETULT:
377       LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
378             (VT == MVT::f64) ? RTLIB::OGE_F64 :
379             (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
380       break;
381     case ISD::SETULE:
382       LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
383             (VT == MVT::f64) ? RTLIB::OGT_F64 :
384             (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
385       break;
386     case ISD::SETUGT:
387       LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
388             (VT == MVT::f64) ? RTLIB::OLE_F64 :
389             (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
390       break;
391     case ISD::SETUGE:
392       LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
393             (VT == MVT::f64) ? RTLIB::OLT_F64 :
394             (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
395       break;
396     default: llvm_unreachable("Do not know how to soften this setcc!");
397     }
398   }
399 
400   // Use the target specific return value for comparions lib calls.
401   EVT RetVT = getCmpLibcallReturnType();
402   SDValue Ops[2] = {NewLHS, NewRHS};
403   TargetLowering::MakeLibCallOptions CallOptions;
404   EVT OpsVT[2] = { OldLHS.getValueType(),
405                    OldRHS.getValueType() };
406   CallOptions.setTypeListBeforeSoften(OpsVT, RetVT, true);
407   auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain);
408   NewLHS = Call.first;
409   NewRHS = DAG.getConstant(0, dl, RetVT);
410 
411   CCCode = getCmpLibcallCC(LC1);
412   if (ShouldInvertCC) {
413     assert(RetVT.isInteger());
414     CCCode = getSetCCInverse(CCCode, RetVT);
415   }
416 
417   if (LC2 == RTLIB::UNKNOWN_LIBCALL) {
418     // Update Chain.
419     Chain = Call.second;
420   } else {
421     EVT SetCCVT =
422         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT);
423     SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode);
424     auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain);
425     CCCode = getCmpLibcallCC(LC2);
426     if (ShouldInvertCC)
427       CCCode = getSetCCInverse(CCCode, RetVT);
428     NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode);
429     if (Chain)
430       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second,
431                           Call2.second);
432     NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl,
433                          Tmp.getValueType(), Tmp, NewLHS);
434     NewRHS = SDValue();
435   }
436 }
437 
438 /// Return the entry encoding for a jump table in the current function. The
439 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
440 unsigned TargetLowering::getJumpTableEncoding() const {
441   // In non-pic modes, just use the address of a block.
442   if (!isPositionIndependent())
443     return MachineJumpTableInfo::EK_BlockAddress;
444 
445   // In PIC mode, if the target supports a GPRel32 directive, use it.
446   if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
447     return MachineJumpTableInfo::EK_GPRel32BlockAddress;
448 
449   // Otherwise, use a label difference.
450   return MachineJumpTableInfo::EK_LabelDifference32;
451 }
452 
453 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
454                                                  SelectionDAG &DAG) const {
455   // If our PIC model is GP relative, use the global offset table as the base.
456   unsigned JTEncoding = getJumpTableEncoding();
457 
458   if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
459       (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
460     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
461 
462   return Table;
463 }
464 
465 /// This returns the relocation base for the given PIC jumptable, the same as
466 /// getPICJumpTableRelocBase, but as an MCExpr.
467 const MCExpr *
468 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
469                                              unsigned JTI,MCContext &Ctx) const{
470   // The normal PIC reloc base is the label at the start of the jump table.
471   return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
472 }
473 
474 bool
475 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
476   const TargetMachine &TM = getTargetMachine();
477   const GlobalValue *GV = GA->getGlobal();
478 
479   // If the address is not even local to this DSO we will have to load it from
480   // a got and then add the offset.
481   if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
482     return false;
483 
484   // If the code is position independent we will have to add a base register.
485   if (isPositionIndependent())
486     return false;
487 
488   // Otherwise we can do it.
489   return true;
490 }
491 
492 //===----------------------------------------------------------------------===//
493 //  Optimization Methods
494 //===----------------------------------------------------------------------===//
495 
496 /// If the specified instruction has a constant integer operand and there are
497 /// bits set in that constant that are not demanded, then clear those bits and
498 /// return true.
499 bool TargetLowering::ShrinkDemandedConstant(SDValue Op,
500                                             const APInt &DemandedBits,
501                                             const APInt &DemandedElts,
502                                             TargetLoweringOpt &TLO) const {
503   SDLoc DL(Op);
504   unsigned Opcode = Op.getOpcode();
505 
506   // Do target-specific constant optimization.
507   if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
508     return TLO.New.getNode();
509 
510   // FIXME: ISD::SELECT, ISD::SELECT_CC
511   switch (Opcode) {
512   default:
513     break;
514   case ISD::XOR:
515   case ISD::AND:
516   case ISD::OR: {
517     auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
518     if (!Op1C || Op1C->isOpaque())
519       return false;
520 
521     // If this is a 'not' op, don't touch it because that's a canonical form.
522     const APInt &C = Op1C->getAPIntValue();
523     if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C))
524       return false;
525 
526     if (!C.isSubsetOf(DemandedBits)) {
527       EVT VT = Op.getValueType();
528       SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT);
529       SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC);
530       return TLO.CombineTo(Op, NewOp);
531     }
532 
533     break;
534   }
535   }
536 
537   return false;
538 }
539 
540 bool TargetLowering::ShrinkDemandedConstant(SDValue Op,
541                                             const APInt &DemandedBits,
542                                             TargetLoweringOpt &TLO) const {
543   EVT VT = Op.getValueType();
544   APInt DemandedElts = VT.isVector()
545                            ? APInt::getAllOnes(VT.getVectorNumElements())
546                            : APInt(1, 1);
547   return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO);
548 }
549 
550 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
551 /// This uses isZExtFree and ZERO_EXTEND for the widening cast, but it could be
552 /// generalized for targets with other types of implicit widening casts.
553 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth,
554                                       const APInt &Demanded,
555                                       TargetLoweringOpt &TLO) const {
556   assert(Op.getNumOperands() == 2 &&
557          "ShrinkDemandedOp only supports binary operators!");
558   assert(Op.getNode()->getNumValues() == 1 &&
559          "ShrinkDemandedOp only supports nodes with one result!");
560 
561   SelectionDAG &DAG = TLO.DAG;
562   SDLoc dl(Op);
563 
564   // Early return, as this function cannot handle vector types.
565   if (Op.getValueType().isVector())
566     return false;
567 
568   // Don't do this if the node has another user, which may require the
569   // full value.
570   if (!Op.getNode()->hasOneUse())
571     return false;
572 
573   // Search for the smallest integer type with free casts to and from
574   // Op's type. For expedience, just check power-of-2 integer types.
575   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
576   unsigned DemandedSize = Demanded.getActiveBits();
577   unsigned SmallVTBits = DemandedSize;
578   if (!isPowerOf2_32(SmallVTBits))
579     SmallVTBits = NextPowerOf2(SmallVTBits);
580   for (; SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
581     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
582     if (TLI.isTruncateFree(Op.getValueType(), SmallVT) &&
583         TLI.isZExtFree(SmallVT, Op.getValueType())) {
584       // We found a type with free casts.
585       SDValue X = DAG.getNode(
586           Op.getOpcode(), dl, SmallVT,
587           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
588           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)));
589       assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
590       SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, Op.getValueType(), X);
591       return TLO.CombineTo(Op, Z);
592     }
593   }
594   return false;
595 }
596 
597 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
598                                           DAGCombinerInfo &DCI) const {
599   SelectionDAG &DAG = DCI.DAG;
600   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
601                         !DCI.isBeforeLegalizeOps());
602   KnownBits Known;
603 
604   bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO);
605   if (Simplified) {
606     DCI.AddToWorklist(Op.getNode());
607     DCI.CommitTargetLoweringOpt(TLO);
608   }
609   return Simplified;
610 }
611 
612 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
613                                           const APInt &DemandedElts,
614                                           DAGCombinerInfo &DCI) const {
615   SelectionDAG &DAG = DCI.DAG;
616   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
617                         !DCI.isBeforeLegalizeOps());
618   KnownBits Known;
619 
620   bool Simplified =
621       SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO);
622   if (Simplified) {
623     DCI.AddToWorklist(Op.getNode());
624     DCI.CommitTargetLoweringOpt(TLO);
625   }
626   return Simplified;
627 }
628 
629 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
630                                           KnownBits &Known,
631                                           TargetLoweringOpt &TLO,
632                                           unsigned Depth,
633                                           bool AssumeSingleUse) const {
634   EVT VT = Op.getValueType();
635 
636   // TODO: We can probably do more work on calculating the known bits and
637   // simplifying the operations for scalable vectors, but for now we just
638   // bail out.
639   if (VT.isScalableVector()) {
640     // Pretend we don't know anything for now.
641     Known = KnownBits(DemandedBits.getBitWidth());
642     return false;
643   }
644 
645   APInt DemandedElts = VT.isVector()
646                            ? APInt::getAllOnes(VT.getVectorNumElements())
647                            : APInt(1, 1);
648   return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth,
649                               AssumeSingleUse);
650 }
651 
652 // TODO: Can we merge SelectionDAG::GetDemandedBits into this?
653 // TODO: Under what circumstances can we create nodes? Constant folding?
654 SDValue TargetLowering::SimplifyMultipleUseDemandedBits(
655     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
656     SelectionDAG &DAG, unsigned Depth) const {
657   // Limit search depth.
658   if (Depth >= SelectionDAG::MaxRecursionDepth)
659     return SDValue();
660 
661   // Ignore UNDEFs.
662   if (Op.isUndef())
663     return SDValue();
664 
665   // Not demanding any bits/elts from Op.
666   if (DemandedBits == 0 || DemandedElts == 0)
667     return DAG.getUNDEF(Op.getValueType());
668 
669   bool IsLE = DAG.getDataLayout().isLittleEndian();
670   unsigned NumElts = DemandedElts.getBitWidth();
671   unsigned BitWidth = DemandedBits.getBitWidth();
672   KnownBits LHSKnown, RHSKnown;
673   switch (Op.getOpcode()) {
674   case ISD::BITCAST: {
675     SDValue Src = peekThroughBitcasts(Op.getOperand(0));
676     EVT SrcVT = Src.getValueType();
677     EVT DstVT = Op.getValueType();
678     if (SrcVT == DstVT)
679       return Src;
680 
681     unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
682     unsigned NumDstEltBits = DstVT.getScalarSizeInBits();
683     if (NumSrcEltBits == NumDstEltBits)
684       if (SDValue V = SimplifyMultipleUseDemandedBits(
685               Src, DemandedBits, DemandedElts, DAG, Depth + 1))
686         return DAG.getBitcast(DstVT, V);
687 
688     if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) {
689       unsigned Scale = NumDstEltBits / NumSrcEltBits;
690       unsigned NumSrcElts = SrcVT.getVectorNumElements();
691       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
692       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
693       for (unsigned i = 0; i != Scale; ++i) {
694         unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
695         unsigned BitOffset = EltOffset * NumSrcEltBits;
696         APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset);
697         if (!Sub.isZero()) {
698           DemandedSrcBits |= Sub;
699           for (unsigned j = 0; j != NumElts; ++j)
700             if (DemandedElts[j])
701               DemandedSrcElts.setBit((j * Scale) + i);
702         }
703       }
704 
705       if (SDValue V = SimplifyMultipleUseDemandedBits(
706               Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
707         return DAG.getBitcast(DstVT, V);
708     }
709 
710     // TODO - bigendian once we have test coverage.
711     if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) {
712       unsigned Scale = NumSrcEltBits / NumDstEltBits;
713       unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
714       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
715       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
716       for (unsigned i = 0; i != NumElts; ++i)
717         if (DemandedElts[i]) {
718           unsigned Offset = (i % Scale) * NumDstEltBits;
719           DemandedSrcBits.insertBits(DemandedBits, Offset);
720           DemandedSrcElts.setBit(i / Scale);
721         }
722 
723       if (SDValue V = SimplifyMultipleUseDemandedBits(
724               Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
725         return DAG.getBitcast(DstVT, V);
726     }
727 
728     break;
729   }
730   case ISD::AND: {
731     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
732     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
733 
734     // If all of the demanded bits are known 1 on one side, return the other.
735     // These bits cannot contribute to the result of the 'and' in this
736     // context.
737     if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
738       return Op.getOperand(0);
739     if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
740       return Op.getOperand(1);
741     break;
742   }
743   case ISD::OR: {
744     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
745     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
746 
747     // If all of the demanded bits are known zero on one side, return the
748     // other.  These bits cannot contribute to the result of the 'or' in this
749     // context.
750     if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
751       return Op.getOperand(0);
752     if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
753       return Op.getOperand(1);
754     break;
755   }
756   case ISD::XOR: {
757     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
758     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
759 
760     // If all of the demanded bits are known zero on one side, return the
761     // other.
762     if (DemandedBits.isSubsetOf(RHSKnown.Zero))
763       return Op.getOperand(0);
764     if (DemandedBits.isSubsetOf(LHSKnown.Zero))
765       return Op.getOperand(1);
766     break;
767   }
768   case ISD::SHL: {
769     // If we are only demanding sign bits then we can use the shift source
770     // directly.
771     if (const APInt *MaxSA =
772             DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
773       SDValue Op0 = Op.getOperand(0);
774       unsigned ShAmt = MaxSA->getZExtValue();
775       unsigned NumSignBits =
776           DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
777       unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
778       if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
779         return Op0;
780     }
781     break;
782   }
783   case ISD::SETCC: {
784     SDValue Op0 = Op.getOperand(0);
785     SDValue Op1 = Op.getOperand(1);
786     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
787     // If (1) we only need the sign-bit, (2) the setcc operands are the same
788     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
789     // -1, we may be able to bypass the setcc.
790     if (DemandedBits.isSignMask() &&
791         Op0.getScalarValueSizeInBits() == BitWidth &&
792         getBooleanContents(Op0.getValueType()) ==
793             BooleanContent::ZeroOrNegativeOneBooleanContent) {
794       // If we're testing X < 0, then this compare isn't needed - just use X!
795       // FIXME: We're limiting to integer types here, but this should also work
796       // if we don't care about FP signed-zero. The use of SETLT with FP means
797       // that we don't care about NaNs.
798       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
799           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
800         return Op0;
801     }
802     break;
803   }
804   case ISD::SIGN_EXTEND_INREG: {
805     // If none of the extended bits are demanded, eliminate the sextinreg.
806     SDValue Op0 = Op.getOperand(0);
807     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
808     unsigned ExBits = ExVT.getScalarSizeInBits();
809     if (DemandedBits.getActiveBits() <= ExBits)
810       return Op0;
811     // If the input is already sign extended, just drop the extension.
812     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
813     if (NumSignBits >= (BitWidth - ExBits + 1))
814       return Op0;
815     break;
816   }
817   case ISD::ANY_EXTEND_VECTOR_INREG:
818   case ISD::SIGN_EXTEND_VECTOR_INREG:
819   case ISD::ZERO_EXTEND_VECTOR_INREG: {
820     // If we only want the lowest element and none of extended bits, then we can
821     // return the bitcasted source vector.
822     SDValue Src = Op.getOperand(0);
823     EVT SrcVT = Src.getValueType();
824     EVT DstVT = Op.getValueType();
825     if (IsLE && DemandedElts == 1 &&
826         DstVT.getSizeInBits() == SrcVT.getSizeInBits() &&
827         DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) {
828       return DAG.getBitcast(DstVT, Src);
829     }
830     break;
831   }
832   case ISD::INSERT_VECTOR_ELT: {
833     // If we don't demand the inserted element, return the base vector.
834     SDValue Vec = Op.getOperand(0);
835     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
836     EVT VecVT = Vec.getValueType();
837     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
838         !DemandedElts[CIdx->getZExtValue()])
839       return Vec;
840     break;
841   }
842   case ISD::INSERT_SUBVECTOR: {
843     SDValue Vec = Op.getOperand(0);
844     SDValue Sub = Op.getOperand(1);
845     uint64_t Idx = Op.getConstantOperandVal(2);
846     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
847     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
848     // If we don't demand the inserted subvector, return the base vector.
849     if (DemandedSubElts == 0)
850       return Vec;
851     // If this simply widens the lowest subvector, see if we can do it earlier.
852     if (Idx == 0 && Vec.isUndef()) {
853       if (SDValue NewSub = SimplifyMultipleUseDemandedBits(
854               Sub, DemandedBits, DemandedSubElts, DAG, Depth + 1))
855         return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
856                            Op.getOperand(0), NewSub, Op.getOperand(2));
857     }
858     break;
859   }
860   case ISD::VECTOR_SHUFFLE: {
861     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
862 
863     // If all the demanded elts are from one operand and are inline,
864     // then we can use the operand directly.
865     bool AllUndef = true, IdentityLHS = true, IdentityRHS = true;
866     for (unsigned i = 0; i != NumElts; ++i) {
867       int M = ShuffleMask[i];
868       if (M < 0 || !DemandedElts[i])
869         continue;
870       AllUndef = false;
871       IdentityLHS &= (M == (int)i);
872       IdentityRHS &= ((M - NumElts) == i);
873     }
874 
875     if (AllUndef)
876       return DAG.getUNDEF(Op.getValueType());
877     if (IdentityLHS)
878       return Op.getOperand(0);
879     if (IdentityRHS)
880       return Op.getOperand(1);
881     break;
882   }
883   default:
884     if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
885       if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode(
886               Op, DemandedBits, DemandedElts, DAG, Depth))
887         return V;
888     break;
889   }
890   return SDValue();
891 }
892 
893 SDValue TargetLowering::SimplifyMultipleUseDemandedBits(
894     SDValue Op, const APInt &DemandedBits, SelectionDAG &DAG,
895     unsigned Depth) const {
896   EVT VT = Op.getValueType();
897   APInt DemandedElts = VT.isVector()
898                            ? APInt::getAllOnes(VT.getVectorNumElements())
899                            : APInt(1, 1);
900   return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
901                                          Depth);
902 }
903 
904 SDValue TargetLowering::SimplifyMultipleUseDemandedVectorElts(
905     SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG,
906     unsigned Depth) const {
907   APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits());
908   return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
909                                          Depth);
910 }
911 
912 // Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1).
913 //      or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1).
914 static SDValue combineShiftToAVG(SDValue Op, SelectionDAG &DAG,
915                                  const TargetLowering &TLI,
916                                  const APInt &DemandedBits,
917                                  const APInt &DemandedElts,
918                                  unsigned Depth) {
919   assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) &&
920          "SRL or SRA node is required here!");
921   // Is the right shift using an immediate value of 1?
922   ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
923   if (!N1C || !N1C->isOne())
924     return SDValue();
925 
926   // We are looking for an avgfloor
927   // add(ext, ext)
928   // or one of these as a avgceil
929   // add(add(ext, ext), 1)
930   // add(add(ext, 1), ext)
931   // add(ext, add(ext, 1))
932   SDValue Add = Op.getOperand(0);
933   if (Add.getOpcode() != ISD::ADD)
934     return SDValue();
935 
936   SDValue ExtOpA = Add.getOperand(0);
937   SDValue ExtOpB = Add.getOperand(1);
938   auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3) {
939     ConstantSDNode *ConstOp;
940     if ((ConstOp = isConstOrConstSplat(Op1, DemandedElts)) &&
941         ConstOp->isOne()) {
942       ExtOpA = Op2;
943       ExtOpB = Op3;
944       return true;
945     }
946     if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) &&
947         ConstOp->isOne()) {
948       ExtOpA = Op1;
949       ExtOpB = Op3;
950       return true;
951     }
952     if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) &&
953         ConstOp->isOne()) {
954       ExtOpA = Op1;
955       ExtOpB = Op2;
956       return true;
957     }
958     return false;
959   };
960   bool IsCeil =
961       (ExtOpA.getOpcode() == ISD::ADD &&
962        MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB)) ||
963       (ExtOpB.getOpcode() == ISD::ADD &&
964        MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA));
965 
966   // If the shift is signed (sra):
967   //  - Needs >= 2 sign bit for both operands.
968   //  - Needs >= 2 zero bits.
969   // If the shift is unsigned (srl):
970   //  - Needs >= 1 zero bit for both operands.
971   //  - Needs 1 demanded bit zero and >= 2 sign bits.
972   unsigned ShiftOpc = Op.getOpcode();
973   bool IsSigned = false;
974   unsigned KnownBits;
975   unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth);
976   unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth);
977   unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1;
978   unsigned NumZeroA =
979       DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros();
980   unsigned NumZeroB =
981       DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros();
982   unsigned NumZero = std::min(NumZeroA, NumZeroB);
983 
984   switch (ShiftOpc) {
985   default:
986     llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG");
987   case ISD::SRA: {
988     if (NumZero >= 2 && NumSigned < NumZero) {
989       IsSigned = false;
990       KnownBits = NumZero;
991       break;
992     }
993     if (NumSigned >= 1) {
994       IsSigned = true;
995       KnownBits = NumSigned;
996       break;
997     }
998     return SDValue();
999   }
1000   case ISD::SRL: {
1001     if (NumZero >= 1 && NumSigned < NumZero) {
1002       IsSigned = false;
1003       KnownBits = NumZero;
1004       break;
1005     }
1006     if (NumSigned >= 1 && DemandedBits.isSignBitClear()) {
1007       IsSigned = true;
1008       KnownBits = NumSigned;
1009       break;
1010     }
1011     return SDValue();
1012   }
1013   }
1014 
1015   unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU)
1016                            : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU);
1017 
1018   // Find the smallest power-2 type that is legal for this vector size and
1019   // operation, given the original type size and the number of known sign/zero
1020   // bits.
1021   EVT VT = Op.getValueType();
1022   unsigned MinWidth =
1023       std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8);
1024   EVT NVT = EVT::getIntegerVT(*DAG.getContext(), PowerOf2Ceil(MinWidth));
1025   if (VT.isVector())
1026     NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount());
1027   if (!TLI.isOperationLegalOrCustom(AVGOpc, NVT))
1028     return SDValue();
1029 
1030   SDLoc DL(Op);
1031   SDValue ResultAVG =
1032       DAG.getNode(AVGOpc, DL, NVT, DAG.getNode(ISD::TRUNCATE, DL, NVT, ExtOpA),
1033                   DAG.getNode(ISD::TRUNCATE, DL, NVT, ExtOpB));
1034   return DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, VT,
1035                      ResultAVG);
1036 }
1037 
1038 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the
1039 /// result of Op are ever used downstream. If we can use this information to
1040 /// simplify Op, create a new simplified DAG node and return true, returning the
1041 /// original and new nodes in Old and New. Otherwise, analyze the expression and
1042 /// return a mask of Known bits for the expression (used to simplify the
1043 /// caller).  The Known bits may only be accurate for those bits in the
1044 /// OriginalDemandedBits and OriginalDemandedElts.
1045 bool TargetLowering::SimplifyDemandedBits(
1046     SDValue Op, const APInt &OriginalDemandedBits,
1047     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
1048     unsigned Depth, bool AssumeSingleUse) const {
1049   unsigned BitWidth = OriginalDemandedBits.getBitWidth();
1050   assert(Op.getScalarValueSizeInBits() == BitWidth &&
1051          "Mask size mismatches value type size!");
1052 
1053   // Don't know anything.
1054   Known = KnownBits(BitWidth);
1055 
1056   // TODO: We can probably do more work on calculating the known bits and
1057   // simplifying the operations for scalable vectors, but for now we just
1058   // bail out.
1059   if (Op.getValueType().isScalableVector())
1060     return false;
1061 
1062   bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
1063   unsigned NumElts = OriginalDemandedElts.getBitWidth();
1064   assert((!Op.getValueType().isVector() ||
1065           NumElts == Op.getValueType().getVectorNumElements()) &&
1066          "Unexpected vector size");
1067 
1068   APInt DemandedBits = OriginalDemandedBits;
1069   APInt DemandedElts = OriginalDemandedElts;
1070   SDLoc dl(Op);
1071   auto &DL = TLO.DAG.getDataLayout();
1072 
1073   // Undef operand.
1074   if (Op.isUndef())
1075     return false;
1076 
1077   if (Op.getOpcode() == ISD::Constant) {
1078     // We know all of the bits for a constant!
1079     Known = KnownBits::makeConstant(cast<ConstantSDNode>(Op)->getAPIntValue());
1080     return false;
1081   }
1082 
1083   if (Op.getOpcode() == ISD::ConstantFP) {
1084     // We know all of the bits for a floating point constant!
1085     Known = KnownBits::makeConstant(
1086         cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt());
1087     return false;
1088   }
1089 
1090   // Other users may use these bits.
1091   EVT VT = Op.getValueType();
1092   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse) {
1093     if (Depth != 0) {
1094       // If not at the root, Just compute the Known bits to
1095       // simplify things downstream.
1096       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1097       return false;
1098     }
1099     // If this is the root being simplified, allow it to have multiple uses,
1100     // just set the DemandedBits/Elts to all bits.
1101     DemandedBits = APInt::getAllOnes(BitWidth);
1102     DemandedElts = APInt::getAllOnes(NumElts);
1103   } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
1104     // Not demanding any bits/elts from Op.
1105     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1106   } else if (Depth >= SelectionDAG::MaxRecursionDepth) {
1107     // Limit search depth.
1108     return false;
1109   }
1110 
1111   KnownBits Known2;
1112   switch (Op.getOpcode()) {
1113   case ISD::TargetConstant:
1114     llvm_unreachable("Can't simplify this node");
1115   case ISD::SCALAR_TO_VECTOR: {
1116     if (!DemandedElts[0])
1117       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1118 
1119     KnownBits SrcKnown;
1120     SDValue Src = Op.getOperand(0);
1121     unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
1122     APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth);
1123     if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
1124       return true;
1125 
1126     // Upper elements are undef, so only get the knownbits if we just demand
1127     // the bottom element.
1128     if (DemandedElts == 1)
1129       Known = SrcKnown.anyextOrTrunc(BitWidth);
1130     break;
1131   }
1132   case ISD::BUILD_VECTOR:
1133     // Collect the known bits that are shared by every demanded element.
1134     // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
1135     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1136     return false; // Don't fall through, will infinitely loop.
1137   case ISD::LOAD: {
1138     auto *LD = cast<LoadSDNode>(Op);
1139     if (getTargetConstantFromLoad(LD)) {
1140       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1141       return false; // Don't fall through, will infinitely loop.
1142     }
1143     if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
1144       // If this is a ZEXTLoad and we are looking at the loaded value.
1145       EVT MemVT = LD->getMemoryVT();
1146       unsigned MemBits = MemVT.getScalarSizeInBits();
1147       Known.Zero.setBitsFrom(MemBits);
1148       return false; // Don't fall through, will infinitely loop.
1149     }
1150     break;
1151   }
1152   case ISD::INSERT_VECTOR_ELT: {
1153     SDValue Vec = Op.getOperand(0);
1154     SDValue Scl = Op.getOperand(1);
1155     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1156     EVT VecVT = Vec.getValueType();
1157 
1158     // If index isn't constant, assume we need all vector elements AND the
1159     // inserted element.
1160     APInt DemandedVecElts(DemandedElts);
1161     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
1162       unsigned Idx = CIdx->getZExtValue();
1163       DemandedVecElts.clearBit(Idx);
1164 
1165       // Inserted element is not required.
1166       if (!DemandedElts[Idx])
1167         return TLO.CombineTo(Op, Vec);
1168     }
1169 
1170     KnownBits KnownScl;
1171     unsigned NumSclBits = Scl.getScalarValueSizeInBits();
1172     APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits);
1173     if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1174       return true;
1175 
1176     Known = KnownScl.anyextOrTrunc(BitWidth);
1177 
1178     KnownBits KnownVec;
1179     if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO,
1180                              Depth + 1))
1181       return true;
1182 
1183     if (!!DemandedVecElts)
1184       Known = KnownBits::commonBits(Known, KnownVec);
1185 
1186     return false;
1187   }
1188   case ISD::INSERT_SUBVECTOR: {
1189     // Demand any elements from the subvector and the remainder from the src its
1190     // inserted into.
1191     SDValue Src = Op.getOperand(0);
1192     SDValue Sub = Op.getOperand(1);
1193     uint64_t Idx = Op.getConstantOperandVal(2);
1194     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1195     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1196     APInt DemandedSrcElts = DemandedElts;
1197     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
1198 
1199     KnownBits KnownSub, KnownSrc;
1200     if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO,
1201                              Depth + 1))
1202       return true;
1203     if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO,
1204                              Depth + 1))
1205       return true;
1206 
1207     Known.Zero.setAllBits();
1208     Known.One.setAllBits();
1209     if (!!DemandedSubElts)
1210       Known = KnownBits::commonBits(Known, KnownSub);
1211     if (!!DemandedSrcElts)
1212       Known = KnownBits::commonBits(Known, KnownSrc);
1213 
1214     // Attempt to avoid multi-use src if we don't need anything from it.
1215     if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() ||
1216         !DemandedSrcElts.isAllOnes()) {
1217       SDValue NewSub = SimplifyMultipleUseDemandedBits(
1218           Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1);
1219       SDValue NewSrc = SimplifyMultipleUseDemandedBits(
1220           Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1221       if (NewSub || NewSrc) {
1222         NewSub = NewSub ? NewSub : Sub;
1223         NewSrc = NewSrc ? NewSrc : Src;
1224         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub,
1225                                         Op.getOperand(2));
1226         return TLO.CombineTo(Op, NewOp);
1227       }
1228     }
1229     break;
1230   }
1231   case ISD::EXTRACT_SUBVECTOR: {
1232     // Offset the demanded elts by the subvector index.
1233     SDValue Src = Op.getOperand(0);
1234     if (Src.getValueType().isScalableVector())
1235       break;
1236     uint64_t Idx = Op.getConstantOperandVal(1);
1237     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1238     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
1239 
1240     if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO,
1241                              Depth + 1))
1242       return true;
1243 
1244     // Attempt to avoid multi-use src if we don't need anything from it.
1245     if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
1246       SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
1247           Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1248       if (DemandedSrc) {
1249         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc,
1250                                         Op.getOperand(1));
1251         return TLO.CombineTo(Op, NewOp);
1252       }
1253     }
1254     break;
1255   }
1256   case ISD::CONCAT_VECTORS: {
1257     Known.Zero.setAllBits();
1258     Known.One.setAllBits();
1259     EVT SubVT = Op.getOperand(0).getValueType();
1260     unsigned NumSubVecs = Op.getNumOperands();
1261     unsigned NumSubElts = SubVT.getVectorNumElements();
1262     for (unsigned i = 0; i != NumSubVecs; ++i) {
1263       APInt DemandedSubElts =
1264           DemandedElts.extractBits(NumSubElts, i * NumSubElts);
1265       if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
1266                                Known2, TLO, Depth + 1))
1267         return true;
1268       // Known bits are shared by every demanded subvector element.
1269       if (!!DemandedSubElts)
1270         Known = KnownBits::commonBits(Known, Known2);
1271     }
1272     break;
1273   }
1274   case ISD::VECTOR_SHUFFLE: {
1275     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1276 
1277     // Collect demanded elements from shuffle operands..
1278     APInt DemandedLHS(NumElts, 0);
1279     APInt DemandedRHS(NumElts, 0);
1280     for (unsigned i = 0; i != NumElts; ++i) {
1281       if (!DemandedElts[i])
1282         continue;
1283       int M = ShuffleMask[i];
1284       if (M < 0) {
1285         // For UNDEF elements, we don't know anything about the common state of
1286         // the shuffle result.
1287         DemandedLHS.clearAllBits();
1288         DemandedRHS.clearAllBits();
1289         break;
1290       }
1291       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
1292       if (M < (int)NumElts)
1293         DemandedLHS.setBit(M);
1294       else
1295         DemandedRHS.setBit(M - NumElts);
1296     }
1297 
1298     if (!!DemandedLHS || !!DemandedRHS) {
1299       SDValue Op0 = Op.getOperand(0);
1300       SDValue Op1 = Op.getOperand(1);
1301 
1302       Known.Zero.setAllBits();
1303       Known.One.setAllBits();
1304       if (!!DemandedLHS) {
1305         if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO,
1306                                  Depth + 1))
1307           return true;
1308         Known = KnownBits::commonBits(Known, Known2);
1309       }
1310       if (!!DemandedRHS) {
1311         if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO,
1312                                  Depth + 1))
1313           return true;
1314         Known = KnownBits::commonBits(Known, Known2);
1315       }
1316 
1317       // Attempt to avoid multi-use ops if we don't need anything from them.
1318       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1319           Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1);
1320       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1321           Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1);
1322       if (DemandedOp0 || DemandedOp1) {
1323         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1324         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1325         SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask);
1326         return TLO.CombineTo(Op, NewOp);
1327       }
1328     }
1329     break;
1330   }
1331   case ISD::AND: {
1332     SDValue Op0 = Op.getOperand(0);
1333     SDValue Op1 = Op.getOperand(1);
1334 
1335     // If the RHS is a constant, check to see if the LHS would be zero without
1336     // using the bits from the RHS.  Below, we use knowledge about the RHS to
1337     // simplify the LHS, here we're using information from the LHS to simplify
1338     // the RHS.
1339     if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) {
1340       // Do not increment Depth here; that can cause an infinite loop.
1341       KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
1342       // If the LHS already has zeros where RHSC does, this 'and' is dead.
1343       if ((LHSKnown.Zero & DemandedBits) ==
1344           (~RHSC->getAPIntValue() & DemandedBits))
1345         return TLO.CombineTo(Op, Op0);
1346 
1347       // If any of the set bits in the RHS are known zero on the LHS, shrink
1348       // the constant.
1349       if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits,
1350                                  DemandedElts, TLO))
1351         return true;
1352 
1353       // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
1354       // constant, but if this 'and' is only clearing bits that were just set by
1355       // the xor, then this 'and' can be eliminated by shrinking the mask of
1356       // the xor. For example, for a 32-bit X:
1357       // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
1358       if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
1359           LHSKnown.One == ~RHSC->getAPIntValue()) {
1360         SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
1361         return TLO.CombineTo(Op, Xor);
1362       }
1363     }
1364 
1365     // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I)
1366     // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits).
1367     if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR &&
1368         (Op0.getOperand(0).isUndef() ||
1369          ISD::isBuildVectorOfConstantSDNodes(Op0.getOperand(0).getNode())) &&
1370         Op0->hasOneUse()) {
1371       unsigned NumSubElts =
1372           Op0.getOperand(1).getValueType().getVectorNumElements();
1373       unsigned SubIdx = Op0.getConstantOperandVal(2);
1374       APInt DemandedSub =
1375           APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts);
1376       KnownBits KnownSubMask =
1377           TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1);
1378       if (DemandedBits.isSubsetOf(KnownSubMask.One)) {
1379         SDValue NewAnd =
1380             TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1);
1381         SDValue NewInsert =
1382             TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd,
1383                             Op0.getOperand(1), Op0.getOperand(2));
1384         return TLO.CombineTo(Op, NewInsert);
1385       }
1386     }
1387 
1388     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1389                              Depth + 1))
1390       return true;
1391     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1392     if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
1393                              Known2, TLO, Depth + 1))
1394       return true;
1395     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1396 
1397     // Attempt to avoid multi-use ops if we don't need anything from them.
1398     if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1399       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1400           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1401       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1402           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1403       if (DemandedOp0 || DemandedOp1) {
1404         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1405         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1406         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1407         return TLO.CombineTo(Op, NewOp);
1408       }
1409     }
1410 
1411     // If all of the demanded bits are known one on one side, return the other.
1412     // These bits cannot contribute to the result of the 'and'.
1413     if (DemandedBits.isSubsetOf(Known2.Zero | Known.One))
1414       return TLO.CombineTo(Op, Op0);
1415     if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
1416       return TLO.CombineTo(Op, Op1);
1417     // If all of the demanded bits in the inputs are known zeros, return zero.
1418     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1419       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
1420     // If the RHS is a constant, see if we can simplify it.
1421     if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts,
1422                                TLO))
1423       return true;
1424     // If the operation can be done in a smaller type, do so.
1425     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1426       return true;
1427 
1428     Known &= Known2;
1429     break;
1430   }
1431   case ISD::OR: {
1432     SDValue Op0 = Op.getOperand(0);
1433     SDValue Op1 = Op.getOperand(1);
1434 
1435     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1436                              Depth + 1))
1437       return true;
1438     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1439     if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
1440                              Known2, TLO, Depth + 1))
1441       return true;
1442     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1443 
1444     // Attempt to avoid multi-use ops if we don't need anything from them.
1445     if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1446       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1447           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1448       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1449           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1450       if (DemandedOp0 || DemandedOp1) {
1451         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1452         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1453         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1454         return TLO.CombineTo(Op, NewOp);
1455       }
1456     }
1457 
1458     // If all of the demanded bits are known zero on one side, return the other.
1459     // These bits cannot contribute to the result of the 'or'.
1460     if (DemandedBits.isSubsetOf(Known2.One | Known.Zero))
1461       return TLO.CombineTo(Op, Op0);
1462     if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
1463       return TLO.CombineTo(Op, Op1);
1464     // If the RHS is a constant, see if we can simplify it.
1465     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1466       return true;
1467     // If the operation can be done in a smaller type, do so.
1468     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1469       return true;
1470 
1471     Known |= Known2;
1472     break;
1473   }
1474   case ISD::XOR: {
1475     SDValue Op0 = Op.getOperand(0);
1476     SDValue Op1 = Op.getOperand(1);
1477 
1478     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1479                              Depth + 1))
1480       return true;
1481     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1482     if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
1483                              Depth + 1))
1484       return true;
1485     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1486 
1487     // Attempt to avoid multi-use ops if we don't need anything from them.
1488     if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1489       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1490           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1491       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1492           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1493       if (DemandedOp0 || DemandedOp1) {
1494         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1495         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1496         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1497         return TLO.CombineTo(Op, NewOp);
1498       }
1499     }
1500 
1501     // If all of the demanded bits are known zero on one side, return the other.
1502     // These bits cannot contribute to the result of the 'xor'.
1503     if (DemandedBits.isSubsetOf(Known.Zero))
1504       return TLO.CombineTo(Op, Op0);
1505     if (DemandedBits.isSubsetOf(Known2.Zero))
1506       return TLO.CombineTo(Op, Op1);
1507     // If the operation can be done in a smaller type, do so.
1508     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1509       return true;
1510 
1511     // If all of the unknown bits are known to be zero on one side or the other
1512     // turn this into an *inclusive* or.
1513     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1514     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1515       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
1516 
1517     ConstantSDNode* C = isConstOrConstSplat(Op1, DemandedElts);
1518     if (C) {
1519       // If one side is a constant, and all of the set bits in the constant are
1520       // also known set on the other side, turn this into an AND, as we know
1521       // the bits will be cleared.
1522       //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1523       // NB: it is okay if more bits are known than are requested
1524       if (C->getAPIntValue() == Known2.One) {
1525         SDValue ANDC =
1526             TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
1527         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
1528       }
1529 
1530       // If the RHS is a constant, see if we can change it. Don't alter a -1
1531       // constant because that's a 'not' op, and that is better for combining
1532       // and codegen.
1533       if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) {
1534         // We're flipping all demanded bits. Flip the undemanded bits too.
1535         SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
1536         return TLO.CombineTo(Op, New);
1537       }
1538     }
1539 
1540     // If we can't turn this into a 'not', try to shrink the constant.
1541     if (!C || !C->isAllOnes())
1542       if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1543         return true;
1544 
1545     Known ^= Known2;
1546     break;
1547   }
1548   case ISD::SELECT:
1549     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO,
1550                              Depth + 1))
1551       return true;
1552     if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO,
1553                              Depth + 1))
1554       return true;
1555     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1556     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1557 
1558     // If the operands are constants, see if we can simplify them.
1559     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1560       return true;
1561 
1562     // Only known if known in both the LHS and RHS.
1563     Known = KnownBits::commonBits(Known, Known2);
1564     break;
1565   case ISD::VSELECT:
1566     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1567                              Known, TLO, Depth + 1))
1568       return true;
1569     if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
1570                              Known2, TLO, Depth + 1))
1571       return true;
1572     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1573     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1574 
1575     // Only known if known in both the LHS and RHS.
1576     Known = KnownBits::commonBits(Known, Known2);
1577     break;
1578   case ISD::SELECT_CC:
1579     if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO,
1580                              Depth + 1))
1581       return true;
1582     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO,
1583                              Depth + 1))
1584       return true;
1585     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1586     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1587 
1588     // If the operands are constants, see if we can simplify them.
1589     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1590       return true;
1591 
1592     // Only known if known in both the LHS and RHS.
1593     Known = KnownBits::commonBits(Known, Known2);
1594     break;
1595   case ISD::SETCC: {
1596     SDValue Op0 = Op.getOperand(0);
1597     SDValue Op1 = Op.getOperand(1);
1598     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1599     // If (1) we only need the sign-bit, (2) the setcc operands are the same
1600     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
1601     // -1, we may be able to bypass the setcc.
1602     if (DemandedBits.isSignMask() &&
1603         Op0.getScalarValueSizeInBits() == BitWidth &&
1604         getBooleanContents(Op0.getValueType()) ==
1605             BooleanContent::ZeroOrNegativeOneBooleanContent) {
1606       // If we're testing X < 0, then this compare isn't needed - just use X!
1607       // FIXME: We're limiting to integer types here, but this should also work
1608       // if we don't care about FP signed-zero. The use of SETLT with FP means
1609       // that we don't care about NaNs.
1610       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
1611           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
1612         return TLO.CombineTo(Op, Op0);
1613 
1614       // TODO: Should we check for other forms of sign-bit comparisons?
1615       // Examples: X <= -1, X >= 0
1616     }
1617     if (getBooleanContents(Op0.getValueType()) ==
1618             TargetLowering::ZeroOrOneBooleanContent &&
1619         BitWidth > 1)
1620       Known.Zero.setBitsFrom(1);
1621     break;
1622   }
1623   case ISD::SHL: {
1624     SDValue Op0 = Op.getOperand(0);
1625     SDValue Op1 = Op.getOperand(1);
1626     EVT ShiftVT = Op1.getValueType();
1627 
1628     if (const APInt *SA =
1629             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1630       unsigned ShAmt = SA->getZExtValue();
1631       if (ShAmt == 0)
1632         return TLO.CombineTo(Op, Op0);
1633 
1634       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1635       // single shift.  We can do this if the bottom bits (which are shifted
1636       // out) are never demanded.
1637       // TODO - support non-uniform vector amounts.
1638       if (Op0.getOpcode() == ISD::SRL) {
1639         if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) {
1640           if (const APInt *SA2 =
1641                   TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) {
1642             unsigned C1 = SA2->getZExtValue();
1643             unsigned Opc = ISD::SHL;
1644             int Diff = ShAmt - C1;
1645             if (Diff < 0) {
1646               Diff = -Diff;
1647               Opc = ISD::SRL;
1648             }
1649             SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1650             return TLO.CombineTo(
1651                 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1652           }
1653         }
1654       }
1655 
1656       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1657       // are not demanded. This will likely allow the anyext to be folded away.
1658       // TODO - support non-uniform vector amounts.
1659       if (Op0.getOpcode() == ISD::ANY_EXTEND) {
1660         SDValue InnerOp = Op0.getOperand(0);
1661         EVT InnerVT = InnerOp.getValueType();
1662         unsigned InnerBits = InnerVT.getScalarSizeInBits();
1663         if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
1664             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
1665           EVT ShTy = getShiftAmountTy(InnerVT, DL);
1666           if (!APInt(BitWidth, ShAmt).isIntN(ShTy.getSizeInBits()))
1667             ShTy = InnerVT;
1668           SDValue NarrowShl =
1669               TLO.DAG.getNode(ISD::SHL, dl, InnerVT, InnerOp,
1670                               TLO.DAG.getConstant(ShAmt, dl, ShTy));
1671           return TLO.CombineTo(
1672               Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
1673         }
1674 
1675         // Repeat the SHL optimization above in cases where an extension
1676         // intervenes: (shl (anyext (shr x, c1)), c2) to
1677         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
1678         // aren't demanded (as above) and that the shifted upper c1 bits of
1679         // x aren't demanded.
1680         // TODO - support non-uniform vector amounts.
1681         if (Op0.hasOneUse() && InnerOp.getOpcode() == ISD::SRL &&
1682             InnerOp.hasOneUse()) {
1683           if (const APInt *SA2 =
1684                   TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) {
1685             unsigned InnerShAmt = SA2->getZExtValue();
1686             if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
1687                 DemandedBits.getActiveBits() <=
1688                     (InnerBits - InnerShAmt + ShAmt) &&
1689                 DemandedBits.countTrailingZeros() >= ShAmt) {
1690               SDValue NewSA =
1691                   TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT);
1692               SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
1693                                                InnerOp.getOperand(0));
1694               return TLO.CombineTo(
1695                   Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
1696             }
1697           }
1698         }
1699       }
1700 
1701       APInt InDemandedMask = DemandedBits.lshr(ShAmt);
1702       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1703                                Depth + 1))
1704         return true;
1705       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1706       Known.Zero <<= ShAmt;
1707       Known.One <<= ShAmt;
1708       // low bits known zero.
1709       Known.Zero.setLowBits(ShAmt);
1710 
1711       // Attempt to avoid multi-use ops if we don't need anything from them.
1712       if (!InDemandedMask.isAllOnesValue() || !DemandedElts.isAllOnesValue()) {
1713         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1714             Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
1715         if (DemandedOp0) {
1716           SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1);
1717           return TLO.CombineTo(Op, NewOp);
1718         }
1719       }
1720 
1721       // Try shrinking the operation as long as the shift amount will still be
1722       // in range.
1723       if ((ShAmt < DemandedBits.getActiveBits()) &&
1724           ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1725         return true;
1726     }
1727 
1728     // If we are only demanding sign bits then we can use the shift source
1729     // directly.
1730     if (const APInt *MaxSA =
1731             TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
1732       unsigned ShAmt = MaxSA->getZExtValue();
1733       unsigned NumSignBits =
1734           TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1735       unsigned UpperDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
1736       if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
1737         return TLO.CombineTo(Op, Op0);
1738     }
1739     break;
1740   }
1741   case ISD::SRL: {
1742     SDValue Op0 = Op.getOperand(0);
1743     SDValue Op1 = Op.getOperand(1);
1744     EVT ShiftVT = Op1.getValueType();
1745 
1746     // Try to match AVG patterns.
1747     if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits,
1748                                         DemandedElts, Depth + 1))
1749       return TLO.CombineTo(Op, AVG);
1750 
1751     if (const APInt *SA =
1752             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1753       unsigned ShAmt = SA->getZExtValue();
1754       if (ShAmt == 0)
1755         return TLO.CombineTo(Op, Op0);
1756 
1757       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
1758       // single shift.  We can do this if the top bits (which are shifted out)
1759       // are never demanded.
1760       // TODO - support non-uniform vector amounts.
1761       if (Op0.getOpcode() == ISD::SHL) {
1762         if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
1763           if (const APInt *SA2 =
1764                   TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) {
1765             unsigned C1 = SA2->getZExtValue();
1766             unsigned Opc = ISD::SRL;
1767             int Diff = ShAmt - C1;
1768             if (Diff < 0) {
1769               Diff = -Diff;
1770               Opc = ISD::SHL;
1771             }
1772             SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1773             return TLO.CombineTo(
1774                 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1775           }
1776         }
1777       }
1778 
1779       APInt InDemandedMask = (DemandedBits << ShAmt);
1780 
1781       // If the shift is exact, then it does demand the low bits (and knows that
1782       // they are zero).
1783       if (Op->getFlags().hasExact())
1784         InDemandedMask.setLowBits(ShAmt);
1785 
1786       // Compute the new bits that are at the top now.
1787       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1788                                Depth + 1))
1789         return true;
1790       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1791       Known.Zero.lshrInPlace(ShAmt);
1792       Known.One.lshrInPlace(ShAmt);
1793       // High bits known zero.
1794       Known.Zero.setHighBits(ShAmt);
1795     }
1796     break;
1797   }
1798   case ISD::SRA: {
1799     SDValue Op0 = Op.getOperand(0);
1800     SDValue Op1 = Op.getOperand(1);
1801     EVT ShiftVT = Op1.getValueType();
1802 
1803     // If we only want bits that already match the signbit then we don't need
1804     // to shift.
1805     unsigned NumHiDemandedBits = BitWidth - DemandedBits.countTrailingZeros();
1806     if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >=
1807         NumHiDemandedBits)
1808       return TLO.CombineTo(Op, Op0);
1809 
1810     // If this is an arithmetic shift right and only the low-bit is set, we can
1811     // always convert this into a logical shr, even if the shift amount is
1812     // variable.  The low bit of the shift cannot be an input sign bit unless
1813     // the shift amount is >= the size of the datatype, which is undefined.
1814     if (DemandedBits.isOne())
1815       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
1816 
1817     // Try to match AVG patterns.
1818     if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits,
1819                                         DemandedElts, Depth + 1))
1820       return TLO.CombineTo(Op, AVG);
1821 
1822     if (const APInt *SA =
1823             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1824       unsigned ShAmt = SA->getZExtValue();
1825       if (ShAmt == 0)
1826         return TLO.CombineTo(Op, Op0);
1827 
1828       APInt InDemandedMask = (DemandedBits << ShAmt);
1829 
1830       // If the shift is exact, then it does demand the low bits (and knows that
1831       // they are zero).
1832       if (Op->getFlags().hasExact())
1833         InDemandedMask.setLowBits(ShAmt);
1834 
1835       // If any of the demanded bits are produced by the sign extension, we also
1836       // demand the input sign bit.
1837       if (DemandedBits.countLeadingZeros() < ShAmt)
1838         InDemandedMask.setSignBit();
1839 
1840       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1841                                Depth + 1))
1842         return true;
1843       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1844       Known.Zero.lshrInPlace(ShAmt);
1845       Known.One.lshrInPlace(ShAmt);
1846 
1847       // If the input sign bit is known to be zero, or if none of the top bits
1848       // are demanded, turn this into an unsigned shift right.
1849       if (Known.Zero[BitWidth - ShAmt - 1] ||
1850           DemandedBits.countLeadingZeros() >= ShAmt) {
1851         SDNodeFlags Flags;
1852         Flags.setExact(Op->getFlags().hasExact());
1853         return TLO.CombineTo(
1854             Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
1855       }
1856 
1857       int Log2 = DemandedBits.exactLogBase2();
1858       if (Log2 >= 0) {
1859         // The bit must come from the sign.
1860         SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT);
1861         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
1862       }
1863 
1864       if (Known.One[BitWidth - ShAmt - 1])
1865         // New bits are known one.
1866         Known.One.setHighBits(ShAmt);
1867 
1868       // Attempt to avoid multi-use ops if we don't need anything from them.
1869       if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
1870         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1871             Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
1872         if (DemandedOp0) {
1873           SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1);
1874           return TLO.CombineTo(Op, NewOp);
1875         }
1876       }
1877     }
1878     break;
1879   }
1880   case ISD::FSHL:
1881   case ISD::FSHR: {
1882     SDValue Op0 = Op.getOperand(0);
1883     SDValue Op1 = Op.getOperand(1);
1884     SDValue Op2 = Op.getOperand(2);
1885     bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
1886 
1887     if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) {
1888       unsigned Amt = SA->getAPIntValue().urem(BitWidth);
1889 
1890       // For fshl, 0-shift returns the 1st arg.
1891       // For fshr, 0-shift returns the 2nd arg.
1892       if (Amt == 0) {
1893         if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
1894                                  Known, TLO, Depth + 1))
1895           return true;
1896         break;
1897       }
1898 
1899       // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
1900       // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
1901       APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
1902       APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
1903       if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
1904                                Depth + 1))
1905         return true;
1906       if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
1907                                Depth + 1))
1908         return true;
1909 
1910       Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt));
1911       Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt));
1912       Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
1913       Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
1914       Known.One |= Known2.One;
1915       Known.Zero |= Known2.Zero;
1916 
1917       // Attempt to avoid multi-use ops if we don't need anything from them.
1918       if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() ||
1919           !DemandedElts.isAllOnes()) {
1920         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1921             Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1);
1922         SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1923             Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1);
1924         if (DemandedOp0 || DemandedOp1) {
1925           DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0;
1926           DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1;
1927           SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0,
1928                                           DemandedOp1, Op2);
1929           return TLO.CombineTo(Op, NewOp);
1930         }
1931       }
1932     }
1933 
1934     // For pow-2 bitwidths we only demand the bottom modulo amt bits.
1935     if (isPowerOf2_32(BitWidth)) {
1936       APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1);
1937       if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts,
1938                                Known2, TLO, Depth + 1))
1939         return true;
1940     }
1941     break;
1942   }
1943   case ISD::ROTL:
1944   case ISD::ROTR: {
1945     SDValue Op0 = Op.getOperand(0);
1946     SDValue Op1 = Op.getOperand(1);
1947     bool IsROTL = (Op.getOpcode() == ISD::ROTL);
1948 
1949     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
1950     if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1))
1951       return TLO.CombineTo(Op, Op0);
1952 
1953     if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
1954       unsigned Amt = SA->getAPIntValue().urem(BitWidth);
1955       unsigned RevAmt = BitWidth - Amt;
1956 
1957       // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt))
1958       // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt)
1959       APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt);
1960       if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
1961                                Depth + 1))
1962         return true;
1963 
1964       // rot*(x, 0) --> x
1965       if (Amt == 0)
1966         return TLO.CombineTo(Op, Op0);
1967 
1968       // See if we don't demand either half of the rotated bits.
1969       if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) &&
1970           DemandedBits.countTrailingZeros() >= (IsROTL ? Amt : RevAmt)) {
1971         Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType());
1972         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1));
1973       }
1974       if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) &&
1975           DemandedBits.countLeadingZeros() >= (IsROTL ? RevAmt : Amt)) {
1976         Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType());
1977         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
1978       }
1979     }
1980 
1981     // For pow-2 bitwidths we only demand the bottom modulo amt bits.
1982     if (isPowerOf2_32(BitWidth)) {
1983       APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1);
1984       if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO,
1985                                Depth + 1))
1986         return true;
1987     }
1988     break;
1989   }
1990   case ISD::UMIN: {
1991     // Check if one arg is always less than (or equal) to the other arg.
1992     SDValue Op0 = Op.getOperand(0);
1993     SDValue Op1 = Op.getOperand(1);
1994     KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
1995     KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
1996     Known = KnownBits::umin(Known0, Known1);
1997     if (Optional<bool> IsULE = KnownBits::ule(Known0, Known1))
1998       return TLO.CombineTo(Op, IsULE.getValue() ? Op0 : Op1);
1999     if (Optional<bool> IsULT = KnownBits::ult(Known0, Known1))
2000       return TLO.CombineTo(Op, IsULT.getValue() ? Op0 : Op1);
2001     break;
2002   }
2003   case ISD::UMAX: {
2004     // Check if one arg is always greater than (or equal) to the other arg.
2005     SDValue Op0 = Op.getOperand(0);
2006     SDValue Op1 = Op.getOperand(1);
2007     KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
2008     KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
2009     Known = KnownBits::umax(Known0, Known1);
2010     if (Optional<bool> IsUGE = KnownBits::uge(Known0, Known1))
2011       return TLO.CombineTo(Op, IsUGE.getValue() ? Op0 : Op1);
2012     if (Optional<bool> IsUGT = KnownBits::ugt(Known0, Known1))
2013       return TLO.CombineTo(Op, IsUGT.getValue() ? Op0 : Op1);
2014     break;
2015   }
2016   case ISD::BITREVERSE: {
2017     SDValue Src = Op.getOperand(0);
2018     APInt DemandedSrcBits = DemandedBits.reverseBits();
2019     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2020                              Depth + 1))
2021       return true;
2022     Known.One = Known2.One.reverseBits();
2023     Known.Zero = Known2.Zero.reverseBits();
2024     break;
2025   }
2026   case ISD::BSWAP: {
2027     SDValue Src = Op.getOperand(0);
2028 
2029     // If the only bits demanded come from one byte of the bswap result,
2030     // just shift the input byte into position to eliminate the bswap.
2031     unsigned NLZ = DemandedBits.countLeadingZeros();
2032     unsigned NTZ = DemandedBits.countTrailingZeros();
2033 
2034     // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
2035     // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
2036     // have 14 leading zeros, round to 8.
2037     NLZ = alignDown(NLZ, 8);
2038     NTZ = alignDown(NTZ, 8);
2039     // If we need exactly one byte, we can do this transformation.
2040     if (BitWidth - NLZ - NTZ == 8) {
2041       // Replace this with either a left or right shift to get the byte into
2042       // the right place.
2043       unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL;
2044       if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) {
2045         EVT ShiftAmtTy = getShiftAmountTy(VT, DL);
2046         unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ;
2047         SDValue ShAmt = TLO.DAG.getConstant(ShiftAmount, dl, ShiftAmtTy);
2048         SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt);
2049         return TLO.CombineTo(Op, NewOp);
2050       }
2051     }
2052 
2053     APInt DemandedSrcBits = DemandedBits.byteSwap();
2054     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2055                              Depth + 1))
2056       return true;
2057     Known.One = Known2.One.byteSwap();
2058     Known.Zero = Known2.Zero.byteSwap();
2059     break;
2060   }
2061   case ISD::CTPOP: {
2062     // If only 1 bit is demanded, replace with PARITY as long as we're before
2063     // op legalization.
2064     // FIXME: Limit to scalars for now.
2065     if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector())
2066       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT,
2067                                                Op.getOperand(0)));
2068 
2069     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2070     break;
2071   }
2072   case ISD::SIGN_EXTEND_INREG: {
2073     SDValue Op0 = Op.getOperand(0);
2074     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2075     unsigned ExVTBits = ExVT.getScalarSizeInBits();
2076 
2077     // If we only care about the highest bit, don't bother shifting right.
2078     if (DemandedBits.isSignMask()) {
2079       unsigned MinSignedBits =
2080           TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1);
2081       bool AlreadySignExtended = ExVTBits >= MinSignedBits;
2082       // However if the input is already sign extended we expect the sign
2083       // extension to be dropped altogether later and do not simplify.
2084       if (!AlreadySignExtended) {
2085         // Compute the correct shift amount type, which must be getShiftAmountTy
2086         // for scalar types after legalization.
2087         SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ExVTBits, dl,
2088                                                getShiftAmountTy(VT, DL));
2089         return TLO.CombineTo(Op,
2090                              TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
2091       }
2092     }
2093 
2094     // If none of the extended bits are demanded, eliminate the sextinreg.
2095     if (DemandedBits.getActiveBits() <= ExVTBits)
2096       return TLO.CombineTo(Op, Op0);
2097 
2098     APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
2099 
2100     // Since the sign extended bits are demanded, we know that the sign
2101     // bit is demanded.
2102     InputDemandedBits.setBit(ExVTBits - 1);
2103 
2104     if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO,
2105                              Depth + 1))
2106       return true;
2107     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2108 
2109     // If the sign bit of the input is known set or clear, then we know the
2110     // top bits of the result.
2111 
2112     // If the input sign bit is known zero, convert this into a zero extension.
2113     if (Known.Zero[ExVTBits - 1])
2114       return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT));
2115 
2116     APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
2117     if (Known.One[ExVTBits - 1]) { // Input sign bit known set
2118       Known.One.setBitsFrom(ExVTBits);
2119       Known.Zero &= Mask;
2120     } else { // Input sign bit unknown
2121       Known.Zero &= Mask;
2122       Known.One &= Mask;
2123     }
2124     break;
2125   }
2126   case ISD::BUILD_PAIR: {
2127     EVT HalfVT = Op.getOperand(0).getValueType();
2128     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
2129 
2130     APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
2131     APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
2132 
2133     KnownBits KnownLo, KnownHi;
2134 
2135     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
2136       return true;
2137 
2138     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
2139       return true;
2140 
2141     Known.Zero = KnownLo.Zero.zext(BitWidth) |
2142                  KnownHi.Zero.zext(BitWidth).shl(HalfBitWidth);
2143 
2144     Known.One = KnownLo.One.zext(BitWidth) |
2145                 KnownHi.One.zext(BitWidth).shl(HalfBitWidth);
2146     break;
2147   }
2148   case ISD::ZERO_EXTEND:
2149   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2150     SDValue Src = Op.getOperand(0);
2151     EVT SrcVT = Src.getValueType();
2152     unsigned InBits = SrcVT.getScalarSizeInBits();
2153     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2154     bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
2155 
2156     // If none of the top bits are demanded, convert this into an any_extend.
2157     if (DemandedBits.getActiveBits() <= InBits) {
2158       // If we only need the non-extended bits of the bottom element
2159       // then we can just bitcast to the result.
2160       if (IsLE && IsVecInReg && DemandedElts == 1 &&
2161           VT.getSizeInBits() == SrcVT.getSizeInBits())
2162         return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2163 
2164       unsigned Opc =
2165           IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND;
2166       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2167         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2168     }
2169 
2170     APInt InDemandedBits = DemandedBits.trunc(InBits);
2171     APInt InDemandedElts = DemandedElts.zext(InElts);
2172     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2173                              Depth + 1))
2174       return true;
2175     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2176     assert(Known.getBitWidth() == InBits && "Src width has changed?");
2177     Known = Known.zext(BitWidth);
2178 
2179     // Attempt to avoid multi-use ops if we don't need anything from them.
2180     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2181             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2182       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2183     break;
2184   }
2185   case ISD::SIGN_EXTEND:
2186   case ISD::SIGN_EXTEND_VECTOR_INREG: {
2187     SDValue Src = Op.getOperand(0);
2188     EVT SrcVT = Src.getValueType();
2189     unsigned InBits = SrcVT.getScalarSizeInBits();
2190     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2191     bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
2192 
2193     // If none of the top bits are demanded, convert this into an any_extend.
2194     if (DemandedBits.getActiveBits() <= InBits) {
2195       // If we only need the non-extended bits of the bottom element
2196       // then we can just bitcast to the result.
2197       if (IsLE && IsVecInReg && DemandedElts == 1 &&
2198           VT.getSizeInBits() == SrcVT.getSizeInBits())
2199         return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2200 
2201       unsigned Opc =
2202           IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND;
2203       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2204         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2205     }
2206 
2207     APInt InDemandedBits = DemandedBits.trunc(InBits);
2208     APInt InDemandedElts = DemandedElts.zext(InElts);
2209 
2210     // Since some of the sign extended bits are demanded, we know that the sign
2211     // bit is demanded.
2212     InDemandedBits.setBit(InBits - 1);
2213 
2214     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2215                              Depth + 1))
2216       return true;
2217     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2218     assert(Known.getBitWidth() == InBits && "Src width has changed?");
2219 
2220     // If the sign bit is known one, the top bits match.
2221     Known = Known.sext(BitWidth);
2222 
2223     // If the sign bit is known zero, convert this to a zero extend.
2224     if (Known.isNonNegative()) {
2225       unsigned Opc =
2226           IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND;
2227       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2228         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2229     }
2230 
2231     // Attempt to avoid multi-use ops if we don't need anything from them.
2232     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2233             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2234       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2235     break;
2236   }
2237   case ISD::ANY_EXTEND:
2238   case ISD::ANY_EXTEND_VECTOR_INREG: {
2239     SDValue Src = Op.getOperand(0);
2240     EVT SrcVT = Src.getValueType();
2241     unsigned InBits = SrcVT.getScalarSizeInBits();
2242     unsigned InElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2243     bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG;
2244 
2245     // If we only need the bottom element then we can just bitcast.
2246     // TODO: Handle ANY_EXTEND?
2247     if (IsLE && IsVecInReg && DemandedElts == 1 &&
2248         VT.getSizeInBits() == SrcVT.getSizeInBits())
2249       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2250 
2251     APInt InDemandedBits = DemandedBits.trunc(InBits);
2252     APInt InDemandedElts = DemandedElts.zext(InElts);
2253     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2254                              Depth + 1))
2255       return true;
2256     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2257     assert(Known.getBitWidth() == InBits && "Src width has changed?");
2258     Known = Known.anyext(BitWidth);
2259 
2260     // Attempt to avoid multi-use ops if we don't need anything from them.
2261     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2262             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2263       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2264     break;
2265   }
2266   case ISD::TRUNCATE: {
2267     SDValue Src = Op.getOperand(0);
2268 
2269     // Simplify the input, using demanded bit information, and compute the known
2270     // zero/one bits live out.
2271     unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
2272     APInt TruncMask = DemandedBits.zext(OperandBitWidth);
2273     if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO,
2274                              Depth + 1))
2275       return true;
2276     Known = Known.trunc(BitWidth);
2277 
2278     // Attempt to avoid multi-use ops if we don't need anything from them.
2279     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2280             Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1))
2281       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc));
2282 
2283     // If the input is only used by this truncate, see if we can shrink it based
2284     // on the known demanded bits.
2285     if (Src.getNode()->hasOneUse()) {
2286       switch (Src.getOpcode()) {
2287       default:
2288         break;
2289       case ISD::SRL:
2290         // Shrink SRL by a constant if none of the high bits shifted in are
2291         // demanded.
2292         if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
2293           // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
2294           // undesirable.
2295           break;
2296 
2297         const APInt *ShAmtC =
2298             TLO.DAG.getValidShiftAmountConstant(Src, DemandedElts);
2299         if (!ShAmtC || ShAmtC->uge(BitWidth))
2300           break;
2301         uint64_t ShVal = ShAmtC->getZExtValue();
2302 
2303         APInt HighBits =
2304             APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
2305         HighBits.lshrInPlace(ShVal);
2306         HighBits = HighBits.trunc(BitWidth);
2307 
2308         if (!(HighBits & DemandedBits)) {
2309           // None of the shifted in bits are needed.  Add a truncate of the
2310           // shift input, then shift it.
2311           SDValue NewShAmt = TLO.DAG.getConstant(
2312               ShVal, dl, getShiftAmountTy(VT, DL, TLO.LegalTypes()));
2313           SDValue NewTrunc =
2314               TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
2315           return TLO.CombineTo(
2316               Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt));
2317         }
2318         break;
2319       }
2320     }
2321 
2322     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2323     break;
2324   }
2325   case ISD::AssertZext: {
2326     // AssertZext demands all of the high bits, plus any of the low bits
2327     // demanded by its users.
2328     EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2329     APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits());
2330     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
2331                              TLO, Depth + 1))
2332       return true;
2333     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2334 
2335     Known.Zero |= ~InMask;
2336     break;
2337   }
2338   case ISD::EXTRACT_VECTOR_ELT: {
2339     SDValue Src = Op.getOperand(0);
2340     SDValue Idx = Op.getOperand(1);
2341     ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount();
2342     unsigned EltBitWidth = Src.getScalarValueSizeInBits();
2343 
2344     if (SrcEltCnt.isScalable())
2345       return false;
2346 
2347     // Demand the bits from every vector element without a constant index.
2348     unsigned NumSrcElts = SrcEltCnt.getFixedValue();
2349     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
2350     if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
2351       if (CIdx->getAPIntValue().ult(NumSrcElts))
2352         DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
2353 
2354     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2355     // anything about the extended bits.
2356     APInt DemandedSrcBits = DemandedBits;
2357     if (BitWidth > EltBitWidth)
2358       DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
2359 
2360     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
2361                              Depth + 1))
2362       return true;
2363 
2364     // Attempt to avoid multi-use ops if we don't need anything from them.
2365     if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
2366       if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
2367               Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
2368         SDValue NewOp =
2369             TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx);
2370         return TLO.CombineTo(Op, NewOp);
2371       }
2372     }
2373 
2374     Known = Known2;
2375     if (BitWidth > EltBitWidth)
2376       Known = Known.anyext(BitWidth);
2377     break;
2378   }
2379   case ISD::BITCAST: {
2380     SDValue Src = Op.getOperand(0);
2381     EVT SrcVT = Src.getValueType();
2382     unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
2383 
2384     // If this is an FP->Int bitcast and if the sign bit is the only
2385     // thing demanded, turn this into a FGETSIGN.
2386     if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
2387         DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
2388         SrcVT.isFloatingPoint()) {
2389       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT);
2390       bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
2391       if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 &&
2392           SrcVT != MVT::f128) {
2393         // Cannot eliminate/lower SHL for f128 yet.
2394         EVT Ty = OpVTLegal ? VT : MVT::i32;
2395         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
2396         // place.  We expect the SHL to be eliminated by other optimizations.
2397         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src);
2398         unsigned OpVTSizeInBits = Op.getValueSizeInBits();
2399         if (!OpVTLegal && OpVTSizeInBits > 32)
2400           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign);
2401         unsigned ShVal = Op.getValueSizeInBits() - 1;
2402         SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT);
2403         return TLO.CombineTo(Op,
2404                              TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
2405       }
2406     }
2407 
2408     // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
2409     // Demand the elt/bit if any of the original elts/bits are demanded.
2410     if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) {
2411       unsigned Scale = BitWidth / NumSrcEltBits;
2412       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2413       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2414       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
2415       for (unsigned i = 0; i != Scale; ++i) {
2416         unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
2417         unsigned BitOffset = EltOffset * NumSrcEltBits;
2418         APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset);
2419         if (!Sub.isZero()) {
2420           DemandedSrcBits |= Sub;
2421           for (unsigned j = 0; j != NumElts; ++j)
2422             if (DemandedElts[j])
2423               DemandedSrcElts.setBit((j * Scale) + i);
2424         }
2425       }
2426 
2427       APInt KnownSrcUndef, KnownSrcZero;
2428       if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2429                                      KnownSrcZero, TLO, Depth + 1))
2430         return true;
2431 
2432       KnownBits KnownSrcBits;
2433       if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2434                                KnownSrcBits, TLO, Depth + 1))
2435         return true;
2436     } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) {
2437       // TODO - bigendian once we have test coverage.
2438       unsigned Scale = NumSrcEltBits / BitWidth;
2439       unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2440       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2441       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
2442       for (unsigned i = 0; i != NumElts; ++i)
2443         if (DemandedElts[i]) {
2444           unsigned Offset = (i % Scale) * BitWidth;
2445           DemandedSrcBits.insertBits(DemandedBits, Offset);
2446           DemandedSrcElts.setBit(i / Scale);
2447         }
2448 
2449       if (SrcVT.isVector()) {
2450         APInt KnownSrcUndef, KnownSrcZero;
2451         if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2452                                        KnownSrcZero, TLO, Depth + 1))
2453           return true;
2454       }
2455 
2456       KnownBits KnownSrcBits;
2457       if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2458                                KnownSrcBits, TLO, Depth + 1))
2459         return true;
2460     }
2461 
2462     // If this is a bitcast, let computeKnownBits handle it.  Only do this on a
2463     // recursive call where Known may be useful to the caller.
2464     if (Depth > 0) {
2465       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2466       return false;
2467     }
2468     break;
2469   }
2470   case ISD::MUL:
2471     if (DemandedBits.isPowerOf2()) {
2472       // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
2473       // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
2474       // odd (has LSB set), then the left-shifted low bit of X is the answer.
2475       unsigned CTZ = DemandedBits.countTrailingZeros();
2476       ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
2477       if (C && C->getAPIntValue().countTrailingZeros() == CTZ) {
2478         EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout());
2479         SDValue AmtC = TLO.DAG.getConstant(CTZ, dl, ShiftAmtTy);
2480         SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC);
2481         return TLO.CombineTo(Op, Shl);
2482       }
2483     }
2484     // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
2485     // X * X is odd iff X is odd.
2486     // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
2487     if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) {
2488       SDValue One = TLO.DAG.getConstant(1, dl, VT);
2489       SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One);
2490       return TLO.CombineTo(Op, And1);
2491     }
2492     LLVM_FALLTHROUGH;
2493   case ISD::ADD:
2494   case ISD::SUB: {
2495     // Add, Sub, and Mul don't demand any bits in positions beyond that
2496     // of the highest bit demanded of them.
2497     SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
2498     SDNodeFlags Flags = Op.getNode()->getFlags();
2499     unsigned DemandedBitsLZ = DemandedBits.countLeadingZeros();
2500     APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2501     if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, Known2, TLO,
2502                              Depth + 1) ||
2503         SimplifyDemandedBits(Op1, LoMask, DemandedElts, Known2, TLO,
2504                              Depth + 1) ||
2505         // See if the operation should be performed at a smaller bit width.
2506         ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) {
2507       if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
2508         // Disable the nsw and nuw flags. We can no longer guarantee that we
2509         // won't wrap after simplification.
2510         Flags.setNoSignedWrap(false);
2511         Flags.setNoUnsignedWrap(false);
2512         SDValue NewOp =
2513             TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
2514         return TLO.CombineTo(Op, NewOp);
2515       }
2516       return true;
2517     }
2518 
2519     // Attempt to avoid multi-use ops if we don't need anything from them.
2520     if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2521       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
2522           Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2523       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
2524           Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2525       if (DemandedOp0 || DemandedOp1) {
2526         Flags.setNoSignedWrap(false);
2527         Flags.setNoUnsignedWrap(false);
2528         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
2529         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
2530         SDValue NewOp =
2531             TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
2532         return TLO.CombineTo(Op, NewOp);
2533       }
2534     }
2535 
2536     // If we have a constant operand, we may be able to turn it into -1 if we
2537     // do not demand the high bits. This can make the constant smaller to
2538     // encode, allow more general folding, or match specialized instruction
2539     // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
2540     // is probably not useful (and could be detrimental).
2541     ConstantSDNode *C = isConstOrConstSplat(Op1);
2542     APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
2543     if (C && !C->isAllOnes() && !C->isOne() &&
2544         (C->getAPIntValue() | HighMask).isAllOnes()) {
2545       SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
2546       // Disable the nsw and nuw flags. We can no longer guarantee that we
2547       // won't wrap after simplification.
2548       Flags.setNoSignedWrap(false);
2549       Flags.setNoUnsignedWrap(false);
2550       SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags);
2551       return TLO.CombineTo(Op, NewOp);
2552     }
2553 
2554     // Match a multiply with a disguised negated-power-of-2 and convert to a
2555     // an equivalent shift-left amount.
2556     // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
2557     auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned {
2558       if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse())
2559         return 0;
2560 
2561       // Don't touch opaque constants. Also, ignore zero and power-of-2
2562       // multiplies. Those will get folded later.
2563       ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1));
2564       if (MulC && !MulC->isOpaque() && !MulC->isZero() &&
2565           !MulC->getAPIntValue().isPowerOf2()) {
2566         APInt UnmaskedC = MulC->getAPIntValue() | HighMask;
2567         if (UnmaskedC.isNegatedPowerOf2())
2568           return (-UnmaskedC).logBase2();
2569       }
2570       return 0;
2571     };
2572 
2573     auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y, unsigned ShlAmt) {
2574       EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout());
2575       SDValue ShlAmtC = TLO.DAG.getConstant(ShlAmt, dl, ShiftAmtTy);
2576       SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC);
2577       SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl);
2578       return TLO.CombineTo(Op, Res);
2579     };
2580 
2581     if (isOperationLegalOrCustom(ISD::SHL, VT)) {
2582       if (Op.getOpcode() == ISD::ADD) {
2583         // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
2584         if (unsigned ShAmt = getShiftLeftAmt(Op0))
2585           return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt);
2586         // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC))
2587         if (unsigned ShAmt = getShiftLeftAmt(Op1))
2588           return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt);
2589       }
2590       if (Op.getOpcode() == ISD::SUB) {
2591         // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC))
2592         if (unsigned ShAmt = getShiftLeftAmt(Op1))
2593           return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt);
2594       }
2595     }
2596 
2597     LLVM_FALLTHROUGH;
2598   }
2599   default:
2600     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
2601       if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts,
2602                                             Known, TLO, Depth))
2603         return true;
2604       break;
2605     }
2606 
2607     // Just use computeKnownBits to compute output bits.
2608     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2609     break;
2610   }
2611 
2612   // If we know the value of all of the demanded bits, return this as a
2613   // constant.
2614   if (!isTargetCanonicalConstantNode(Op) &&
2615       DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
2616     // Avoid folding to a constant if any OpaqueConstant is involved.
2617     const SDNode *N = Op.getNode();
2618     for (SDNode *Op :
2619          llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) {
2620       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
2621         if (C->isOpaque())
2622           return false;
2623     }
2624     if (VT.isInteger())
2625       return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
2626     if (VT.isFloatingPoint())
2627       return TLO.CombineTo(
2628           Op,
2629           TLO.DAG.getConstantFP(
2630               APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT));
2631   }
2632 
2633   return false;
2634 }
2635 
2636 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op,
2637                                                 const APInt &DemandedElts,
2638                                                 DAGCombinerInfo &DCI) const {
2639   SelectionDAG &DAG = DCI.DAG;
2640   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
2641                         !DCI.isBeforeLegalizeOps());
2642 
2643   APInt KnownUndef, KnownZero;
2644   bool Simplified =
2645       SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
2646   if (Simplified) {
2647     DCI.AddToWorklist(Op.getNode());
2648     DCI.CommitTargetLoweringOpt(TLO);
2649   }
2650 
2651   return Simplified;
2652 }
2653 
2654 /// Given a vector binary operation and known undefined elements for each input
2655 /// operand, compute whether each element of the output is undefined.
2656 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG,
2657                                          const APInt &UndefOp0,
2658                                          const APInt &UndefOp1) {
2659   EVT VT = BO.getValueType();
2660   assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() &&
2661          "Vector binop only");
2662 
2663   EVT EltVT = VT.getVectorElementType();
2664   unsigned NumElts = VT.getVectorNumElements();
2665   assert(UndefOp0.getBitWidth() == NumElts &&
2666          UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
2667 
2668   auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
2669                                    const APInt &UndefVals) {
2670     if (UndefVals[Index])
2671       return DAG.getUNDEF(EltVT);
2672 
2673     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2674       // Try hard to make sure that the getNode() call is not creating temporary
2675       // nodes. Ignore opaque integers because they do not constant fold.
2676       SDValue Elt = BV->getOperand(Index);
2677       auto *C = dyn_cast<ConstantSDNode>(Elt);
2678       if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
2679         return Elt;
2680     }
2681 
2682     return SDValue();
2683   };
2684 
2685   APInt KnownUndef = APInt::getZero(NumElts);
2686   for (unsigned i = 0; i != NumElts; ++i) {
2687     // If both inputs for this element are either constant or undef and match
2688     // the element type, compute the constant/undef result for this element of
2689     // the vector.
2690     // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
2691     // not handle FP constants. The code within getNode() should be refactored
2692     // to avoid the danger of creating a bogus temporary node here.
2693     SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
2694     SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
2695     if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
2696       if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
2697         KnownUndef.setBit(i);
2698   }
2699   return KnownUndef;
2700 }
2701 
2702 bool TargetLowering::SimplifyDemandedVectorElts(
2703     SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
2704     APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
2705     bool AssumeSingleUse) const {
2706   EVT VT = Op.getValueType();
2707   unsigned Opcode = Op.getOpcode();
2708   APInt DemandedElts = OriginalDemandedElts;
2709   unsigned NumElts = DemandedElts.getBitWidth();
2710   assert(VT.isVector() && "Expected vector op");
2711 
2712   KnownUndef = KnownZero = APInt::getZero(NumElts);
2713 
2714   const TargetLowering &TLI = TLO.DAG.getTargetLoweringInfo();
2715   if (!TLI.shouldSimplifyDemandedVectorElts(Op, TLO))
2716     return false;
2717 
2718   // TODO: For now we assume we know nothing about scalable vectors.
2719   if (VT.isScalableVector())
2720     return false;
2721 
2722   assert(VT.getVectorNumElements() == NumElts &&
2723          "Mask size mismatches value type element count!");
2724 
2725   // Undef operand.
2726   if (Op.isUndef()) {
2727     KnownUndef.setAllBits();
2728     return false;
2729   }
2730 
2731   // If Op has other users, assume that all elements are needed.
2732   if (!Op.getNode()->hasOneUse() && !AssumeSingleUse)
2733     DemandedElts.setAllBits();
2734 
2735   // Not demanding any elements from Op.
2736   if (DemandedElts == 0) {
2737     KnownUndef.setAllBits();
2738     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2739   }
2740 
2741   // Limit search depth.
2742   if (Depth >= SelectionDAG::MaxRecursionDepth)
2743     return false;
2744 
2745   SDLoc DL(Op);
2746   unsigned EltSizeInBits = VT.getScalarSizeInBits();
2747   bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
2748 
2749   // Helper for demanding the specified elements and all the bits of both binary
2750   // operands.
2751   auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) {
2752     SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts,
2753                                                            TLO.DAG, Depth + 1);
2754     SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts,
2755                                                            TLO.DAG, Depth + 1);
2756     if (NewOp0 || NewOp1) {
2757       SDValue NewOp = TLO.DAG.getNode(
2758           Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0, NewOp1 ? NewOp1 : Op1);
2759       return TLO.CombineTo(Op, NewOp);
2760     }
2761     return false;
2762   };
2763 
2764   switch (Opcode) {
2765   case ISD::SCALAR_TO_VECTOR: {
2766     if (!DemandedElts[0]) {
2767       KnownUndef.setAllBits();
2768       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
2769     }
2770     SDValue ScalarSrc = Op.getOperand(0);
2771     if (ScalarSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
2772       SDValue Src = ScalarSrc.getOperand(0);
2773       SDValue Idx = ScalarSrc.getOperand(1);
2774       EVT SrcVT = Src.getValueType();
2775 
2776       ElementCount SrcEltCnt = SrcVT.getVectorElementCount();
2777 
2778       if (SrcEltCnt.isScalable())
2779         return false;
2780 
2781       unsigned NumSrcElts = SrcEltCnt.getFixedValue();
2782       if (isNullConstant(Idx)) {
2783         APInt SrcDemandedElts = APInt::getOneBitSet(NumSrcElts, 0);
2784         APInt SrcUndef = KnownUndef.zextOrTrunc(NumSrcElts);
2785         APInt SrcZero = KnownZero.zextOrTrunc(NumSrcElts);
2786         if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2787                                        TLO, Depth + 1))
2788           return true;
2789       }
2790     }
2791     KnownUndef.setHighBits(NumElts - 1);
2792     break;
2793   }
2794   case ISD::BITCAST: {
2795     SDValue Src = Op.getOperand(0);
2796     EVT SrcVT = Src.getValueType();
2797 
2798     // We only handle vectors here.
2799     // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits?
2800     if (!SrcVT.isVector())
2801       break;
2802 
2803     // Fast handling of 'identity' bitcasts.
2804     unsigned NumSrcElts = SrcVT.getVectorNumElements();
2805     if (NumSrcElts == NumElts)
2806       return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
2807                                         KnownZero, TLO, Depth + 1);
2808 
2809     APInt SrcDemandedElts, SrcZero, SrcUndef;
2810 
2811     // Bitcast from 'large element' src vector to 'small element' vector, we
2812     // must demand a source element if any DemandedElt maps to it.
2813     if ((NumElts % NumSrcElts) == 0) {
2814       unsigned Scale = NumElts / NumSrcElts;
2815       SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2816       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2817                                      TLO, Depth + 1))
2818         return true;
2819 
2820       // Try calling SimplifyDemandedBits, converting demanded elts to the bits
2821       // of the large element.
2822       // TODO - bigendian once we have test coverage.
2823       if (IsLE) {
2824         unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
2825         APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits);
2826         for (unsigned i = 0; i != NumElts; ++i)
2827           if (DemandedElts[i]) {
2828             unsigned Ofs = (i % Scale) * EltSizeInBits;
2829             SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
2830           }
2831 
2832         KnownBits Known;
2833         if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known,
2834                                  TLO, Depth + 1))
2835           return true;
2836 
2837         // The bitcast has split each wide element into a number of
2838         // narrow subelements. We have just computed the Known bits
2839         // for wide elements. See if element splitting results in
2840         // some subelements being zero. Only for demanded elements!
2841         for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) {
2842           if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits)
2843                    .isAllOnes())
2844             continue;
2845           for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) {
2846             unsigned Elt = Scale * SrcElt + SubElt;
2847             if (DemandedElts[Elt])
2848               KnownZero.setBit(Elt);
2849           }
2850         }
2851       }
2852 
2853       // If the src element is zero/undef then all the output elements will be -
2854       // only demanded elements are guaranteed to be correct.
2855       for (unsigned i = 0; i != NumSrcElts; ++i) {
2856         if (SrcDemandedElts[i]) {
2857           if (SrcZero[i])
2858             KnownZero.setBits(i * Scale, (i + 1) * Scale);
2859           if (SrcUndef[i])
2860             KnownUndef.setBits(i * Scale, (i + 1) * Scale);
2861         }
2862       }
2863     }
2864 
2865     // Bitcast from 'small element' src vector to 'large element' vector, we
2866     // demand all smaller source elements covered by the larger demanded element
2867     // of this vector.
2868     if ((NumSrcElts % NumElts) == 0) {
2869       unsigned Scale = NumSrcElts / NumElts;
2870       SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
2871       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
2872                                      TLO, Depth + 1))
2873         return true;
2874 
2875       // If all the src elements covering an output element are zero/undef, then
2876       // the output element will be as well, assuming it was demanded.
2877       for (unsigned i = 0; i != NumElts; ++i) {
2878         if (DemandedElts[i]) {
2879           if (SrcZero.extractBits(Scale, i * Scale).isAllOnes())
2880             KnownZero.setBit(i);
2881           if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes())
2882             KnownUndef.setBit(i);
2883         }
2884       }
2885     }
2886     break;
2887   }
2888   case ISD::BUILD_VECTOR: {
2889     // Check all elements and simplify any unused elements with UNDEF.
2890     if (!DemandedElts.isAllOnes()) {
2891       // Don't simplify BROADCASTS.
2892       if (llvm::any_of(Op->op_values(),
2893                        [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
2894         SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end());
2895         bool Updated = false;
2896         for (unsigned i = 0; i != NumElts; ++i) {
2897           if (!DemandedElts[i] && !Ops[i].isUndef()) {
2898             Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
2899             KnownUndef.setBit(i);
2900             Updated = true;
2901           }
2902         }
2903         if (Updated)
2904           return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
2905       }
2906     }
2907     for (unsigned i = 0; i != NumElts; ++i) {
2908       SDValue SrcOp = Op.getOperand(i);
2909       if (SrcOp.isUndef()) {
2910         KnownUndef.setBit(i);
2911       } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
2912                  (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) {
2913         KnownZero.setBit(i);
2914       }
2915     }
2916     break;
2917   }
2918   case ISD::CONCAT_VECTORS: {
2919     EVT SubVT = Op.getOperand(0).getValueType();
2920     unsigned NumSubVecs = Op.getNumOperands();
2921     unsigned NumSubElts = SubVT.getVectorNumElements();
2922     for (unsigned i = 0; i != NumSubVecs; ++i) {
2923       SDValue SubOp = Op.getOperand(i);
2924       APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
2925       APInt SubUndef, SubZero;
2926       if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
2927                                      Depth + 1))
2928         return true;
2929       KnownUndef.insertBits(SubUndef, i * NumSubElts);
2930       KnownZero.insertBits(SubZero, i * NumSubElts);
2931     }
2932 
2933     // Attempt to avoid multi-use ops if we don't need anything from them.
2934     if (!DemandedElts.isAllOnes()) {
2935       bool FoundNewSub = false;
2936       SmallVector<SDValue, 2> DemandedSubOps;
2937       for (unsigned i = 0; i != NumSubVecs; ++i) {
2938         SDValue SubOp = Op.getOperand(i);
2939         APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
2940         SDValue NewSubOp = SimplifyMultipleUseDemandedVectorElts(
2941             SubOp, SubElts, TLO.DAG, Depth + 1);
2942         DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp);
2943         FoundNewSub = NewSubOp ? true : FoundNewSub;
2944       }
2945       if (FoundNewSub) {
2946         SDValue NewOp =
2947             TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps);
2948         return TLO.CombineTo(Op, NewOp);
2949       }
2950     }
2951     break;
2952   }
2953   case ISD::INSERT_SUBVECTOR: {
2954     // Demand any elements from the subvector and the remainder from the src its
2955     // inserted into.
2956     SDValue Src = Op.getOperand(0);
2957     SDValue Sub = Op.getOperand(1);
2958     uint64_t Idx = Op.getConstantOperandVal(2);
2959     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2960     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2961     APInt DemandedSrcElts = DemandedElts;
2962     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
2963 
2964     APInt SubUndef, SubZero;
2965     if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
2966                                    Depth + 1))
2967       return true;
2968 
2969     // If none of the src operand elements are demanded, replace it with undef.
2970     if (!DemandedSrcElts && !Src.isUndef())
2971       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
2972                                                TLO.DAG.getUNDEF(VT), Sub,
2973                                                Op.getOperand(2)));
2974 
2975     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
2976                                    TLO, Depth + 1))
2977       return true;
2978     KnownUndef.insertBits(SubUndef, Idx);
2979     KnownZero.insertBits(SubZero, Idx);
2980 
2981     // Attempt to avoid multi-use ops if we don't need anything from them.
2982     if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) {
2983       SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
2984           Src, DemandedSrcElts, TLO.DAG, Depth + 1);
2985       SDValue NewSub = SimplifyMultipleUseDemandedVectorElts(
2986           Sub, DemandedSubElts, TLO.DAG, Depth + 1);
2987       if (NewSrc || NewSub) {
2988         NewSrc = NewSrc ? NewSrc : Src;
2989         NewSub = NewSub ? NewSub : Sub;
2990         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
2991                                         NewSub, Op.getOperand(2));
2992         return TLO.CombineTo(Op, NewOp);
2993       }
2994     }
2995     break;
2996   }
2997   case ISD::EXTRACT_SUBVECTOR: {
2998     // Offset the demanded elts by the subvector index.
2999     SDValue Src = Op.getOperand(0);
3000     if (Src.getValueType().isScalableVector())
3001       break;
3002     uint64_t Idx = Op.getConstantOperandVal(1);
3003     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3004     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3005 
3006     APInt SrcUndef, SrcZero;
3007     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3008                                    Depth + 1))
3009       return true;
3010     KnownUndef = SrcUndef.extractBits(NumElts, Idx);
3011     KnownZero = SrcZero.extractBits(NumElts, Idx);
3012 
3013     // Attempt to avoid multi-use ops if we don't need anything from them.
3014     if (!DemandedElts.isAllOnes()) {
3015       SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
3016           Src, DemandedSrcElts, TLO.DAG, Depth + 1);
3017       if (NewSrc) {
3018         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3019                                         Op.getOperand(1));
3020         return TLO.CombineTo(Op, NewOp);
3021       }
3022     }
3023     break;
3024   }
3025   case ISD::INSERT_VECTOR_ELT: {
3026     SDValue Vec = Op.getOperand(0);
3027     SDValue Scl = Op.getOperand(1);
3028     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3029 
3030     // For a legal, constant insertion index, if we don't need this insertion
3031     // then strip it, else remove it from the demanded elts.
3032     if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
3033       unsigned Idx = CIdx->getZExtValue();
3034       if (!DemandedElts[Idx])
3035         return TLO.CombineTo(Op, Vec);
3036 
3037       APInt DemandedVecElts(DemandedElts);
3038       DemandedVecElts.clearBit(Idx);
3039       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
3040                                      KnownZero, TLO, Depth + 1))
3041         return true;
3042 
3043       KnownUndef.setBitVal(Idx, Scl.isUndef());
3044 
3045       KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl));
3046       break;
3047     }
3048 
3049     APInt VecUndef, VecZero;
3050     if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
3051                                    Depth + 1))
3052       return true;
3053     // Without knowing the insertion index we can't set KnownUndef/KnownZero.
3054     break;
3055   }
3056   case ISD::VSELECT: {
3057     // Try to transform the select condition based on the current demanded
3058     // elements.
3059     // TODO: If a condition element is undef, we can choose from one arm of the
3060     //       select (and if one arm is undef, then we can propagate that to the
3061     //       result).
3062     // TODO - add support for constant vselect masks (see IR version of this).
3063     APInt UnusedUndef, UnusedZero;
3064     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, UnusedUndef,
3065                                    UnusedZero, TLO, Depth + 1))
3066       return true;
3067 
3068     // See if we can simplify either vselect operand.
3069     APInt DemandedLHS(DemandedElts);
3070     APInt DemandedRHS(DemandedElts);
3071     APInt UndefLHS, ZeroLHS;
3072     APInt UndefRHS, ZeroRHS;
3073     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedLHS, UndefLHS,
3074                                    ZeroLHS, TLO, Depth + 1))
3075       return true;
3076     if (SimplifyDemandedVectorElts(Op.getOperand(2), DemandedRHS, UndefRHS,
3077                                    ZeroRHS, TLO, Depth + 1))
3078       return true;
3079 
3080     KnownUndef = UndefLHS & UndefRHS;
3081     KnownZero = ZeroLHS & ZeroRHS;
3082     break;
3083   }
3084   case ISD::VECTOR_SHUFFLE: {
3085     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
3086 
3087     // Collect demanded elements from shuffle operands..
3088     APInt DemandedLHS(NumElts, 0);
3089     APInt DemandedRHS(NumElts, 0);
3090     for (unsigned i = 0; i != NumElts; ++i) {
3091       int M = ShuffleMask[i];
3092       if (M < 0 || !DemandedElts[i])
3093         continue;
3094       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
3095       if (M < (int)NumElts)
3096         DemandedLHS.setBit(M);
3097       else
3098         DemandedRHS.setBit(M - NumElts);
3099     }
3100 
3101     // See if we can simplify either shuffle operand.
3102     APInt UndefLHS, ZeroLHS;
3103     APInt UndefRHS, ZeroRHS;
3104     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedLHS, UndefLHS,
3105                                    ZeroLHS, TLO, Depth + 1))
3106       return true;
3107     if (SimplifyDemandedVectorElts(Op.getOperand(1), DemandedRHS, UndefRHS,
3108                                    ZeroRHS, TLO, Depth + 1))
3109       return true;
3110 
3111     // Simplify mask using undef elements from LHS/RHS.
3112     bool Updated = false;
3113     bool IdentityLHS = true, IdentityRHS = true;
3114     SmallVector<int, 32> NewMask(ShuffleMask.begin(), ShuffleMask.end());
3115     for (unsigned i = 0; i != NumElts; ++i) {
3116       int &M = NewMask[i];
3117       if (M < 0)
3118         continue;
3119       if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
3120           (M >= (int)NumElts && UndefRHS[M - NumElts])) {
3121         Updated = true;
3122         M = -1;
3123       }
3124       IdentityLHS &= (M < 0) || (M == (int)i);
3125       IdentityRHS &= (M < 0) || ((M - NumElts) == i);
3126     }
3127 
3128     // Update legal shuffle masks based on demanded elements if it won't reduce
3129     // to Identity which can cause premature removal of the shuffle mask.
3130     if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
3131       SDValue LegalShuffle =
3132           buildLegalVectorShuffle(VT, DL, Op.getOperand(0), Op.getOperand(1),
3133                                   NewMask, TLO.DAG);
3134       if (LegalShuffle)
3135         return TLO.CombineTo(Op, LegalShuffle);
3136     }
3137 
3138     // Propagate undef/zero elements from LHS/RHS.
3139     for (unsigned i = 0; i != NumElts; ++i) {
3140       int M = ShuffleMask[i];
3141       if (M < 0) {
3142         KnownUndef.setBit(i);
3143       } else if (M < (int)NumElts) {
3144         if (UndefLHS[M])
3145           KnownUndef.setBit(i);
3146         if (ZeroLHS[M])
3147           KnownZero.setBit(i);
3148       } else {
3149         if (UndefRHS[M - NumElts])
3150           KnownUndef.setBit(i);
3151         if (ZeroRHS[M - NumElts])
3152           KnownZero.setBit(i);
3153       }
3154     }
3155     break;
3156   }
3157   case ISD::ANY_EXTEND_VECTOR_INREG:
3158   case ISD::SIGN_EXTEND_VECTOR_INREG:
3159   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3160     APInt SrcUndef, SrcZero;
3161     SDValue Src = Op.getOperand(0);
3162     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3163     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3164     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3165                                    Depth + 1))
3166       return true;
3167     KnownZero = SrcZero.zextOrTrunc(NumElts);
3168     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
3169 
3170     if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
3171         Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
3172         DemandedSrcElts == 1) {
3173       // aext - if we just need the bottom element then we can bitcast.
3174       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
3175     }
3176 
3177     if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
3178       // zext(undef) upper bits are guaranteed to be zero.
3179       if (DemandedElts.isSubsetOf(KnownUndef))
3180         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3181       KnownUndef.clearAllBits();
3182 
3183       // zext - if we just need the bottom element then we can mask:
3184       // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and.
3185       if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND &&
3186           Op->isOnlyUserOf(Src.getNode()) &&
3187           Op.getValueSizeInBits() == Src.getValueSizeInBits()) {
3188         SDLoc DL(Op);
3189         EVT SrcVT = Src.getValueType();
3190         EVT SrcSVT = SrcVT.getScalarType();
3191         SmallVector<SDValue> MaskElts;
3192         MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT));
3193         MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT));
3194         SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts);
3195         if (SDValue Fold = TLO.DAG.FoldConstantArithmetic(
3196                 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) {
3197           Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold);
3198           return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold));
3199         }
3200       }
3201     }
3202     break;
3203   }
3204 
3205   // TODO: There are more binop opcodes that could be handled here - MIN,
3206   // MAX, saturated math, etc.
3207   case ISD::ADD: {
3208     SDValue Op0 = Op.getOperand(0);
3209     SDValue Op1 = Op.getOperand(1);
3210     if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) {
3211       APInt UndefLHS, ZeroLHS;
3212       if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3213                                      Depth + 1, /*AssumeSingleUse*/ true))
3214         return true;
3215     }
3216     LLVM_FALLTHROUGH;
3217   }
3218   case ISD::OR:
3219   case ISD::XOR:
3220   case ISD::SUB:
3221   case ISD::FADD:
3222   case ISD::FSUB:
3223   case ISD::FMUL:
3224   case ISD::FDIV:
3225   case ISD::FREM: {
3226     SDValue Op0 = Op.getOperand(0);
3227     SDValue Op1 = Op.getOperand(1);
3228 
3229     APInt UndefRHS, ZeroRHS;
3230     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3231                                    Depth + 1))
3232       return true;
3233     APInt UndefLHS, ZeroLHS;
3234     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3235                                    Depth + 1))
3236       return true;
3237 
3238     KnownZero = ZeroLHS & ZeroRHS;
3239     KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
3240 
3241     // Attempt to avoid multi-use ops if we don't need anything from them.
3242     // TODO - use KnownUndef to relax the demandedelts?
3243     if (!DemandedElts.isAllOnes())
3244       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3245         return true;
3246     break;
3247   }
3248   case ISD::SHL:
3249   case ISD::SRL:
3250   case ISD::SRA:
3251   case ISD::ROTL:
3252   case ISD::ROTR: {
3253     SDValue Op0 = Op.getOperand(0);
3254     SDValue Op1 = Op.getOperand(1);
3255 
3256     APInt UndefRHS, ZeroRHS;
3257     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3258                                    Depth + 1))
3259       return true;
3260     APInt UndefLHS, ZeroLHS;
3261     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3262                                    Depth + 1))
3263       return true;
3264 
3265     KnownZero = ZeroLHS;
3266     KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
3267 
3268     // Attempt to avoid multi-use ops if we don't need anything from them.
3269     // TODO - use KnownUndef to relax the demandedelts?
3270     if (!DemandedElts.isAllOnes())
3271       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3272         return true;
3273     break;
3274   }
3275   case ISD::MUL:
3276   case ISD::AND: {
3277     SDValue Op0 = Op.getOperand(0);
3278     SDValue Op1 = Op.getOperand(1);
3279 
3280     APInt SrcUndef, SrcZero;
3281     if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
3282                                    Depth + 1))
3283       return true;
3284     if (SimplifyDemandedVectorElts(Op0, DemandedElts, KnownUndef, KnownZero,
3285                                    TLO, Depth + 1))
3286       return true;
3287 
3288     // If either side has a zero element, then the result element is zero, even
3289     // if the other is an UNDEF.
3290     // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
3291     // and then handle 'and' nodes with the rest of the binop opcodes.
3292     KnownZero |= SrcZero;
3293     KnownUndef &= SrcUndef;
3294     KnownUndef &= ~KnownZero;
3295 
3296     // Attempt to avoid multi-use ops if we don't need anything from them.
3297     // TODO - use KnownUndef to relax the demandedelts?
3298     if (!DemandedElts.isAllOnes())
3299       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3300         return true;
3301     break;
3302   }
3303   case ISD::TRUNCATE:
3304   case ISD::SIGN_EXTEND:
3305   case ISD::ZERO_EXTEND:
3306     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
3307                                    KnownZero, TLO, Depth + 1))
3308       return true;
3309 
3310     if (Op.getOpcode() == ISD::ZERO_EXTEND) {
3311       // zext(undef) upper bits are guaranteed to be zero.
3312       if (DemandedElts.isSubsetOf(KnownUndef))
3313         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3314       KnownUndef.clearAllBits();
3315     }
3316     break;
3317   default: {
3318     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
3319       if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
3320                                                   KnownZero, TLO, Depth))
3321         return true;
3322     } else {
3323       KnownBits Known;
3324       APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
3325       if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
3326                                TLO, Depth, AssumeSingleUse))
3327         return true;
3328     }
3329     break;
3330   }
3331   }
3332   assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
3333 
3334   // Constant fold all undef cases.
3335   // TODO: Handle zero cases as well.
3336   if (DemandedElts.isSubsetOf(KnownUndef))
3337     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3338 
3339   return false;
3340 }
3341 
3342 /// Determine which of the bits specified in Mask are known to be either zero or
3343 /// one and return them in the Known.
3344 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
3345                                                    KnownBits &Known,
3346                                                    const APInt &DemandedElts,
3347                                                    const SelectionDAG &DAG,
3348                                                    unsigned Depth) const {
3349   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3350           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3351           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3352           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3353          "Should use MaskedValueIsZero if you don't know whether Op"
3354          " is a target node!");
3355   Known.resetAll();
3356 }
3357 
3358 void TargetLowering::computeKnownBitsForTargetInstr(
3359     GISelKnownBits &Analysis, Register R, KnownBits &Known,
3360     const APInt &DemandedElts, const MachineRegisterInfo &MRI,
3361     unsigned Depth) const {
3362   Known.resetAll();
3363 }
3364 
3365 void TargetLowering::computeKnownBitsForFrameIndex(
3366   const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const {
3367   // The low bits are known zero if the pointer is aligned.
3368   Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx)));
3369 }
3370 
3371 Align TargetLowering::computeKnownAlignForTargetInstr(
3372   GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI,
3373   unsigned Depth) const {
3374   return Align(1);
3375 }
3376 
3377 /// This method can be implemented by targets that want to expose additional
3378 /// information about sign bits to the DAG Combiner.
3379 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
3380                                                          const APInt &,
3381                                                          const SelectionDAG &,
3382                                                          unsigned Depth) const {
3383   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3384           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3385           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3386           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3387          "Should use ComputeNumSignBits if you don't know whether Op"
3388          " is a target node!");
3389   return 1;
3390 }
3391 
3392 unsigned TargetLowering::computeNumSignBitsForTargetInstr(
3393   GISelKnownBits &Analysis, Register R, const APInt &DemandedElts,
3394   const MachineRegisterInfo &MRI, unsigned Depth) const {
3395   return 1;
3396 }
3397 
3398 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
3399     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
3400     TargetLoweringOpt &TLO, unsigned Depth) const {
3401   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3402           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3403           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3404           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3405          "Should use SimplifyDemandedVectorElts if you don't know whether Op"
3406          " is a target node!");
3407   return false;
3408 }
3409 
3410 bool TargetLowering::SimplifyDemandedBitsForTargetNode(
3411     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3412     KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
3413   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3414           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3415           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3416           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3417          "Should use SimplifyDemandedBits if you don't know whether Op"
3418          " is a target node!");
3419   computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
3420   return false;
3421 }
3422 
3423 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
3424     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3425     SelectionDAG &DAG, unsigned Depth) const {
3426   assert(
3427       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3428        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3429        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3430        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3431       "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
3432       " is a target node!");
3433   return SDValue();
3434 }
3435 
3436 SDValue
3437 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0,
3438                                         SDValue N1, MutableArrayRef<int> Mask,
3439                                         SelectionDAG &DAG) const {
3440   bool LegalMask = isShuffleMaskLegal(Mask, VT);
3441   if (!LegalMask) {
3442     std::swap(N0, N1);
3443     ShuffleVectorSDNode::commuteMask(Mask);
3444     LegalMask = isShuffleMaskLegal(Mask, VT);
3445   }
3446 
3447   if (!LegalMask)
3448     return SDValue();
3449 
3450   return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
3451 }
3452 
3453 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const {
3454   return nullptr;
3455 }
3456 
3457 bool TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode(
3458     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
3459     bool PoisonOnly, unsigned Depth) const {
3460   assert(
3461       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3462        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3463        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3464        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3465       "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op"
3466       " is a target node!");
3467   return false;
3468 }
3469 
3470 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
3471                                                   const SelectionDAG &DAG,
3472                                                   bool SNaN,
3473                                                   unsigned Depth) const {
3474   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3475           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3476           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3477           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3478          "Should use isKnownNeverNaN if you don't know whether Op"
3479          " is a target node!");
3480   return false;
3481 }
3482 
3483 bool TargetLowering::isSplatValueForTargetNode(SDValue Op,
3484                                                const APInt &DemandedElts,
3485                                                APInt &UndefElts,
3486                                                unsigned Depth) const {
3487   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3488           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3489           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3490           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3491          "Should use isSplatValue if you don't know whether Op"
3492          " is a target node!");
3493   return false;
3494 }
3495 
3496 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
3497 // work with truncating build vectors and vectors with elements of less than
3498 // 8 bits.
3499 bool TargetLowering::isConstTrueVal(SDValue N) const {
3500   if (!N)
3501     return false;
3502 
3503   unsigned EltWidth;
3504   APInt CVal;
3505   if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false,
3506                                                /*AllowTruncation=*/true)) {
3507     CVal = CN->getAPIntValue();
3508     EltWidth = N.getValueType().getScalarSizeInBits();
3509   } else
3510     return false;
3511 
3512   // If this is a truncating splat, truncate the splat value.
3513   // Otherwise, we may fail to match the expected values below.
3514   if (EltWidth < CVal.getBitWidth())
3515     CVal = CVal.trunc(EltWidth);
3516 
3517   switch (getBooleanContents(N.getValueType())) {
3518   case UndefinedBooleanContent:
3519     return CVal[0];
3520   case ZeroOrOneBooleanContent:
3521     return CVal.isOne();
3522   case ZeroOrNegativeOneBooleanContent:
3523     return CVal.isAllOnes();
3524   }
3525 
3526   llvm_unreachable("Invalid boolean contents");
3527 }
3528 
3529 bool TargetLowering::isConstFalseVal(SDValue N) const {
3530   if (!N)
3531     return false;
3532 
3533   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
3534   if (!CN) {
3535     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
3536     if (!BV)
3537       return false;
3538 
3539     // Only interested in constant splats, we don't care about undef
3540     // elements in identifying boolean constants and getConstantSplatNode
3541     // returns NULL if all ops are undef;
3542     CN = BV->getConstantSplatNode();
3543     if (!CN)
3544       return false;
3545   }
3546 
3547   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
3548     return !CN->getAPIntValue()[0];
3549 
3550   return CN->isZero();
3551 }
3552 
3553 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
3554                                        bool SExt) const {
3555   if (VT == MVT::i1)
3556     return N->isOne();
3557 
3558   TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
3559   switch (Cnt) {
3560   case TargetLowering::ZeroOrOneBooleanContent:
3561     // An extended value of 1 is always true, unless its original type is i1,
3562     // in which case it will be sign extended to -1.
3563     return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
3564   case TargetLowering::UndefinedBooleanContent:
3565   case TargetLowering::ZeroOrNegativeOneBooleanContent:
3566     return N->isAllOnes() && SExt;
3567   }
3568   llvm_unreachable("Unexpected enumeration.");
3569 }
3570 
3571 /// This helper function of SimplifySetCC tries to optimize the comparison when
3572 /// either operand of the SetCC node is a bitwise-and instruction.
3573 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
3574                                          ISD::CondCode Cond, const SDLoc &DL,
3575                                          DAGCombinerInfo &DCI) const {
3576   if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
3577     std::swap(N0, N1);
3578 
3579   SelectionDAG &DAG = DCI.DAG;
3580   EVT OpVT = N0.getValueType();
3581   if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
3582       (Cond != ISD::SETEQ && Cond != ISD::SETNE))
3583     return SDValue();
3584 
3585   // (X & Y) != 0 --> zextOrTrunc(X & Y)
3586   // iff everything but LSB is known zero:
3587   if (Cond == ISD::SETNE && isNullConstant(N1) &&
3588       (getBooleanContents(OpVT) == TargetLowering::UndefinedBooleanContent ||
3589        getBooleanContents(OpVT) == TargetLowering::ZeroOrOneBooleanContent)) {
3590     unsigned NumEltBits = OpVT.getScalarSizeInBits();
3591     APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1);
3592     if (DAG.MaskedValueIsZero(N0, UpperBits))
3593       return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT);
3594   }
3595 
3596   // Match these patterns in any of their permutations:
3597   // (X & Y) == Y
3598   // (X & Y) != Y
3599   SDValue X, Y;
3600   if (N0.getOperand(0) == N1) {
3601     X = N0.getOperand(1);
3602     Y = N0.getOperand(0);
3603   } else if (N0.getOperand(1) == N1) {
3604     X = N0.getOperand(0);
3605     Y = N0.getOperand(1);
3606   } else {
3607     return SDValue();
3608   }
3609 
3610   SDValue Zero = DAG.getConstant(0, DL, OpVT);
3611   if (DAG.isKnownToBeAPowerOfTwo(Y)) {
3612     // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
3613     // Note that where Y is variable and is known to have at most one bit set
3614     // (for example, if it is Z & 1) we cannot do this; the expressions are not
3615     // equivalent when Y == 0.
3616     assert(OpVT.isInteger());
3617     Cond = ISD::getSetCCInverse(Cond, OpVT);
3618     if (DCI.isBeforeLegalizeOps() ||
3619         isCondCodeLegal(Cond, N0.getSimpleValueType()))
3620       return DAG.getSetCC(DL, VT, N0, Zero, Cond);
3621   } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
3622     // If the target supports an 'and-not' or 'and-complement' logic operation,
3623     // try to use that to make a comparison operation more efficient.
3624     // But don't do this transform if the mask is a single bit because there are
3625     // more efficient ways to deal with that case (for example, 'bt' on x86 or
3626     // 'rlwinm' on PPC).
3627 
3628     // Bail out if the compare operand that we want to turn into a zero is
3629     // already a zero (otherwise, infinite loop).
3630     auto *YConst = dyn_cast<ConstantSDNode>(Y);
3631     if (YConst && YConst->isZero())
3632       return SDValue();
3633 
3634     // Transform this into: ~X & Y == 0.
3635     SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
3636     SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
3637     return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
3638   }
3639 
3640   return SDValue();
3641 }
3642 
3643 /// There are multiple IR patterns that could be checking whether certain
3644 /// truncation of a signed number would be lossy or not. The pattern which is
3645 /// best at IR level, may not lower optimally. Thus, we want to unfold it.
3646 /// We are looking for the following pattern: (KeptBits is a constant)
3647 ///   (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
3648 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
3649 /// KeptBits also can't be 1, that would have been folded to  %x dstcond 0
3650 /// We will unfold it into the natural trunc+sext pattern:
3651 ///   ((%x << C) a>> C) dstcond %x
3652 /// Where  C = bitwidth(x) - KeptBits  and  C u< bitwidth(x)
3653 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
3654     EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
3655     const SDLoc &DL) const {
3656   // We must be comparing with a constant.
3657   ConstantSDNode *C1;
3658   if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
3659     return SDValue();
3660 
3661   // N0 should be:  add %x, (1 << (KeptBits-1))
3662   if (N0->getOpcode() != ISD::ADD)
3663     return SDValue();
3664 
3665   // And we must be 'add'ing a constant.
3666   ConstantSDNode *C01;
3667   if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
3668     return SDValue();
3669 
3670   SDValue X = N0->getOperand(0);
3671   EVT XVT = X.getValueType();
3672 
3673   // Validate constants ...
3674 
3675   APInt I1 = C1->getAPIntValue();
3676 
3677   ISD::CondCode NewCond;
3678   if (Cond == ISD::CondCode::SETULT) {
3679     NewCond = ISD::CondCode::SETEQ;
3680   } else if (Cond == ISD::CondCode::SETULE) {
3681     NewCond = ISD::CondCode::SETEQ;
3682     // But need to 'canonicalize' the constant.
3683     I1 += 1;
3684   } else if (Cond == ISD::CondCode::SETUGT) {
3685     NewCond = ISD::CondCode::SETNE;
3686     // But need to 'canonicalize' the constant.
3687     I1 += 1;
3688   } else if (Cond == ISD::CondCode::SETUGE) {
3689     NewCond = ISD::CondCode::SETNE;
3690   } else
3691     return SDValue();
3692 
3693   APInt I01 = C01->getAPIntValue();
3694 
3695   auto checkConstants = [&I1, &I01]() -> bool {
3696     // Both of them must be power-of-two, and the constant from setcc is bigger.
3697     return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
3698   };
3699 
3700   if (checkConstants()) {
3701     // Great, e.g. got  icmp ult i16 (add i16 %x, 128), 256
3702   } else {
3703     // What if we invert constants? (and the target predicate)
3704     I1.negate();
3705     I01.negate();
3706     assert(XVT.isInteger());
3707     NewCond = getSetCCInverse(NewCond, XVT);
3708     if (!checkConstants())
3709       return SDValue();
3710     // Great, e.g. got  icmp uge i16 (add i16 %x, -128), -256
3711   }
3712 
3713   // They are power-of-two, so which bit is set?
3714   const unsigned KeptBits = I1.logBase2();
3715   const unsigned KeptBitsMinusOne = I01.logBase2();
3716 
3717   // Magic!
3718   if (KeptBits != (KeptBitsMinusOne + 1))
3719     return SDValue();
3720   assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
3721 
3722   // We don't want to do this in every single case.
3723   SelectionDAG &DAG = DCI.DAG;
3724   if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck(
3725           XVT, KeptBits))
3726     return SDValue();
3727 
3728   const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits;
3729   assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable");
3730 
3731   // Unfold into:  ((%x << C) a>> C) cond %x
3732   // Where 'cond' will be either 'eq' or 'ne'.
3733   SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT);
3734   SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt);
3735   SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt);
3736   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond);
3737 
3738   return T2;
3739 }
3740 
3741 // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
3742 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
3743     EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
3744     DAGCombinerInfo &DCI, const SDLoc &DL) const {
3745   assert(isConstOrConstSplat(N1C) &&
3746          isConstOrConstSplat(N1C)->getAPIntValue().isZero() &&
3747          "Should be a comparison with 0.");
3748   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
3749          "Valid only for [in]equality comparisons.");
3750 
3751   unsigned NewShiftOpcode;
3752   SDValue X, C, Y;
3753 
3754   SelectionDAG &DAG = DCI.DAG;
3755   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3756 
3757   // Look for '(C l>>/<< Y)'.
3758   auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) {
3759     // The shift should be one-use.
3760     if (!V.hasOneUse())
3761       return false;
3762     unsigned OldShiftOpcode = V.getOpcode();
3763     switch (OldShiftOpcode) {
3764     case ISD::SHL:
3765       NewShiftOpcode = ISD::SRL;
3766       break;
3767     case ISD::SRL:
3768       NewShiftOpcode = ISD::SHL;
3769       break;
3770     default:
3771       return false; // must be a logical shift.
3772     }
3773     // We should be shifting a constant.
3774     // FIXME: best to use isConstantOrConstantVector().
3775     C = V.getOperand(0);
3776     ConstantSDNode *CC =
3777         isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
3778     if (!CC)
3779       return false;
3780     Y = V.getOperand(1);
3781 
3782     ConstantSDNode *XC =
3783         isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
3784     return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
3785         X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
3786   };
3787 
3788   // LHS of comparison should be an one-use 'and'.
3789   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
3790     return SDValue();
3791 
3792   X = N0.getOperand(0);
3793   SDValue Mask = N0.getOperand(1);
3794 
3795   // 'and' is commutative!
3796   if (!Match(Mask)) {
3797     std::swap(X, Mask);
3798     if (!Match(Mask))
3799       return SDValue();
3800   }
3801 
3802   EVT VT = X.getValueType();
3803 
3804   // Produce:
3805   // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
3806   SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
3807   SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
3808   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
3809   return T2;
3810 }
3811 
3812 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as
3813 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
3814 /// handle the commuted versions of these patterns.
3815 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
3816                                            ISD::CondCode Cond, const SDLoc &DL,
3817                                            DAGCombinerInfo &DCI) const {
3818   unsigned BOpcode = N0.getOpcode();
3819   assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
3820          "Unexpected binop");
3821   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
3822 
3823   // (X + Y) == X --> Y == 0
3824   // (X - Y) == X --> Y == 0
3825   // (X ^ Y) == X --> Y == 0
3826   SelectionDAG &DAG = DCI.DAG;
3827   EVT OpVT = N0.getValueType();
3828   SDValue X = N0.getOperand(0);
3829   SDValue Y = N0.getOperand(1);
3830   if (X == N1)
3831     return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
3832 
3833   if (Y != N1)
3834     return SDValue();
3835 
3836   // (X + Y) == Y --> X == 0
3837   // (X ^ Y) == Y --> X == 0
3838   if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
3839     return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
3840 
3841   // The shift would not be valid if the operands are boolean (i1).
3842   if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
3843     return SDValue();
3844 
3845   // (X - Y) == Y --> X == Y << 1
3846   EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(),
3847                                  !DCI.isBeforeLegalize());
3848   SDValue One = DAG.getConstant(1, DL, ShiftVT);
3849   SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
3850   if (!DCI.isCalledByLegalizer())
3851     DCI.AddToWorklist(YShl1.getNode());
3852   return DAG.getSetCC(DL, VT, X, YShl1, Cond);
3853 }
3854 
3855 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT,
3856                                       SDValue N0, const APInt &C1,
3857                                       ISD::CondCode Cond, const SDLoc &dl,
3858                                       SelectionDAG &DAG) {
3859   // Look through truncs that don't change the value of a ctpop.
3860   // FIXME: Add vector support? Need to be careful with setcc result type below.
3861   SDValue CTPOP = N0;
3862   if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
3863       N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits()))
3864     CTPOP = N0.getOperand(0);
3865 
3866   if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
3867     return SDValue();
3868 
3869   EVT CTVT = CTPOP.getValueType();
3870   SDValue CTOp = CTPOP.getOperand(0);
3871 
3872   // If this is a vector CTPOP, keep the CTPOP if it is legal.
3873   // TODO: Should we check if CTPOP is legal(or custom) for scalars?
3874   if (VT.isVector() && TLI.isOperationLegal(ISD::CTPOP, CTVT))
3875     return SDValue();
3876 
3877   // (ctpop x) u< 2 -> (x & x-1) == 0
3878   // (ctpop x) u> 1 -> (x & x-1) != 0
3879   if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
3880     unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
3881     if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
3882       return SDValue();
3883     if (C1 == 0 && (Cond == ISD::SETULT))
3884       return SDValue(); // This is handled elsewhere.
3885 
3886     unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
3887 
3888     SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
3889     SDValue Result = CTOp;
3890     for (unsigned i = 0; i < Passes; i++) {
3891       SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
3892       Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
3893     }
3894     ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
3895     return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
3896   }
3897 
3898   // If ctpop is not supported, expand a power-of-2 comparison based on it.
3899   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
3900     // For scalars, keep CTPOP if it is legal or custom.
3901     if (!VT.isVector() && TLI.isOperationLegalOrCustom(ISD::CTPOP, CTVT))
3902       return SDValue();
3903     // This is based on X86's custom lowering for CTPOP which produces more
3904     // instructions than the expansion here.
3905 
3906     // (ctpop x) == 1 --> (x != 0) && ((x & x-1) == 0)
3907     // (ctpop x) != 1 --> (x == 0) || ((x & x-1) != 0)
3908     SDValue Zero = DAG.getConstant(0, dl, CTVT);
3909     SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
3910     assert(CTVT.isInteger());
3911     ISD::CondCode InvCond = ISD::getSetCCInverse(Cond, CTVT);
3912     SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
3913     SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
3914     SDValue LHS = DAG.getSetCC(dl, VT, CTOp, Zero, InvCond);
3915     SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
3916     unsigned LogicOpcode = Cond == ISD::SETEQ ? ISD::AND : ISD::OR;
3917     return DAG.getNode(LogicOpcode, dl, VT, LHS, RHS);
3918   }
3919 
3920   return SDValue();
3921 }
3922 
3923 static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1,
3924                                    ISD::CondCode Cond, const SDLoc &dl,
3925                                    SelectionDAG &DAG) {
3926   if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
3927     return SDValue();
3928 
3929   auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
3930   if (!C1 || !(C1->isZero() || C1->isAllOnes()))
3931     return SDValue();
3932 
3933   auto getRotateSource = [](SDValue X) {
3934     if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR)
3935       return X.getOperand(0);
3936     return SDValue();
3937   };
3938 
3939   // Peek through a rotated value compared against 0 or -1:
3940   // (rot X, Y) == 0/-1 --> X == 0/-1
3941   // (rot X, Y) != 0/-1 --> X != 0/-1
3942   if (SDValue R = getRotateSource(N0))
3943     return DAG.getSetCC(dl, VT, R, N1, Cond);
3944 
3945   // Peek through an 'or' of a rotated value compared against 0:
3946   // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0
3947   // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0
3948   //
3949   // TODO: Add the 'and' with -1 sibling.
3950   // TODO: Recurse through a series of 'or' ops to find the rotate.
3951   EVT OpVT = N0.getValueType();
3952   if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) {
3953     if (SDValue R = getRotateSource(N0.getOperand(0))) {
3954       SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1));
3955       return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
3956     }
3957     if (SDValue R = getRotateSource(N0.getOperand(1))) {
3958       SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0));
3959       return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
3960     }
3961   }
3962 
3963   return SDValue();
3964 }
3965 
3966 static SDValue foldSetCCWithFunnelShift(EVT VT, SDValue N0, SDValue N1,
3967                                         ISD::CondCode Cond, const SDLoc &dl,
3968                                         SelectionDAG &DAG) {
3969   // If we are testing for all-bits-clear, we might be able to do that with
3970   // less shifting since bit-order does not matter.
3971   if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
3972     return SDValue();
3973 
3974   auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
3975   if (!C1 || !C1->isZero())
3976     return SDValue();
3977 
3978   if (!N0.hasOneUse() ||
3979       (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR))
3980     return SDValue();
3981 
3982   unsigned BitWidth = N0.getScalarValueSizeInBits();
3983   auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2));
3984   if (!ShAmtC || ShAmtC->getAPIntValue().uge(BitWidth))
3985     return SDValue();
3986 
3987   // Canonicalize fshr as fshl to reduce pattern-matching.
3988   unsigned ShAmt = ShAmtC->getZExtValue();
3989   if (N0.getOpcode() == ISD::FSHR)
3990     ShAmt = BitWidth - ShAmt;
3991 
3992   // Match an 'or' with a specific operand 'Other' in either commuted variant.
3993   SDValue X, Y;
3994   auto matchOr = [&X, &Y](SDValue Or, SDValue Other) {
3995     if (Or.getOpcode() != ISD::OR || !Or.hasOneUse())
3996       return false;
3997     if (Or.getOperand(0) == Other) {
3998       X = Or.getOperand(0);
3999       Y = Or.getOperand(1);
4000       return true;
4001     }
4002     if (Or.getOperand(1) == Other) {
4003       X = Or.getOperand(1);
4004       Y = Or.getOperand(0);
4005       return true;
4006     }
4007     return false;
4008   };
4009 
4010   EVT OpVT = N0.getValueType();
4011   EVT ShAmtVT = N0.getOperand(2).getValueType();
4012   SDValue F0 = N0.getOperand(0);
4013   SDValue F1 = N0.getOperand(1);
4014   if (matchOr(F0, F1)) {
4015     // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0
4016     SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT);
4017     SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt);
4018     SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4019     return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4020   }
4021   if (matchOr(F1, F0)) {
4022     // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0
4023     SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT);
4024     SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt);
4025     SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4026     return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4027   }
4028 
4029   return SDValue();
4030 }
4031 
4032 /// Try to simplify a setcc built with the specified operands and cc. If it is
4033 /// unable to simplify it, return a null SDValue.
4034 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
4035                                       ISD::CondCode Cond, bool foldBooleans,
4036                                       DAGCombinerInfo &DCI,
4037                                       const SDLoc &dl) const {
4038   SelectionDAG &DAG = DCI.DAG;
4039   const DataLayout &Layout = DAG.getDataLayout();
4040   EVT OpVT = N0.getValueType();
4041 
4042   // Constant fold or commute setcc.
4043   if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
4044     return Fold;
4045 
4046   bool N0ConstOrSplat =
4047       isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
4048   bool N1ConstOrSplat =
4049       isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
4050 
4051   // Ensure that the constant occurs on the RHS and fold constant comparisons.
4052   // TODO: Handle non-splat vector constants. All undef causes trouble.
4053   // FIXME: We can't yet fold constant scalable vector splats, so avoid an
4054   // infinite loop here when we encounter one.
4055   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
4056   if (N0ConstOrSplat && (!OpVT.isScalableVector() || !N1ConstOrSplat) &&
4057       (DCI.isBeforeLegalizeOps() ||
4058        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
4059     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
4060 
4061   // If we have a subtract with the same 2 non-constant operands as this setcc
4062   // -- but in reverse order -- then try to commute the operands of this setcc
4063   // to match. A matching pair of setcc (cmp) and sub may be combined into 1
4064   // instruction on some targets.
4065   if (!N0ConstOrSplat && !N1ConstOrSplat &&
4066       (DCI.isBeforeLegalizeOps() ||
4067        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
4068       DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
4069       !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
4070     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
4071 
4072   if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG))
4073     return V;
4074 
4075   if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG))
4076     return V;
4077 
4078   if (auto *N1C = isConstOrConstSplat(N1)) {
4079     const APInt &C1 = N1C->getAPIntValue();
4080 
4081     // Optimize some CTPOP cases.
4082     if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
4083       return V;
4084 
4085     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
4086     // equality comparison, then we're just comparing whether X itself is
4087     // zero.
4088     if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) &&
4089         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
4090         isPowerOf2_32(N0.getScalarValueSizeInBits())) {
4091       if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
4092         if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4093             ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
4094           if ((C1 == 0) == (Cond == ISD::SETEQ)) {
4095             // (srl (ctlz x), 5) == 0  -> X != 0
4096             // (srl (ctlz x), 5) != 1  -> X != 0
4097             Cond = ISD::SETNE;
4098           } else {
4099             // (srl (ctlz x), 5) != 0  -> X == 0
4100             // (srl (ctlz x), 5) == 1  -> X == 0
4101             Cond = ISD::SETEQ;
4102           }
4103           SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
4104           return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
4105                               Cond);
4106         }
4107       }
4108     }
4109   }
4110 
4111   // FIXME: Support vectors.
4112   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
4113     const APInt &C1 = N1C->getAPIntValue();
4114 
4115     // (zext x) == C --> x == (trunc C)
4116     // (sext x) == C --> x == (trunc C)
4117     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4118         DCI.isBeforeLegalize() && N0->hasOneUse()) {
4119       unsigned MinBits = N0.getValueSizeInBits();
4120       SDValue PreExt;
4121       bool Signed = false;
4122       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
4123         // ZExt
4124         MinBits = N0->getOperand(0).getValueSizeInBits();
4125         PreExt = N0->getOperand(0);
4126       } else if (N0->getOpcode() == ISD::AND) {
4127         // DAGCombine turns costly ZExts into ANDs
4128         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
4129           if ((C->getAPIntValue()+1).isPowerOf2()) {
4130             MinBits = C->getAPIntValue().countTrailingOnes();
4131             PreExt = N0->getOperand(0);
4132           }
4133       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
4134         // SExt
4135         MinBits = N0->getOperand(0).getValueSizeInBits();
4136         PreExt = N0->getOperand(0);
4137         Signed = true;
4138       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
4139         // ZEXTLOAD / SEXTLOAD
4140         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
4141           MinBits = LN0->getMemoryVT().getSizeInBits();
4142           PreExt = N0;
4143         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
4144           Signed = true;
4145           MinBits = LN0->getMemoryVT().getSizeInBits();
4146           PreExt = N0;
4147         }
4148       }
4149 
4150       // Figure out how many bits we need to preserve this constant.
4151       unsigned ReqdBits = Signed ? C1.getMinSignedBits() : C1.getActiveBits();
4152 
4153       // Make sure we're not losing bits from the constant.
4154       if (MinBits > 0 &&
4155           MinBits < C1.getBitWidth() &&
4156           MinBits >= ReqdBits) {
4157         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
4158         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
4159           // Will get folded away.
4160           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
4161           if (MinBits == 1 && C1 == 1)
4162             // Invert the condition.
4163             return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
4164                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4165           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
4166           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
4167         }
4168 
4169         // If truncating the setcc operands is not desirable, we can still
4170         // simplify the expression in some cases:
4171         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
4172         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
4173         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
4174         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
4175         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
4176         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
4177         SDValue TopSetCC = N0->getOperand(0);
4178         unsigned N0Opc = N0->getOpcode();
4179         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
4180         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
4181             TopSetCC.getOpcode() == ISD::SETCC &&
4182             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
4183             (isConstFalseVal(N1) ||
4184              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
4185 
4186           bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) ||
4187                          (!N1C->isZero() && Cond == ISD::SETNE);
4188 
4189           if (!Inverse)
4190             return TopSetCC;
4191 
4192           ISD::CondCode InvCond = ISD::getSetCCInverse(
4193               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
4194               TopSetCC.getOperand(0).getValueType());
4195           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
4196                                       TopSetCC.getOperand(1),
4197                                       InvCond);
4198         }
4199       }
4200     }
4201 
4202     // If the LHS is '(and load, const)', the RHS is 0, the test is for
4203     // equality or unsigned, and all 1 bits of the const are in the same
4204     // partial word, see if we can shorten the load.
4205     if (DCI.isBeforeLegalize() &&
4206         !ISD::isSignedIntSetCC(Cond) &&
4207         N0.getOpcode() == ISD::AND && C1 == 0 &&
4208         N0.getNode()->hasOneUse() &&
4209         isa<LoadSDNode>(N0.getOperand(0)) &&
4210         N0.getOperand(0).getNode()->hasOneUse() &&
4211         isa<ConstantSDNode>(N0.getOperand(1))) {
4212       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
4213       APInt bestMask;
4214       unsigned bestWidth = 0, bestOffset = 0;
4215       if (Lod->isSimple() && Lod->isUnindexed()) {
4216         unsigned origWidth = N0.getValueSizeInBits();
4217         unsigned maskWidth = origWidth;
4218         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
4219         // 8 bits, but have to be careful...
4220         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
4221           origWidth = Lod->getMemoryVT().getSizeInBits();
4222         const APInt &Mask = N0.getConstantOperandAPInt(1);
4223         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
4224           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
4225           for (unsigned offset=0; offset<origWidth/width; offset++) {
4226             if (Mask.isSubsetOf(newMask)) {
4227               if (Layout.isLittleEndian())
4228                 bestOffset = (uint64_t)offset * (width/8);
4229               else
4230                 bestOffset = (origWidth/width - offset - 1) * (width/8);
4231               bestMask = Mask.lshr(offset * (width/8) * 8);
4232               bestWidth = width;
4233               break;
4234             }
4235             newMask <<= width;
4236           }
4237         }
4238       }
4239       if (bestWidth) {
4240         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
4241         if (newVT.isRound() &&
4242             shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) {
4243           SDValue Ptr = Lod->getBasePtr();
4244           if (bestOffset != 0)
4245             Ptr =
4246                 DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(bestOffset), dl);
4247           SDValue NewLoad =
4248               DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
4249                           Lod->getPointerInfo().getWithOffset(bestOffset),
4250                           Lod->getOriginalAlign());
4251           return DAG.getSetCC(dl, VT,
4252                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
4253                                       DAG.getConstant(bestMask.trunc(bestWidth),
4254                                                       dl, newVT)),
4255                               DAG.getConstant(0LL, dl, newVT), Cond);
4256         }
4257       }
4258     }
4259 
4260     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
4261     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
4262       unsigned InSize = N0.getOperand(0).getValueSizeInBits();
4263 
4264       // If the comparison constant has bits in the upper part, the
4265       // zero-extended value could never match.
4266       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
4267                                               C1.getBitWidth() - InSize))) {
4268         switch (Cond) {
4269         case ISD::SETUGT:
4270         case ISD::SETUGE:
4271         case ISD::SETEQ:
4272           return DAG.getConstant(0, dl, VT);
4273         case ISD::SETULT:
4274         case ISD::SETULE:
4275         case ISD::SETNE:
4276           return DAG.getConstant(1, dl, VT);
4277         case ISD::SETGT:
4278         case ISD::SETGE:
4279           // True if the sign bit of C1 is set.
4280           return DAG.getConstant(C1.isNegative(), dl, VT);
4281         case ISD::SETLT:
4282         case ISD::SETLE:
4283           // True if the sign bit of C1 isn't set.
4284           return DAG.getConstant(C1.isNonNegative(), dl, VT);
4285         default:
4286           break;
4287         }
4288       }
4289 
4290       // Otherwise, we can perform the comparison with the low bits.
4291       switch (Cond) {
4292       case ISD::SETEQ:
4293       case ISD::SETNE:
4294       case ISD::SETUGT:
4295       case ISD::SETUGE:
4296       case ISD::SETULT:
4297       case ISD::SETULE: {
4298         EVT newVT = N0.getOperand(0).getValueType();
4299         if (DCI.isBeforeLegalizeOps() ||
4300             (isOperationLegal(ISD::SETCC, newVT) &&
4301              isCondCodeLegal(Cond, newVT.getSimpleVT()))) {
4302           EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
4303           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
4304 
4305           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
4306                                           NewConst, Cond);
4307           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
4308         }
4309         break;
4310       }
4311       default:
4312         break; // todo, be more careful with signed comparisons
4313       }
4314     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4315                (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4316                !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(),
4317                                       OpVT)) {
4318       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
4319       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
4320       EVT ExtDstTy = N0.getValueType();
4321       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
4322 
4323       // If the constant doesn't fit into the number of bits for the source of
4324       // the sign extension, it is impossible for both sides to be equal.
4325       if (C1.getMinSignedBits() > ExtSrcTyBits)
4326         return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
4327 
4328       assert(ExtDstTy == N0.getOperand(0).getValueType() &&
4329              ExtDstTy != ExtSrcTy && "Unexpected types!");
4330       APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
4331       SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
4332                                    DAG.getConstant(Imm, dl, ExtDstTy));
4333       if (!DCI.isCalledByLegalizer())
4334         DCI.AddToWorklist(ZextOp.getNode());
4335       // Otherwise, make this a use of a zext.
4336       return DAG.getSetCC(dl, VT, ZextOp,
4337                           DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
4338     } else if ((N1C->isZero() || N1C->isOne()) &&
4339                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4340       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
4341       if (N0.getOpcode() == ISD::SETCC &&
4342           isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
4343           (N0.getValueType() == MVT::i1 ||
4344            getBooleanContents(N0.getOperand(0).getValueType()) ==
4345                        ZeroOrOneBooleanContent)) {
4346         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
4347         if (TrueWhenTrue)
4348           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
4349         // Invert the condition.
4350         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4351         CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType());
4352         if (DCI.isBeforeLegalizeOps() ||
4353             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
4354           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
4355       }
4356 
4357       if ((N0.getOpcode() == ISD::XOR ||
4358            (N0.getOpcode() == ISD::AND &&
4359             N0.getOperand(0).getOpcode() == ISD::XOR &&
4360             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
4361           isOneConstant(N0.getOperand(1))) {
4362         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
4363         // can only do this if the top bits are known zero.
4364         unsigned BitWidth = N0.getValueSizeInBits();
4365         if (DAG.MaskedValueIsZero(N0,
4366                                   APInt::getHighBitsSet(BitWidth,
4367                                                         BitWidth-1))) {
4368           // Okay, get the un-inverted input value.
4369           SDValue Val;
4370           if (N0.getOpcode() == ISD::XOR) {
4371             Val = N0.getOperand(0);
4372           } else {
4373             assert(N0.getOpcode() == ISD::AND &&
4374                     N0.getOperand(0).getOpcode() == ISD::XOR);
4375             // ((X^1)&1)^1 -> X & 1
4376             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
4377                               N0.getOperand(0).getOperand(0),
4378                               N0.getOperand(1));
4379           }
4380 
4381           return DAG.getSetCC(dl, VT, Val, N1,
4382                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4383         }
4384       } else if (N1C->isOne()) {
4385         SDValue Op0 = N0;
4386         if (Op0.getOpcode() == ISD::TRUNCATE)
4387           Op0 = Op0.getOperand(0);
4388 
4389         if ((Op0.getOpcode() == ISD::XOR) &&
4390             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
4391             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
4392           SDValue XorLHS = Op0.getOperand(0);
4393           SDValue XorRHS = Op0.getOperand(1);
4394           // Ensure that the input setccs return an i1 type or 0/1 value.
4395           if (Op0.getValueType() == MVT::i1 ||
4396               (getBooleanContents(XorLHS.getOperand(0).getValueType()) ==
4397                       ZeroOrOneBooleanContent &&
4398                getBooleanContents(XorRHS.getOperand(0).getValueType()) ==
4399                         ZeroOrOneBooleanContent)) {
4400             // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
4401             Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
4402             return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
4403           }
4404         }
4405         if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
4406           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
4407           if (Op0.getValueType().bitsGT(VT))
4408             Op0 = DAG.getNode(ISD::AND, dl, VT,
4409                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
4410                           DAG.getConstant(1, dl, VT));
4411           else if (Op0.getValueType().bitsLT(VT))
4412             Op0 = DAG.getNode(ISD::AND, dl, VT,
4413                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
4414                         DAG.getConstant(1, dl, VT));
4415 
4416           return DAG.getSetCC(dl, VT, Op0,
4417                               DAG.getConstant(0, dl, Op0.getValueType()),
4418                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4419         }
4420         if (Op0.getOpcode() == ISD::AssertZext &&
4421             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
4422           return DAG.getSetCC(dl, VT, Op0,
4423                               DAG.getConstant(0, dl, Op0.getValueType()),
4424                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4425       }
4426     }
4427 
4428     // Given:
4429     //   icmp eq/ne (urem %x, %y), 0
4430     // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
4431     //   icmp eq/ne %x, 0
4432     if (N0.getOpcode() == ISD::UREM && N1C->isZero() &&
4433         (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4434       KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
4435       KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
4436       if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
4437         return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
4438     }
4439 
4440     // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0
4441     //  and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0
4442     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4443         N0.getOpcode() == ISD::SRA && isa<ConstantSDNode>(N0.getOperand(1)) &&
4444         N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 &&
4445         N1C && N1C->isAllOnes()) {
4446       return DAG.getSetCC(dl, VT, N0.getOperand(0),
4447                           DAG.getConstant(0, dl, OpVT),
4448                           Cond == ISD::SETEQ ? ISD::SETLT : ISD::SETGE);
4449     }
4450 
4451     if (SDValue V =
4452             optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
4453       return V;
4454   }
4455 
4456   // These simplifications apply to splat vectors as well.
4457   // TODO: Handle more splat vector cases.
4458   if (auto *N1C = isConstOrConstSplat(N1)) {
4459     const APInt &C1 = N1C->getAPIntValue();
4460 
4461     APInt MinVal, MaxVal;
4462     unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
4463     if (ISD::isSignedIntSetCC(Cond)) {
4464       MinVal = APInt::getSignedMinValue(OperandBitSize);
4465       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
4466     } else {
4467       MinVal = APInt::getMinValue(OperandBitSize);
4468       MaxVal = APInt::getMaxValue(OperandBitSize);
4469     }
4470 
4471     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
4472     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
4473       // X >= MIN --> true
4474       if (C1 == MinVal)
4475         return DAG.getBoolConstant(true, dl, VT, OpVT);
4476 
4477       if (!VT.isVector()) { // TODO: Support this for vectors.
4478         // X >= C0 --> X > (C0 - 1)
4479         APInt C = C1 - 1;
4480         ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
4481         if ((DCI.isBeforeLegalizeOps() ||
4482              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
4483             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
4484                                   isLegalICmpImmediate(C.getSExtValue())))) {
4485           return DAG.getSetCC(dl, VT, N0,
4486                               DAG.getConstant(C, dl, N1.getValueType()),
4487                               NewCC);
4488         }
4489       }
4490     }
4491 
4492     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
4493       // X <= MAX --> true
4494       if (C1 == MaxVal)
4495         return DAG.getBoolConstant(true, dl, VT, OpVT);
4496 
4497       // X <= C0 --> X < (C0 + 1)
4498       if (!VT.isVector()) { // TODO: Support this for vectors.
4499         APInt C = C1 + 1;
4500         ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
4501         if ((DCI.isBeforeLegalizeOps() ||
4502              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
4503             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
4504                                   isLegalICmpImmediate(C.getSExtValue())))) {
4505           return DAG.getSetCC(dl, VT, N0,
4506                               DAG.getConstant(C, dl, N1.getValueType()),
4507                               NewCC);
4508         }
4509       }
4510     }
4511 
4512     if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
4513       if (C1 == MinVal)
4514         return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
4515 
4516       // TODO: Support this for vectors after legalize ops.
4517       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4518         // Canonicalize setlt X, Max --> setne X, Max
4519         if (C1 == MaxVal)
4520           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
4521 
4522         // If we have setult X, 1, turn it into seteq X, 0
4523         if (C1 == MinVal+1)
4524           return DAG.getSetCC(dl, VT, N0,
4525                               DAG.getConstant(MinVal, dl, N0.getValueType()),
4526                               ISD::SETEQ);
4527       }
4528     }
4529 
4530     if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
4531       if (C1 == MaxVal)
4532         return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
4533 
4534       // TODO: Support this for vectors after legalize ops.
4535       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4536         // Canonicalize setgt X, Min --> setne X, Min
4537         if (C1 == MinVal)
4538           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
4539 
4540         // If we have setugt X, Max-1, turn it into seteq X, Max
4541         if (C1 == MaxVal-1)
4542           return DAG.getSetCC(dl, VT, N0,
4543                               DAG.getConstant(MaxVal, dl, N0.getValueType()),
4544                               ISD::SETEQ);
4545       }
4546     }
4547 
4548     if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
4549       // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
4550       if (C1.isZero())
4551         if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
4552                 VT, N0, N1, Cond, DCI, dl))
4553           return CC;
4554 
4555       // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
4556       // For example, when high 32-bits of i64 X are known clear:
4557       // all bits clear: (X | (Y<<32)) ==  0 --> (X | Y) ==  0
4558       // all bits set:   (X | (Y<<32)) == -1 --> (X & Y) == -1
4559       bool CmpZero = N1C->getAPIntValue().isZero();
4560       bool CmpNegOne = N1C->getAPIntValue().isAllOnes();
4561       if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
4562         // Match or(lo,shl(hi,bw/2)) pattern.
4563         auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
4564           unsigned EltBits = V.getScalarValueSizeInBits();
4565           if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
4566             return false;
4567           SDValue LHS = V.getOperand(0);
4568           SDValue RHS = V.getOperand(1);
4569           APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
4570           // Unshifted element must have zero upperbits.
4571           if (RHS.getOpcode() == ISD::SHL &&
4572               isa<ConstantSDNode>(RHS.getOperand(1)) &&
4573               RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
4574               DAG.MaskedValueIsZero(LHS, HiBits)) {
4575             Lo = LHS;
4576             Hi = RHS.getOperand(0);
4577             return true;
4578           }
4579           if (LHS.getOpcode() == ISD::SHL &&
4580               isa<ConstantSDNode>(LHS.getOperand(1)) &&
4581               LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
4582               DAG.MaskedValueIsZero(RHS, HiBits)) {
4583             Lo = RHS;
4584             Hi = LHS.getOperand(0);
4585             return true;
4586           }
4587           return false;
4588         };
4589 
4590         auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
4591           unsigned EltBits = N0.getScalarValueSizeInBits();
4592           unsigned HalfBits = EltBits / 2;
4593           APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
4594           SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
4595           SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
4596           SDValue NewN0 =
4597               DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
4598           SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
4599           return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
4600         };
4601 
4602         SDValue Lo, Hi;
4603         if (IsConcat(N0, Lo, Hi))
4604           return MergeConcat(Lo, Hi);
4605 
4606         if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
4607           SDValue Lo0, Lo1, Hi0, Hi1;
4608           if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
4609               IsConcat(N0.getOperand(1), Lo1, Hi1)) {
4610             return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
4611                                DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
4612           }
4613         }
4614       }
4615     }
4616 
4617     // If we have "setcc X, C0", check to see if we can shrink the immediate
4618     // by changing cc.
4619     // TODO: Support this for vectors after legalize ops.
4620     if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4621       // SETUGT X, SINTMAX  -> SETLT X, 0
4622       // SETUGE X, SINTMIN -> SETLT X, 0
4623       if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
4624           (Cond == ISD::SETUGE && C1.isMinSignedValue()))
4625         return DAG.getSetCC(dl, VT, N0,
4626                             DAG.getConstant(0, dl, N1.getValueType()),
4627                             ISD::SETLT);
4628 
4629       // SETULT X, SINTMIN  -> SETGT X, -1
4630       // SETULE X, SINTMAX  -> SETGT X, -1
4631       if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
4632           (Cond == ISD::SETULE && C1.isMaxSignedValue()))
4633         return DAG.getSetCC(dl, VT, N0,
4634                             DAG.getAllOnesConstant(dl, N1.getValueType()),
4635                             ISD::SETGT);
4636     }
4637   }
4638 
4639   // Back to non-vector simplifications.
4640   // TODO: Can we do these for vector splats?
4641   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
4642     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4643     const APInt &C1 = N1C->getAPIntValue();
4644     EVT ShValTy = N0.getValueType();
4645 
4646     // Fold bit comparisons when we can. This will result in an
4647     // incorrect value when boolean false is negative one, unless
4648     // the bitsize is 1 in which case the false value is the same
4649     // in practice regardless of the representation.
4650     if ((VT.getSizeInBits() == 1 ||
4651          getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) &&
4652         (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4653         (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
4654         N0.getOpcode() == ISD::AND) {
4655       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4656         EVT ShiftTy =
4657             getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
4658         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
4659           // Perform the xform if the AND RHS is a single bit.
4660           unsigned ShCt = AndRHS->getAPIntValue().logBase2();
4661           if (AndRHS->getAPIntValue().isPowerOf2() &&
4662               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
4663             return DAG.getNode(ISD::TRUNCATE, dl, VT,
4664                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4665                                            DAG.getConstant(ShCt, dl, ShiftTy)));
4666           }
4667         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
4668           // (X & 8) == 8  -->  (X & 8) >> 3
4669           // Perform the xform if C1 is a single bit.
4670           unsigned ShCt = C1.logBase2();
4671           if (C1.isPowerOf2() &&
4672               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
4673             return DAG.getNode(ISD::TRUNCATE, dl, VT,
4674                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4675                                            DAG.getConstant(ShCt, dl, ShiftTy)));
4676           }
4677         }
4678       }
4679     }
4680 
4681     if (C1.getMinSignedBits() <= 64 &&
4682         !isLegalICmpImmediate(C1.getSExtValue())) {
4683       EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
4684       // (X & -256) == 256 -> (X >> 8) == 1
4685       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4686           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
4687         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4688           const APInt &AndRHSC = AndRHS->getAPIntValue();
4689           if (AndRHSC.isNegatedPowerOf2() && (AndRHSC & C1) == C1) {
4690             unsigned ShiftBits = AndRHSC.countTrailingZeros();
4691             if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
4692               SDValue Shift =
4693                 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0),
4694                             DAG.getConstant(ShiftBits, dl, ShiftTy));
4695               SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy);
4696               return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
4697             }
4698           }
4699         }
4700       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
4701                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
4702         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
4703         // X <  0x100000000 -> (X >> 32) <  1
4704         // X >= 0x100000000 -> (X >> 32) >= 1
4705         // X <= 0x0ffffffff -> (X >> 32) <  1
4706         // X >  0x0ffffffff -> (X >> 32) >= 1
4707         unsigned ShiftBits;
4708         APInt NewC = C1;
4709         ISD::CondCode NewCond = Cond;
4710         if (AdjOne) {
4711           ShiftBits = C1.countTrailingOnes();
4712           NewC = NewC + 1;
4713           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
4714         } else {
4715           ShiftBits = C1.countTrailingZeros();
4716         }
4717         NewC.lshrInPlace(ShiftBits);
4718         if (ShiftBits && NewC.getMinSignedBits() <= 64 &&
4719             isLegalICmpImmediate(NewC.getSExtValue()) &&
4720             !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
4721           SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0,
4722                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
4723           SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
4724           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
4725         }
4726       }
4727     }
4728   }
4729 
4730   if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) {
4731     auto *CFP = cast<ConstantFPSDNode>(N1);
4732     assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
4733 
4734     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
4735     // constant if knowing that the operand is non-nan is enough.  We prefer to
4736     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
4737     // materialize 0.0.
4738     if (Cond == ISD::SETO || Cond == ISD::SETUO)
4739       return DAG.getSetCC(dl, VT, N0, N0, Cond);
4740 
4741     // setcc (fneg x), C -> setcc swap(pred) x, -C
4742     if (N0.getOpcode() == ISD::FNEG) {
4743       ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
4744       if (DCI.isBeforeLegalizeOps() ||
4745           isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
4746         SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
4747         return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
4748       }
4749     }
4750 
4751     // If the condition is not legal, see if we can find an equivalent one
4752     // which is legal.
4753     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
4754       // If the comparison was an awkward floating-point == or != and one of
4755       // the comparison operands is infinity or negative infinity, convert the
4756       // condition to a less-awkward <= or >=.
4757       if (CFP->getValueAPF().isInfinity()) {
4758         bool IsNegInf = CFP->getValueAPF().isNegative();
4759         ISD::CondCode NewCond = ISD::SETCC_INVALID;
4760         switch (Cond) {
4761         case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
4762         case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
4763         case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
4764         case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
4765         default: break;
4766         }
4767         if (NewCond != ISD::SETCC_INVALID &&
4768             isCondCodeLegal(NewCond, N0.getSimpleValueType()))
4769           return DAG.getSetCC(dl, VT, N0, N1, NewCond);
4770       }
4771     }
4772   }
4773 
4774   if (N0 == N1) {
4775     // The sext(setcc()) => setcc() optimization relies on the appropriate
4776     // constant being emitted.
4777     assert(!N0.getValueType().isInteger() &&
4778            "Integer types should be handled by FoldSetCC");
4779 
4780     bool EqTrue = ISD::isTrueWhenEqual(Cond);
4781     unsigned UOF = ISD::getUnorderedFlavor(Cond);
4782     if (UOF == 2) // FP operators that are undefined on NaNs.
4783       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
4784     if (UOF == unsigned(EqTrue))
4785       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
4786     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
4787     // if it is not already.
4788     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
4789     if (NewCond != Cond &&
4790         (DCI.isBeforeLegalizeOps() ||
4791                             isCondCodeLegal(NewCond, N0.getSimpleValueType())))
4792       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
4793   }
4794 
4795   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4796       N0.getValueType().isInteger()) {
4797     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
4798         N0.getOpcode() == ISD::XOR) {
4799       // Simplify (X+Y) == (X+Z) -->  Y == Z
4800       if (N0.getOpcode() == N1.getOpcode()) {
4801         if (N0.getOperand(0) == N1.getOperand(0))
4802           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
4803         if (N0.getOperand(1) == N1.getOperand(1))
4804           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
4805         if (isCommutativeBinOp(N0.getOpcode())) {
4806           // If X op Y == Y op X, try other combinations.
4807           if (N0.getOperand(0) == N1.getOperand(1))
4808             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
4809                                 Cond);
4810           if (N0.getOperand(1) == N1.getOperand(0))
4811             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
4812                                 Cond);
4813         }
4814       }
4815 
4816       // If RHS is a legal immediate value for a compare instruction, we need
4817       // to be careful about increasing register pressure needlessly.
4818       bool LegalRHSImm = false;
4819 
4820       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
4821         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4822           // Turn (X+C1) == C2 --> X == C2-C1
4823           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse())
4824             return DAG.getSetCC(
4825                 dl, VT, N0.getOperand(0),
4826                 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(),
4827                                 dl, N0.getValueType()),
4828                 Cond);
4829 
4830           // Turn (X^C1) == C2 --> X == C1^C2
4831           if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse())
4832             return DAG.getSetCC(
4833                 dl, VT, N0.getOperand(0),
4834                 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(),
4835                                 dl, N0.getValueType()),
4836                 Cond);
4837         }
4838 
4839         // Turn (C1-X) == C2 --> X == C1-C2
4840         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4841           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse())
4842             return DAG.getSetCC(
4843                 dl, VT, N0.getOperand(1),
4844                 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(),
4845                                 dl, N0.getValueType()),
4846                 Cond);
4847 
4848         // Could RHSC fold directly into a compare?
4849         if (RHSC->getValueType(0).getSizeInBits() <= 64)
4850           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
4851       }
4852 
4853       // (X+Y) == X --> Y == 0 and similar folds.
4854       // Don't do this if X is an immediate that can fold into a cmp
4855       // instruction and X+Y has other uses. It could be an induction variable
4856       // chain, and the transform would increase register pressure.
4857       if (!LegalRHSImm || N0.hasOneUse())
4858         if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
4859           return V;
4860     }
4861 
4862     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
4863         N1.getOpcode() == ISD::XOR)
4864       if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
4865         return V;
4866 
4867     if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
4868       return V;
4869   }
4870 
4871   // Fold remainder of division by a constant.
4872   if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
4873       N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4874     AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4875 
4876     // When division is cheap or optimizing for minimum size,
4877     // fall through to DIVREM creation by skipping this fold.
4878     if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) {
4879       if (N0.getOpcode() == ISD::UREM) {
4880         if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
4881           return Folded;
4882       } else if (N0.getOpcode() == ISD::SREM) {
4883         if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
4884           return Folded;
4885       }
4886     }
4887   }
4888 
4889   // Fold away ALL boolean setcc's.
4890   if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
4891     SDValue Temp;
4892     switch (Cond) {
4893     default: llvm_unreachable("Unknown integer setcc!");
4894     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
4895       Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
4896       N0 = DAG.getNOT(dl, Temp, OpVT);
4897       if (!DCI.isCalledByLegalizer())
4898         DCI.AddToWorklist(Temp.getNode());
4899       break;
4900     case ISD::SETNE:  // X != Y   -->  (X^Y)
4901       N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
4902       break;
4903     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
4904     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
4905       Temp = DAG.getNOT(dl, N0, OpVT);
4906       N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
4907       if (!DCI.isCalledByLegalizer())
4908         DCI.AddToWorklist(Temp.getNode());
4909       break;
4910     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
4911     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
4912       Temp = DAG.getNOT(dl, N1, OpVT);
4913       N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
4914       if (!DCI.isCalledByLegalizer())
4915         DCI.AddToWorklist(Temp.getNode());
4916       break;
4917     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
4918     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
4919       Temp = DAG.getNOT(dl, N0, OpVT);
4920       N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
4921       if (!DCI.isCalledByLegalizer())
4922         DCI.AddToWorklist(Temp.getNode());
4923       break;
4924     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
4925     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
4926       Temp = DAG.getNOT(dl, N1, OpVT);
4927       N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
4928       break;
4929     }
4930     if (VT.getScalarType() != MVT::i1) {
4931       if (!DCI.isCalledByLegalizer())
4932         DCI.AddToWorklist(N0.getNode());
4933       // FIXME: If running after legalize, we probably can't do this.
4934       ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT));
4935       N0 = DAG.getNode(ExtendCode, dl, VT, N0);
4936     }
4937     return N0;
4938   }
4939 
4940   // Could not fold it.
4941   return SDValue();
4942 }
4943 
4944 /// Returns true (and the GlobalValue and the offset) if the node is a
4945 /// GlobalAddress + offset.
4946 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA,
4947                                     int64_t &Offset) const {
4948 
4949   SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
4950 
4951   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
4952     GA = GASD->getGlobal();
4953     Offset += GASD->getOffset();
4954     return true;
4955   }
4956 
4957   if (N->getOpcode() == ISD::ADD) {
4958     SDValue N1 = N->getOperand(0);
4959     SDValue N2 = N->getOperand(1);
4960     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
4961       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
4962         Offset += V->getSExtValue();
4963         return true;
4964       }
4965     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
4966       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
4967         Offset += V->getSExtValue();
4968         return true;
4969       }
4970     }
4971   }
4972 
4973   return false;
4974 }
4975 
4976 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
4977                                           DAGCombinerInfo &DCI) const {
4978   // Default implementation: no optimization.
4979   return SDValue();
4980 }
4981 
4982 //===----------------------------------------------------------------------===//
4983 //  Inline Assembler Implementation Methods
4984 //===----------------------------------------------------------------------===//
4985 
4986 TargetLowering::ConstraintType
4987 TargetLowering::getConstraintType(StringRef Constraint) const {
4988   unsigned S = Constraint.size();
4989 
4990   if (S == 1) {
4991     switch (Constraint[0]) {
4992     default: break;
4993     case 'r':
4994       return C_RegisterClass;
4995     case 'm': // memory
4996     case 'o': // offsetable
4997     case 'V': // not offsetable
4998       return C_Memory;
4999     case 'p': // Address.
5000       return C_Address;
5001     case 'n': // Simple Integer
5002     case 'E': // Floating Point Constant
5003     case 'F': // Floating Point Constant
5004       return C_Immediate;
5005     case 'i': // Simple Integer or Relocatable Constant
5006     case 's': // Relocatable Constant
5007     case 'X': // Allow ANY value.
5008     case 'I': // Target registers.
5009     case 'J':
5010     case 'K':
5011     case 'L':
5012     case 'M':
5013     case 'N':
5014     case 'O':
5015     case 'P':
5016     case '<':
5017     case '>':
5018       return C_Other;
5019     }
5020   }
5021 
5022   if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
5023     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
5024       return C_Memory;
5025     return C_Register;
5026   }
5027   return C_Unknown;
5028 }
5029 
5030 /// Try to replace an X constraint, which matches anything, with another that
5031 /// has more specific requirements based on the type of the corresponding
5032 /// operand.
5033 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5034   if (ConstraintVT.isInteger())
5035     return "r";
5036   if (ConstraintVT.isFloatingPoint())
5037     return "f"; // works for many targets
5038   return nullptr;
5039 }
5040 
5041 SDValue TargetLowering::LowerAsmOutputForConstraint(
5042     SDValue &Chain, SDValue &Flag, const SDLoc &DL,
5043     const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
5044   return SDValue();
5045 }
5046 
5047 /// Lower the specified operand into the Ops vector.
5048 /// If it is invalid, don't add anything to Ops.
5049 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
5050                                                   std::string &Constraint,
5051                                                   std::vector<SDValue> &Ops,
5052                                                   SelectionDAG &DAG) const {
5053 
5054   if (Constraint.length() > 1) return;
5055 
5056   char ConstraintLetter = Constraint[0];
5057   switch (ConstraintLetter) {
5058   default: break;
5059   case 'X':    // Allows any operand
5060   case 'i':    // Simple Integer or Relocatable Constant
5061   case 'n':    // Simple Integer
5062   case 's': {  // Relocatable Constant
5063 
5064     ConstantSDNode *C;
5065     uint64_t Offset = 0;
5066 
5067     // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
5068     // etc., since getelementpointer is variadic. We can't use
5069     // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
5070     // while in this case the GA may be furthest from the root node which is
5071     // likely an ISD::ADD.
5072     while (true) {
5073       if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
5074         // gcc prints these as sign extended.  Sign extend value to 64 bits
5075         // now; without this it would get ZExt'd later in
5076         // ScheduleDAGSDNodes::EmitNode, which is very generic.
5077         bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
5078         BooleanContent BCont = getBooleanContents(MVT::i64);
5079         ISD::NodeType ExtOpc =
5080             IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
5081         int64_t ExtVal =
5082             ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
5083         Ops.push_back(
5084             DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
5085         return;
5086       }
5087       if (ConstraintLetter != 'n') {
5088         if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5089           Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5090                                                    GA->getValueType(0),
5091                                                    Offset + GA->getOffset()));
5092           return;
5093         }
5094         if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
5095           Ops.push_back(DAG.getTargetBlockAddress(
5096               BA->getBlockAddress(), BA->getValueType(0),
5097               Offset + BA->getOffset(), BA->getTargetFlags()));
5098           return;
5099         }
5100         if (isa<BasicBlockSDNode>(Op)) {
5101           Ops.push_back(Op);
5102           return;
5103         }
5104       }
5105       const unsigned OpCode = Op.getOpcode();
5106       if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
5107         if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
5108           Op = Op.getOperand(1);
5109         // Subtraction is not commutative.
5110         else if (OpCode == ISD::ADD &&
5111                  (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
5112           Op = Op.getOperand(0);
5113         else
5114           return;
5115         Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
5116         continue;
5117       }
5118       return;
5119     }
5120     break;
5121   }
5122   }
5123 }
5124 
5125 std::pair<unsigned, const TargetRegisterClass *>
5126 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
5127                                              StringRef Constraint,
5128                                              MVT VT) const {
5129   if (Constraint.empty() || Constraint[0] != '{')
5130     return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
5131   assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
5132 
5133   // Remove the braces from around the name.
5134   StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
5135 
5136   std::pair<unsigned, const TargetRegisterClass *> R =
5137       std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
5138 
5139   // Figure out which register class contains this reg.
5140   for (const TargetRegisterClass *RC : RI->regclasses()) {
5141     // If none of the value types for this register class are valid, we
5142     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
5143     if (!isLegalRC(*RI, *RC))
5144       continue;
5145 
5146     for (const MCPhysReg &PR : *RC) {
5147       if (RegName.equals_insensitive(RI->getRegAsmName(PR))) {
5148         std::pair<unsigned, const TargetRegisterClass *> S =
5149             std::make_pair(PR, RC);
5150 
5151         // If this register class has the requested value type, return it,
5152         // otherwise keep searching and return the first class found
5153         // if no other is found which explicitly has the requested type.
5154         if (RI->isTypeLegalForClass(*RC, VT))
5155           return S;
5156         if (!R.second)
5157           R = S;
5158       }
5159     }
5160   }
5161 
5162   return R;
5163 }
5164 
5165 //===----------------------------------------------------------------------===//
5166 // Constraint Selection.
5167 
5168 /// Return true of this is an input operand that is a matching constraint like
5169 /// "4".
5170 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
5171   assert(!ConstraintCode.empty() && "No known constraint!");
5172   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
5173 }
5174 
5175 /// If this is an input matching constraint, this method returns the output
5176 /// operand it matches.
5177 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
5178   assert(!ConstraintCode.empty() && "No known constraint!");
5179   return atoi(ConstraintCode.c_str());
5180 }
5181 
5182 /// Split up the constraint string from the inline assembly value into the
5183 /// specific constraints and their prefixes, and also tie in the associated
5184 /// operand values.
5185 /// If this returns an empty vector, and if the constraint string itself
5186 /// isn't empty, there was an error parsing.
5187 TargetLowering::AsmOperandInfoVector
5188 TargetLowering::ParseConstraints(const DataLayout &DL,
5189                                  const TargetRegisterInfo *TRI,
5190                                  const CallBase &Call) const {
5191   /// Information about all of the constraints.
5192   AsmOperandInfoVector ConstraintOperands;
5193   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
5194   unsigned maCount = 0; // Largest number of multiple alternative constraints.
5195 
5196   // Do a prepass over the constraints, canonicalizing them, and building up the
5197   // ConstraintOperands list.
5198   unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5199   unsigned ResNo = 0; // ResNo - The result number of the next output.
5200 
5201   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
5202     ConstraintOperands.emplace_back(std::move(CI));
5203     AsmOperandInfo &OpInfo = ConstraintOperands.back();
5204 
5205     // Update multiple alternative constraint count.
5206     if (OpInfo.multipleAlternatives.size() > maCount)
5207       maCount = OpInfo.multipleAlternatives.size();
5208 
5209     OpInfo.ConstraintVT = MVT::Other;
5210 
5211     // Compute the value type for each operand.
5212     switch (OpInfo.Type) {
5213     case InlineAsm::isOutput:
5214       // Indirect outputs just consume an argument.
5215       if (OpInfo.isIndirect) {
5216         OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
5217         break;
5218       }
5219 
5220       // The return value of the call is this value.  As such, there is no
5221       // corresponding argument.
5222       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
5223       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
5224         OpInfo.ConstraintVT =
5225             getSimpleValueType(DL, STy->getElementType(ResNo));
5226       } else {
5227         assert(ResNo == 0 && "Asm only has one result!");
5228         OpInfo.ConstraintVT =
5229             getAsmOperandValueType(DL, Call.getType()).getSimpleVT();
5230       }
5231       ++ResNo;
5232       break;
5233     case InlineAsm::isInput:
5234       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
5235       break;
5236     case InlineAsm::isClobber:
5237       // Nothing to do.
5238       break;
5239     }
5240 
5241     if (OpInfo.CallOperandVal) {
5242       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
5243       if (OpInfo.isIndirect) {
5244         OpTy = Call.getParamElementType(ArgNo);
5245         assert(OpTy && "Indirect operand must have elementtype attribute");
5246       }
5247 
5248       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
5249       if (StructType *STy = dyn_cast<StructType>(OpTy))
5250         if (STy->getNumElements() == 1)
5251           OpTy = STy->getElementType(0);
5252 
5253       // If OpTy is not a single value, it may be a struct/union that we
5254       // can tile with integers.
5255       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5256         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
5257         switch (BitSize) {
5258         default: break;
5259         case 1:
5260         case 8:
5261         case 16:
5262         case 32:
5263         case 64:
5264         case 128:
5265           OpInfo.ConstraintVT =
5266               MVT::getVT(IntegerType::get(OpTy->getContext(), BitSize), true);
5267           break;
5268         }
5269       } else if (PointerType *PT = dyn_cast<PointerType>(OpTy)) {
5270         unsigned PtrSize = DL.getPointerSizeInBits(PT->getAddressSpace());
5271         OpInfo.ConstraintVT = MVT::getIntegerVT(PtrSize);
5272       } else {
5273         OpInfo.ConstraintVT = MVT::getVT(OpTy, true);
5274       }
5275 
5276       ArgNo++;
5277     }
5278   }
5279 
5280   // If we have multiple alternative constraints, select the best alternative.
5281   if (!ConstraintOperands.empty()) {
5282     if (maCount) {
5283       unsigned bestMAIndex = 0;
5284       int bestWeight = -1;
5285       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
5286       int weight = -1;
5287       unsigned maIndex;
5288       // Compute the sums of the weights for each alternative, keeping track
5289       // of the best (highest weight) one so far.
5290       for (maIndex = 0; maIndex < maCount; ++maIndex) {
5291         int weightSum = 0;
5292         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
5293              cIndex != eIndex; ++cIndex) {
5294           AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
5295           if (OpInfo.Type == InlineAsm::isClobber)
5296             continue;
5297 
5298           // If this is an output operand with a matching input operand,
5299           // look up the matching input. If their types mismatch, e.g. one
5300           // is an integer, the other is floating point, or their sizes are
5301           // different, flag it as an maCantMatch.
5302           if (OpInfo.hasMatchingInput()) {
5303             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5304             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5305               if ((OpInfo.ConstraintVT.isInteger() !=
5306                    Input.ConstraintVT.isInteger()) ||
5307                   (OpInfo.ConstraintVT.getSizeInBits() !=
5308                    Input.ConstraintVT.getSizeInBits())) {
5309                 weightSum = -1; // Can't match.
5310                 break;
5311               }
5312             }
5313           }
5314           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
5315           if (weight == -1) {
5316             weightSum = -1;
5317             break;
5318           }
5319           weightSum += weight;
5320         }
5321         // Update best.
5322         if (weightSum > bestWeight) {
5323           bestWeight = weightSum;
5324           bestMAIndex = maIndex;
5325         }
5326       }
5327 
5328       // Now select chosen alternative in each constraint.
5329       for (AsmOperandInfo &cInfo : ConstraintOperands)
5330         if (cInfo.Type != InlineAsm::isClobber)
5331           cInfo.selectAlternative(bestMAIndex);
5332     }
5333   }
5334 
5335   // Check and hook up tied operands, choose constraint code to use.
5336   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
5337        cIndex != eIndex; ++cIndex) {
5338     AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
5339 
5340     // If this is an output operand with a matching input operand, look up the
5341     // matching input. If their types mismatch, e.g. one is an integer, the
5342     // other is floating point, or their sizes are different, flag it as an
5343     // error.
5344     if (OpInfo.hasMatchingInput()) {
5345       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5346 
5347       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5348         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
5349             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
5350                                          OpInfo.ConstraintVT);
5351         std::pair<unsigned, const TargetRegisterClass *> InputRC =
5352             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
5353                                          Input.ConstraintVT);
5354         if ((OpInfo.ConstraintVT.isInteger() !=
5355              Input.ConstraintVT.isInteger()) ||
5356             (MatchRC.second != InputRC.second)) {
5357           report_fatal_error("Unsupported asm: input constraint"
5358                              " with a matching output constraint of"
5359                              " incompatible type!");
5360         }
5361       }
5362     }
5363   }
5364 
5365   return ConstraintOperands;
5366 }
5367 
5368 /// Return an integer indicating how general CT is.
5369 static unsigned getConstraintGenerality(TargetLowering::ConstraintType CT) {
5370   switch (CT) {
5371   case TargetLowering::C_Immediate:
5372   case TargetLowering::C_Other:
5373   case TargetLowering::C_Unknown:
5374     return 0;
5375   case TargetLowering::C_Register:
5376     return 1;
5377   case TargetLowering::C_RegisterClass:
5378     return 2;
5379   case TargetLowering::C_Memory:
5380   case TargetLowering::C_Address:
5381     return 3;
5382   }
5383   llvm_unreachable("Invalid constraint type");
5384 }
5385 
5386 /// Examine constraint type and operand type and determine a weight value.
5387 /// This object must already have been set up with the operand type
5388 /// and the current alternative constraint selected.
5389 TargetLowering::ConstraintWeight
5390   TargetLowering::getMultipleConstraintMatchWeight(
5391     AsmOperandInfo &info, int maIndex) const {
5392   InlineAsm::ConstraintCodeVector *rCodes;
5393   if (maIndex >= (int)info.multipleAlternatives.size())
5394     rCodes = &info.Codes;
5395   else
5396     rCodes = &info.multipleAlternatives[maIndex].Codes;
5397   ConstraintWeight BestWeight = CW_Invalid;
5398 
5399   // Loop over the options, keeping track of the most general one.
5400   for (const std::string &rCode : *rCodes) {
5401     ConstraintWeight weight =
5402         getSingleConstraintMatchWeight(info, rCode.c_str());
5403     if (weight > BestWeight)
5404       BestWeight = weight;
5405   }
5406 
5407   return BestWeight;
5408 }
5409 
5410 /// Examine constraint type and operand type and determine a weight value.
5411 /// This object must already have been set up with the operand type
5412 /// and the current alternative constraint selected.
5413 TargetLowering::ConstraintWeight
5414   TargetLowering::getSingleConstraintMatchWeight(
5415     AsmOperandInfo &info, const char *constraint) const {
5416   ConstraintWeight weight = CW_Invalid;
5417   Value *CallOperandVal = info.CallOperandVal;
5418     // If we don't have a value, we can't do a match,
5419     // but allow it at the lowest weight.
5420   if (!CallOperandVal)
5421     return CW_Default;
5422   // Look at the constraint type.
5423   switch (*constraint) {
5424     case 'i': // immediate integer.
5425     case 'n': // immediate integer with a known value.
5426       if (isa<ConstantInt>(CallOperandVal))
5427         weight = CW_Constant;
5428       break;
5429     case 's': // non-explicit intregal immediate.
5430       if (isa<GlobalValue>(CallOperandVal))
5431         weight = CW_Constant;
5432       break;
5433     case 'E': // immediate float if host format.
5434     case 'F': // immediate float.
5435       if (isa<ConstantFP>(CallOperandVal))
5436         weight = CW_Constant;
5437       break;
5438     case '<': // memory operand with autodecrement.
5439     case '>': // memory operand with autoincrement.
5440     case 'm': // memory operand.
5441     case 'o': // offsettable memory operand
5442     case 'V': // non-offsettable memory operand
5443       weight = CW_Memory;
5444       break;
5445     case 'r': // general register.
5446     case 'g': // general register, memory operand or immediate integer.
5447               // note: Clang converts "g" to "imr".
5448       if (CallOperandVal->getType()->isIntegerTy())
5449         weight = CW_Register;
5450       break;
5451     case 'X': // any operand.
5452   default:
5453     weight = CW_Default;
5454     break;
5455   }
5456   return weight;
5457 }
5458 
5459 /// If there are multiple different constraints that we could pick for this
5460 /// operand (e.g. "imr") try to pick the 'best' one.
5461 /// This is somewhat tricky: constraints fall into four classes:
5462 ///    Other         -> immediates and magic values
5463 ///    Register      -> one specific register
5464 ///    RegisterClass -> a group of regs
5465 ///    Memory        -> memory
5466 /// Ideally, we would pick the most specific constraint possible: if we have
5467 /// something that fits into a register, we would pick it.  The problem here
5468 /// is that if we have something that could either be in a register or in
5469 /// memory that use of the register could cause selection of *other*
5470 /// operands to fail: they might only succeed if we pick memory.  Because of
5471 /// this the heuristic we use is:
5472 ///
5473 ///  1) If there is an 'other' constraint, and if the operand is valid for
5474 ///     that constraint, use it.  This makes us take advantage of 'i'
5475 ///     constraints when available.
5476 ///  2) Otherwise, pick the most general constraint present.  This prefers
5477 ///     'm' over 'r', for example.
5478 ///
5479 static void ChooseConstraint(TargetLowering::AsmOperandInfo &OpInfo,
5480                              const TargetLowering &TLI,
5481                              SDValue Op, SelectionDAG *DAG) {
5482   assert(OpInfo.Codes.size() > 1 && "Doesn't have multiple constraint options");
5483   unsigned BestIdx = 0;
5484   TargetLowering::ConstraintType BestType = TargetLowering::C_Unknown;
5485   int BestGenerality = -1;
5486 
5487   // Loop over the options, keeping track of the most general one.
5488   for (unsigned i = 0, e = OpInfo.Codes.size(); i != e; ++i) {
5489     TargetLowering::ConstraintType CType =
5490       TLI.getConstraintType(OpInfo.Codes[i]);
5491 
5492     // Indirect 'other' or 'immediate' constraints are not allowed.
5493     if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
5494                                CType == TargetLowering::C_Register ||
5495                                CType == TargetLowering::C_RegisterClass))
5496       continue;
5497 
5498     // If this is an 'other' or 'immediate' constraint, see if the operand is
5499     // valid for it. For example, on X86 we might have an 'rI' constraint. If
5500     // the operand is an integer in the range [0..31] we want to use I (saving a
5501     // load of a register), otherwise we must use 'r'.
5502     if ((CType == TargetLowering::C_Other ||
5503          CType == TargetLowering::C_Immediate) && Op.getNode()) {
5504       assert(OpInfo.Codes[i].size() == 1 &&
5505              "Unhandled multi-letter 'other' constraint");
5506       std::vector<SDValue> ResultOps;
5507       TLI.LowerAsmOperandForConstraint(Op, OpInfo.Codes[i],
5508                                        ResultOps, *DAG);
5509       if (!ResultOps.empty()) {
5510         BestType = CType;
5511         BestIdx = i;
5512         break;
5513       }
5514     }
5515 
5516     // Things with matching constraints can only be registers, per gcc
5517     // documentation.  This mainly affects "g" constraints.
5518     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
5519       continue;
5520 
5521     // This constraint letter is more general than the previous one, use it.
5522     int Generality = getConstraintGenerality(CType);
5523     if (Generality > BestGenerality) {
5524       BestType = CType;
5525       BestIdx = i;
5526       BestGenerality = Generality;
5527     }
5528   }
5529 
5530   OpInfo.ConstraintCode = OpInfo.Codes[BestIdx];
5531   OpInfo.ConstraintType = BestType;
5532 }
5533 
5534 /// Determines the constraint code and constraint type to use for the specific
5535 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
5536 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
5537                                             SDValue Op,
5538                                             SelectionDAG *DAG) const {
5539   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
5540 
5541   // Single-letter constraints ('r') are very common.
5542   if (OpInfo.Codes.size() == 1) {
5543     OpInfo.ConstraintCode = OpInfo.Codes[0];
5544     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
5545   } else {
5546     ChooseConstraint(OpInfo, *this, Op, DAG);
5547   }
5548 
5549   // 'X' matches anything.
5550   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
5551     // Constants are handled elsewhere.  For Functions, the type here is the
5552     // type of the result, which is not what we want to look at; leave them
5553     // alone.
5554     Value *v = OpInfo.CallOperandVal;
5555     if (isa<ConstantInt>(v) || isa<Function>(v)) {
5556       return;
5557     }
5558 
5559     if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) {
5560       OpInfo.ConstraintCode = "i";
5561       return;
5562     }
5563 
5564     // Otherwise, try to resolve it to something we know about by looking at
5565     // the actual operand type.
5566     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
5567       OpInfo.ConstraintCode = Repl;
5568       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
5569     }
5570   }
5571 }
5572 
5573 /// Given an exact SDIV by a constant, create a multiplication
5574 /// with the multiplicative inverse of the constant.
5575 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N,
5576                               const SDLoc &dl, SelectionDAG &DAG,
5577                               SmallVectorImpl<SDNode *> &Created) {
5578   SDValue Op0 = N->getOperand(0);
5579   SDValue Op1 = N->getOperand(1);
5580   EVT VT = N->getValueType(0);
5581   EVT SVT = VT.getScalarType();
5582   EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
5583   EVT ShSVT = ShVT.getScalarType();
5584 
5585   bool UseSRA = false;
5586   SmallVector<SDValue, 16> Shifts, Factors;
5587 
5588   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
5589     if (C->isZero())
5590       return false;
5591     APInt Divisor = C->getAPIntValue();
5592     unsigned Shift = Divisor.countTrailingZeros();
5593     if (Shift) {
5594       Divisor.ashrInPlace(Shift);
5595       UseSRA = true;
5596     }
5597     // Calculate the multiplicative inverse, using Newton's method.
5598     APInt t;
5599     APInt Factor = Divisor;
5600     while ((t = Divisor * Factor) != 1)
5601       Factor *= APInt(Divisor.getBitWidth(), 2) - t;
5602     Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
5603     Factors.push_back(DAG.getConstant(Factor, dl, SVT));
5604     return true;
5605   };
5606 
5607   // Collect all magic values from the build vector.
5608   if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
5609     return SDValue();
5610 
5611   SDValue Shift, Factor;
5612   if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
5613     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
5614     Factor = DAG.getBuildVector(VT, dl, Factors);
5615   } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
5616     assert(Shifts.size() == 1 && Factors.size() == 1 &&
5617            "Expected matchUnaryPredicate to return one element for scalable "
5618            "vectors");
5619     Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
5620     Factor = DAG.getSplatVector(VT, dl, Factors[0]);
5621   } else {
5622     assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
5623     Shift = Shifts[0];
5624     Factor = Factors[0];
5625   }
5626 
5627   SDValue Res = Op0;
5628 
5629   // Shift the value upfront if it is even, so the LSB is one.
5630   if (UseSRA) {
5631     // TODO: For UDIV use SRL instead of SRA.
5632     SDNodeFlags Flags;
5633     Flags.setExact(true);
5634     Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags);
5635     Created.push_back(Res.getNode());
5636   }
5637 
5638   return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
5639 }
5640 
5641 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
5642                               SelectionDAG &DAG,
5643                               SmallVectorImpl<SDNode *> &Created) const {
5644   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5645   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5646   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
5647     return SDValue(N, 0); // Lower SDIV as SDIV
5648   return SDValue();
5649 }
5650 
5651 SDValue
5652 TargetLowering::BuildSREMPow2(SDNode *N, const APInt &Divisor,
5653                               SelectionDAG &DAG,
5654                               SmallVectorImpl<SDNode *> &Created) const {
5655   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
5656   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5657   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
5658     return SDValue(N, 0); // Lower SREM as SREM
5659   return SDValue();
5660 }
5661 
5662 /// Given an ISD::SDIV node expressing a divide by constant,
5663 /// return a DAG expression to select that will generate the same value by
5664 /// multiplying by a magic number.
5665 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
5666 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
5667                                   bool IsAfterLegalization,
5668                                   SmallVectorImpl<SDNode *> &Created) const {
5669   SDLoc dl(N);
5670   EVT VT = N->getValueType(0);
5671   EVT SVT = VT.getScalarType();
5672   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5673   EVT ShSVT = ShVT.getScalarType();
5674   unsigned EltBits = VT.getScalarSizeInBits();
5675   EVT MulVT;
5676 
5677   // Check to see if we can do this.
5678   // FIXME: We should be more aggressive here.
5679   if (!isTypeLegal(VT)) {
5680     // Limit this to simple scalars for now.
5681     if (VT.isVector() || !VT.isSimple())
5682       return SDValue();
5683 
5684     // If this type will be promoted to a large enough type with a legal
5685     // multiply operation, we can go ahead and do this transform.
5686     if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger)
5687       return SDValue();
5688 
5689     MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
5690     if (MulVT.getSizeInBits() < (2 * EltBits) ||
5691         !isOperationLegal(ISD::MUL, MulVT))
5692       return SDValue();
5693   }
5694 
5695   // If the sdiv has an 'exact' bit we can use a simpler lowering.
5696   if (N->getFlags().hasExact())
5697     return BuildExactSDIV(*this, N, dl, DAG, Created);
5698 
5699   SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
5700 
5701   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
5702     if (C->isZero())
5703       return false;
5704 
5705     const APInt &Divisor = C->getAPIntValue();
5706     SignedDivisionByConstantInfo magics = SignedDivisionByConstantInfo::get(Divisor);
5707     int NumeratorFactor = 0;
5708     int ShiftMask = -1;
5709 
5710     if (Divisor.isOne() || Divisor.isAllOnes()) {
5711       // If d is +1/-1, we just multiply the numerator by +1/-1.
5712       NumeratorFactor = Divisor.getSExtValue();
5713       magics.Magic = 0;
5714       magics.ShiftAmount = 0;
5715       ShiftMask = 0;
5716     } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) {
5717       // If d > 0 and m < 0, add the numerator.
5718       NumeratorFactor = 1;
5719     } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) {
5720       // If d < 0 and m > 0, subtract the numerator.
5721       NumeratorFactor = -1;
5722     }
5723 
5724     MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT));
5725     Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT));
5726     Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT));
5727     ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT));
5728     return true;
5729   };
5730 
5731   SDValue N0 = N->getOperand(0);
5732   SDValue N1 = N->getOperand(1);
5733 
5734   // Collect the shifts / magic values from each element.
5735   if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern))
5736     return SDValue();
5737 
5738   SDValue MagicFactor, Factor, Shift, ShiftMask;
5739   if (N1.getOpcode() == ISD::BUILD_VECTOR) {
5740     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
5741     Factor = DAG.getBuildVector(VT, dl, Factors);
5742     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
5743     ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
5744   } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
5745     assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
5746            Shifts.size() == 1 && ShiftMasks.size() == 1 &&
5747            "Expected matchUnaryPredicate to return one element for scalable "
5748            "vectors");
5749     MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
5750     Factor = DAG.getSplatVector(VT, dl, Factors[0]);
5751     Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
5752     ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
5753   } else {
5754     assert(isa<ConstantSDNode>(N1) && "Expected a constant");
5755     MagicFactor = MagicFactors[0];
5756     Factor = Factors[0];
5757     Shift = Shifts[0];
5758     ShiftMask = ShiftMasks[0];
5759   }
5760 
5761   // Multiply the numerator (operand 0) by the magic value.
5762   // FIXME: We should support doing a MUL in a wider type.
5763   auto GetMULHS = [&](SDValue X, SDValue Y) {
5764     // If the type isn't legal, use a wider mul of the the type calculated
5765     // earlier.
5766     if (!isTypeLegal(VT)) {
5767       X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
5768       Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
5769       Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
5770       Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
5771                       DAG.getShiftAmountConstant(EltBits, MulVT, dl));
5772       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
5773     }
5774 
5775     if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization))
5776       return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
5777     if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) {
5778       SDValue LoHi =
5779           DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
5780       return SDValue(LoHi.getNode(), 1);
5781     }
5782     return SDValue();
5783   };
5784 
5785   SDValue Q = GetMULHS(N0, MagicFactor);
5786   if (!Q)
5787     return SDValue();
5788 
5789   Created.push_back(Q.getNode());
5790 
5791   // (Optionally) Add/subtract the numerator using Factor.
5792   Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
5793   Created.push_back(Factor.getNode());
5794   Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
5795   Created.push_back(Q.getNode());
5796 
5797   // Shift right algebraic by shift value.
5798   Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
5799   Created.push_back(Q.getNode());
5800 
5801   // Extract the sign bit, mask it and add it to the quotient.
5802   SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
5803   SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
5804   Created.push_back(T.getNode());
5805   T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
5806   Created.push_back(T.getNode());
5807   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
5808 }
5809 
5810 /// Given an ISD::UDIV node expressing a divide by constant,
5811 /// return a DAG expression to select that will generate the same value by
5812 /// multiplying by a magic number.
5813 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
5814 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
5815                                   bool IsAfterLegalization,
5816                                   SmallVectorImpl<SDNode *> &Created) const {
5817   SDLoc dl(N);
5818   EVT VT = N->getValueType(0);
5819   EVT SVT = VT.getScalarType();
5820   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
5821   EVT ShSVT = ShVT.getScalarType();
5822   unsigned EltBits = VT.getScalarSizeInBits();
5823   EVT MulVT;
5824 
5825   // Check to see if we can do this.
5826   // FIXME: We should be more aggressive here.
5827   if (!isTypeLegal(VT)) {
5828     // Limit this to simple scalars for now.
5829     if (VT.isVector() || !VT.isSimple())
5830       return SDValue();
5831 
5832     // If this type will be promoted to a large enough type with a legal
5833     // multiply operation, we can go ahead and do this transform.
5834     if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger)
5835       return SDValue();
5836 
5837     MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
5838     if (MulVT.getSizeInBits() < (2 * EltBits) ||
5839         !isOperationLegal(ISD::MUL, MulVT))
5840       return SDValue();
5841   }
5842 
5843   bool UseNPQ = false;
5844   SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
5845 
5846   auto BuildUDIVPattern = [&](ConstantSDNode *C) {
5847     if (C->isZero())
5848       return false;
5849     // FIXME: We should use a narrower constant when the upper
5850     // bits are known to be zero.
5851     const APInt& Divisor = C->getAPIntValue();
5852     UnsignedDivisonByConstantInfo magics = UnsignedDivisonByConstantInfo::get(Divisor);
5853     unsigned PreShift = 0, PostShift = 0;
5854 
5855     // If the divisor is even, we can avoid using the expensive fixup by
5856     // shifting the divided value upfront.
5857     if (magics.IsAdd != 0 && !Divisor[0]) {
5858       PreShift = Divisor.countTrailingZeros();
5859       // Get magic number for the shifted divisor.
5860       magics = UnsignedDivisonByConstantInfo::get(Divisor.lshr(PreShift), PreShift);
5861       assert(magics.IsAdd == 0 && "Should use cheap fixup now");
5862     }
5863 
5864     APInt Magic = magics.Magic;
5865 
5866     unsigned SelNPQ;
5867     if (magics.IsAdd == 0 || Divisor.isOne()) {
5868       assert(magics.ShiftAmount < Divisor.getBitWidth() &&
5869              "We shouldn't generate an undefined shift!");
5870       PostShift = magics.ShiftAmount;
5871       SelNPQ = false;
5872     } else {
5873       PostShift = magics.ShiftAmount - 1;
5874       SelNPQ = true;
5875     }
5876 
5877     PreShifts.push_back(DAG.getConstant(PreShift, dl, ShSVT));
5878     MagicFactors.push_back(DAG.getConstant(Magic, dl, SVT));
5879     NPQFactors.push_back(
5880         DAG.getConstant(SelNPQ ? APInt::getOneBitSet(EltBits, EltBits - 1)
5881                                : APInt::getZero(EltBits),
5882                         dl, SVT));
5883     PostShifts.push_back(DAG.getConstant(PostShift, dl, ShSVT));
5884     UseNPQ |= SelNPQ;
5885     return true;
5886   };
5887 
5888   SDValue N0 = N->getOperand(0);
5889   SDValue N1 = N->getOperand(1);
5890 
5891   // Collect the shifts/magic values from each element.
5892   if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern))
5893     return SDValue();
5894 
5895   SDValue PreShift, PostShift, MagicFactor, NPQFactor;
5896   if (N1.getOpcode() == ISD::BUILD_VECTOR) {
5897     PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
5898     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
5899     NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
5900     PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
5901   } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
5902     assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
5903            NPQFactors.size() == 1 && PostShifts.size() == 1 &&
5904            "Expected matchUnaryPredicate to return one for scalable vectors");
5905     PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
5906     MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
5907     NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
5908     PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
5909   } else {
5910     assert(isa<ConstantSDNode>(N1) && "Expected a constant");
5911     PreShift = PreShifts[0];
5912     MagicFactor = MagicFactors[0];
5913     PostShift = PostShifts[0];
5914   }
5915 
5916   SDValue Q = N0;
5917   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
5918   Created.push_back(Q.getNode());
5919 
5920   // FIXME: We should support doing a MUL in a wider type.
5921   auto GetMULHU = [&](SDValue X, SDValue Y) {
5922     // If the type isn't legal, use a wider mul of the the type calculated
5923     // earlier.
5924     if (!isTypeLegal(VT)) {
5925       X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
5926       Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
5927       Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
5928       Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
5929                       DAG.getShiftAmountConstant(EltBits, MulVT, dl));
5930       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
5931     }
5932 
5933     if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization))
5934       return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
5935     if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) {
5936       SDValue LoHi =
5937           DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
5938       return SDValue(LoHi.getNode(), 1);
5939     }
5940     return SDValue(); // No mulhu or equivalent
5941   };
5942 
5943   // Multiply the numerator (operand 0) by the magic value.
5944   Q = GetMULHU(Q, MagicFactor);
5945   if (!Q)
5946     return SDValue();
5947 
5948   Created.push_back(Q.getNode());
5949 
5950   if (UseNPQ) {
5951     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
5952     Created.push_back(NPQ.getNode());
5953 
5954     // For vectors we might have a mix of non-NPQ/NPQ paths, so use
5955     // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
5956     if (VT.isVector())
5957       NPQ = GetMULHU(NPQ, NPQFactor);
5958     else
5959       NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
5960 
5961     Created.push_back(NPQ.getNode());
5962 
5963     Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
5964     Created.push_back(Q.getNode());
5965   }
5966 
5967   Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
5968   Created.push_back(Q.getNode());
5969 
5970   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
5971 
5972   SDValue One = DAG.getConstant(1, dl, VT);
5973   SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
5974   return DAG.getSelect(dl, VT, IsOne, N0, Q);
5975 }
5976 
5977 /// If all values in Values that *don't* match the predicate are same 'splat'
5978 /// value, then replace all values with that splat value.
5979 /// Else, if AlternativeReplacement was provided, then replace all values that
5980 /// do match predicate with AlternativeReplacement value.
5981 static void
5982 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values,
5983                           std::function<bool(SDValue)> Predicate,
5984                           SDValue AlternativeReplacement = SDValue()) {
5985   SDValue Replacement;
5986   // Is there a value for which the Predicate does *NOT* match? What is it?
5987   auto SplatValue = llvm::find_if_not(Values, Predicate);
5988   if (SplatValue != Values.end()) {
5989     // Does Values consist only of SplatValue's and values matching Predicate?
5990     if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
5991           return Value == *SplatValue || Predicate(Value);
5992         })) // Then we shall replace values matching predicate with SplatValue.
5993       Replacement = *SplatValue;
5994   }
5995   if (!Replacement) {
5996     // Oops, we did not find the "baseline" splat value.
5997     if (!AlternativeReplacement)
5998       return; // Nothing to do.
5999     // Let's replace with provided value then.
6000     Replacement = AlternativeReplacement;
6001   }
6002   std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
6003 }
6004 
6005 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
6006 /// where the divisor is constant and the comparison target is zero,
6007 /// return a DAG expression that will generate the same comparison result
6008 /// using only multiplications, additions and shifts/rotations.
6009 /// Ref: "Hacker's Delight" 10-17.
6010 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
6011                                         SDValue CompTargetNode,
6012                                         ISD::CondCode Cond,
6013                                         DAGCombinerInfo &DCI,
6014                                         const SDLoc &DL) const {
6015   SmallVector<SDNode *, 5> Built;
6016   if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
6017                                          DCI, DL, Built)) {
6018     for (SDNode *N : Built)
6019       DCI.AddToWorklist(N);
6020     return Folded;
6021   }
6022 
6023   return SDValue();
6024 }
6025 
6026 SDValue
6027 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
6028                                   SDValue CompTargetNode, ISD::CondCode Cond,
6029                                   DAGCombinerInfo &DCI, const SDLoc &DL,
6030                                   SmallVectorImpl<SDNode *> &Created) const {
6031   // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q)
6032   // - D must be constant, with D = D0 * 2^K where D0 is odd
6033   // - P is the multiplicative inverse of D0 modulo 2^W
6034   // - Q = floor(((2^W) - 1) / D)
6035   // where W is the width of the common type of N and D.
6036   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
6037          "Only applicable for (in)equality comparisons.");
6038 
6039   SelectionDAG &DAG = DCI.DAG;
6040 
6041   EVT VT = REMNode.getValueType();
6042   EVT SVT = VT.getScalarType();
6043   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize());
6044   EVT ShSVT = ShVT.getScalarType();
6045 
6046   // If MUL is unavailable, we cannot proceed in any case.
6047   if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
6048     return SDValue();
6049 
6050   bool ComparingWithAllZeros = true;
6051   bool AllComparisonsWithNonZerosAreTautological = true;
6052   bool HadTautologicalLanes = false;
6053   bool AllLanesAreTautological = true;
6054   bool HadEvenDivisor = false;
6055   bool AllDivisorsArePowerOfTwo = true;
6056   bool HadTautologicalInvertedLanes = false;
6057   SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts;
6058 
6059   auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
6060     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
6061     if (CDiv->isZero())
6062       return false;
6063 
6064     const APInt &D = CDiv->getAPIntValue();
6065     const APInt &Cmp = CCmp->getAPIntValue();
6066 
6067     ComparingWithAllZeros &= Cmp.isZero();
6068 
6069     // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
6070     // if C2 is not less than C1, the comparison is always false.
6071     // But we will only be able to produce the comparison that will give the
6072     // opposive tautological answer. So this lane would need to be fixed up.
6073     bool TautologicalInvertedLane = D.ule(Cmp);
6074     HadTautologicalInvertedLanes |= TautologicalInvertedLane;
6075 
6076     // If all lanes are tautological (either all divisors are ones, or divisor
6077     // is not greater than the constant we are comparing with),
6078     // we will prefer to avoid the fold.
6079     bool TautologicalLane = D.isOne() || TautologicalInvertedLane;
6080     HadTautologicalLanes |= TautologicalLane;
6081     AllLanesAreTautological &= TautologicalLane;
6082 
6083     // If we are comparing with non-zero, we need'll need  to subtract said
6084     // comparison value from the LHS. But there is no point in doing that if
6085     // every lane where we are comparing with non-zero is tautological..
6086     if (!Cmp.isZero())
6087       AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
6088 
6089     // Decompose D into D0 * 2^K
6090     unsigned K = D.countTrailingZeros();
6091     assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
6092     APInt D0 = D.lshr(K);
6093 
6094     // D is even if it has trailing zeros.
6095     HadEvenDivisor |= (K != 0);
6096     // D is a power-of-two if D0 is one.
6097     // If all divisors are power-of-two, we will prefer to avoid the fold.
6098     AllDivisorsArePowerOfTwo &= D0.isOne();
6099 
6100     // P = inv(D0, 2^W)
6101     // 2^W requires W + 1 bits, so we have to extend and then truncate.
6102     unsigned W = D.getBitWidth();
6103     APInt P = D0.zext(W + 1)
6104                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
6105                   .trunc(W);
6106     assert(!P.isZero() && "No multiplicative inverse!"); // unreachable
6107     assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
6108 
6109     // Q = floor((2^W - 1) u/ D)
6110     // R = ((2^W - 1) u% D)
6111     APInt Q, R;
6112     APInt::udivrem(APInt::getAllOnes(W), D, Q, R);
6113 
6114     // If we are comparing with zero, then that comparison constant is okay,
6115     // else it may need to be one less than that.
6116     if (Cmp.ugt(R))
6117       Q -= 1;
6118 
6119     assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) &&
6120            "We are expecting that K is always less than all-ones for ShSVT");
6121 
6122     // If the lane is tautological the result can be constant-folded.
6123     if (TautologicalLane) {
6124       // Set P and K amount to a bogus values so we can try to splat them.
6125       P = 0;
6126       K = -1;
6127       // And ensure that comparison constant is tautological,
6128       // it will always compare true/false.
6129       Q = -1;
6130     }
6131 
6132     PAmts.push_back(DAG.getConstant(P, DL, SVT));
6133     KAmts.push_back(
6134         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
6135     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
6136     return true;
6137   };
6138 
6139   SDValue N = REMNode.getOperand(0);
6140   SDValue D = REMNode.getOperand(1);
6141 
6142   // Collect the values from each element.
6143   if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
6144     return SDValue();
6145 
6146   // If all lanes are tautological, the result can be constant-folded.
6147   if (AllLanesAreTautological)
6148     return SDValue();
6149 
6150   // If this is a urem by a powers-of-two, avoid the fold since it can be
6151   // best implemented as a bit test.
6152   if (AllDivisorsArePowerOfTwo)
6153     return SDValue();
6154 
6155   SDValue PVal, KVal, QVal;
6156   if (D.getOpcode() == ISD::BUILD_VECTOR) {
6157     if (HadTautologicalLanes) {
6158       // Try to turn PAmts into a splat, since we don't care about the values
6159       // that are currently '0'. If we can't, just keep '0'`s.
6160       turnVectorIntoSplatVector(PAmts, isNullConstant);
6161       // Try to turn KAmts into a splat, since we don't care about the values
6162       // that are currently '-1'. If we can't, change them to '0'`s.
6163       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
6164                                 DAG.getConstant(0, DL, ShSVT));
6165     }
6166 
6167     PVal = DAG.getBuildVector(VT, DL, PAmts);
6168     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
6169     QVal = DAG.getBuildVector(VT, DL, QAmts);
6170   } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
6171     assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 &&
6172            "Expected matchBinaryPredicate to return one element for "
6173            "SPLAT_VECTORs");
6174     PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
6175     KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
6176     QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
6177   } else {
6178     PVal = PAmts[0];
6179     KVal = KAmts[0];
6180     QVal = QAmts[0];
6181   }
6182 
6183   if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
6184     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
6185       return SDValue(); // FIXME: Could/should use `ISD::ADD`?
6186     assert(CompTargetNode.getValueType() == N.getValueType() &&
6187            "Expecting that the types on LHS and RHS of comparisons match.");
6188     N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
6189   }
6190 
6191   // (mul N, P)
6192   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
6193   Created.push_back(Op0.getNode());
6194 
6195   // Rotate right only if any divisor was even. We avoid rotates for all-odd
6196   // divisors as a performance improvement, since rotating by 0 is a no-op.
6197   if (HadEvenDivisor) {
6198     // We need ROTR to do this.
6199     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
6200       return SDValue();
6201     // UREM: (rotr (mul N, P), K)
6202     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
6203     Created.push_back(Op0.getNode());
6204   }
6205 
6206   // UREM: (setule/setugt (rotr (mul N, P), K), Q)
6207   SDValue NewCC =
6208       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
6209                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
6210   if (!HadTautologicalInvertedLanes)
6211     return NewCC;
6212 
6213   // If any lanes previously compared always-false, the NewCC will give
6214   // always-true result for them, so we need to fixup those lanes.
6215   // Or the other way around for inequality predicate.
6216   assert(VT.isVector() && "Can/should only get here for vectors.");
6217   Created.push_back(NewCC.getNode());
6218 
6219   // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
6220   // if C2 is not less than C1, the comparison is always false.
6221   // But we have produced the comparison that will give the
6222   // opposive tautological answer. So these lanes would need to be fixed up.
6223   SDValue TautologicalInvertedChannels =
6224       DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
6225   Created.push_back(TautologicalInvertedChannels.getNode());
6226 
6227   // NOTE: we avoid letting illegal types through even if we're before legalize
6228   // ops – legalization has a hard time producing good code for this.
6229   if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
6230     // If we have a vector select, let's replace the comparison results in the
6231     // affected lanes with the correct tautological result.
6232     SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
6233                                               DL, SETCCVT, SETCCVT);
6234     return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
6235                        Replacement, NewCC);
6236   }
6237 
6238   // Else, we can just invert the comparison result in the appropriate lanes.
6239   //
6240   // NOTE: see the note above VSELECT above.
6241   if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
6242     return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
6243                        TautologicalInvertedChannels);
6244 
6245   return SDValue(); // Don't know how to lower.
6246 }
6247 
6248 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
6249 /// where the divisor is constant and the comparison target is zero,
6250 /// return a DAG expression that will generate the same comparison result
6251 /// using only multiplications, additions and shifts/rotations.
6252 /// Ref: "Hacker's Delight" 10-17.
6253 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
6254                                         SDValue CompTargetNode,
6255                                         ISD::CondCode Cond,
6256                                         DAGCombinerInfo &DCI,
6257                                         const SDLoc &DL) const {
6258   SmallVector<SDNode *, 7> Built;
6259   if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
6260                                          DCI, DL, Built)) {
6261     assert(Built.size() <= 7 && "Max size prediction failed.");
6262     for (SDNode *N : Built)
6263       DCI.AddToWorklist(N);
6264     return Folded;
6265   }
6266 
6267   return SDValue();
6268 }
6269 
6270 SDValue
6271 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
6272                                   SDValue CompTargetNode, ISD::CondCode Cond,
6273                                   DAGCombinerInfo &DCI, const SDLoc &DL,
6274                                   SmallVectorImpl<SDNode *> &Created) const {
6275   // Fold:
6276   //   (seteq/ne (srem N, D), 0)
6277   // To:
6278   //   (setule/ugt (rotr (add (mul N, P), A), K), Q)
6279   //
6280   // - D must be constant, with D = D0 * 2^K where D0 is odd
6281   // - P is the multiplicative inverse of D0 modulo 2^W
6282   // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
6283   // - Q = floor((2 * A) / (2^K))
6284   // where W is the width of the common type of N and D.
6285   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
6286          "Only applicable for (in)equality comparisons.");
6287 
6288   SelectionDAG &DAG = DCI.DAG;
6289 
6290   EVT VT = REMNode.getValueType();
6291   EVT SVT = VT.getScalarType();
6292   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize());
6293   EVT ShSVT = ShVT.getScalarType();
6294 
6295   // If we are after ops legalization, and MUL is unavailable, we can not
6296   // proceed.
6297   if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
6298     return SDValue();
6299 
6300   // TODO: Could support comparing with non-zero too.
6301   ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
6302   if (!CompTarget || !CompTarget->isZero())
6303     return SDValue();
6304 
6305   bool HadIntMinDivisor = false;
6306   bool HadOneDivisor = false;
6307   bool AllDivisorsAreOnes = true;
6308   bool HadEvenDivisor = false;
6309   bool NeedToApplyOffset = false;
6310   bool AllDivisorsArePowerOfTwo = true;
6311   SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
6312 
6313   auto BuildSREMPattern = [&](ConstantSDNode *C) {
6314     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
6315     if (C->isZero())
6316       return false;
6317 
6318     // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
6319 
6320     // WARNING: this fold is only valid for positive divisors!
6321     APInt D = C->getAPIntValue();
6322     if (D.isNegative())
6323       D.negate(); //  `rem %X, -C` is equivalent to `rem %X, C`
6324 
6325     HadIntMinDivisor |= D.isMinSignedValue();
6326 
6327     // If all divisors are ones, we will prefer to avoid the fold.
6328     HadOneDivisor |= D.isOne();
6329     AllDivisorsAreOnes &= D.isOne();
6330 
6331     // Decompose D into D0 * 2^K
6332     unsigned K = D.countTrailingZeros();
6333     assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
6334     APInt D0 = D.lshr(K);
6335 
6336     if (!D.isMinSignedValue()) {
6337       // D is even if it has trailing zeros; unless it's INT_MIN, in which case
6338       // we don't care about this lane in this fold, we'll special-handle it.
6339       HadEvenDivisor |= (K != 0);
6340     }
6341 
6342     // D is a power-of-two if D0 is one. This includes INT_MIN.
6343     // If all divisors are power-of-two, we will prefer to avoid the fold.
6344     AllDivisorsArePowerOfTwo &= D0.isOne();
6345 
6346     // P = inv(D0, 2^W)
6347     // 2^W requires W + 1 bits, so we have to extend and then truncate.
6348     unsigned W = D.getBitWidth();
6349     APInt P = D0.zext(W + 1)
6350                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
6351                   .trunc(W);
6352     assert(!P.isZero() && "No multiplicative inverse!"); // unreachable
6353     assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
6354 
6355     // A = floor((2^(W - 1) - 1) / D0) & -2^K
6356     APInt A = APInt::getSignedMaxValue(W).udiv(D0);
6357     A.clearLowBits(K);
6358 
6359     if (!D.isMinSignedValue()) {
6360       // If divisor INT_MIN, then we don't care about this lane in this fold,
6361       // we'll special-handle it.
6362       NeedToApplyOffset |= A != 0;
6363     }
6364 
6365     // Q = floor((2 * A) / (2^K))
6366     APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
6367 
6368     assert(APInt::getAllOnes(SVT.getSizeInBits()).ugt(A) &&
6369            "We are expecting that A is always less than all-ones for SVT");
6370     assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) &&
6371            "We are expecting that K is always less than all-ones for ShSVT");
6372 
6373     // If the divisor is 1 the result can be constant-folded. Likewise, we
6374     // don't care about INT_MIN lanes, those can be set to undef if appropriate.
6375     if (D.isOne()) {
6376       // Set P, A and K to a bogus values so we can try to splat them.
6377       P = 0;
6378       A = -1;
6379       K = -1;
6380 
6381       // x ?% 1 == 0  <-->  true  <-->  x u<= -1
6382       Q = -1;
6383     }
6384 
6385     PAmts.push_back(DAG.getConstant(P, DL, SVT));
6386     AAmts.push_back(DAG.getConstant(A, DL, SVT));
6387     KAmts.push_back(
6388         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
6389     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
6390     return true;
6391   };
6392 
6393   SDValue N = REMNode.getOperand(0);
6394   SDValue D = REMNode.getOperand(1);
6395 
6396   // Collect the values from each element.
6397   if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
6398     return SDValue();
6399 
6400   // If this is a srem by a one, avoid the fold since it can be constant-folded.
6401   if (AllDivisorsAreOnes)
6402     return SDValue();
6403 
6404   // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
6405   // since it can be best implemented as a bit test.
6406   if (AllDivisorsArePowerOfTwo)
6407     return SDValue();
6408 
6409   SDValue PVal, AVal, KVal, QVal;
6410   if (D.getOpcode() == ISD::BUILD_VECTOR) {
6411     if (HadOneDivisor) {
6412       // Try to turn PAmts into a splat, since we don't care about the values
6413       // that are currently '0'. If we can't, just keep '0'`s.
6414       turnVectorIntoSplatVector(PAmts, isNullConstant);
6415       // Try to turn AAmts into a splat, since we don't care about the
6416       // values that are currently '-1'. If we can't, change them to '0'`s.
6417       turnVectorIntoSplatVector(AAmts, isAllOnesConstant,
6418                                 DAG.getConstant(0, DL, SVT));
6419       // Try to turn KAmts into a splat, since we don't care about the values
6420       // that are currently '-1'. If we can't, change them to '0'`s.
6421       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
6422                                 DAG.getConstant(0, DL, ShSVT));
6423     }
6424 
6425     PVal = DAG.getBuildVector(VT, DL, PAmts);
6426     AVal = DAG.getBuildVector(VT, DL, AAmts);
6427     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
6428     QVal = DAG.getBuildVector(VT, DL, QAmts);
6429   } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
6430     assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
6431            QAmts.size() == 1 &&
6432            "Expected matchUnaryPredicate to return one element for scalable "
6433            "vectors");
6434     PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
6435     AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
6436     KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
6437     QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
6438   } else {
6439     assert(isa<ConstantSDNode>(D) && "Expected a constant");
6440     PVal = PAmts[0];
6441     AVal = AAmts[0];
6442     KVal = KAmts[0];
6443     QVal = QAmts[0];
6444   }
6445 
6446   // (mul N, P)
6447   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
6448   Created.push_back(Op0.getNode());
6449 
6450   if (NeedToApplyOffset) {
6451     // We need ADD to do this.
6452     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
6453       return SDValue();
6454 
6455     // (add (mul N, P), A)
6456     Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
6457     Created.push_back(Op0.getNode());
6458   }
6459 
6460   // Rotate right only if any divisor was even. We avoid rotates for all-odd
6461   // divisors as a performance improvement, since rotating by 0 is a no-op.
6462   if (HadEvenDivisor) {
6463     // We need ROTR to do this.
6464     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
6465       return SDValue();
6466     // SREM: (rotr (add (mul N, P), A), K)
6467     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
6468     Created.push_back(Op0.getNode());
6469   }
6470 
6471   // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
6472   SDValue Fold =
6473       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
6474                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
6475 
6476   // If we didn't have lanes with INT_MIN divisor, then we're done.
6477   if (!HadIntMinDivisor)
6478     return Fold;
6479 
6480   // That fold is only valid for positive divisors. Which effectively means,
6481   // it is invalid for INT_MIN divisors. So if we have such a lane,
6482   // we must fix-up results for said lanes.
6483   assert(VT.isVector() && "Can/should only get here for vectors.");
6484 
6485   // NOTE: we avoid letting illegal types through even if we're before legalize
6486   // ops – legalization has a hard time producing good code for the code that
6487   // follows.
6488   if (!isOperationLegalOrCustom(ISD::SETEQ, VT) ||
6489       !isOperationLegalOrCustom(ISD::AND, VT) ||
6490       !isOperationLegalOrCustom(Cond, VT) ||
6491       !isOperationLegalOrCustom(ISD::VSELECT, SETCCVT))
6492     return SDValue();
6493 
6494   Created.push_back(Fold.getNode());
6495 
6496   SDValue IntMin = DAG.getConstant(
6497       APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT);
6498   SDValue IntMax = DAG.getConstant(
6499       APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT);
6500   SDValue Zero =
6501       DAG.getConstant(APInt::getZero(SVT.getScalarSizeInBits()), DL, VT);
6502 
6503   // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded.
6504   SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ);
6505   Created.push_back(DivisorIsIntMin.getNode());
6506 
6507   // (N s% INT_MIN) ==/!= 0  <-->  (N & INT_MAX) ==/!= 0
6508   SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax);
6509   Created.push_back(Masked.getNode());
6510   SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond);
6511   Created.push_back(MaskedIsZero.getNode());
6512 
6513   // To produce final result we need to blend 2 vectors: 'SetCC' and
6514   // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick
6515   // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is
6516   // constant-folded, select can get lowered to a shuffle with constant mask.
6517   SDValue Blended = DAG.getNode(ISD::VSELECT, DL, SETCCVT, DivisorIsIntMin,
6518                                 MaskedIsZero, Fold);
6519 
6520   return Blended;
6521 }
6522 
6523 bool TargetLowering::
6524 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
6525   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
6526     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
6527                                 "be a constant integer");
6528     return true;
6529   }
6530 
6531   return false;
6532 }
6533 
6534 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
6535                                          const DenormalMode &Mode) const {
6536   SDLoc DL(Op);
6537   EVT VT = Op.getValueType();
6538   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6539   SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
6540   // Testing it with denormal inputs to avoid wrong estimate.
6541   if (Mode.Input == DenormalMode::IEEE) {
6542     // This is specifically a check for the handling of denormal inputs,
6543     // not the result.
6544 
6545     // Test = fabs(X) < SmallestNormal
6546     const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
6547     APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
6548     SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
6549     SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op);
6550     return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT);
6551   }
6552   // Test = X == 0.0
6553   return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
6554 }
6555 
6556 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
6557                                              bool LegalOps, bool OptForSize,
6558                                              NegatibleCost &Cost,
6559                                              unsigned Depth) const {
6560   // fneg is removable even if it has multiple uses.
6561   if (Op.getOpcode() == ISD::FNEG) {
6562     Cost = NegatibleCost::Cheaper;
6563     return Op.getOperand(0);
6564   }
6565 
6566   // Don't recurse exponentially.
6567   if (Depth > SelectionDAG::MaxRecursionDepth)
6568     return SDValue();
6569 
6570   // Pre-increment recursion depth for use in recursive calls.
6571   ++Depth;
6572   const SDNodeFlags Flags = Op->getFlags();
6573   const TargetOptions &Options = DAG.getTarget().Options;
6574   EVT VT = Op.getValueType();
6575   unsigned Opcode = Op.getOpcode();
6576 
6577   // Don't allow anything with multiple uses unless we know it is free.
6578   if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
6579     bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
6580                         isFPExtFree(VT, Op.getOperand(0).getValueType());
6581     if (!IsFreeExtend)
6582       return SDValue();
6583   }
6584 
6585   auto RemoveDeadNode = [&](SDValue N) {
6586     if (N && N.getNode()->use_empty())
6587       DAG.RemoveDeadNode(N.getNode());
6588   };
6589 
6590   SDLoc DL(Op);
6591 
6592   // Because getNegatedExpression can delete nodes we need a handle to keep
6593   // temporary nodes alive in case the recursion manages to create an identical
6594   // node.
6595   std::list<HandleSDNode> Handles;
6596 
6597   switch (Opcode) {
6598   case ISD::ConstantFP: {
6599     // Don't invert constant FP values after legalization unless the target says
6600     // the negated constant is legal.
6601     bool IsOpLegal =
6602         isOperationLegal(ISD::ConstantFP, VT) ||
6603         isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
6604                      OptForSize);
6605 
6606     if (LegalOps && !IsOpLegal)
6607       break;
6608 
6609     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
6610     V.changeSign();
6611     SDValue CFP = DAG.getConstantFP(V, DL, VT);
6612 
6613     // If we already have the use of the negated floating constant, it is free
6614     // to negate it even it has multiple uses.
6615     if (!Op.hasOneUse() && CFP.use_empty())
6616       break;
6617     Cost = NegatibleCost::Neutral;
6618     return CFP;
6619   }
6620   case ISD::BUILD_VECTOR: {
6621     // Only permit BUILD_VECTOR of constants.
6622     if (llvm::any_of(Op->op_values(), [&](SDValue N) {
6623           return !N.isUndef() && !isa<ConstantFPSDNode>(N);
6624         }))
6625       break;
6626 
6627     bool IsOpLegal =
6628         (isOperationLegal(ISD::ConstantFP, VT) &&
6629          isOperationLegal(ISD::BUILD_VECTOR, VT)) ||
6630         llvm::all_of(Op->op_values(), [&](SDValue N) {
6631           return N.isUndef() ||
6632                  isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
6633                               OptForSize);
6634         });
6635 
6636     if (LegalOps && !IsOpLegal)
6637       break;
6638 
6639     SmallVector<SDValue, 4> Ops;
6640     for (SDValue C : Op->op_values()) {
6641       if (C.isUndef()) {
6642         Ops.push_back(C);
6643         continue;
6644       }
6645       APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
6646       V.changeSign();
6647       Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
6648     }
6649     Cost = NegatibleCost::Neutral;
6650     return DAG.getBuildVector(VT, DL, Ops);
6651   }
6652   case ISD::FADD: {
6653     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6654       break;
6655 
6656     // After operation legalization, it might not be legal to create new FSUBs.
6657     if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
6658       break;
6659     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6660 
6661     // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
6662     NegatibleCost CostX = NegatibleCost::Expensive;
6663     SDValue NegX =
6664         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6665     // Prevent this node from being deleted by the next call.
6666     if (NegX)
6667       Handles.emplace_back(NegX);
6668 
6669     // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
6670     NegatibleCost CostY = NegatibleCost::Expensive;
6671     SDValue NegY =
6672         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6673 
6674     // We're done with the handles.
6675     Handles.clear();
6676 
6677     // Negate the X if its cost is less or equal than Y.
6678     if (NegX && (CostX <= CostY)) {
6679       Cost = CostX;
6680       SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
6681       if (NegY != N)
6682         RemoveDeadNode(NegY);
6683       return N;
6684     }
6685 
6686     // Negate the Y if it is not expensive.
6687     if (NegY) {
6688       Cost = CostY;
6689       SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
6690       if (NegX != N)
6691         RemoveDeadNode(NegX);
6692       return N;
6693     }
6694     break;
6695   }
6696   case ISD::FSUB: {
6697     // We can't turn -(A-B) into B-A when we honor signed zeros.
6698     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6699       break;
6700 
6701     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6702     // fold (fneg (fsub 0, Y)) -> Y
6703     if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
6704       if (C->isZero()) {
6705         Cost = NegatibleCost::Cheaper;
6706         return Y;
6707       }
6708 
6709     // fold (fneg (fsub X, Y)) -> (fsub Y, X)
6710     Cost = NegatibleCost::Neutral;
6711     return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
6712   }
6713   case ISD::FMUL:
6714   case ISD::FDIV: {
6715     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
6716 
6717     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
6718     NegatibleCost CostX = NegatibleCost::Expensive;
6719     SDValue NegX =
6720         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6721     // Prevent this node from being deleted by the next call.
6722     if (NegX)
6723       Handles.emplace_back(NegX);
6724 
6725     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
6726     NegatibleCost CostY = NegatibleCost::Expensive;
6727     SDValue NegY =
6728         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6729 
6730     // We're done with the handles.
6731     Handles.clear();
6732 
6733     // Negate the X if its cost is less or equal than Y.
6734     if (NegX && (CostX <= CostY)) {
6735       Cost = CostX;
6736       SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
6737       if (NegY != N)
6738         RemoveDeadNode(NegY);
6739       return N;
6740     }
6741 
6742     // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
6743     if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
6744       if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
6745         break;
6746 
6747     // Negate the Y if it is not expensive.
6748     if (NegY) {
6749       Cost = CostY;
6750       SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
6751       if (NegX != N)
6752         RemoveDeadNode(NegX);
6753       return N;
6754     }
6755     break;
6756   }
6757   case ISD::FMA:
6758   case ISD::FMAD: {
6759     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
6760       break;
6761 
6762     SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
6763     NegatibleCost CostZ = NegatibleCost::Expensive;
6764     SDValue NegZ =
6765         getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
6766     // Give up if fail to negate the Z.
6767     if (!NegZ)
6768       break;
6769 
6770     // Prevent this node from being deleted by the next two calls.
6771     Handles.emplace_back(NegZ);
6772 
6773     // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
6774     NegatibleCost CostX = NegatibleCost::Expensive;
6775     SDValue NegX =
6776         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
6777     // Prevent this node from being deleted by the next call.
6778     if (NegX)
6779       Handles.emplace_back(NegX);
6780 
6781     // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
6782     NegatibleCost CostY = NegatibleCost::Expensive;
6783     SDValue NegY =
6784         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
6785 
6786     // We're done with the handles.
6787     Handles.clear();
6788 
6789     // Negate the X if its cost is less or equal than Y.
6790     if (NegX && (CostX <= CostY)) {
6791       Cost = std::min(CostX, CostZ);
6792       SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
6793       if (NegY != N)
6794         RemoveDeadNode(NegY);
6795       return N;
6796     }
6797 
6798     // Negate the Y if it is not expensive.
6799     if (NegY) {
6800       Cost = std::min(CostY, CostZ);
6801       SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
6802       if (NegX != N)
6803         RemoveDeadNode(NegX);
6804       return N;
6805     }
6806     break;
6807   }
6808 
6809   case ISD::FP_EXTEND:
6810   case ISD::FSIN:
6811     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
6812                                             OptForSize, Cost, Depth))
6813       return DAG.getNode(Opcode, DL, VT, NegV);
6814     break;
6815   case ISD::FP_ROUND:
6816     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
6817                                             OptForSize, Cost, Depth))
6818       return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
6819     break;
6820   }
6821 
6822   return SDValue();
6823 }
6824 
6825 //===----------------------------------------------------------------------===//
6826 // Legalization Utilities
6827 //===----------------------------------------------------------------------===//
6828 
6829 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
6830                                     SDValue LHS, SDValue RHS,
6831                                     SmallVectorImpl<SDValue> &Result,
6832                                     EVT HiLoVT, SelectionDAG &DAG,
6833                                     MulExpansionKind Kind, SDValue LL,
6834                                     SDValue LH, SDValue RL, SDValue RH) const {
6835   assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
6836          Opcode == ISD::SMUL_LOHI);
6837 
6838   bool HasMULHS = (Kind == MulExpansionKind::Always) ||
6839                   isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
6840   bool HasMULHU = (Kind == MulExpansionKind::Always) ||
6841                   isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
6842   bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
6843                       isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
6844   bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
6845                       isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
6846 
6847   if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
6848     return false;
6849 
6850   unsigned OuterBitSize = VT.getScalarSizeInBits();
6851   unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
6852 
6853   // LL, LH, RL, and RH must be either all NULL or all set to a value.
6854   assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
6855          (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
6856 
6857   SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
6858   auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
6859                           bool Signed) -> bool {
6860     if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
6861       Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
6862       Hi = SDValue(Lo.getNode(), 1);
6863       return true;
6864     }
6865     if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
6866       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
6867       Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
6868       return true;
6869     }
6870     return false;
6871   };
6872 
6873   SDValue Lo, Hi;
6874 
6875   if (!LL.getNode() && !RL.getNode() &&
6876       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
6877     LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
6878     RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
6879   }
6880 
6881   if (!LL.getNode())
6882     return false;
6883 
6884   APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
6885   if (DAG.MaskedValueIsZero(LHS, HighMask) &&
6886       DAG.MaskedValueIsZero(RHS, HighMask)) {
6887     // The inputs are both zero-extended.
6888     if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
6889       Result.push_back(Lo);
6890       Result.push_back(Hi);
6891       if (Opcode != ISD::MUL) {
6892         SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
6893         Result.push_back(Zero);
6894         Result.push_back(Zero);
6895       }
6896       return true;
6897     }
6898   }
6899 
6900   if (!VT.isVector() && Opcode == ISD::MUL &&
6901       DAG.ComputeNumSignBits(LHS) > InnerBitSize &&
6902       DAG.ComputeNumSignBits(RHS) > InnerBitSize) {
6903     // The input values are both sign-extended.
6904     // TODO non-MUL case?
6905     if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
6906       Result.push_back(Lo);
6907       Result.push_back(Hi);
6908       return true;
6909     }
6910   }
6911 
6912   unsigned ShiftAmount = OuterBitSize - InnerBitSize;
6913   EVT ShiftAmountTy = getShiftAmountTy(VT, DAG.getDataLayout());
6914   SDValue Shift = DAG.getConstant(ShiftAmount, dl, ShiftAmountTy);
6915 
6916   if (!LH.getNode() && !RH.getNode() &&
6917       isOperationLegalOrCustom(ISD::SRL, VT) &&
6918       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
6919     LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
6920     LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
6921     RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
6922     RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
6923   }
6924 
6925   if (!LH.getNode())
6926     return false;
6927 
6928   if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
6929     return false;
6930 
6931   Result.push_back(Lo);
6932 
6933   if (Opcode == ISD::MUL) {
6934     RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
6935     LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
6936     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
6937     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
6938     Result.push_back(Hi);
6939     return true;
6940   }
6941 
6942   // Compute the full width result.
6943   auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
6944     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
6945     Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
6946     Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
6947     return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
6948   };
6949 
6950   SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
6951   if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
6952     return false;
6953 
6954   // This is effectively the add part of a multiply-add of half-sized operands,
6955   // so it cannot overflow.
6956   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
6957 
6958   if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
6959     return false;
6960 
6961   SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
6962   EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6963 
6964   bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
6965                   isOperationLegalOrCustom(ISD::ADDE, VT));
6966   if (UseGlue)
6967     Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
6968                        Merge(Lo, Hi));
6969   else
6970     Next = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(VT, BoolType), Next,
6971                        Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
6972 
6973   SDValue Carry = Next.getValue(1);
6974   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
6975   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
6976 
6977   if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
6978     return false;
6979 
6980   if (UseGlue)
6981     Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
6982                      Carry);
6983   else
6984     Hi = DAG.getNode(ISD::ADDCARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
6985                      Zero, Carry);
6986 
6987   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
6988 
6989   if (Opcode == ISD::SMUL_LOHI) {
6990     SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
6991                                   DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
6992     Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
6993 
6994     NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
6995                           DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
6996     Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
6997   }
6998 
6999   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
7000   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
7001   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
7002   return true;
7003 }
7004 
7005 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
7006                                SelectionDAG &DAG, MulExpansionKind Kind,
7007                                SDValue LL, SDValue LH, SDValue RL,
7008                                SDValue RH) const {
7009   SmallVector<SDValue, 2> Result;
7010   bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
7011                            N->getOperand(0), N->getOperand(1), Result, HiLoVT,
7012                            DAG, Kind, LL, LH, RL, RH);
7013   if (Ok) {
7014     assert(Result.size() == 2);
7015     Lo = Result[0];
7016     Hi = Result[1];
7017   }
7018   return Ok;
7019 }
7020 
7021 // Check that (every element of) Z is undef or not an exact multiple of BW.
7022 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
7023   return ISD::matchUnaryPredicate(
7024       Z,
7025       [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
7026       true);
7027 }
7028 
7029 SDValue TargetLowering::expandFunnelShift(SDNode *Node,
7030                                           SelectionDAG &DAG) const {
7031   EVT VT = Node->getValueType(0);
7032 
7033   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
7034                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
7035                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
7036                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
7037     return SDValue();
7038 
7039   SDValue X = Node->getOperand(0);
7040   SDValue Y = Node->getOperand(1);
7041   SDValue Z = Node->getOperand(2);
7042 
7043   unsigned BW = VT.getScalarSizeInBits();
7044   bool IsFSHL = Node->getOpcode() == ISD::FSHL;
7045   SDLoc DL(SDValue(Node, 0));
7046 
7047   EVT ShVT = Z.getValueType();
7048 
7049   // If a funnel shift in the other direction is more supported, use it.
7050   unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
7051   if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
7052       isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
7053     if (isNonZeroModBitWidthOrUndef(Z, BW)) {
7054       // fshl X, Y, Z -> fshr X, Y, -Z
7055       // fshr X, Y, Z -> fshl X, Y, -Z
7056       SDValue Zero = DAG.getConstant(0, DL, ShVT);
7057       Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z);
7058     } else {
7059       // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
7060       // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
7061       SDValue One = DAG.getConstant(1, DL, ShVT);
7062       if (IsFSHL) {
7063         Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
7064         X = DAG.getNode(ISD::SRL, DL, VT, X, One);
7065       } else {
7066         X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
7067         Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
7068       }
7069       Z = DAG.getNOT(DL, Z, ShVT);
7070     }
7071     return DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
7072   }
7073 
7074   SDValue ShX, ShY;
7075   SDValue ShAmt, InvShAmt;
7076   if (isNonZeroModBitWidthOrUndef(Z, BW)) {
7077     // fshl: X << C | Y >> (BW - C)
7078     // fshr: X << (BW - C) | Y >> C
7079     // where C = Z % BW is not zero
7080     SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
7081     ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
7082     InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
7083     ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
7084     ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
7085   } else {
7086     // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
7087     // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
7088     SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
7089     if (isPowerOf2_32(BW)) {
7090       // Z % BW -> Z & (BW - 1)
7091       ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
7092       // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
7093       InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
7094     } else {
7095       SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
7096       ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
7097       InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
7098     }
7099 
7100     SDValue One = DAG.getConstant(1, DL, ShVT);
7101     if (IsFSHL) {
7102       ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
7103       SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
7104       ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
7105     } else {
7106       SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
7107       ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
7108       ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
7109     }
7110   }
7111   return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
7112 }
7113 
7114 // TODO: Merge with expandFunnelShift.
7115 SDValue TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps,
7116                                   SelectionDAG &DAG) const {
7117   EVT VT = Node->getValueType(0);
7118   unsigned EltSizeInBits = VT.getScalarSizeInBits();
7119   bool IsLeft = Node->getOpcode() == ISD::ROTL;
7120   SDValue Op0 = Node->getOperand(0);
7121   SDValue Op1 = Node->getOperand(1);
7122   SDLoc DL(SDValue(Node, 0));
7123 
7124   EVT ShVT = Op1.getValueType();
7125   SDValue Zero = DAG.getConstant(0, DL, ShVT);
7126 
7127   // If a rotate in the other direction is more supported, use it.
7128   unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
7129   if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
7130       isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
7131     SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
7132     return DAG.getNode(RevRot, DL, VT, Op0, Sub);
7133   }
7134 
7135   if (!AllowVectorOps && VT.isVector() &&
7136       (!isOperationLegalOrCustom(ISD::SHL, VT) ||
7137        !isOperationLegalOrCustom(ISD::SRL, VT) ||
7138        !isOperationLegalOrCustom(ISD::SUB, VT) ||
7139        !isOperationLegalOrCustomOrPromote(ISD::OR, VT) ||
7140        !isOperationLegalOrCustomOrPromote(ISD::AND, VT)))
7141     return SDValue();
7142 
7143   unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
7144   unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
7145   SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
7146   SDValue ShVal;
7147   SDValue HsVal;
7148   if (isPowerOf2_32(EltSizeInBits)) {
7149     // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
7150     // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
7151     SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
7152     SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
7153     ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
7154     SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
7155     HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
7156   } else {
7157     // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
7158     // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
7159     SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
7160     SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
7161     ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
7162     SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
7163     SDValue One = DAG.getConstant(1, DL, ShVT);
7164     HsVal =
7165         DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
7166   }
7167   return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
7168 }
7169 
7170 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi,
7171                                       SelectionDAG &DAG) const {
7172   assert(Node->getNumOperands() == 3 && "Not a double-shift!");
7173   EVT VT = Node->getValueType(0);
7174   unsigned VTBits = VT.getScalarSizeInBits();
7175   assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
7176 
7177   bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
7178   bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
7179   SDValue ShOpLo = Node->getOperand(0);
7180   SDValue ShOpHi = Node->getOperand(1);
7181   SDValue ShAmt = Node->getOperand(2);
7182   EVT ShAmtVT = ShAmt.getValueType();
7183   EVT ShAmtCCVT =
7184       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
7185   SDLoc dl(Node);
7186 
7187   // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
7188   // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
7189   // away during isel.
7190   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
7191                                   DAG.getConstant(VTBits - 1, dl, ShAmtVT));
7192   SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7193                                      DAG.getConstant(VTBits - 1, dl, ShAmtVT))
7194                        : DAG.getConstant(0, dl, VT);
7195 
7196   SDValue Tmp2, Tmp3;
7197   if (IsSHL) {
7198     Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
7199     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
7200   } else {
7201     Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
7202     Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
7203   }
7204 
7205   // If the shift amount is larger or equal than the width of a part we don't
7206   // use the result from the FSHL/FSHR. Insert a test and select the appropriate
7207   // values for large shift amounts.
7208   SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
7209                                 DAG.getConstant(VTBits, dl, ShAmtVT));
7210   SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
7211                               DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
7212 
7213   if (IsSHL) {
7214     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
7215     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
7216   } else {
7217     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
7218     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
7219   }
7220 }
7221 
7222 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
7223                                       SelectionDAG &DAG) const {
7224   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
7225   SDValue Src = Node->getOperand(OpNo);
7226   EVT SrcVT = Src.getValueType();
7227   EVT DstVT = Node->getValueType(0);
7228   SDLoc dl(SDValue(Node, 0));
7229 
7230   // FIXME: Only f32 to i64 conversions are supported.
7231   if (SrcVT != MVT::f32 || DstVT != MVT::i64)
7232     return false;
7233 
7234   if (Node->isStrictFPOpcode())
7235     // When a NaN is converted to an integer a trap is allowed. We can't
7236     // use this expansion here because it would eliminate that trap. Other
7237     // traps are also allowed and cannot be eliminated. See
7238     // IEEE 754-2008 sec 5.8.
7239     return false;
7240 
7241   // Expand f32 -> i64 conversion
7242   // This algorithm comes from compiler-rt's implementation of fixsfdi:
7243   // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
7244   unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
7245   EVT IntVT = SrcVT.changeTypeToInteger();
7246   EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
7247 
7248   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
7249   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
7250   SDValue Bias = DAG.getConstant(127, dl, IntVT);
7251   SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
7252   SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
7253   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
7254 
7255   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
7256 
7257   SDValue ExponentBits = DAG.getNode(
7258       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
7259       DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
7260   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
7261 
7262   SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
7263                              DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
7264                              DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
7265   Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
7266 
7267   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
7268                           DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
7269                           DAG.getConstant(0x00800000, dl, IntVT));
7270 
7271   R = DAG.getZExtOrTrunc(R, dl, DstVT);
7272 
7273   R = DAG.getSelectCC(
7274       dl, Exponent, ExponentLoBit,
7275       DAG.getNode(ISD::SHL, dl, DstVT, R,
7276                   DAG.getZExtOrTrunc(
7277                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
7278                       dl, IntShVT)),
7279       DAG.getNode(ISD::SRL, dl, DstVT, R,
7280                   DAG.getZExtOrTrunc(
7281                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
7282                       dl, IntShVT)),
7283       ISD::SETGT);
7284 
7285   SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
7286                             DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
7287 
7288   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
7289                            DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
7290   return true;
7291 }
7292 
7293 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result,
7294                                       SDValue &Chain,
7295                                       SelectionDAG &DAG) const {
7296   SDLoc dl(SDValue(Node, 0));
7297   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
7298   SDValue Src = Node->getOperand(OpNo);
7299 
7300   EVT SrcVT = Src.getValueType();
7301   EVT DstVT = Node->getValueType(0);
7302   EVT SetCCVT =
7303       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
7304   EVT DstSetCCVT =
7305       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
7306 
7307   // Only expand vector types if we have the appropriate vector bit operations.
7308   unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
7309                                                    ISD::FP_TO_SINT;
7310   if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
7311                            !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT)))
7312     return false;
7313 
7314   // If the maximum float value is smaller then the signed integer range,
7315   // the destination signmask can't be represented by the float, so we can
7316   // just use FP_TO_SINT directly.
7317   const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT);
7318   APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
7319   APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
7320   if (APFloat::opOverflow &
7321       APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
7322     if (Node->isStrictFPOpcode()) {
7323       Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
7324                            { Node->getOperand(0), Src });
7325       Chain = Result.getValue(1);
7326     } else
7327       Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
7328     return true;
7329   }
7330 
7331   // Don't expand it if there isn't cheap fsub instruction.
7332   if (!isOperationLegalOrCustom(
7333           Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
7334     return false;
7335 
7336   SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
7337   SDValue Sel;
7338 
7339   if (Node->isStrictFPOpcode()) {
7340     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
7341                        Node->getOperand(0), /*IsSignaling*/ true);
7342     Chain = Sel.getValue(1);
7343   } else {
7344     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
7345   }
7346 
7347   bool Strict = Node->isStrictFPOpcode() ||
7348                 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
7349 
7350   if (Strict) {
7351     // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
7352     // signmask then offset (the result of which should be fully representable).
7353     // Sel = Src < 0x8000000000000000
7354     // FltOfs = select Sel, 0, 0x8000000000000000
7355     // IntOfs = select Sel, 0, 0x8000000000000000
7356     // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
7357 
7358     // TODO: Should any fast-math-flags be set for the FSUB?
7359     SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
7360                                    DAG.getConstantFP(0.0, dl, SrcVT), Cst);
7361     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
7362     SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
7363                                    DAG.getConstant(0, dl, DstVT),
7364                                    DAG.getConstant(SignMask, dl, DstVT));
7365     SDValue SInt;
7366     if (Node->isStrictFPOpcode()) {
7367       SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
7368                                 { Chain, Src, FltOfs });
7369       SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
7370                          { Val.getValue(1), Val });
7371       Chain = SInt.getValue(1);
7372     } else {
7373       SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
7374       SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
7375     }
7376     Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
7377   } else {
7378     // Expand based on maximum range of FP_TO_SINT:
7379     // True = fp_to_sint(Src)
7380     // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
7381     // Result = select (Src < 0x8000000000000000), True, False
7382 
7383     SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
7384     // TODO: Should any fast-math-flags be set for the FSUB?
7385     SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
7386                                 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
7387     False = DAG.getNode(ISD::XOR, dl, DstVT, False,
7388                         DAG.getConstant(SignMask, dl, DstVT));
7389     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
7390     Result = DAG.getSelect(dl, DstVT, Sel, True, False);
7391   }
7392   return true;
7393 }
7394 
7395 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result,
7396                                       SDValue &Chain,
7397                                       SelectionDAG &DAG) const {
7398   // This transform is not correct for converting 0 when rounding mode is set
7399   // to round toward negative infinity which will produce -0.0. So disable under
7400   // strictfp.
7401   if (Node->isStrictFPOpcode())
7402     return false;
7403 
7404   SDValue Src = Node->getOperand(0);
7405   EVT SrcVT = Src.getValueType();
7406   EVT DstVT = Node->getValueType(0);
7407 
7408   if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
7409     return false;
7410 
7411   // Only expand vector types if we have the appropriate vector bit operations.
7412   if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
7413                            !isOperationLegalOrCustom(ISD::FADD, DstVT) ||
7414                            !isOperationLegalOrCustom(ISD::FSUB, DstVT) ||
7415                            !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) ||
7416                            !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT)))
7417     return false;
7418 
7419   SDLoc dl(SDValue(Node, 0));
7420   EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout());
7421 
7422   // Implementation of unsigned i64 to f64 following the algorithm in
7423   // __floatundidf in compiler_rt.  This implementation performs rounding
7424   // correctly in all rounding modes with the exception of converting 0
7425   // when rounding toward negative infinity. In that case the fsub will produce
7426   // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect.
7427   SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
7428   SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
7429       BitsToDouble(UINT64_C(0x4530000000100000)), dl, DstVT);
7430   SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
7431   SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
7432   SDValue HiShift = DAG.getConstant(32, dl, ShiftVT);
7433 
7434   SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
7435   SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
7436   SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
7437   SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
7438   SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
7439   SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
7440   SDValue HiSub =
7441       DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
7442   Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
7443   return true;
7444 }
7445 
7446 SDValue
7447 TargetLowering::createSelectForFMINNUM_FMAXNUM(SDNode *Node,
7448                                                SelectionDAG &DAG) const {
7449   unsigned Opcode = Node->getOpcode();
7450   assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM ||
7451           Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) &&
7452          "Wrong opcode");
7453 
7454   if (Node->getFlags().hasNoNaNs()) {
7455     ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
7456     SDValue Op1 = Node->getOperand(0);
7457     SDValue Op2 = Node->getOperand(1);
7458     SDValue SelCC = DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred);
7459     // Copy FMF flags, but always set the no-signed-zeros flag
7460     // as this is implied by the FMINNUM/FMAXNUM semantics.
7461     SDNodeFlags Flags = Node->getFlags();
7462     Flags.setNoSignedZeros(true);
7463     SelCC->setFlags(Flags);
7464     return SelCC;
7465   }
7466 
7467   return SDValue();
7468 }
7469 
7470 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node,
7471                                               SelectionDAG &DAG) const {
7472   SDLoc dl(Node);
7473   unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ?
7474     ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
7475   EVT VT = Node->getValueType(0);
7476 
7477   if (VT.isScalableVector())
7478     report_fatal_error(
7479         "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
7480 
7481   if (isOperationLegalOrCustom(NewOp, VT)) {
7482     SDValue Quiet0 = Node->getOperand(0);
7483     SDValue Quiet1 = Node->getOperand(1);
7484 
7485     if (!Node->getFlags().hasNoNaNs()) {
7486       // Insert canonicalizes if it's possible we need to quiet to get correct
7487       // sNaN behavior.
7488       if (!DAG.isKnownNeverSNaN(Quiet0)) {
7489         Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
7490                              Node->getFlags());
7491       }
7492       if (!DAG.isKnownNeverSNaN(Quiet1)) {
7493         Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
7494                              Node->getFlags());
7495       }
7496     }
7497 
7498     return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
7499   }
7500 
7501   // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
7502   // instead if there are no NaNs.
7503   if (Node->getFlags().hasNoNaNs()) {
7504     unsigned IEEE2018Op =
7505         Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
7506     if (isOperationLegalOrCustom(IEEE2018Op, VT)) {
7507       return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
7508                          Node->getOperand(1), Node->getFlags());
7509     }
7510   }
7511 
7512   if (SDValue SelCC = createSelectForFMINNUM_FMAXNUM(Node, DAG))
7513     return SelCC;
7514 
7515   return SDValue();
7516 }
7517 
7518 SDValue TargetLowering::expandIS_FPCLASS(EVT ResultVT, SDValue Op,
7519                                          unsigned Test, SDNodeFlags Flags,
7520                                          const SDLoc &DL,
7521                                          SelectionDAG &DAG) const {
7522   EVT OperandVT = Op.getValueType();
7523   assert(OperandVT.isFloatingPoint());
7524 
7525   // Degenerated cases.
7526   if (Test == 0)
7527     return DAG.getBoolConstant(false, DL, ResultVT, OperandVT);
7528   if ((Test & fcAllFlags) == fcAllFlags)
7529     return DAG.getBoolConstant(true, DL, ResultVT, OperandVT);
7530 
7531   // PPC double double is a pair of doubles, of which the higher part determines
7532   // the value class.
7533   if (OperandVT == MVT::ppcf128) {
7534     Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op,
7535                      DAG.getConstant(1, DL, MVT::i32));
7536     OperandVT = MVT::f64;
7537   }
7538 
7539   // Some checks may be represented as inversion of simpler check, for example
7540   // "inf|normal|subnormal|zero" => !"nan".
7541   bool IsInverted = false;
7542   if (unsigned InvertedCheck = getInvertedFPClassTest(Test)) {
7543     IsInverted = true;
7544     Test = InvertedCheck;
7545   }
7546 
7547   // Floating-point type properties.
7548   EVT ScalarFloatVT = OperandVT.getScalarType();
7549   const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext());
7550   const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics();
7551   bool IsF80 = (ScalarFloatVT == MVT::f80);
7552 
7553   // Some checks can be implemented using float comparisons, if floating point
7554   // exceptions are ignored.
7555   if (Flags.hasNoFPExcept() &&
7556       isOperationLegalOrCustom(ISD::SETCC, OperandVT.getScalarType())) {
7557     if (Test == fcZero)
7558       return DAG.getSetCC(DL, ResultVT, Op,
7559                           DAG.getConstantFP(0.0, DL, OperandVT),
7560                           IsInverted ? ISD::SETUNE : ISD::SETOEQ);
7561     if (Test == fcNan)
7562       return DAG.getSetCC(DL, ResultVT, Op, Op,
7563                           IsInverted ? ISD::SETO : ISD::SETUO);
7564   }
7565 
7566   // In the general case use integer operations.
7567   unsigned BitSize = OperandVT.getScalarSizeInBits();
7568   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), BitSize);
7569   if (OperandVT.isVector())
7570     IntVT = EVT::getVectorVT(*DAG.getContext(), IntVT,
7571                              OperandVT.getVectorElementCount());
7572   SDValue OpAsInt = DAG.getBitcast(IntVT, Op);
7573 
7574   // Various masks.
7575   APInt SignBit = APInt::getSignMask(BitSize);
7576   APInt ValueMask = APInt::getSignedMaxValue(BitSize);     // All bits but sign.
7577   APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit.
7578   const unsigned ExplicitIntBitInF80 = 63;
7579   APInt ExpMask = Inf;
7580   if (IsF80)
7581     ExpMask.clearBit(ExplicitIntBitInF80);
7582   APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf;
7583   APInt QNaNBitMask =
7584       APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1);
7585   APInt InvertionMask = APInt::getAllOnesValue(ResultVT.getScalarSizeInBits());
7586 
7587   SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT);
7588   SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT);
7589   SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT);
7590   SDValue ZeroV = DAG.getConstant(0, DL, IntVT);
7591   SDValue InfV = DAG.getConstant(Inf, DL, IntVT);
7592   SDValue ResultInvertionMask = DAG.getConstant(InvertionMask, DL, ResultVT);
7593 
7594   SDValue Res;
7595   const auto appendResult = [&](SDValue PartialRes) {
7596     if (PartialRes) {
7597       if (Res)
7598         Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes);
7599       else
7600         Res = PartialRes;
7601     }
7602   };
7603 
7604   SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set.
7605   const auto getIntBitIsSet = [&]() -> SDValue {
7606     if (!IntBitIsSetV) {
7607       APInt IntBitMask(BitSize, 0);
7608       IntBitMask.setBit(ExplicitIntBitInF80);
7609       SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT);
7610       SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV);
7611       IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE);
7612     }
7613     return IntBitIsSetV;
7614   };
7615 
7616   // Split the value into sign bit and absolute value.
7617   SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV);
7618   SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt,
7619                                DAG.getConstant(0.0, DL, IntVT), ISD::SETLT);
7620 
7621   // Tests that involve more than one class should be processed first.
7622   SDValue PartialRes;
7623 
7624   if (IsF80)
7625     ; // Detect finite numbers of f80 by checking individual classes because
7626       // they have different settings of the explicit integer bit.
7627   else if ((Test & fcFinite) == fcFinite) {
7628     // finite(V) ==> abs(V) < exp_mask
7629     PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
7630     Test &= ~fcFinite;
7631   } else if ((Test & fcFinite) == fcPosFinite) {
7632     // finite(V) && V > 0 ==> V < exp_mask
7633     PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT);
7634     Test &= ~fcPosFinite;
7635   } else if ((Test & fcFinite) == fcNegFinite) {
7636     // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1
7637     PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
7638     PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
7639     Test &= ~fcNegFinite;
7640   }
7641   appendResult(PartialRes);
7642 
7643   // Check for individual classes.
7644 
7645   if (unsigned PartialCheck = Test & fcZero) {
7646     if (PartialCheck == fcPosZero)
7647       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ);
7648     else if (PartialCheck == fcZero)
7649       PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ);
7650     else // ISD::fcNegZero
7651       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ);
7652     appendResult(PartialRes);
7653   }
7654 
7655   if (unsigned PartialCheck = Test & fcInf) {
7656     if (PartialCheck == fcPosInf)
7657       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ);
7658     else if (PartialCheck == fcInf)
7659       PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ);
7660     else { // ISD::fcNegInf
7661       APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt();
7662       SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT);
7663       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ);
7664     }
7665     appendResult(PartialRes);
7666   }
7667 
7668   if (unsigned PartialCheck = Test & fcNan) {
7669     APInt InfWithQnanBit = Inf | QNaNBitMask;
7670     SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT);
7671     if (PartialCheck == fcNan) {
7672       // isnan(V) ==> abs(V) > int(inf)
7673       PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
7674       if (IsF80) {
7675         // Recognize unsupported values as NaNs for compatibility with glibc.
7676         // In them (exp(V)==0) == int_bit.
7677         SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV);
7678         SDValue ExpIsZero =
7679             DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
7680         SDValue IsPseudo =
7681             DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ);
7682         PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo);
7683       }
7684     } else if (PartialCheck == fcQNan) {
7685       // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit)
7686       PartialRes =
7687           DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE);
7688     } else { // ISD::fcSNan
7689       // issignaling(V) ==> abs(V) > unsigned(Inf) &&
7690       //                    abs(V) < (unsigned(Inf) | quiet_bit)
7691       SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
7692       SDValue IsNotQnan =
7693           DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT);
7694       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan);
7695     }
7696     appendResult(PartialRes);
7697   }
7698 
7699   if (unsigned PartialCheck = Test & fcSubnormal) {
7700     // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set)
7701     // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set)
7702     SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV;
7703     SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT);
7704     SDValue VMinusOneV =
7705         DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT));
7706     PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT);
7707     if (PartialCheck == fcNegSubnormal)
7708       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
7709     appendResult(PartialRes);
7710   }
7711 
7712   if (unsigned PartialCheck = Test & fcNormal) {
7713     // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1))
7714     APInt ExpLSB = ExpMask & ~(ExpMask.shl(1));
7715     SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT);
7716     SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV);
7717     APInt ExpLimit = ExpMask - ExpLSB;
7718     SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT);
7719     PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT);
7720     if (PartialCheck == fcNegNormal)
7721       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
7722     else if (PartialCheck == fcPosNormal) {
7723       SDValue PosSignV =
7724           DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInvertionMask);
7725       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV);
7726     }
7727     if (IsF80)
7728       PartialRes =
7729           DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet());
7730     appendResult(PartialRes);
7731   }
7732 
7733   if (!Res)
7734     return DAG.getConstant(IsInverted, DL, ResultVT);
7735   if (IsInverted)
7736     Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInvertionMask);
7737   return Res;
7738 }
7739 
7740 // Only expand vector types if we have the appropriate vector bit operations.
7741 static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) {
7742   assert(VT.isVector() && "Expected vector type");
7743   unsigned Len = VT.getScalarSizeInBits();
7744   return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
7745          TLI.isOperationLegalOrCustom(ISD::SUB, VT) &&
7746          TLI.isOperationLegalOrCustom(ISD::SRL, VT) &&
7747          (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
7748          TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT);
7749 }
7750 
7751 SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &DAG) const {
7752   SDLoc dl(Node);
7753   EVT VT = Node->getValueType(0);
7754   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7755   SDValue Op = Node->getOperand(0);
7756   unsigned Len = VT.getScalarSizeInBits();
7757   assert(VT.isInteger() && "CTPOP not implemented for this type.");
7758 
7759   // TODO: Add support for irregular type lengths.
7760   if (!(Len <= 128 && Len % 8 == 0))
7761     return SDValue();
7762 
7763   // Only expand vector types if we have the appropriate vector bit operations.
7764   if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
7765     return SDValue();
7766 
7767   // This is the "best" algorithm from
7768   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
7769   SDValue Mask55 =
7770       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
7771   SDValue Mask33 =
7772       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
7773   SDValue Mask0F =
7774       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
7775 
7776   // v = v - ((v >> 1) & 0x55555555...)
7777   Op = DAG.getNode(ISD::SUB, dl, VT, Op,
7778                    DAG.getNode(ISD::AND, dl, VT,
7779                                DAG.getNode(ISD::SRL, dl, VT, Op,
7780                                            DAG.getConstant(1, dl, ShVT)),
7781                                Mask55));
7782   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
7783   Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
7784                    DAG.getNode(ISD::AND, dl, VT,
7785                                DAG.getNode(ISD::SRL, dl, VT, Op,
7786                                            DAG.getConstant(2, dl, ShVT)),
7787                                Mask33));
7788   // v = (v + (v >> 4)) & 0x0F0F0F0F...
7789   Op = DAG.getNode(ISD::AND, dl, VT,
7790                    DAG.getNode(ISD::ADD, dl, VT, Op,
7791                                DAG.getNode(ISD::SRL, dl, VT, Op,
7792                                            DAG.getConstant(4, dl, ShVT))),
7793                    Mask0F);
7794 
7795   if (Len <= 8)
7796     return Op;
7797 
7798   // Avoid the multiply if we only have 2 bytes to add.
7799   // TODO: Only doing this for scalars because vectors weren't as obviously
7800   // improved.
7801   if (Len == 16 && !VT.isVector()) {
7802     // v = (v + (v >> 8)) & 0x00FF;
7803     return DAG.getNode(ISD::AND, dl, VT,
7804                      DAG.getNode(ISD::ADD, dl, VT, Op,
7805                                  DAG.getNode(ISD::SRL, dl, VT, Op,
7806                                              DAG.getConstant(8, dl, ShVT))),
7807                      DAG.getConstant(0xFF, dl, VT));
7808   }
7809 
7810   // v = (v * 0x01010101...) >> (Len - 8)
7811   SDValue Mask01 =
7812       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
7813   return DAG.getNode(ISD::SRL, dl, VT,
7814                      DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
7815                      DAG.getConstant(Len - 8, dl, ShVT));
7816 }
7817 
7818 SDValue TargetLowering::expandCTLZ(SDNode *Node, SelectionDAG &DAG) const {
7819   SDLoc dl(Node);
7820   EVT VT = Node->getValueType(0);
7821   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7822   SDValue Op = Node->getOperand(0);
7823   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
7824 
7825   // If the non-ZERO_UNDEF version is supported we can use that instead.
7826   if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF &&
7827       isOperationLegalOrCustom(ISD::CTLZ, VT))
7828     return DAG.getNode(ISD::CTLZ, dl, VT, Op);
7829 
7830   // If the ZERO_UNDEF version is supported use that and handle the zero case.
7831   if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) {
7832     EVT SetCCVT =
7833         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7834     SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op);
7835     SDValue Zero = DAG.getConstant(0, dl, VT);
7836     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
7837     return DAG.getSelect(dl, VT, SrcIsZero,
7838                          DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
7839   }
7840 
7841   // Only expand vector types if we have the appropriate vector bit operations.
7842   // This includes the operations needed to expand CTPOP if it isn't supported.
7843   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
7844                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
7845                          !canExpandVectorCTPOP(*this, VT)) ||
7846                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
7847                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
7848     return SDValue();
7849 
7850   // for now, we do this:
7851   // x = x | (x >> 1);
7852   // x = x | (x >> 2);
7853   // ...
7854   // x = x | (x >>16);
7855   // x = x | (x >>32); // for 64-bit input
7856   // return popcount(~x);
7857   //
7858   // Ref: "Hacker's Delight" by Henry Warren
7859   for (unsigned i = 0; (1U << i) <= (NumBitsPerElt / 2); ++i) {
7860     SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
7861     Op = DAG.getNode(ISD::OR, dl, VT, Op,
7862                      DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
7863   }
7864   Op = DAG.getNOT(dl, Op, VT);
7865   return DAG.getNode(ISD::CTPOP, dl, VT, Op);
7866 }
7867 
7868 SDValue TargetLowering::expandCTTZ(SDNode *Node, SelectionDAG &DAG) const {
7869   SDLoc dl(Node);
7870   EVT VT = Node->getValueType(0);
7871   SDValue Op = Node->getOperand(0);
7872   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
7873 
7874   // If the non-ZERO_UNDEF version is supported we can use that instead.
7875   if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
7876       isOperationLegalOrCustom(ISD::CTTZ, VT))
7877     return DAG.getNode(ISD::CTTZ, dl, VT, Op);
7878 
7879   // If the ZERO_UNDEF version is supported use that and handle the zero case.
7880   if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) {
7881     EVT SetCCVT =
7882         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7883     SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op);
7884     SDValue Zero = DAG.getConstant(0, dl, VT);
7885     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
7886     return DAG.getSelect(dl, VT, SrcIsZero,
7887                          DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
7888   }
7889 
7890   // Only expand vector types if we have the appropriate vector bit operations.
7891   // This includes the operations needed to expand CTPOP if it isn't supported.
7892   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
7893                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
7894                          !isOperationLegalOrCustom(ISD::CTLZ, VT) &&
7895                          !canExpandVectorCTPOP(*this, VT)) ||
7896                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
7897                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
7898                         !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
7899     return SDValue();
7900 
7901   // for now, we use: { return popcount(~x & (x - 1)); }
7902   // unless the target has ctlz but not ctpop, in which case we use:
7903   // { return 32 - nlz(~x & (x-1)); }
7904   // Ref: "Hacker's Delight" by Henry Warren
7905   SDValue Tmp = DAG.getNode(
7906       ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
7907       DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
7908 
7909   // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
7910   if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) {
7911     return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
7912                        DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
7913   }
7914 
7915   return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
7916 }
7917 
7918 SDValue TargetLowering::expandABS(SDNode *N, SelectionDAG &DAG,
7919                                   bool IsNegative) const {
7920   SDLoc dl(N);
7921   EVT VT = N->getValueType(0);
7922   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
7923   SDValue Op = N->getOperand(0);
7924 
7925   // abs(x) -> smax(x,sub(0,x))
7926   if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
7927       isOperationLegal(ISD::SMAX, VT)) {
7928     SDValue Zero = DAG.getConstant(0, dl, VT);
7929     return DAG.getNode(ISD::SMAX, dl, VT, Op,
7930                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7931   }
7932 
7933   // abs(x) -> umin(x,sub(0,x))
7934   if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
7935       isOperationLegal(ISD::UMIN, VT)) {
7936     SDValue Zero = DAG.getConstant(0, dl, VT);
7937     Op = DAG.getFreeze(Op);
7938     return DAG.getNode(ISD::UMIN, dl, VT, Op,
7939                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7940   }
7941 
7942   // 0 - abs(x) -> smin(x, sub(0,x))
7943   if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
7944       isOperationLegal(ISD::SMIN, VT)) {
7945     Op = DAG.getFreeze(Op);
7946     SDValue Zero = DAG.getConstant(0, dl, VT);
7947     return DAG.getNode(ISD::SMIN, dl, VT, Op,
7948                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
7949   }
7950 
7951   // Only expand vector types if we have the appropriate vector operations.
7952   if (VT.isVector() &&
7953       (!isOperationLegalOrCustom(ISD::SRA, VT) ||
7954        (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
7955        (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
7956        !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
7957     return SDValue();
7958 
7959   Op = DAG.getFreeze(Op);
7960   SDValue Shift =
7961       DAG.getNode(ISD::SRA, dl, VT, Op,
7962                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT));
7963   SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
7964 
7965   // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
7966   if (!IsNegative)
7967     return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift);
7968 
7969   // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
7970   return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
7971 }
7972 
7973 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const {
7974   SDLoc dl(N);
7975   EVT VT = N->getValueType(0);
7976   SDValue Op = N->getOperand(0);
7977 
7978   if (!VT.isSimple())
7979     return SDValue();
7980 
7981   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
7982   SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
7983   switch (VT.getSimpleVT().getScalarType().SimpleTy) {
7984   default:
7985     return SDValue();
7986   case MVT::i16:
7987     // Use a rotate by 8. This can be further expanded if necessary.
7988     return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7989   case MVT::i32:
7990     Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7991     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7992     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
7993     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
7994     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
7995                        DAG.getConstant(0xFF0000, dl, VT));
7996     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
7997     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
7998     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
7999     return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
8000   case MVT::i64:
8001     Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
8002     Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
8003     Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
8004     Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
8005     Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
8006     Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
8007     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
8008     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
8009     Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7,
8010                        DAG.getConstant(255ULL<<48, dl, VT));
8011     Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6,
8012                        DAG.getConstant(255ULL<<40, dl, VT));
8013     Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5,
8014                        DAG.getConstant(255ULL<<32, dl, VT));
8015     Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
8016                        DAG.getConstant(255ULL<<24, dl, VT));
8017     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
8018                        DAG.getConstant(255ULL<<16, dl, VT));
8019     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
8020                        DAG.getConstant(255ULL<<8 , dl, VT));
8021     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
8022     Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
8023     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
8024     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
8025     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
8026     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
8027     return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
8028   }
8029 }
8030 
8031 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const {
8032   SDLoc dl(N);
8033   EVT VT = N->getValueType(0);
8034   SDValue Op = N->getOperand(0);
8035   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
8036   unsigned Sz = VT.getScalarSizeInBits();
8037 
8038   SDValue Tmp, Tmp2, Tmp3;
8039 
8040   // If we can, perform BSWAP first and then the mask+swap the i4, then i2
8041   // and finally the i1 pairs.
8042   // TODO: We can easily support i4/i2 legal types if any target ever does.
8043   if (Sz >= 8 && isPowerOf2_32(Sz)) {
8044     // Create the masks - repeating the pattern every byte.
8045     APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
8046     APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
8047     APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
8048 
8049     // BSWAP if the type is wider than a single byte.
8050     Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
8051 
8052     // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
8053     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
8054     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
8055     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
8056     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
8057     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8058 
8059     // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
8060     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
8061     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
8062     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
8063     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
8064     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8065 
8066     // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
8067     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
8068     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
8069     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
8070     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
8071     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
8072     return Tmp;
8073   }
8074 
8075   Tmp = DAG.getConstant(0, dl, VT);
8076   for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
8077     if (I < J)
8078       Tmp2 =
8079           DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
8080     else
8081       Tmp2 =
8082           DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
8083 
8084     APInt Shift(Sz, 1);
8085     Shift <<= J;
8086     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
8087     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
8088   }
8089 
8090   return Tmp;
8091 }
8092 
8093 std::pair<SDValue, SDValue>
8094 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
8095                                     SelectionDAG &DAG) const {
8096   SDLoc SL(LD);
8097   SDValue Chain = LD->getChain();
8098   SDValue BasePTR = LD->getBasePtr();
8099   EVT SrcVT = LD->getMemoryVT();
8100   EVT DstVT = LD->getValueType(0);
8101   ISD::LoadExtType ExtType = LD->getExtensionType();
8102 
8103   if (SrcVT.isScalableVector())
8104     report_fatal_error("Cannot scalarize scalable vector loads");
8105 
8106   unsigned NumElem = SrcVT.getVectorNumElements();
8107 
8108   EVT SrcEltVT = SrcVT.getScalarType();
8109   EVT DstEltVT = DstVT.getScalarType();
8110 
8111   // A vector must always be stored in memory as-is, i.e. without any padding
8112   // between the elements, since various code depend on it, e.g. in the
8113   // handling of a bitcast of a vector type to int, which may be done with a
8114   // vector store followed by an integer load. A vector that does not have
8115   // elements that are byte-sized must therefore be stored as an integer
8116   // built out of the extracted vector elements.
8117   if (!SrcEltVT.isByteSized()) {
8118     unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
8119     EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
8120 
8121     unsigned NumSrcBits = SrcVT.getSizeInBits();
8122     EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
8123 
8124     unsigned SrcEltBits = SrcEltVT.getSizeInBits();
8125     SDValue SrcEltBitMask = DAG.getConstant(
8126         APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
8127 
8128     // Load the whole vector and avoid masking off the top bits as it makes
8129     // the codegen worse.
8130     SDValue Load =
8131         DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR,
8132                        LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(),
8133                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
8134 
8135     SmallVector<SDValue, 8> Vals;
8136     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
8137       unsigned ShiftIntoIdx =
8138           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
8139       SDValue ShiftAmount =
8140           DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(),
8141                                      LoadVT, SL, /*LegalTypes=*/false);
8142       SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
8143       SDValue Elt =
8144           DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
8145       SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
8146 
8147       if (ExtType != ISD::NON_EXTLOAD) {
8148         unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
8149         Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
8150       }
8151 
8152       Vals.push_back(Scalar);
8153     }
8154 
8155     SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
8156     return std::make_pair(Value, Load.getValue(1));
8157   }
8158 
8159   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
8160   assert(SrcEltVT.isByteSized());
8161 
8162   SmallVector<SDValue, 8> Vals;
8163   SmallVector<SDValue, 8> LoadChains;
8164 
8165   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
8166     SDValue ScalarLoad =
8167         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
8168                        LD->getPointerInfo().getWithOffset(Idx * Stride),
8169                        SrcEltVT, LD->getOriginalAlign(),
8170                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
8171 
8172     BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::Fixed(Stride));
8173 
8174     Vals.push_back(ScalarLoad.getValue(0));
8175     LoadChains.push_back(ScalarLoad.getValue(1));
8176   }
8177 
8178   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
8179   SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
8180 
8181   return std::make_pair(Value, NewChain);
8182 }
8183 
8184 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
8185                                              SelectionDAG &DAG) const {
8186   SDLoc SL(ST);
8187 
8188   SDValue Chain = ST->getChain();
8189   SDValue BasePtr = ST->getBasePtr();
8190   SDValue Value = ST->getValue();
8191   EVT StVT = ST->getMemoryVT();
8192 
8193   if (StVT.isScalableVector())
8194     report_fatal_error("Cannot scalarize scalable vector stores");
8195 
8196   // The type of the data we want to save
8197   EVT RegVT = Value.getValueType();
8198   EVT RegSclVT = RegVT.getScalarType();
8199 
8200   // The type of data as saved in memory.
8201   EVT MemSclVT = StVT.getScalarType();
8202 
8203   unsigned NumElem = StVT.getVectorNumElements();
8204 
8205   // A vector must always be stored in memory as-is, i.e. without any padding
8206   // between the elements, since various code depend on it, e.g. in the
8207   // handling of a bitcast of a vector type to int, which may be done with a
8208   // vector store followed by an integer load. A vector that does not have
8209   // elements that are byte-sized must therefore be stored as an integer
8210   // built out of the extracted vector elements.
8211   if (!MemSclVT.isByteSized()) {
8212     unsigned NumBits = StVT.getSizeInBits();
8213     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
8214 
8215     SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
8216 
8217     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
8218       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
8219                                 DAG.getVectorIdxConstant(Idx, SL));
8220       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
8221       SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
8222       unsigned ShiftIntoIdx =
8223           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
8224       SDValue ShiftAmount =
8225           DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
8226       SDValue ShiftedElt =
8227           DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
8228       CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
8229     }
8230 
8231     return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
8232                         ST->getOriginalAlign(), ST->getMemOperand()->getFlags(),
8233                         ST->getAAInfo());
8234   }
8235 
8236   // Store Stride in bytes
8237   unsigned Stride = MemSclVT.getSizeInBits() / 8;
8238   assert(Stride && "Zero stride!");
8239   // Extract each of the elements from the original vector and save them into
8240   // memory individually.
8241   SmallVector<SDValue, 8> Stores;
8242   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
8243     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
8244                               DAG.getVectorIdxConstant(Idx, SL));
8245 
8246     SDValue Ptr =
8247         DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Idx * Stride));
8248 
8249     // This scalar TruncStore may be illegal, but we legalize it later.
8250     SDValue Store = DAG.getTruncStore(
8251         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
8252         MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(),
8253         ST->getAAInfo());
8254 
8255     Stores.push_back(Store);
8256   }
8257 
8258   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
8259 }
8260 
8261 std::pair<SDValue, SDValue>
8262 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
8263   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
8264          "unaligned indexed loads not implemented!");
8265   SDValue Chain = LD->getChain();
8266   SDValue Ptr = LD->getBasePtr();
8267   EVT VT = LD->getValueType(0);
8268   EVT LoadedVT = LD->getMemoryVT();
8269   SDLoc dl(LD);
8270   auto &MF = DAG.getMachineFunction();
8271 
8272   if (VT.isFloatingPoint() || VT.isVector()) {
8273     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
8274     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
8275       if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
8276           LoadedVT.isVector()) {
8277         // Scalarize the load and let the individual components be handled.
8278         return scalarizeVectorLoad(LD, DAG);
8279       }
8280 
8281       // Expand to a (misaligned) integer load of the same size,
8282       // then bitconvert to floating point or vector.
8283       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
8284                                     LD->getMemOperand());
8285       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
8286       if (LoadedVT != VT)
8287         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
8288                              ISD::ANY_EXTEND, dl, VT, Result);
8289 
8290       return std::make_pair(Result, newLoad.getValue(1));
8291     }
8292 
8293     // Copy the value to a (aligned) stack slot using (unaligned) integer
8294     // loads and stores, then do a (aligned) load from the stack slot.
8295     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
8296     unsigned LoadedBytes = LoadedVT.getStoreSize();
8297     unsigned RegBytes = RegVT.getSizeInBits() / 8;
8298     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
8299 
8300     // Make sure the stack slot is also aligned for the register type.
8301     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
8302     auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
8303     SmallVector<SDValue, 8> Stores;
8304     SDValue StackPtr = StackBase;
8305     unsigned Offset = 0;
8306 
8307     EVT PtrVT = Ptr.getValueType();
8308     EVT StackPtrVT = StackPtr.getValueType();
8309 
8310     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
8311     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
8312 
8313     // Do all but one copies using the full register width.
8314     for (unsigned i = 1; i < NumRegs; i++) {
8315       // Load one integer register's worth from the original location.
8316       SDValue Load = DAG.getLoad(
8317           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
8318           LD->getOriginalAlign(), LD->getMemOperand()->getFlags(),
8319           LD->getAAInfo());
8320       // Follow the load with a store to the stack slot.  Remember the store.
8321       Stores.push_back(DAG.getStore(
8322           Load.getValue(1), dl, Load, StackPtr,
8323           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
8324       // Increment the pointers.
8325       Offset += RegBytes;
8326 
8327       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
8328       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
8329     }
8330 
8331     // The last copy may be partial.  Do an extending load.
8332     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
8333                                   8 * (LoadedBytes - Offset));
8334     SDValue Load =
8335         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
8336                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
8337                        LD->getOriginalAlign(), LD->getMemOperand()->getFlags(),
8338                        LD->getAAInfo());
8339     // Follow the load with a store to the stack slot.  Remember the store.
8340     // On big-endian machines this requires a truncating store to ensure
8341     // that the bits end up in the right place.
8342     Stores.push_back(DAG.getTruncStore(
8343         Load.getValue(1), dl, Load, StackPtr,
8344         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
8345 
8346     // The order of the stores doesn't matter - say it with a TokenFactor.
8347     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8348 
8349     // Finally, perform the original load only redirected to the stack slot.
8350     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
8351                           MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
8352                           LoadedVT);
8353 
8354     // Callers expect a MERGE_VALUES node.
8355     return std::make_pair(Load, TF);
8356   }
8357 
8358   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
8359          "Unaligned load of unsupported type.");
8360 
8361   // Compute the new VT that is half the size of the old one.  This is an
8362   // integer MVT.
8363   unsigned NumBits = LoadedVT.getSizeInBits();
8364   EVT NewLoadedVT;
8365   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
8366   NumBits >>= 1;
8367 
8368   Align Alignment = LD->getOriginalAlign();
8369   unsigned IncrementSize = NumBits / 8;
8370   ISD::LoadExtType HiExtType = LD->getExtensionType();
8371 
8372   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
8373   if (HiExtType == ISD::NON_EXTLOAD)
8374     HiExtType = ISD::ZEXTLOAD;
8375 
8376   // Load the value in two parts
8377   SDValue Lo, Hi;
8378   if (DAG.getDataLayout().isLittleEndian()) {
8379     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
8380                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
8381                         LD->getAAInfo());
8382 
8383     Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
8384     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
8385                         LD->getPointerInfo().getWithOffset(IncrementSize),
8386                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
8387                         LD->getAAInfo());
8388   } else {
8389     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
8390                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
8391                         LD->getAAInfo());
8392 
8393     Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
8394     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
8395                         LD->getPointerInfo().getWithOffset(IncrementSize),
8396                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
8397                         LD->getAAInfo());
8398   }
8399 
8400   // aggregate the two parts
8401   SDValue ShiftAmount =
8402       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
8403                                                     DAG.getDataLayout()));
8404   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
8405   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
8406 
8407   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
8408                              Hi.getValue(1));
8409 
8410   return std::make_pair(Result, TF);
8411 }
8412 
8413 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
8414                                              SelectionDAG &DAG) const {
8415   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
8416          "unaligned indexed stores not implemented!");
8417   SDValue Chain = ST->getChain();
8418   SDValue Ptr = ST->getBasePtr();
8419   SDValue Val = ST->getValue();
8420   EVT VT = Val.getValueType();
8421   Align Alignment = ST->getOriginalAlign();
8422   auto &MF = DAG.getMachineFunction();
8423   EVT StoreMemVT = ST->getMemoryVT();
8424 
8425   SDLoc dl(ST);
8426   if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
8427     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8428     if (isTypeLegal(intVT)) {
8429       if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
8430           StoreMemVT.isVector()) {
8431         // Scalarize the store and let the individual components be handled.
8432         SDValue Result = scalarizeVectorStore(ST, DAG);
8433         return Result;
8434       }
8435       // Expand to a bitconvert of the value to the integer type of the
8436       // same size, then a (misaligned) int store.
8437       // FIXME: Does not handle truncating floating point stores!
8438       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
8439       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
8440                             Alignment, ST->getMemOperand()->getFlags());
8441       return Result;
8442     }
8443     // Do a (aligned) store to a stack slot, then copy from the stack slot
8444     // to the final destination using (unaligned) integer loads and stores.
8445     MVT RegVT = getRegisterType(
8446         *DAG.getContext(),
8447         EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
8448     EVT PtrVT = Ptr.getValueType();
8449     unsigned StoredBytes = StoreMemVT.getStoreSize();
8450     unsigned RegBytes = RegVT.getSizeInBits() / 8;
8451     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
8452 
8453     // Make sure the stack slot is also aligned for the register type.
8454     SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
8455     auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
8456 
8457     // Perform the original store, only redirected to the stack slot.
8458     SDValue Store = DAG.getTruncStore(
8459         Chain, dl, Val, StackPtr,
8460         MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
8461 
8462     EVT StackPtrVT = StackPtr.getValueType();
8463 
8464     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
8465     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
8466     SmallVector<SDValue, 8> Stores;
8467     unsigned Offset = 0;
8468 
8469     // Do all but one copies using the full register width.
8470     for (unsigned i = 1; i < NumRegs; i++) {
8471       // Load one integer register's worth from the stack slot.
8472       SDValue Load = DAG.getLoad(
8473           RegVT, dl, Store, StackPtr,
8474           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
8475       // Store it to the final location.  Remember the store.
8476       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
8477                                     ST->getPointerInfo().getWithOffset(Offset),
8478                                     ST->getOriginalAlign(),
8479                                     ST->getMemOperand()->getFlags()));
8480       // Increment the pointers.
8481       Offset += RegBytes;
8482       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
8483       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
8484     }
8485 
8486     // The last store may be partial.  Do a truncating store.  On big-endian
8487     // machines this requires an extending load from the stack slot to ensure
8488     // that the bits are in the right place.
8489     EVT LoadMemVT =
8490         EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
8491 
8492     // Load from the stack slot.
8493     SDValue Load = DAG.getExtLoad(
8494         ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
8495         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
8496 
8497     Stores.push_back(
8498         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
8499                           ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
8500                           ST->getOriginalAlign(),
8501                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
8502     // The order of the stores doesn't matter - say it with a TokenFactor.
8503     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
8504     return Result;
8505   }
8506 
8507   assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
8508          "Unaligned store of unknown type.");
8509   // Get the half-size VT
8510   EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
8511   unsigned NumBits = NewStoredVT.getFixedSizeInBits();
8512   unsigned IncrementSize = NumBits / 8;
8513 
8514   // Divide the stored value in two parts.
8515   SDValue ShiftAmount = DAG.getConstant(
8516       NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout()));
8517   SDValue Lo = Val;
8518   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
8519 
8520   // Store the two parts
8521   SDValue Store1, Store2;
8522   Store1 = DAG.getTruncStore(Chain, dl,
8523                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
8524                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
8525                              ST->getMemOperand()->getFlags());
8526 
8527   Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::Fixed(IncrementSize));
8528   Store2 = DAG.getTruncStore(
8529       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
8530       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
8531       ST->getMemOperand()->getFlags(), ST->getAAInfo());
8532 
8533   SDValue Result =
8534       DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
8535   return Result;
8536 }
8537 
8538 SDValue
8539 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
8540                                        const SDLoc &DL, EVT DataVT,
8541                                        SelectionDAG &DAG,
8542                                        bool IsCompressedMemory) const {
8543   SDValue Increment;
8544   EVT AddrVT = Addr.getValueType();
8545   EVT MaskVT = Mask.getValueType();
8546   assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
8547          "Incompatible types of Data and Mask");
8548   if (IsCompressedMemory) {
8549     if (DataVT.isScalableVector())
8550       report_fatal_error(
8551           "Cannot currently handle compressed memory with scalable vectors");
8552     // Incrementing the pointer according to number of '1's in the mask.
8553     EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
8554     SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
8555     if (MaskIntVT.getSizeInBits() < 32) {
8556       MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
8557       MaskIntVT = MVT::i32;
8558     }
8559 
8560     // Count '1's with POPCNT.
8561     Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
8562     Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
8563     // Scale is an element size in bytes.
8564     SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
8565                                     AddrVT);
8566     Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
8567   } else if (DataVT.isScalableVector()) {
8568     Increment = DAG.getVScale(DL, AddrVT,
8569                               APInt(AddrVT.getFixedSizeInBits(),
8570                                     DataVT.getStoreSize().getKnownMinSize()));
8571   } else
8572     Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT);
8573 
8574   return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
8575 }
8576 
8577 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx,
8578                                        EVT VecVT, const SDLoc &dl,
8579                                        ElementCount SubEC) {
8580   assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
8581          "Cannot index a scalable vector within a fixed-width vector");
8582 
8583   unsigned NElts = VecVT.getVectorMinNumElements();
8584   unsigned NumSubElts = SubEC.getKnownMinValue();
8585   EVT IdxVT = Idx.getValueType();
8586 
8587   if (VecVT.isScalableVector() && !SubEC.isScalable()) {
8588     // If this is a constant index and we know the value plus the number of the
8589     // elements in the subvector minus one is less than the minimum number of
8590     // elements then it's safe to return Idx.
8591     if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx))
8592       if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts)
8593         return Idx;
8594     SDValue VS =
8595         DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts));
8596     unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT;
8597     SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS,
8598                               DAG.getConstant(NumSubElts, dl, IdxVT));
8599     return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub);
8600   }
8601   if (isPowerOf2_32(NElts) && NumSubElts == 1) {
8602     APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts));
8603     return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
8604                        DAG.getConstant(Imm, dl, IdxVT));
8605   }
8606   unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0;
8607   return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
8608                      DAG.getConstant(MaxIndex, dl, IdxVT));
8609 }
8610 
8611 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
8612                                                 SDValue VecPtr, EVT VecVT,
8613                                                 SDValue Index) const {
8614   return getVectorSubVecPointer(
8615       DAG, VecPtr, VecVT,
8616       EVT::getVectorVT(*DAG.getContext(), VecVT.getVectorElementType(), 1),
8617       Index);
8618 }
8619 
8620 SDValue TargetLowering::getVectorSubVecPointer(SelectionDAG &DAG,
8621                                                SDValue VecPtr, EVT VecVT,
8622                                                EVT SubVecVT,
8623                                                SDValue Index) const {
8624   SDLoc dl(Index);
8625   // Make sure the index type is big enough to compute in.
8626   Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
8627 
8628   EVT EltVT = VecVT.getVectorElementType();
8629 
8630   // Calculate the element offset and add it to the pointer.
8631   unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
8632   assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
8633          "Converting bits to bytes lost precision");
8634   assert(SubVecVT.getVectorElementType() == EltVT &&
8635          "Sub-vector must be a vector with matching element type");
8636   Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
8637                                   SubVecVT.getVectorElementCount());
8638 
8639   EVT IdxVT = Index.getValueType();
8640   if (SubVecVT.isScalableVector())
8641     Index =
8642         DAG.getNode(ISD::MUL, dl, IdxVT, Index,
8643                     DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1)));
8644 
8645   Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
8646                       DAG.getConstant(EltSize, dl, IdxVT));
8647   return DAG.getMemBasePlusOffset(VecPtr, Index, dl);
8648 }
8649 
8650 //===----------------------------------------------------------------------===//
8651 // Implementation of Emulated TLS Model
8652 //===----------------------------------------------------------------------===//
8653 
8654 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
8655                                                 SelectionDAG &DAG) const {
8656   // Access to address of TLS varialbe xyz is lowered to a function call:
8657   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
8658   EVT PtrVT = getPointerTy(DAG.getDataLayout());
8659   PointerType *VoidPtrType = Type::getInt8PtrTy(*DAG.getContext());
8660   SDLoc dl(GA);
8661 
8662   ArgListTy Args;
8663   ArgListEntry Entry;
8664   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
8665   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
8666   StringRef EmuTlsVarName(NameString);
8667   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
8668   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
8669   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
8670   Entry.Ty = VoidPtrType;
8671   Args.push_back(Entry);
8672 
8673   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
8674 
8675   TargetLowering::CallLoweringInfo CLI(DAG);
8676   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
8677   CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
8678   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
8679 
8680   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8681   // At last for X86 targets, maybe good for other targets too?
8682   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
8683   MFI.setAdjustsStack(true); // Is this only for X86 target?
8684   MFI.setHasCalls(true);
8685 
8686   assert((GA->getOffset() == 0) &&
8687          "Emulated TLS must have zero offset in GlobalAddressSDNode");
8688   return CallResult.first;
8689 }
8690 
8691 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
8692                                                 SelectionDAG &DAG) const {
8693   assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
8694   if (!isCtlzFast())
8695     return SDValue();
8696   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8697   SDLoc dl(Op);
8698   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
8699     if (C->isZero() && CC == ISD::SETEQ) {
8700       EVT VT = Op.getOperand(0).getValueType();
8701       SDValue Zext = Op.getOperand(0);
8702       if (VT.bitsLT(MVT::i32)) {
8703         VT = MVT::i32;
8704         Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
8705       }
8706       unsigned Log2b = Log2_32(VT.getSizeInBits());
8707       SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
8708       SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
8709                                 DAG.getConstant(Log2b, dl, MVT::i32));
8710       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
8711     }
8712   }
8713   return SDValue();
8714 }
8715 
8716 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const {
8717   SDValue Op0 = Node->getOperand(0);
8718   SDValue Op1 = Node->getOperand(1);
8719   EVT VT = Op0.getValueType();
8720   unsigned Opcode = Node->getOpcode();
8721   SDLoc DL(Node);
8722 
8723   // umin(x,y) -> sub(x,usubsat(x,y))
8724   if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
8725       isOperationLegal(ISD::USUBSAT, VT)) {
8726     return DAG.getNode(ISD::SUB, DL, VT, Op0,
8727                        DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
8728   }
8729 
8730   // umax(x,y) -> add(x,usubsat(y,x))
8731   if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
8732       isOperationLegal(ISD::USUBSAT, VT)) {
8733     return DAG.getNode(ISD::ADD, DL, VT, Op0,
8734                        DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
8735   }
8736 
8737   // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
8738   ISD::CondCode CC;
8739   switch (Opcode) {
8740   default: llvm_unreachable("How did we get here?");
8741   case ISD::SMAX: CC = ISD::SETGT; break;
8742   case ISD::SMIN: CC = ISD::SETLT; break;
8743   case ISD::UMAX: CC = ISD::SETUGT; break;
8744   case ISD::UMIN: CC = ISD::SETULT; break;
8745   }
8746 
8747   // FIXME: Should really try to split the vector in case it's legal on a
8748   // subvector.
8749   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
8750     return DAG.UnrollVectorOp(Node);
8751 
8752   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8753   SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
8754   return DAG.getSelect(DL, VT, Cond, Op0, Op1);
8755 }
8756 
8757 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const {
8758   unsigned Opcode = Node->getOpcode();
8759   SDValue LHS = Node->getOperand(0);
8760   SDValue RHS = Node->getOperand(1);
8761   EVT VT = LHS.getValueType();
8762   SDLoc dl(Node);
8763 
8764   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
8765   assert(VT.isInteger() && "Expected operands to be integers");
8766 
8767   // usub.sat(a, b) -> umax(a, b) - b
8768   if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
8769     SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
8770     return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
8771   }
8772 
8773   // uadd.sat(a, b) -> umin(a, ~b) + b
8774   if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
8775     SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
8776     SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
8777     return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
8778   }
8779 
8780   unsigned OverflowOp;
8781   switch (Opcode) {
8782   case ISD::SADDSAT:
8783     OverflowOp = ISD::SADDO;
8784     break;
8785   case ISD::UADDSAT:
8786     OverflowOp = ISD::UADDO;
8787     break;
8788   case ISD::SSUBSAT:
8789     OverflowOp = ISD::SSUBO;
8790     break;
8791   case ISD::USUBSAT:
8792     OverflowOp = ISD::USUBO;
8793     break;
8794   default:
8795     llvm_unreachable("Expected method to receive signed or unsigned saturation "
8796                      "addition or subtraction node.");
8797   }
8798 
8799   // FIXME: Should really try to split the vector in case it's legal on a
8800   // subvector.
8801   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
8802     return DAG.UnrollVectorOp(Node);
8803 
8804   unsigned BitWidth = LHS.getScalarValueSizeInBits();
8805   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8806   SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8807   SDValue SumDiff = Result.getValue(0);
8808   SDValue Overflow = Result.getValue(1);
8809   SDValue Zero = DAG.getConstant(0, dl, VT);
8810   SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
8811 
8812   if (Opcode == ISD::UADDSAT) {
8813     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
8814       // (LHS + RHS) | OverflowMask
8815       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
8816       return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
8817     }
8818     // Overflow ? 0xffff.... : (LHS + RHS)
8819     return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
8820   }
8821 
8822   if (Opcode == ISD::USUBSAT) {
8823     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
8824       // (LHS - RHS) & ~OverflowMask
8825       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
8826       SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
8827       return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
8828     }
8829     // Overflow ? 0 : (LHS - RHS)
8830     return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
8831   }
8832 
8833   // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
8834   APInt MinVal = APInt::getSignedMinValue(BitWidth);
8835   SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
8836   SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
8837                               DAG.getConstant(BitWidth - 1, dl, VT));
8838   Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
8839   return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
8840 }
8841 
8842 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const {
8843   unsigned Opcode = Node->getOpcode();
8844   bool IsSigned = Opcode == ISD::SSHLSAT;
8845   SDValue LHS = Node->getOperand(0);
8846   SDValue RHS = Node->getOperand(1);
8847   EVT VT = LHS.getValueType();
8848   SDLoc dl(Node);
8849 
8850   assert((Node->getOpcode() == ISD::SSHLSAT ||
8851           Node->getOpcode() == ISD::USHLSAT) &&
8852           "Expected a SHLSAT opcode");
8853   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
8854   assert(VT.isInteger() && "Expected operands to be integers");
8855 
8856   // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
8857 
8858   unsigned BW = VT.getScalarSizeInBits();
8859   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
8860   SDValue Orig =
8861       DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
8862 
8863   SDValue SatVal;
8864   if (IsSigned) {
8865     SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
8866     SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
8867     SatVal = DAG.getSelectCC(dl, LHS, DAG.getConstant(0, dl, VT),
8868                              SatMin, SatMax, ISD::SETLT);
8869   } else {
8870     SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
8871   }
8872   Result = DAG.getSelectCC(dl, LHS, Orig, SatVal, Result, ISD::SETNE);
8873 
8874   return Result;
8875 }
8876 
8877 SDValue
8878 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const {
8879   assert((Node->getOpcode() == ISD::SMULFIX ||
8880           Node->getOpcode() == ISD::UMULFIX ||
8881           Node->getOpcode() == ISD::SMULFIXSAT ||
8882           Node->getOpcode() == ISD::UMULFIXSAT) &&
8883          "Expected a fixed point multiplication opcode");
8884 
8885   SDLoc dl(Node);
8886   SDValue LHS = Node->getOperand(0);
8887   SDValue RHS = Node->getOperand(1);
8888   EVT VT = LHS.getValueType();
8889   unsigned Scale = Node->getConstantOperandVal(2);
8890   bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
8891                      Node->getOpcode() == ISD::UMULFIXSAT);
8892   bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
8893                  Node->getOpcode() == ISD::SMULFIXSAT);
8894   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8895   unsigned VTSize = VT.getScalarSizeInBits();
8896 
8897   if (!Scale) {
8898     // [us]mul.fix(a, b, 0) -> mul(a, b)
8899     if (!Saturating) {
8900       if (isOperationLegalOrCustom(ISD::MUL, VT))
8901         return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
8902     } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
8903       SDValue Result =
8904           DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8905       SDValue Product = Result.getValue(0);
8906       SDValue Overflow = Result.getValue(1);
8907       SDValue Zero = DAG.getConstant(0, dl, VT);
8908 
8909       APInt MinVal = APInt::getSignedMinValue(VTSize);
8910       APInt MaxVal = APInt::getSignedMaxValue(VTSize);
8911       SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
8912       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
8913       // Xor the inputs, if resulting sign bit is 0 the product will be
8914       // positive, else negative.
8915       SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
8916       SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
8917       Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
8918       return DAG.getSelect(dl, VT, Overflow, Result, Product);
8919     } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
8920       SDValue Result =
8921           DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
8922       SDValue Product = Result.getValue(0);
8923       SDValue Overflow = Result.getValue(1);
8924 
8925       APInt MaxVal = APInt::getMaxValue(VTSize);
8926       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
8927       return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
8928     }
8929   }
8930 
8931   assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
8932          "Expected scale to be less than the number of bits if signed or at "
8933          "most the number of bits if unsigned.");
8934   assert(LHS.getValueType() == RHS.getValueType() &&
8935          "Expected both operands to be the same type");
8936 
8937   // Get the upper and lower bits of the result.
8938   SDValue Lo, Hi;
8939   unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
8940   unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
8941   if (isOperationLegalOrCustom(LoHiOp, VT)) {
8942     SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
8943     Lo = Result.getValue(0);
8944     Hi = Result.getValue(1);
8945   } else if (isOperationLegalOrCustom(HiOp, VT)) {
8946     Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
8947     Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
8948   } else if (VT.isVector()) {
8949     return SDValue();
8950   } else {
8951     report_fatal_error("Unable to expand fixed point multiplication.");
8952   }
8953 
8954   if (Scale == VTSize)
8955     // Result is just the top half since we'd be shifting by the width of the
8956     // operand. Overflow impossible so this works for both UMULFIX and
8957     // UMULFIXSAT.
8958     return Hi;
8959 
8960   // The result will need to be shifted right by the scale since both operands
8961   // are scaled. The result is given to us in 2 halves, so we only want part of
8962   // both in the result.
8963   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
8964   SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
8965                                DAG.getConstant(Scale, dl, ShiftTy));
8966   if (!Saturating)
8967     return Result;
8968 
8969   if (!Signed) {
8970     // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
8971     // widened multiplication) aren't all zeroes.
8972 
8973     // Saturate to max if ((Hi >> Scale) != 0),
8974     // which is the same as if (Hi > ((1 << Scale) - 1))
8975     APInt MaxVal = APInt::getMaxValue(VTSize);
8976     SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale),
8977                                       dl, VT);
8978     Result = DAG.getSelectCC(dl, Hi, LowMask,
8979                              DAG.getConstant(MaxVal, dl, VT), Result,
8980                              ISD::SETUGT);
8981 
8982     return Result;
8983   }
8984 
8985   // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
8986   // widened multiplication) aren't all ones or all zeroes.
8987 
8988   SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
8989   SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
8990 
8991   if (Scale == 0) {
8992     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
8993                                DAG.getConstant(VTSize - 1, dl, ShiftTy));
8994     SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
8995     // Saturated to SatMin if wide product is negative, and SatMax if wide
8996     // product is positive ...
8997     SDValue Zero = DAG.getConstant(0, dl, VT);
8998     SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax,
8999                                                ISD::SETLT);
9000     // ... but only if we overflowed.
9001     return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
9002   }
9003 
9004   //  We handled Scale==0 above so all the bits to examine is in Hi.
9005 
9006   // Saturate to max if ((Hi >> (Scale - 1)) > 0),
9007   // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
9008   SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1),
9009                                     dl, VT);
9010   Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT);
9011   // Saturate to min if (Hi >> (Scale - 1)) < -1),
9012   // which is the same as if (HI < (-1 << (Scale - 1))
9013   SDValue HighMask =
9014       DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1),
9015                       dl, VT);
9016   Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT);
9017   return Result;
9018 }
9019 
9020 SDValue
9021 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl,
9022                                     SDValue LHS, SDValue RHS,
9023                                     unsigned Scale, SelectionDAG &DAG) const {
9024   assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
9025           Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
9026          "Expected a fixed point division opcode");
9027 
9028   EVT VT = LHS.getValueType();
9029   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
9030   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
9031   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
9032 
9033   // If there is enough room in the type to upscale the LHS or downscale the
9034   // RHS before the division, we can perform it in this type without having to
9035   // resize. For signed operations, the LHS headroom is the number of
9036   // redundant sign bits, and for unsigned ones it is the number of zeroes.
9037   // The headroom for the RHS is the number of trailing zeroes.
9038   unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
9039                             : DAG.computeKnownBits(LHS).countMinLeadingZeros();
9040   unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
9041 
9042   // For signed saturating operations, we need to be able to detect true integer
9043   // division overflow; that is, when you have MIN / -EPS. However, this
9044   // is undefined behavior and if we emit divisions that could take such
9045   // values it may cause undesired behavior (arithmetic exceptions on x86, for
9046   // example).
9047   // Avoid this by requiring an extra bit so that we never get this case.
9048   // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
9049   // signed saturating division, we need to emit a whopping 32-bit division.
9050   if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
9051     return SDValue();
9052 
9053   unsigned LHSShift = std::min(LHSLead, Scale);
9054   unsigned RHSShift = Scale - LHSShift;
9055 
9056   // At this point, we know that if we shift the LHS up by LHSShift and the
9057   // RHS down by RHSShift, we can emit a regular division with a final scaling
9058   // factor of Scale.
9059 
9060   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
9061   if (LHSShift)
9062     LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
9063                       DAG.getConstant(LHSShift, dl, ShiftTy));
9064   if (RHSShift)
9065     RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
9066                       DAG.getConstant(RHSShift, dl, ShiftTy));
9067 
9068   SDValue Quot;
9069   if (Signed) {
9070     // For signed operations, if the resulting quotient is negative and the
9071     // remainder is nonzero, subtract 1 from the quotient to round towards
9072     // negative infinity.
9073     SDValue Rem;
9074     // FIXME: Ideally we would always produce an SDIVREM here, but if the
9075     // type isn't legal, SDIVREM cannot be expanded. There is no reason why
9076     // we couldn't just form a libcall, but the type legalizer doesn't do it.
9077     if (isTypeLegal(VT) &&
9078         isOperationLegalOrCustom(ISD::SDIVREM, VT)) {
9079       Quot = DAG.getNode(ISD::SDIVREM, dl,
9080                          DAG.getVTList(VT, VT),
9081                          LHS, RHS);
9082       Rem = Quot.getValue(1);
9083       Quot = Quot.getValue(0);
9084     } else {
9085       Quot = DAG.getNode(ISD::SDIV, dl, VT,
9086                          LHS, RHS);
9087       Rem = DAG.getNode(ISD::SREM, dl, VT,
9088                         LHS, RHS);
9089     }
9090     SDValue Zero = DAG.getConstant(0, dl, VT);
9091     SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
9092     SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
9093     SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
9094     SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
9095     SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
9096                                DAG.getConstant(1, dl, VT));
9097     Quot = DAG.getSelect(dl, VT,
9098                          DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
9099                          Sub1, Quot);
9100   } else
9101     Quot = DAG.getNode(ISD::UDIV, dl, VT,
9102                        LHS, RHS);
9103 
9104   return Quot;
9105 }
9106 
9107 void TargetLowering::expandUADDSUBO(
9108     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
9109   SDLoc dl(Node);
9110   SDValue LHS = Node->getOperand(0);
9111   SDValue RHS = Node->getOperand(1);
9112   bool IsAdd = Node->getOpcode() == ISD::UADDO;
9113 
9114   // If ADD/SUBCARRY is legal, use that instead.
9115   unsigned OpcCarry = IsAdd ? ISD::ADDCARRY : ISD::SUBCARRY;
9116   if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
9117     SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
9118     SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
9119                                     { LHS, RHS, CarryIn });
9120     Result = SDValue(NodeCarry.getNode(), 0);
9121     Overflow = SDValue(NodeCarry.getNode(), 1);
9122     return;
9123   }
9124 
9125   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
9126                             LHS.getValueType(), LHS, RHS);
9127 
9128   EVT ResultType = Node->getValueType(1);
9129   EVT SetCCType = getSetCCResultType(
9130       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
9131   SDValue SetCC;
9132   if (IsAdd && isOneConstant(RHS)) {
9133     // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces
9134     // the live range of X. We assume comparing with 0 is cheap.
9135     // The general case (X + C) < C is not necessarily beneficial. Although we
9136     // reduce the live range of X, we may introduce the materialization of
9137     // constant C.
9138     SetCC =
9139         DAG.getSetCC(dl, SetCCType, Result,
9140                      DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ);
9141   } else {
9142     ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
9143     SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
9144   }
9145   Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
9146 }
9147 
9148 void TargetLowering::expandSADDSUBO(
9149     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
9150   SDLoc dl(Node);
9151   SDValue LHS = Node->getOperand(0);
9152   SDValue RHS = Node->getOperand(1);
9153   bool IsAdd = Node->getOpcode() == ISD::SADDO;
9154 
9155   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
9156                             LHS.getValueType(), LHS, RHS);
9157 
9158   EVT ResultType = Node->getValueType(1);
9159   EVT OType = getSetCCResultType(
9160       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
9161 
9162   // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
9163   unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
9164   if (isOperationLegal(OpcSat, LHS.getValueType())) {
9165     SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
9166     SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
9167     Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
9168     return;
9169   }
9170 
9171   SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
9172 
9173   // For an addition, the result should be less than one of the operands (LHS)
9174   // if and only if the other operand (RHS) is negative, otherwise there will
9175   // be overflow.
9176   // For a subtraction, the result should be less than one of the operands
9177   // (LHS) if and only if the other operand (RHS) is (non-zero) positive,
9178   // otherwise there will be overflow.
9179   SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
9180   SDValue ConditionRHS =
9181       DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT);
9182 
9183   Overflow = DAG.getBoolExtOrTrunc(
9184       DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl,
9185       ResultType, ResultType);
9186 }
9187 
9188 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result,
9189                                 SDValue &Overflow, SelectionDAG &DAG) const {
9190   SDLoc dl(Node);
9191   EVT VT = Node->getValueType(0);
9192   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
9193   SDValue LHS = Node->getOperand(0);
9194   SDValue RHS = Node->getOperand(1);
9195   bool isSigned = Node->getOpcode() == ISD::SMULO;
9196 
9197   // For power-of-two multiplications we can use a simpler shift expansion.
9198   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
9199     const APInt &C = RHSC->getAPIntValue();
9200     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
9201     if (C.isPowerOf2()) {
9202       // smulo(x, signed_min) is same as umulo(x, signed_min).
9203       bool UseArithShift = isSigned && !C.isMinSignedValue();
9204       EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout());
9205       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy);
9206       Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
9207       Overflow = DAG.getSetCC(dl, SetCCVT,
9208           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
9209                       dl, VT, Result, ShiftAmt),
9210           LHS, ISD::SETNE);
9211       return true;
9212     }
9213   }
9214 
9215   EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2);
9216   if (VT.isVector())
9217     WideVT =
9218         EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount());
9219 
9220   SDValue BottomHalf;
9221   SDValue TopHalf;
9222   static const unsigned Ops[2][3] =
9223       { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
9224         { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
9225   if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
9226     BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
9227     TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
9228   } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
9229     BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
9230                              RHS);
9231     TopHalf = BottomHalf.getValue(1);
9232   } else if (isTypeLegal(WideVT)) {
9233     LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
9234     RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
9235     SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
9236     BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
9237     SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl,
9238         getShiftAmountTy(WideVT, DAG.getDataLayout()));
9239     TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
9240                           DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
9241   } else {
9242     if (VT.isVector())
9243       return false;
9244 
9245     // We can fall back to a libcall with an illegal type for the MUL if we
9246     // have a libcall big enough.
9247     // Also, we can fall back to a division in some cases, but that's a big
9248     // performance hit in the general case.
9249     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
9250     if (WideVT == MVT::i16)
9251       LC = RTLIB::MUL_I16;
9252     else if (WideVT == MVT::i32)
9253       LC = RTLIB::MUL_I32;
9254     else if (WideVT == MVT::i64)
9255       LC = RTLIB::MUL_I64;
9256     else if (WideVT == MVT::i128)
9257       LC = RTLIB::MUL_I128;
9258     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
9259 
9260     SDValue HiLHS;
9261     SDValue HiRHS;
9262     if (isSigned) {
9263       // The high part is obtained by SRA'ing all but one of the bits of low
9264       // part.
9265       unsigned LoSize = VT.getFixedSizeInBits();
9266       HiLHS =
9267           DAG.getNode(ISD::SRA, dl, VT, LHS,
9268                       DAG.getConstant(LoSize - 1, dl,
9269                                       getPointerTy(DAG.getDataLayout())));
9270       HiRHS =
9271           DAG.getNode(ISD::SRA, dl, VT, RHS,
9272                       DAG.getConstant(LoSize - 1, dl,
9273                                       getPointerTy(DAG.getDataLayout())));
9274     } else {
9275         HiLHS = DAG.getConstant(0, dl, VT);
9276         HiRHS = DAG.getConstant(0, dl, VT);
9277     }
9278 
9279     // Here we're passing the 2 arguments explicitly as 4 arguments that are
9280     // pre-lowered to the correct types. This all depends upon WideVT not
9281     // being a legal type for the architecture and thus has to be split to
9282     // two arguments.
9283     SDValue Ret;
9284     TargetLowering::MakeLibCallOptions CallOptions;
9285     CallOptions.setSExt(isSigned);
9286     CallOptions.setIsPostTypeLegalization(true);
9287     if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) {
9288       // Halves of WideVT are packed into registers in different order
9289       // depending on platform endianness. This is usually handled by
9290       // the C calling convention, but we can't defer to it in
9291       // the legalizer.
9292       SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
9293       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
9294     } else {
9295       SDValue Args[] = { HiLHS, LHS, HiRHS, RHS };
9296       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
9297     }
9298     assert(Ret.getOpcode() == ISD::MERGE_VALUES &&
9299            "Ret value is a collection of constituent nodes holding result.");
9300     if (DAG.getDataLayout().isLittleEndian()) {
9301       // Same as above.
9302       BottomHalf = Ret.getOperand(0);
9303       TopHalf = Ret.getOperand(1);
9304     } else {
9305       BottomHalf = Ret.getOperand(1);
9306       TopHalf = Ret.getOperand(0);
9307     }
9308   }
9309 
9310   Result = BottomHalf;
9311   if (isSigned) {
9312     SDValue ShiftAmt = DAG.getConstant(
9313         VT.getScalarSizeInBits() - 1, dl,
9314         getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout()));
9315     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
9316     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
9317   } else {
9318     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
9319                             DAG.getConstant(0, dl, VT), ISD::SETNE);
9320   }
9321 
9322   // Truncate the result if SetCC returns a larger type than needed.
9323   EVT RType = Node->getValueType(1);
9324   if (RType.bitsLT(Overflow.getValueType()))
9325     Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
9326 
9327   assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
9328          "Unexpected result type for S/UMULO legalization");
9329   return true;
9330 }
9331 
9332 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const {
9333   SDLoc dl(Node);
9334   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
9335   SDValue Op = Node->getOperand(0);
9336   EVT VT = Op.getValueType();
9337 
9338   if (VT.isScalableVector())
9339     report_fatal_error(
9340         "Expanding reductions for scalable vectors is undefined.");
9341 
9342   // Try to use a shuffle reduction for power of two vectors.
9343   if (VT.isPow2VectorType()) {
9344     while (VT.getVectorNumElements() > 1) {
9345       EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
9346       if (!isOperationLegalOrCustom(BaseOpcode, HalfVT))
9347         break;
9348 
9349       SDValue Lo, Hi;
9350       std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
9351       Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi);
9352       VT = HalfVT;
9353     }
9354   }
9355 
9356   EVT EltVT = VT.getVectorElementType();
9357   unsigned NumElts = VT.getVectorNumElements();
9358 
9359   SmallVector<SDValue, 8> Ops;
9360   DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
9361 
9362   SDValue Res = Ops[0];
9363   for (unsigned i = 1; i < NumElts; i++)
9364     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags());
9365 
9366   // Result type may be wider than element type.
9367   if (EltVT != Node->getValueType(0))
9368     Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
9369   return Res;
9370 }
9371 
9372 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const {
9373   SDLoc dl(Node);
9374   SDValue AccOp = Node->getOperand(0);
9375   SDValue VecOp = Node->getOperand(1);
9376   SDNodeFlags Flags = Node->getFlags();
9377 
9378   EVT VT = VecOp.getValueType();
9379   EVT EltVT = VT.getVectorElementType();
9380 
9381   if (VT.isScalableVector())
9382     report_fatal_error(
9383         "Expanding reductions for scalable vectors is undefined.");
9384 
9385   unsigned NumElts = VT.getVectorNumElements();
9386 
9387   SmallVector<SDValue, 8> Ops;
9388   DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
9389 
9390   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
9391 
9392   SDValue Res = AccOp;
9393   for (unsigned i = 0; i < NumElts; i++)
9394     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
9395 
9396   return Res;
9397 }
9398 
9399 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result,
9400                                SelectionDAG &DAG) const {
9401   EVT VT = Node->getValueType(0);
9402   SDLoc dl(Node);
9403   bool isSigned = Node->getOpcode() == ISD::SREM;
9404   unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
9405   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
9406   SDValue Dividend = Node->getOperand(0);
9407   SDValue Divisor = Node->getOperand(1);
9408   if (isOperationLegalOrCustom(DivRemOpc, VT)) {
9409     SDVTList VTs = DAG.getVTList(VT, VT);
9410     Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
9411     return true;
9412   }
9413   if (isOperationLegalOrCustom(DivOpc, VT)) {
9414     // X % Y -> X-X/Y*Y
9415     SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
9416     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
9417     Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
9418     return true;
9419   }
9420   return false;
9421 }
9422 
9423 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node,
9424                                             SelectionDAG &DAG) const {
9425   bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
9426   SDLoc dl(SDValue(Node, 0));
9427   SDValue Src = Node->getOperand(0);
9428 
9429   // DstVT is the result type, while SatVT is the size to which we saturate
9430   EVT SrcVT = Src.getValueType();
9431   EVT DstVT = Node->getValueType(0);
9432 
9433   EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
9434   unsigned SatWidth = SatVT.getScalarSizeInBits();
9435   unsigned DstWidth = DstVT.getScalarSizeInBits();
9436   assert(SatWidth <= DstWidth &&
9437          "Expected saturation width smaller than result width");
9438 
9439   // Determine minimum and maximum integer values and their corresponding
9440   // floating-point values.
9441   APInt MinInt, MaxInt;
9442   if (IsSigned) {
9443     MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
9444     MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
9445   } else {
9446     MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
9447     MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
9448   }
9449 
9450   // We cannot risk emitting FP_TO_XINT nodes with a source VT of f16, as
9451   // libcall emission cannot handle this. Large result types will fail.
9452   if (SrcVT == MVT::f16) {
9453     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
9454     SrcVT = Src.getValueType();
9455   }
9456 
9457   APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT));
9458   APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT));
9459 
9460   APFloat::opStatus MinStatus =
9461       MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
9462   APFloat::opStatus MaxStatus =
9463       MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
9464   bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
9465                              !(MaxStatus & APFloat::opStatus::opInexact);
9466 
9467   SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
9468   SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
9469 
9470   // If the integer bounds are exactly representable as floats and min/max are
9471   // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
9472   // of comparisons and selects.
9473   bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) &&
9474                      isOperationLegal(ISD::FMAXNUM, SrcVT);
9475   if (AreExactFloatBounds && MinMaxLegal) {
9476     SDValue Clamped = Src;
9477 
9478     // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat.
9479     Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode);
9480     // Clamp by MaxFloat from above. NaN cannot occur.
9481     Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode);
9482     // Convert clamped value to integer.
9483     SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
9484                                   dl, DstVT, Clamped);
9485 
9486     // In the unsigned case we're done, because we mapped NaN to MinFloat,
9487     // which will cast to zero.
9488     if (!IsSigned)
9489       return FpToInt;
9490 
9491     // Otherwise, select 0 if Src is NaN.
9492     SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
9493     return DAG.getSelectCC(dl, Src, Src, ZeroInt, FpToInt,
9494                            ISD::CondCode::SETUO);
9495   }
9496 
9497   SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
9498   SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
9499 
9500   // Result of direct conversion. The assumption here is that the operation is
9501   // non-trapping and it's fine to apply it to an out-of-range value if we
9502   // select it away later.
9503   SDValue FpToInt =
9504       DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
9505 
9506   SDValue Select = FpToInt;
9507 
9508   // If Src ULT MinFloat, select MinInt. In particular, this also selects
9509   // MinInt if Src is NaN.
9510   Select = DAG.getSelectCC(dl, Src, MinFloatNode, MinIntNode, Select,
9511                            ISD::CondCode::SETULT);
9512   // If Src OGT MaxFloat, select MaxInt.
9513   Select = DAG.getSelectCC(dl, Src, MaxFloatNode, MaxIntNode, Select,
9514                            ISD::CondCode::SETOGT);
9515 
9516   // In the unsigned case we are done, because we mapped NaN to MinInt, which
9517   // is already zero.
9518   if (!IsSigned)
9519     return Select;
9520 
9521   // Otherwise, select 0 if Src is NaN.
9522   SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
9523   return DAG.getSelectCC(dl, Src, Src, ZeroInt, Select, ISD::CondCode::SETUO);
9524 }
9525 
9526 SDValue TargetLowering::expandVectorSplice(SDNode *Node,
9527                                            SelectionDAG &DAG) const {
9528   assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!");
9529   assert(Node->getValueType(0).isScalableVector() &&
9530          "Fixed length vector types expected to use SHUFFLE_VECTOR!");
9531 
9532   EVT VT = Node->getValueType(0);
9533   SDValue V1 = Node->getOperand(0);
9534   SDValue V2 = Node->getOperand(1);
9535   int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue();
9536   SDLoc DL(Node);
9537 
9538   // Expand through memory thusly:
9539   //  Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
9540   //  Store V1, Ptr
9541   //  Store V2, Ptr + sizeof(V1)
9542   //  If (Imm < 0)
9543   //    TrailingElts = -Imm
9544   //    Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt))
9545   //  else
9546   //    Ptr = Ptr + (Imm * sizeof(VT.Elt))
9547   //  Res = Load Ptr
9548 
9549   Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
9550 
9551   EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
9552                                VT.getVectorElementCount() * 2);
9553   SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
9554   EVT PtrVT = StackPtr.getValueType();
9555   auto &MF = DAG.getMachineFunction();
9556   auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
9557   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
9558 
9559   // Store the lo part of CONCAT_VECTORS(V1, V2)
9560   SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo);
9561   // Store the hi part of CONCAT_VECTORS(V1, V2)
9562   SDValue OffsetToV2 = DAG.getVScale(
9563       DL, PtrVT,
9564       APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize()));
9565   SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2);
9566   SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo);
9567 
9568   if (Imm >= 0) {
9569     // Load back the required element. getVectorElementPointer takes care of
9570     // clamping the index if it's out-of-bounds.
9571     StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2));
9572     // Load the spliced result
9573     return DAG.getLoad(VT, DL, StoreV2, StackPtr,
9574                        MachinePointerInfo::getUnknownStack(MF));
9575   }
9576 
9577   uint64_t TrailingElts = -Imm;
9578 
9579   // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2.
9580   TypeSize EltByteSize = VT.getVectorElementType().getStoreSize();
9581   SDValue TrailingBytes =
9582       DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT);
9583 
9584   if (TrailingElts > VT.getVectorMinNumElements()) {
9585     SDValue VLBytes = DAG.getVScale(
9586         DL, PtrVT,
9587         APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinSize()));
9588     TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes);
9589   }
9590 
9591   // Calculate the start address of the spliced result.
9592   StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
9593 
9594   // Load the spliced result
9595   return DAG.getLoad(VT, DL, StoreV2, StackPtr2,
9596                      MachinePointerInfo::getUnknownStack(MF));
9597 }
9598 
9599 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT,
9600                                            SDValue &LHS, SDValue &RHS,
9601                                            SDValue &CC, SDValue Mask,
9602                                            SDValue EVL, bool &NeedInvert,
9603                                            const SDLoc &dl, SDValue &Chain,
9604                                            bool IsSignaling) const {
9605   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9606   MVT OpVT = LHS.getSimpleValueType();
9607   ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
9608   NeedInvert = false;
9609   assert(!EVL == !Mask && "VP Mask and EVL must either both be set or unset");
9610   bool IsNonVP = !EVL;
9611   switch (TLI.getCondCodeAction(CCCode, OpVT)) {
9612   default:
9613     llvm_unreachable("Unknown condition code action!");
9614   case TargetLowering::Legal:
9615     // Nothing to do.
9616     break;
9617   case TargetLowering::Expand: {
9618     ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode);
9619     if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
9620       std::swap(LHS, RHS);
9621       CC = DAG.getCondCode(InvCC);
9622       return true;
9623     }
9624     // Swapping operands didn't work. Try inverting the condition.
9625     bool NeedSwap = false;
9626     InvCC = getSetCCInverse(CCCode, OpVT);
9627     if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
9628       // If inverting the condition is not enough, try swapping operands
9629       // on top of it.
9630       InvCC = ISD::getSetCCSwappedOperands(InvCC);
9631       NeedSwap = true;
9632     }
9633     if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
9634       CC = DAG.getCondCode(InvCC);
9635       NeedInvert = true;
9636       if (NeedSwap)
9637         std::swap(LHS, RHS);
9638       return true;
9639     }
9640 
9641     ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
9642     unsigned Opc = 0;
9643     switch (CCCode) {
9644     default:
9645       llvm_unreachable("Don't know how to expand this condition!");
9646     case ISD::SETUO:
9647       if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) {
9648         CC1 = ISD::SETUNE;
9649         CC2 = ISD::SETUNE;
9650         Opc = ISD::OR;
9651         break;
9652       }
9653       assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) &&
9654              "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
9655       NeedInvert = true;
9656       LLVM_FALLTHROUGH;
9657     case ISD::SETO:
9658       assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) &&
9659              "If SETO is expanded, SETOEQ must be legal!");
9660       CC1 = ISD::SETOEQ;
9661       CC2 = ISD::SETOEQ;
9662       Opc = ISD::AND;
9663       break;
9664     case ISD::SETONE:
9665     case ISD::SETUEQ:
9666       // If the SETUO or SETO CC isn't legal, we might be able to use
9667       // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
9668       // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
9669       // the operands.
9670       CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
9671       if (!TLI.isCondCodeLegal(CC2, OpVT) &&
9672           (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) ||
9673            TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) {
9674         CC1 = ISD::SETOGT;
9675         CC2 = ISD::SETOLT;
9676         Opc = ISD::OR;
9677         NeedInvert = ((unsigned)CCCode & 0x8U);
9678         break;
9679       }
9680       LLVM_FALLTHROUGH;
9681     case ISD::SETOEQ:
9682     case ISD::SETOGT:
9683     case ISD::SETOGE:
9684     case ISD::SETOLT:
9685     case ISD::SETOLE:
9686     case ISD::SETUNE:
9687     case ISD::SETUGT:
9688     case ISD::SETUGE:
9689     case ISD::SETULT:
9690     case ISD::SETULE:
9691       // If we are floating point, assign and break, otherwise fall through.
9692       if (!OpVT.isInteger()) {
9693         // We can use the 4th bit to tell if we are the unordered
9694         // or ordered version of the opcode.
9695         CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
9696         Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
9697         CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
9698         break;
9699       }
9700       // Fallthrough if we are unsigned integer.
9701       LLVM_FALLTHROUGH;
9702     case ISD::SETLE:
9703     case ISD::SETGT:
9704     case ISD::SETGE:
9705     case ISD::SETLT:
9706     case ISD::SETNE:
9707     case ISD::SETEQ:
9708       // If all combinations of inverting the condition and swapping operands
9709       // didn't work then we have no means to expand the condition.
9710       llvm_unreachable("Don't know how to expand this condition!");
9711     }
9712 
9713     SDValue SetCC1, SetCC2;
9714     if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
9715       // If we aren't the ordered or unorder operation,
9716       // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
9717       if (IsNonVP) {
9718         SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
9719         SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
9720       } else {
9721         SetCC1 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC1, Mask, EVL);
9722         SetCC2 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC2, Mask, EVL);
9723       }
9724     } else {
9725       // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
9726       if (IsNonVP) {
9727         SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
9728         SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
9729       } else {
9730         SetCC1 = DAG.getSetCCVP(dl, VT, LHS, LHS, CC1, Mask, EVL);
9731         SetCC2 = DAG.getSetCCVP(dl, VT, RHS, RHS, CC2, Mask, EVL);
9732       }
9733     }
9734     if (Chain)
9735       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
9736                           SetCC2.getValue(1));
9737     if (IsNonVP)
9738       LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
9739     else {
9740       // Transform the binary opcode to the VP equivalent.
9741       assert((Opc == ISD::OR || Opc == ISD::AND) && "Unexpected opcode");
9742       Opc = Opc == ISD::OR ? ISD::VP_OR : ISD::VP_AND;
9743       LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2, Mask, EVL);
9744     }
9745     RHS = SDValue();
9746     CC = SDValue();
9747     return true;
9748   }
9749   }
9750   return false;
9751 }
9752