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