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