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