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