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