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