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