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