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