xref: /freebsd-src/contrib/llvm-project/llvm/lib/CodeGen/SelectionDAG/TargetLowering.cpp (revision cb14a3fe5122c879eae1fb480ed7ce82a699ddb6)
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/Analysis/VectorUtils.h"
16 #include "llvm/CodeGen/CallingConvLower.h"
17 #include "llvm/CodeGen/CodeGenCommonISel.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineJumpTableInfo.h"
21 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/CodeGen/SelectionDAG.h"
24 #include "llvm/CodeGen/TargetRegisterInfo.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/GlobalVariable.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/MC/MCAsmInfo.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/Support/DivisionByConstantInfo.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/KnownBits.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include <cctype>
37 using namespace llvm;
38 
39 /// NOTE: The TargetMachine owns TLOF.
40 TargetLowering::TargetLowering(const TargetMachine &tm)
41     : TargetLoweringBase(tm) {}
42 
43 const char *TargetLowering::getTargetNodeName(unsigned Opcode) const {
44   return nullptr;
45 }
46 
47 bool TargetLowering::isPositionIndependent() const {
48   return getTargetMachine().isPositionIndependent();
49 }
50 
51 /// Check whether a given call node is in tail position within its function. If
52 /// so, it sets Chain to the input chain of the tail call.
53 bool TargetLowering::isInTailCallPosition(SelectionDAG &DAG, SDNode *Node,
54                                           SDValue &Chain) const {
55   const Function &F = DAG.getMachineFunction().getFunction();
56 
57   // First, check if tail calls have been disabled in this function.
58   if (F.getFnAttribute("disable-tail-calls").getValueAsBool())
59     return false;
60 
61   // Conservatively require the attributes of the call to match those of
62   // the return. Ignore following attributes because they don't affect the
63   // call sequence.
64   AttrBuilder CallerAttrs(F.getContext(), F.getAttributes().getRetAttrs());
65   for (const auto &Attr : {Attribute::Alignment, Attribute::Dereferenceable,
66                            Attribute::DereferenceableOrNull, Attribute::NoAlias,
67                            Attribute::NonNull, Attribute::NoUndef})
68     CallerAttrs.removeAttribute(Attr);
69 
70   if (CallerAttrs.hasAttributes())
71     return false;
72 
73   // It's not safe to eliminate the sign / zero extension of the return value.
74   if (CallerAttrs.contains(Attribute::ZExt) ||
75       CallerAttrs.contains(Attribute::SExt))
76     return false;
77 
78   // Check if the only use is a function return node.
79   return isUsedByReturnOnly(Node, Chain);
80 }
81 
82 bool TargetLowering::parametersInCSRMatch(const MachineRegisterInfo &MRI,
83     const uint32_t *CallerPreservedMask,
84     const SmallVectorImpl<CCValAssign> &ArgLocs,
85     const SmallVectorImpl<SDValue> &OutVals) const {
86   for (unsigned I = 0, E = ArgLocs.size(); I != E; ++I) {
87     const CCValAssign &ArgLoc = ArgLocs[I];
88     if (!ArgLoc.isRegLoc())
89       continue;
90     MCRegister Reg = ArgLoc.getLocReg();
91     // Only look at callee saved registers.
92     if (MachineOperand::clobbersPhysReg(CallerPreservedMask, Reg))
93       continue;
94     // Check that we pass the value used for the caller.
95     // (We look for a CopyFromReg reading a virtual register that is used
96     //  for the function live-in value of register Reg)
97     SDValue Value = OutVals[I];
98     if (Value->getOpcode() == ISD::AssertZext)
99       Value = Value.getOperand(0);
100     if (Value->getOpcode() != ISD::CopyFromReg)
101       return false;
102     Register ArgReg = cast<RegisterSDNode>(Value->getOperand(1))->getReg();
103     if (MRI.getLiveInPhysReg(ArgReg) != Reg)
104       return false;
105   }
106   return true;
107 }
108 
109 /// Set CallLoweringInfo attribute flags based on a call instruction
110 /// and called function attributes.
111 void TargetLoweringBase::ArgListEntry::setAttributes(const CallBase *Call,
112                                                      unsigned ArgIdx) {
113   IsSExt = Call->paramHasAttr(ArgIdx, Attribute::SExt);
114   IsZExt = Call->paramHasAttr(ArgIdx, Attribute::ZExt);
115   IsInReg = Call->paramHasAttr(ArgIdx, Attribute::InReg);
116   IsSRet = Call->paramHasAttr(ArgIdx, Attribute::StructRet);
117   IsNest = Call->paramHasAttr(ArgIdx, Attribute::Nest);
118   IsByVal = Call->paramHasAttr(ArgIdx, Attribute::ByVal);
119   IsPreallocated = Call->paramHasAttr(ArgIdx, Attribute::Preallocated);
120   IsInAlloca = Call->paramHasAttr(ArgIdx, Attribute::InAlloca);
121   IsReturned = Call->paramHasAttr(ArgIdx, Attribute::Returned);
122   IsSwiftSelf = Call->paramHasAttr(ArgIdx, Attribute::SwiftSelf);
123   IsSwiftAsync = Call->paramHasAttr(ArgIdx, Attribute::SwiftAsync);
124   IsSwiftError = Call->paramHasAttr(ArgIdx, Attribute::SwiftError);
125   Alignment = Call->getParamStackAlign(ArgIdx);
126   IndirectType = nullptr;
127   assert(IsByVal + IsPreallocated + IsInAlloca + IsSRet <= 1 &&
128          "multiple ABI attributes?");
129   if (IsByVal) {
130     IndirectType = Call->getParamByValType(ArgIdx);
131     if (!Alignment)
132       Alignment = Call->getParamAlign(ArgIdx);
133   }
134   if (IsPreallocated)
135     IndirectType = Call->getParamPreallocatedType(ArgIdx);
136   if (IsInAlloca)
137     IndirectType = Call->getParamInAllocaType(ArgIdx);
138   if (IsSRet)
139     IndirectType = Call->getParamStructRetType(ArgIdx);
140 }
141 
142 /// Generate a libcall taking the given operands as arguments and returning a
143 /// result of type RetVT.
144 std::pair<SDValue, SDValue>
145 TargetLowering::makeLibCall(SelectionDAG &DAG, RTLIB::Libcall LC, EVT RetVT,
146                             ArrayRef<SDValue> Ops,
147                             MakeLibCallOptions CallOptions,
148                             const SDLoc &dl,
149                             SDValue InChain) const {
150   if (!InChain)
151     InChain = DAG.getEntryNode();
152 
153   TargetLowering::ArgListTy Args;
154   Args.reserve(Ops.size());
155 
156   TargetLowering::ArgListEntry Entry;
157   for (unsigned i = 0; i < Ops.size(); ++i) {
158     SDValue NewOp = Ops[i];
159     Entry.Node = NewOp;
160     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
161     Entry.IsSExt = shouldSignExtendTypeInLibCall(NewOp.getValueType(),
162                                                  CallOptions.IsSExt);
163     Entry.IsZExt = !Entry.IsSExt;
164 
165     if (CallOptions.IsSoften &&
166         !shouldExtendTypeInLibCall(CallOptions.OpsVTBeforeSoften[i])) {
167       Entry.IsSExt = Entry.IsZExt = false;
168     }
169     Args.push_back(Entry);
170   }
171 
172   if (LC == RTLIB::UNKNOWN_LIBCALL)
173     report_fatal_error("Unsupported library call operation!");
174   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
175                                          getPointerTy(DAG.getDataLayout()));
176 
177   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
178   TargetLowering::CallLoweringInfo CLI(DAG);
179   bool signExtend = shouldSignExtendTypeInLibCall(RetVT, CallOptions.IsSExt);
180   bool zeroExtend = !signExtend;
181 
182   if (CallOptions.IsSoften &&
183       !shouldExtendTypeInLibCall(CallOptions.RetVTBeforeSoften)) {
184     signExtend = zeroExtend = false;
185   }
186 
187   CLI.setDebugLoc(dl)
188       .setChain(InChain)
189       .setLibCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
190       .setNoReturn(CallOptions.DoesNotReturn)
191       .setDiscardResult(!CallOptions.IsReturnValueUsed)
192       .setIsPostTypeLegalization(CallOptions.IsPostTypeLegalization)
193       .setSExtResult(signExtend)
194       .setZExtResult(zeroExtend);
195   return LowerCallTo(CLI);
196 }
197 
198 bool TargetLowering::findOptimalMemOpLowering(
199     std::vector<EVT> &MemOps, unsigned Limit, const MemOp &Op, unsigned DstAS,
200     unsigned SrcAS, const AttributeList &FuncAttributes) const {
201   if (Limit != ~unsigned(0) && Op.isMemcpyWithFixedDstAlign() &&
202       Op.getSrcAlign() < Op.getDstAlign())
203     return false;
204 
205   EVT VT = getOptimalMemOpType(Op, FuncAttributes);
206 
207   if (VT == MVT::Other) {
208     // Use the largest integer type whose alignment constraints are satisfied.
209     // We only need to check DstAlign here as SrcAlign is always greater or
210     // equal to DstAlign (or zero).
211     VT = MVT::i64;
212     if (Op.isFixedDstAlign())
213       while (Op.getDstAlign() < (VT.getSizeInBits() / 8) &&
214              !allowsMisalignedMemoryAccesses(VT, DstAS, Op.getDstAlign()))
215         VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
216     assert(VT.isInteger());
217 
218     // Find the largest legal integer type.
219     MVT LVT = MVT::i64;
220     while (!isTypeLegal(LVT))
221       LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
222     assert(LVT.isInteger());
223 
224     // If the type we've chosen is larger than the largest legal integer type
225     // then use that instead.
226     if (VT.bitsGT(LVT))
227       VT = LVT;
228   }
229 
230   unsigned NumMemOps = 0;
231   uint64_t Size = Op.size();
232   while (Size) {
233     unsigned VTSize = VT.getSizeInBits() / 8;
234     while (VTSize > Size) {
235       // For now, only use non-vector load / store's for the left-over pieces.
236       EVT NewVT = VT;
237       unsigned NewVTSize;
238 
239       bool Found = false;
240       if (VT.isVector() || VT.isFloatingPoint()) {
241         NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
242         if (isOperationLegalOrCustom(ISD::STORE, NewVT) &&
243             isSafeMemOpType(NewVT.getSimpleVT()))
244           Found = true;
245         else if (NewVT == MVT::i64 &&
246                  isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
247                  isSafeMemOpType(MVT::f64)) {
248           // i64 is usually not legal on 32-bit targets, but f64 may be.
249           NewVT = MVT::f64;
250           Found = true;
251         }
252       }
253 
254       if (!Found) {
255         do {
256           NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
257           if (NewVT == MVT::i8)
258             break;
259         } while (!isSafeMemOpType(NewVT.getSimpleVT()));
260       }
261       NewVTSize = NewVT.getSizeInBits() / 8;
262 
263       // If the new VT cannot cover all of the remaining bits, then consider
264       // issuing a (or a pair of) unaligned and overlapping load / store.
265       unsigned Fast;
266       if (NumMemOps && Op.allowOverlap() && NewVTSize < Size &&
267           allowsMisalignedMemoryAccesses(
268               VT, DstAS, Op.isFixedDstAlign() ? Op.getDstAlign() : Align(1),
269               MachineMemOperand::MONone, &Fast) &&
270           Fast)
271         VTSize = Size;
272       else {
273         VT = NewVT;
274         VTSize = NewVTSize;
275       }
276     }
277 
278     if (++NumMemOps > Limit)
279       return false;
280 
281     MemOps.push_back(VT);
282     Size -= VTSize;
283   }
284 
285   return true;
286 }
287 
288 /// Soften the operands of a comparison. This code is shared among BR_CC,
289 /// SELECT_CC, and SETCC handlers.
290 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
291                                          SDValue &NewLHS, SDValue &NewRHS,
292                                          ISD::CondCode &CCCode,
293                                          const SDLoc &dl, const SDValue OldLHS,
294                                          const SDValue OldRHS) const {
295   SDValue Chain;
296   return softenSetCCOperands(DAG, VT, NewLHS, NewRHS, CCCode, dl, OldLHS,
297                              OldRHS, Chain);
298 }
299 
300 void TargetLowering::softenSetCCOperands(SelectionDAG &DAG, EVT VT,
301                                          SDValue &NewLHS, SDValue &NewRHS,
302                                          ISD::CondCode &CCCode,
303                                          const SDLoc &dl, const SDValue OldLHS,
304                                          const SDValue OldRHS,
305                                          SDValue &Chain,
306                                          bool IsSignaling) const {
307   // FIXME: Currently we cannot really respect all IEEE predicates due to libgcc
308   // not supporting it. We can update this code when libgcc provides such
309   // functions.
310 
311   assert((VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128 || VT == MVT::ppcf128)
312          && "Unsupported setcc type!");
313 
314   // Expand into one or more soft-fp libcall(s).
315   RTLIB::Libcall LC1 = RTLIB::UNKNOWN_LIBCALL, LC2 = RTLIB::UNKNOWN_LIBCALL;
316   bool ShouldInvertCC = false;
317   switch (CCCode) {
318   case ISD::SETEQ:
319   case ISD::SETOEQ:
320     LC1 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
321           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
322           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
323     break;
324   case ISD::SETNE:
325   case ISD::SETUNE:
326     LC1 = (VT == MVT::f32) ? RTLIB::UNE_F32 :
327           (VT == MVT::f64) ? RTLIB::UNE_F64 :
328           (VT == MVT::f128) ? RTLIB::UNE_F128 : RTLIB::UNE_PPCF128;
329     break;
330   case ISD::SETGE:
331   case ISD::SETOGE:
332     LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
333           (VT == MVT::f64) ? RTLIB::OGE_F64 :
334           (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
335     break;
336   case ISD::SETLT:
337   case ISD::SETOLT:
338     LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
339           (VT == MVT::f64) ? RTLIB::OLT_F64 :
340           (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
341     break;
342   case ISD::SETLE:
343   case ISD::SETOLE:
344     LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
345           (VT == MVT::f64) ? RTLIB::OLE_F64 :
346           (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
347     break;
348   case ISD::SETGT:
349   case ISD::SETOGT:
350     LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
351           (VT == MVT::f64) ? RTLIB::OGT_F64 :
352           (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
353     break;
354   case ISD::SETO:
355     ShouldInvertCC = true;
356     [[fallthrough]];
357   case ISD::SETUO:
358     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
359           (VT == MVT::f64) ? RTLIB::UO_F64 :
360           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
361     break;
362   case ISD::SETONE:
363     // SETONE = O && UNE
364     ShouldInvertCC = true;
365     [[fallthrough]];
366   case ISD::SETUEQ:
367     LC1 = (VT == MVT::f32) ? RTLIB::UO_F32 :
368           (VT == MVT::f64) ? RTLIB::UO_F64 :
369           (VT == MVT::f128) ? RTLIB::UO_F128 : RTLIB::UO_PPCF128;
370     LC2 = (VT == MVT::f32) ? RTLIB::OEQ_F32 :
371           (VT == MVT::f64) ? RTLIB::OEQ_F64 :
372           (VT == MVT::f128) ? RTLIB::OEQ_F128 : RTLIB::OEQ_PPCF128;
373     break;
374   default:
375     // Invert CC for unordered comparisons
376     ShouldInvertCC = true;
377     switch (CCCode) {
378     case ISD::SETULT:
379       LC1 = (VT == MVT::f32) ? RTLIB::OGE_F32 :
380             (VT == MVT::f64) ? RTLIB::OGE_F64 :
381             (VT == MVT::f128) ? RTLIB::OGE_F128 : RTLIB::OGE_PPCF128;
382       break;
383     case ISD::SETULE:
384       LC1 = (VT == MVT::f32) ? RTLIB::OGT_F32 :
385             (VT == MVT::f64) ? RTLIB::OGT_F64 :
386             (VT == MVT::f128) ? RTLIB::OGT_F128 : RTLIB::OGT_PPCF128;
387       break;
388     case ISD::SETUGT:
389       LC1 = (VT == MVT::f32) ? RTLIB::OLE_F32 :
390             (VT == MVT::f64) ? RTLIB::OLE_F64 :
391             (VT == MVT::f128) ? RTLIB::OLE_F128 : RTLIB::OLE_PPCF128;
392       break;
393     case ISD::SETUGE:
394       LC1 = (VT == MVT::f32) ? RTLIB::OLT_F32 :
395             (VT == MVT::f64) ? RTLIB::OLT_F64 :
396             (VT == MVT::f128) ? RTLIB::OLT_F128 : RTLIB::OLT_PPCF128;
397       break;
398     default: llvm_unreachable("Do not know how to soften this setcc!");
399     }
400   }
401 
402   // Use the target specific return value for comparison lib calls.
403   EVT RetVT = getCmpLibcallReturnType();
404   SDValue Ops[2] = {NewLHS, NewRHS};
405   TargetLowering::MakeLibCallOptions CallOptions;
406   EVT OpsVT[2] = { OldLHS.getValueType(),
407                    OldRHS.getValueType() };
408   CallOptions.setTypeListBeforeSoften(OpsVT, RetVT, true);
409   auto Call = makeLibCall(DAG, LC1, RetVT, Ops, CallOptions, dl, Chain);
410   NewLHS = Call.first;
411   NewRHS = DAG.getConstant(0, dl, RetVT);
412 
413   CCCode = getCmpLibcallCC(LC1);
414   if (ShouldInvertCC) {
415     assert(RetVT.isInteger());
416     CCCode = getSetCCInverse(CCCode, RetVT);
417   }
418 
419   if (LC2 == RTLIB::UNKNOWN_LIBCALL) {
420     // Update Chain.
421     Chain = Call.second;
422   } else {
423     EVT SetCCVT =
424         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), RetVT);
425     SDValue Tmp = DAG.getSetCC(dl, SetCCVT, NewLHS, NewRHS, CCCode);
426     auto Call2 = makeLibCall(DAG, LC2, RetVT, Ops, CallOptions, dl, Chain);
427     CCCode = getCmpLibcallCC(LC2);
428     if (ShouldInvertCC)
429       CCCode = getSetCCInverse(CCCode, RetVT);
430     NewLHS = DAG.getSetCC(dl, SetCCVT, Call2.first, NewRHS, CCCode);
431     if (Chain)
432       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Call.second,
433                           Call2.second);
434     NewLHS = DAG.getNode(ShouldInvertCC ? ISD::AND : ISD::OR, dl,
435                          Tmp.getValueType(), Tmp, NewLHS);
436     NewRHS = SDValue();
437   }
438 }
439 
440 /// Return the entry encoding for a jump table in the current function. The
441 /// returned value is a member of the MachineJumpTableInfo::JTEntryKind enum.
442 unsigned TargetLowering::getJumpTableEncoding() const {
443   // In non-pic modes, just use the address of a block.
444   if (!isPositionIndependent())
445     return MachineJumpTableInfo::EK_BlockAddress;
446 
447   // In PIC mode, if the target supports a GPRel32 directive, use it.
448   if (getTargetMachine().getMCAsmInfo()->getGPRel32Directive() != nullptr)
449     return MachineJumpTableInfo::EK_GPRel32BlockAddress;
450 
451   // Otherwise, use a label difference.
452   return MachineJumpTableInfo::EK_LabelDifference32;
453 }
454 
455 SDValue TargetLowering::getPICJumpTableRelocBase(SDValue Table,
456                                                  SelectionDAG &DAG) const {
457   // If our PIC model is GP relative, use the global offset table as the base.
458   unsigned JTEncoding = getJumpTableEncoding();
459 
460   if ((JTEncoding == MachineJumpTableInfo::EK_GPRel64BlockAddress) ||
461       (JTEncoding == MachineJumpTableInfo::EK_GPRel32BlockAddress))
462     return DAG.getGLOBAL_OFFSET_TABLE(getPointerTy(DAG.getDataLayout()));
463 
464   return Table;
465 }
466 
467 /// This returns the relocation base for the given PIC jumptable, the same as
468 /// getPICJumpTableRelocBase, but as an MCExpr.
469 const MCExpr *
470 TargetLowering::getPICJumpTableRelocBaseExpr(const MachineFunction *MF,
471                                              unsigned JTI,MCContext &Ctx) const{
472   // The normal PIC reloc base is the label at the start of the jump table.
473   return MCSymbolRefExpr::create(MF->getJTISymbol(JTI, Ctx), Ctx);
474 }
475 
476 SDValue TargetLowering::expandIndirectJTBranch(const SDLoc &dl, SDValue Value,
477                                                SDValue Addr, int JTI,
478                                                SelectionDAG &DAG) const {
479   SDValue Chain = Value;
480   // Jump table debug info is only needed if CodeView is enabled.
481   if (DAG.getTarget().getTargetTriple().isOSBinFormatCOFF()) {
482     Chain = DAG.getJumpTableDebugInfo(JTI, Chain, dl);
483   }
484   return DAG.getNode(ISD::BRIND, dl, MVT::Other, Chain, Addr);
485 }
486 
487 bool
488 TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
489   const TargetMachine &TM = getTargetMachine();
490   const GlobalValue *GV = GA->getGlobal();
491 
492   // If the address is not even local to this DSO we will have to load it from
493   // a got and then add the offset.
494   if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
495     return false;
496 
497   // If the code is position independent we will have to add a base register.
498   if (isPositionIndependent())
499     return false;
500 
501   // Otherwise we can do it.
502   return true;
503 }
504 
505 //===----------------------------------------------------------------------===//
506 //  Optimization Methods
507 //===----------------------------------------------------------------------===//
508 
509 /// If the specified instruction has a constant integer operand and there are
510 /// bits set in that constant that are not demanded, then clear those bits and
511 /// return true.
512 bool TargetLowering::ShrinkDemandedConstant(SDValue Op,
513                                             const APInt &DemandedBits,
514                                             const APInt &DemandedElts,
515                                             TargetLoweringOpt &TLO) const {
516   SDLoc DL(Op);
517   unsigned Opcode = Op.getOpcode();
518 
519   // Early-out if we've ended up calling an undemanded node, leave this to
520   // constant folding.
521   if (DemandedBits.isZero() || DemandedElts.isZero())
522     return false;
523 
524   // Do target-specific constant optimization.
525   if (targetShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
526     return TLO.New.getNode();
527 
528   // FIXME: ISD::SELECT, ISD::SELECT_CC
529   switch (Opcode) {
530   default:
531     break;
532   case ISD::XOR:
533   case ISD::AND:
534   case ISD::OR: {
535     auto *Op1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
536     if (!Op1C || Op1C->isOpaque())
537       return false;
538 
539     // If this is a 'not' op, don't touch it because that's a canonical form.
540     const APInt &C = Op1C->getAPIntValue();
541     if (Opcode == ISD::XOR && DemandedBits.isSubsetOf(C))
542       return false;
543 
544     if (!C.isSubsetOf(DemandedBits)) {
545       EVT VT = Op.getValueType();
546       SDValue NewC = TLO.DAG.getConstant(DemandedBits & C, DL, VT);
547       SDValue NewOp = TLO.DAG.getNode(Opcode, DL, VT, Op.getOperand(0), NewC);
548       return TLO.CombineTo(Op, NewOp);
549     }
550 
551     break;
552   }
553   }
554 
555   return false;
556 }
557 
558 bool TargetLowering::ShrinkDemandedConstant(SDValue Op,
559                                             const APInt &DemandedBits,
560                                             TargetLoweringOpt &TLO) const {
561   EVT VT = Op.getValueType();
562   APInt DemandedElts = VT.isVector()
563                            ? APInt::getAllOnes(VT.getVectorNumElements())
564                            : APInt(1, 1);
565   return ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO);
566 }
567 
568 /// Convert x+y to (VT)((SmallVT)x+(SmallVT)y) if the casts are free.
569 /// This uses isTruncateFree/isZExtFree and ANY_EXTEND for the widening cast,
570 /// but it could be generalized for targets with other types of implicit
571 /// widening casts.
572 bool TargetLowering::ShrinkDemandedOp(SDValue Op, unsigned BitWidth,
573                                       const APInt &DemandedBits,
574                                       TargetLoweringOpt &TLO) const {
575   assert(Op.getNumOperands() == 2 &&
576          "ShrinkDemandedOp only supports binary operators!");
577   assert(Op.getNode()->getNumValues() == 1 &&
578          "ShrinkDemandedOp only supports nodes with one result!");
579 
580   EVT VT = Op.getValueType();
581   SelectionDAG &DAG = TLO.DAG;
582   SDLoc dl(Op);
583 
584   // Early return, as this function cannot handle vector types.
585   if (VT.isVector())
586     return false;
587 
588   // Don't do this if the node has another user, which may require the
589   // full value.
590   if (!Op.getNode()->hasOneUse())
591     return false;
592 
593   // Search for the smallest integer type with free casts to and from
594   // Op's type. For expedience, just check power-of-2 integer types.
595   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
596   unsigned DemandedSize = DemandedBits.getActiveBits();
597   for (unsigned SmallVTBits = llvm::bit_ceil(DemandedSize);
598        SmallVTBits < BitWidth; SmallVTBits = NextPowerOf2(SmallVTBits)) {
599     EVT SmallVT = EVT::getIntegerVT(*DAG.getContext(), SmallVTBits);
600     if (TLI.isTruncateFree(VT, SmallVT) && TLI.isZExtFree(SmallVT, VT)) {
601       // We found a type with free casts.
602       SDValue X = DAG.getNode(
603           Op.getOpcode(), dl, SmallVT,
604           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(0)),
605           DAG.getNode(ISD::TRUNCATE, dl, SmallVT, Op.getOperand(1)));
606       assert(DemandedSize <= SmallVTBits && "Narrowed below demanded bits?");
607       SDValue Z = DAG.getNode(ISD::ANY_EXTEND, dl, VT, X);
608       return TLO.CombineTo(Op, Z);
609     }
610   }
611   return false;
612 }
613 
614 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
615                                           DAGCombinerInfo &DCI) const {
616   SelectionDAG &DAG = DCI.DAG;
617   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
618                         !DCI.isBeforeLegalizeOps());
619   KnownBits Known;
620 
621   bool Simplified = SimplifyDemandedBits(Op, DemandedBits, Known, TLO);
622   if (Simplified) {
623     DCI.AddToWorklist(Op.getNode());
624     DCI.CommitTargetLoweringOpt(TLO);
625   }
626   return Simplified;
627 }
628 
629 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
630                                           const APInt &DemandedElts,
631                                           DAGCombinerInfo &DCI) const {
632   SelectionDAG &DAG = DCI.DAG;
633   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
634                         !DCI.isBeforeLegalizeOps());
635   KnownBits Known;
636 
637   bool Simplified =
638       SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO);
639   if (Simplified) {
640     DCI.AddToWorklist(Op.getNode());
641     DCI.CommitTargetLoweringOpt(TLO);
642   }
643   return Simplified;
644 }
645 
646 bool TargetLowering::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
647                                           KnownBits &Known,
648                                           TargetLoweringOpt &TLO,
649                                           unsigned Depth,
650                                           bool AssumeSingleUse) const {
651   EVT VT = Op.getValueType();
652 
653   // Since the number of lanes in a scalable vector is unknown at compile time,
654   // we track one bit which is implicitly broadcast to all lanes.  This means
655   // that all lanes in a scalable vector are considered demanded.
656   APInt DemandedElts = VT.isFixedLengthVector()
657                            ? APInt::getAllOnes(VT.getVectorNumElements())
658                            : APInt(1, 1);
659   return SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, Depth,
660                               AssumeSingleUse);
661 }
662 
663 // TODO: Under what circumstances can we create nodes? Constant folding?
664 SDValue TargetLowering::SimplifyMultipleUseDemandedBits(
665     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
666     SelectionDAG &DAG, unsigned Depth) const {
667   EVT VT = Op.getValueType();
668 
669   // Limit search depth.
670   if (Depth >= SelectionDAG::MaxRecursionDepth)
671     return SDValue();
672 
673   // Ignore UNDEFs.
674   if (Op.isUndef())
675     return SDValue();
676 
677   // Not demanding any bits/elts from Op.
678   if (DemandedBits == 0 || DemandedElts == 0)
679     return DAG.getUNDEF(VT);
680 
681   bool IsLE = DAG.getDataLayout().isLittleEndian();
682   unsigned NumElts = DemandedElts.getBitWidth();
683   unsigned BitWidth = DemandedBits.getBitWidth();
684   KnownBits LHSKnown, RHSKnown;
685   switch (Op.getOpcode()) {
686   case ISD::BITCAST: {
687     if (VT.isScalableVector())
688       return SDValue();
689 
690     SDValue Src = peekThroughBitcasts(Op.getOperand(0));
691     EVT SrcVT = Src.getValueType();
692     EVT DstVT = Op.getValueType();
693     if (SrcVT == DstVT)
694       return Src;
695 
696     unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
697     unsigned NumDstEltBits = DstVT.getScalarSizeInBits();
698     if (NumSrcEltBits == NumDstEltBits)
699       if (SDValue V = SimplifyMultipleUseDemandedBits(
700               Src, DemandedBits, DemandedElts, DAG, Depth + 1))
701         return DAG.getBitcast(DstVT, V);
702 
703     if (SrcVT.isVector() && (NumDstEltBits % NumSrcEltBits) == 0) {
704       unsigned Scale = NumDstEltBits / NumSrcEltBits;
705       unsigned NumSrcElts = SrcVT.getVectorNumElements();
706       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
707       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
708       for (unsigned i = 0; i != Scale; ++i) {
709         unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
710         unsigned BitOffset = EltOffset * NumSrcEltBits;
711         APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset);
712         if (!Sub.isZero()) {
713           DemandedSrcBits |= Sub;
714           for (unsigned j = 0; j != NumElts; ++j)
715             if (DemandedElts[j])
716               DemandedSrcElts.setBit((j * Scale) + i);
717         }
718       }
719 
720       if (SDValue V = SimplifyMultipleUseDemandedBits(
721               Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
722         return DAG.getBitcast(DstVT, V);
723     }
724 
725     // TODO - bigendian once we have test coverage.
726     if (IsLE && (NumSrcEltBits % NumDstEltBits) == 0) {
727       unsigned Scale = NumSrcEltBits / NumDstEltBits;
728       unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
729       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
730       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
731       for (unsigned i = 0; i != NumElts; ++i)
732         if (DemandedElts[i]) {
733           unsigned Offset = (i % Scale) * NumDstEltBits;
734           DemandedSrcBits.insertBits(DemandedBits, Offset);
735           DemandedSrcElts.setBit(i / Scale);
736         }
737 
738       if (SDValue V = SimplifyMultipleUseDemandedBits(
739               Src, DemandedSrcBits, DemandedSrcElts, DAG, Depth + 1))
740         return DAG.getBitcast(DstVT, V);
741     }
742 
743     break;
744   }
745   case ISD::AND: {
746     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
747     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
748 
749     // If all of the demanded bits are known 1 on one side, return the other.
750     // These bits cannot contribute to the result of the 'and' in this
751     // context.
752     if (DemandedBits.isSubsetOf(LHSKnown.Zero | RHSKnown.One))
753       return Op.getOperand(0);
754     if (DemandedBits.isSubsetOf(RHSKnown.Zero | LHSKnown.One))
755       return Op.getOperand(1);
756     break;
757   }
758   case ISD::OR: {
759     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
760     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
761 
762     // If all of the demanded bits are known zero on one side, return the
763     // other.  These bits cannot contribute to the result of the 'or' in this
764     // context.
765     if (DemandedBits.isSubsetOf(LHSKnown.One | RHSKnown.Zero))
766       return Op.getOperand(0);
767     if (DemandedBits.isSubsetOf(RHSKnown.One | LHSKnown.Zero))
768       return Op.getOperand(1);
769     break;
770   }
771   case ISD::XOR: {
772     LHSKnown = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
773     RHSKnown = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
774 
775     // If all of the demanded bits are known zero on one side, return the
776     // other.
777     if (DemandedBits.isSubsetOf(RHSKnown.Zero))
778       return Op.getOperand(0);
779     if (DemandedBits.isSubsetOf(LHSKnown.Zero))
780       return Op.getOperand(1);
781     break;
782   }
783   case ISD::SHL: {
784     // If we are only demanding sign bits then we can use the shift source
785     // directly.
786     if (const APInt *MaxSA =
787             DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
788       SDValue Op0 = Op.getOperand(0);
789       unsigned ShAmt = MaxSA->getZExtValue();
790       unsigned NumSignBits =
791           DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
792       unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
793       if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
794         return Op0;
795     }
796     break;
797   }
798   case ISD::SETCC: {
799     SDValue Op0 = Op.getOperand(0);
800     SDValue Op1 = Op.getOperand(1);
801     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
802     // If (1) we only need the sign-bit, (2) the setcc operands are the same
803     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
804     // -1, we may be able to bypass the setcc.
805     if (DemandedBits.isSignMask() &&
806         Op0.getScalarValueSizeInBits() == BitWidth &&
807         getBooleanContents(Op0.getValueType()) ==
808             BooleanContent::ZeroOrNegativeOneBooleanContent) {
809       // If we're testing X < 0, then this compare isn't needed - just use X!
810       // FIXME: We're limiting to integer types here, but this should also work
811       // if we don't care about FP signed-zero. The use of SETLT with FP means
812       // that we don't care about NaNs.
813       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
814           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
815         return Op0;
816     }
817     break;
818   }
819   case ISD::SIGN_EXTEND_INREG: {
820     // If none of the extended bits are demanded, eliminate the sextinreg.
821     SDValue Op0 = Op.getOperand(0);
822     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
823     unsigned ExBits = ExVT.getScalarSizeInBits();
824     if (DemandedBits.getActiveBits() <= ExBits &&
825         shouldRemoveRedundantExtend(Op))
826       return Op0;
827     // If the input is already sign extended, just drop the extension.
828     unsigned NumSignBits = DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
829     if (NumSignBits >= (BitWidth - ExBits + 1))
830       return Op0;
831     break;
832   }
833   case ISD::ANY_EXTEND_VECTOR_INREG:
834   case ISD::SIGN_EXTEND_VECTOR_INREG:
835   case ISD::ZERO_EXTEND_VECTOR_INREG: {
836     if (VT.isScalableVector())
837       return SDValue();
838 
839     // If we only want the lowest element and none of extended bits, then we can
840     // return the bitcasted source vector.
841     SDValue Src = Op.getOperand(0);
842     EVT SrcVT = Src.getValueType();
843     EVT DstVT = Op.getValueType();
844     if (IsLE && DemandedElts == 1 &&
845         DstVT.getSizeInBits() == SrcVT.getSizeInBits() &&
846         DemandedBits.getActiveBits() <= SrcVT.getScalarSizeInBits()) {
847       return DAG.getBitcast(DstVT, Src);
848     }
849     break;
850   }
851   case ISD::INSERT_VECTOR_ELT: {
852     if (VT.isScalableVector())
853       return SDValue();
854 
855     // If we don't demand the inserted element, return the base vector.
856     SDValue Vec = Op.getOperand(0);
857     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
858     EVT VecVT = Vec.getValueType();
859     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements()) &&
860         !DemandedElts[CIdx->getZExtValue()])
861       return Vec;
862     break;
863   }
864   case ISD::INSERT_SUBVECTOR: {
865     if (VT.isScalableVector())
866       return SDValue();
867 
868     SDValue Vec = Op.getOperand(0);
869     SDValue Sub = Op.getOperand(1);
870     uint64_t Idx = Op.getConstantOperandVal(2);
871     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
872     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
873     // If we don't demand the inserted subvector, return the base vector.
874     if (DemandedSubElts == 0)
875       return Vec;
876     break;
877   }
878   case ISD::VECTOR_SHUFFLE: {
879     assert(!VT.isScalableVector());
880     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
881 
882     // If all the demanded elts are from one operand and are inline,
883     // then we can use the operand directly.
884     bool AllUndef = true, IdentityLHS = true, IdentityRHS = true;
885     for (unsigned i = 0; i != NumElts; ++i) {
886       int M = ShuffleMask[i];
887       if (M < 0 || !DemandedElts[i])
888         continue;
889       AllUndef = false;
890       IdentityLHS &= (M == (int)i);
891       IdentityRHS &= ((M - NumElts) == i);
892     }
893 
894     if (AllUndef)
895       return DAG.getUNDEF(Op.getValueType());
896     if (IdentityLHS)
897       return Op.getOperand(0);
898     if (IdentityRHS)
899       return Op.getOperand(1);
900     break;
901   }
902   default:
903     // TODO: Probably okay to remove after audit; here to reduce change size
904     // in initial enablement patch for scalable vectors
905     if (VT.isScalableVector())
906       return SDValue();
907 
908     if (Op.getOpcode() >= ISD::BUILTIN_OP_END)
909       if (SDValue V = SimplifyMultipleUseDemandedBitsForTargetNode(
910               Op, DemandedBits, DemandedElts, DAG, Depth))
911         return V;
912     break;
913   }
914   return SDValue();
915 }
916 
917 SDValue TargetLowering::SimplifyMultipleUseDemandedBits(
918     SDValue Op, const APInt &DemandedBits, SelectionDAG &DAG,
919     unsigned Depth) const {
920   EVT VT = Op.getValueType();
921   // Since the number of lanes in a scalable vector is unknown at compile time,
922   // we track one bit which is implicitly broadcast to all lanes.  This means
923   // that all lanes in a scalable vector are considered demanded.
924   APInt DemandedElts = VT.isFixedLengthVector()
925                            ? APInt::getAllOnes(VT.getVectorNumElements())
926                            : APInt(1, 1);
927   return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
928                                          Depth);
929 }
930 
931 SDValue TargetLowering::SimplifyMultipleUseDemandedVectorElts(
932     SDValue Op, const APInt &DemandedElts, SelectionDAG &DAG,
933     unsigned Depth) const {
934   APInt DemandedBits = APInt::getAllOnes(Op.getScalarValueSizeInBits());
935   return SimplifyMultipleUseDemandedBits(Op, DemandedBits, DemandedElts, DAG,
936                                          Depth);
937 }
938 
939 // Attempt to form ext(avgfloor(A, B)) from shr(add(ext(A), ext(B)), 1).
940 //      or to form ext(avgceil(A, B)) from shr(add(ext(A), ext(B), 1), 1).
941 static SDValue combineShiftToAVG(SDValue Op, SelectionDAG &DAG,
942                                  const TargetLowering &TLI,
943                                  const APInt &DemandedBits,
944                                  const APInt &DemandedElts,
945                                  unsigned Depth) {
946   assert((Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SRA) &&
947          "SRL or SRA node is required here!");
948   // Is the right shift using an immediate value of 1?
949   ConstantSDNode *N1C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
950   if (!N1C || !N1C->isOne())
951     return SDValue();
952 
953   // We are looking for an avgfloor
954   // add(ext, ext)
955   // or one of these as a avgceil
956   // add(add(ext, ext), 1)
957   // add(add(ext, 1), ext)
958   // add(ext, add(ext, 1))
959   SDValue Add = Op.getOperand(0);
960   if (Add.getOpcode() != ISD::ADD)
961     return SDValue();
962 
963   SDValue ExtOpA = Add.getOperand(0);
964   SDValue ExtOpB = Add.getOperand(1);
965   SDValue Add2;
966   auto MatchOperands = [&](SDValue Op1, SDValue Op2, SDValue Op3, SDValue A) {
967     ConstantSDNode *ConstOp;
968     if ((ConstOp = isConstOrConstSplat(Op2, DemandedElts)) &&
969         ConstOp->isOne()) {
970       ExtOpA = Op1;
971       ExtOpB = Op3;
972       Add2 = A;
973       return true;
974     }
975     if ((ConstOp = isConstOrConstSplat(Op3, DemandedElts)) &&
976         ConstOp->isOne()) {
977       ExtOpA = Op1;
978       ExtOpB = Op2;
979       Add2 = A;
980       return true;
981     }
982     return false;
983   };
984   bool IsCeil =
985       (ExtOpA.getOpcode() == ISD::ADD &&
986        MatchOperands(ExtOpA.getOperand(0), ExtOpA.getOperand(1), ExtOpB, ExtOpA)) ||
987       (ExtOpB.getOpcode() == ISD::ADD &&
988        MatchOperands(ExtOpB.getOperand(0), ExtOpB.getOperand(1), ExtOpA, ExtOpB));
989 
990   // If the shift is signed (sra):
991   //  - Needs >= 2 sign bit for both operands.
992   //  - Needs >= 2 zero bits.
993   // If the shift is unsigned (srl):
994   //  - Needs >= 1 zero bit for both operands.
995   //  - Needs 1 demanded bit zero and >= 2 sign bits.
996   unsigned ShiftOpc = Op.getOpcode();
997   bool IsSigned = false;
998   unsigned KnownBits;
999   unsigned NumSignedA = DAG.ComputeNumSignBits(ExtOpA, DemandedElts, Depth);
1000   unsigned NumSignedB = DAG.ComputeNumSignBits(ExtOpB, DemandedElts, Depth);
1001   unsigned NumSigned = std::min(NumSignedA, NumSignedB) - 1;
1002   unsigned NumZeroA =
1003       DAG.computeKnownBits(ExtOpA, DemandedElts, Depth).countMinLeadingZeros();
1004   unsigned NumZeroB =
1005       DAG.computeKnownBits(ExtOpB, DemandedElts, Depth).countMinLeadingZeros();
1006   unsigned NumZero = std::min(NumZeroA, NumZeroB);
1007 
1008   switch (ShiftOpc) {
1009   default:
1010     llvm_unreachable("Unexpected ShiftOpc in combineShiftToAVG");
1011   case ISD::SRA: {
1012     if (NumZero >= 2 && NumSigned < NumZero) {
1013       IsSigned = false;
1014       KnownBits = NumZero;
1015       break;
1016     }
1017     if (NumSigned >= 1) {
1018       IsSigned = true;
1019       KnownBits = NumSigned;
1020       break;
1021     }
1022     return SDValue();
1023   }
1024   case ISD::SRL: {
1025     if (NumZero >= 1 && NumSigned < NumZero) {
1026       IsSigned = false;
1027       KnownBits = NumZero;
1028       break;
1029     }
1030     if (NumSigned >= 1 && DemandedBits.isSignBitClear()) {
1031       IsSigned = true;
1032       KnownBits = NumSigned;
1033       break;
1034     }
1035     return SDValue();
1036   }
1037   }
1038 
1039   unsigned AVGOpc = IsCeil ? (IsSigned ? ISD::AVGCEILS : ISD::AVGCEILU)
1040                            : (IsSigned ? ISD::AVGFLOORS : ISD::AVGFLOORU);
1041 
1042   // Find the smallest power-2 type that is legal for this vector size and
1043   // operation, given the original type size and the number of known sign/zero
1044   // bits.
1045   EVT VT = Op.getValueType();
1046   unsigned MinWidth =
1047       std::max<unsigned>(VT.getScalarSizeInBits() - KnownBits, 8);
1048   EVT NVT = EVT::getIntegerVT(*DAG.getContext(), llvm::bit_ceil(MinWidth));
1049   if (VT.isVector())
1050     NVT = EVT::getVectorVT(*DAG.getContext(), NVT, VT.getVectorElementCount());
1051   if (!TLI.isOperationLegalOrCustom(AVGOpc, NVT)) {
1052     // If we could not transform, and (both) adds are nuw/nsw, we can use the
1053     // larger type size to do the transform.
1054     if (!TLI.isOperationLegalOrCustom(AVGOpc, VT))
1055       return SDValue();
1056     if (DAG.willNotOverflowAdd(IsSigned, Add.getOperand(0),
1057                                Add.getOperand(1)) &&
1058         (!Add2 || DAG.willNotOverflowAdd(IsSigned, Add2.getOperand(0),
1059                                          Add2.getOperand(1))))
1060       NVT = VT;
1061     else
1062       return SDValue();
1063   }
1064 
1065   SDLoc DL(Op);
1066   SDValue ResultAVG =
1067       DAG.getNode(AVGOpc, DL, NVT, DAG.getNode(ISD::TRUNCATE, DL, NVT, ExtOpA),
1068                   DAG.getNode(ISD::TRUNCATE, DL, NVT, ExtOpB));
1069   return DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL, VT,
1070                      ResultAVG);
1071 }
1072 
1073 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the
1074 /// result of Op are ever used downstream. If we can use this information to
1075 /// simplify Op, create a new simplified DAG node and return true, returning the
1076 /// original and new nodes in Old and New. Otherwise, analyze the expression and
1077 /// return a mask of Known bits for the expression (used to simplify the
1078 /// caller).  The Known bits may only be accurate for those bits in the
1079 /// OriginalDemandedBits and OriginalDemandedElts.
1080 bool TargetLowering::SimplifyDemandedBits(
1081     SDValue Op, const APInt &OriginalDemandedBits,
1082     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
1083     unsigned Depth, bool AssumeSingleUse) const {
1084   unsigned BitWidth = OriginalDemandedBits.getBitWidth();
1085   assert(Op.getScalarValueSizeInBits() == BitWidth &&
1086          "Mask size mismatches value type size!");
1087 
1088   // Don't know anything.
1089   Known = KnownBits(BitWidth);
1090 
1091   EVT VT = Op.getValueType();
1092   bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
1093   unsigned NumElts = OriginalDemandedElts.getBitWidth();
1094   assert((!VT.isFixedLengthVector() || NumElts == VT.getVectorNumElements()) &&
1095          "Unexpected vector size");
1096 
1097   APInt DemandedBits = OriginalDemandedBits;
1098   APInt DemandedElts = OriginalDemandedElts;
1099   SDLoc dl(Op);
1100   auto &DL = TLO.DAG.getDataLayout();
1101 
1102   // Undef operand.
1103   if (Op.isUndef())
1104     return false;
1105 
1106   // We can't simplify target constants.
1107   if (Op.getOpcode() == ISD::TargetConstant)
1108     return false;
1109 
1110   if (Op.getOpcode() == ISD::Constant) {
1111     // We know all of the bits for a constant!
1112     Known = KnownBits::makeConstant(cast<ConstantSDNode>(Op)->getAPIntValue());
1113     return false;
1114   }
1115 
1116   if (Op.getOpcode() == ISD::ConstantFP) {
1117     // We know all of the bits for a floating point constant!
1118     Known = KnownBits::makeConstant(
1119         cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt());
1120     return false;
1121   }
1122 
1123   // Other users may use these bits.
1124   bool HasMultiUse = false;
1125   if (!AssumeSingleUse && !Op.getNode()->hasOneUse()) {
1126     if (Depth >= SelectionDAG::MaxRecursionDepth) {
1127       // Limit search depth.
1128       return false;
1129     }
1130     // Allow multiple uses, just set the DemandedBits/Elts to all bits.
1131     DemandedBits = APInt::getAllOnes(BitWidth);
1132     DemandedElts = APInt::getAllOnes(NumElts);
1133     HasMultiUse = true;
1134   } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
1135     // Not demanding any bits/elts from Op.
1136     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1137   } else if (Depth >= SelectionDAG::MaxRecursionDepth) {
1138     // Limit search depth.
1139     return false;
1140   }
1141 
1142   KnownBits Known2;
1143   switch (Op.getOpcode()) {
1144   case ISD::SCALAR_TO_VECTOR: {
1145     if (VT.isScalableVector())
1146       return false;
1147     if (!DemandedElts[0])
1148       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1149 
1150     KnownBits SrcKnown;
1151     SDValue Src = Op.getOperand(0);
1152     unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
1153     APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth);
1154     if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
1155       return true;
1156 
1157     // Upper elements are undef, so only get the knownbits if we just demand
1158     // the bottom element.
1159     if (DemandedElts == 1)
1160       Known = SrcKnown.anyextOrTrunc(BitWidth);
1161     break;
1162   }
1163   case ISD::BUILD_VECTOR:
1164     // Collect the known bits that are shared by every demanded element.
1165     // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
1166     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1167     return false; // Don't fall through, will infinitely loop.
1168   case ISD::SPLAT_VECTOR: {
1169     SDValue Scl = Op.getOperand(0);
1170     APInt DemandedSclBits = DemandedBits.zextOrTrunc(Scl.getValueSizeInBits());
1171     KnownBits KnownScl;
1172     if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1173       return true;
1174 
1175     // Implicitly truncate the bits to match the official semantics of
1176     // SPLAT_VECTOR.
1177     Known = KnownScl.trunc(BitWidth);
1178     break;
1179   }
1180   case ISD::LOAD: {
1181     auto *LD = cast<LoadSDNode>(Op);
1182     if (getTargetConstantFromLoad(LD)) {
1183       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1184       return false; // Don't fall through, will infinitely loop.
1185     }
1186     if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
1187       // If this is a ZEXTLoad and we are looking at the loaded value.
1188       EVT MemVT = LD->getMemoryVT();
1189       unsigned MemBits = MemVT.getScalarSizeInBits();
1190       Known.Zero.setBitsFrom(MemBits);
1191       return false; // Don't fall through, will infinitely loop.
1192     }
1193     break;
1194   }
1195   case ISD::INSERT_VECTOR_ELT: {
1196     if (VT.isScalableVector())
1197       return false;
1198     SDValue Vec = Op.getOperand(0);
1199     SDValue Scl = Op.getOperand(1);
1200     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1201     EVT VecVT = Vec.getValueType();
1202 
1203     // If index isn't constant, assume we need all vector elements AND the
1204     // inserted element.
1205     APInt DemandedVecElts(DemandedElts);
1206     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
1207       unsigned Idx = CIdx->getZExtValue();
1208       DemandedVecElts.clearBit(Idx);
1209 
1210       // Inserted element is not required.
1211       if (!DemandedElts[Idx])
1212         return TLO.CombineTo(Op, Vec);
1213     }
1214 
1215     KnownBits KnownScl;
1216     unsigned NumSclBits = Scl.getScalarValueSizeInBits();
1217     APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits);
1218     if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1219       return true;
1220 
1221     Known = KnownScl.anyextOrTrunc(BitWidth);
1222 
1223     KnownBits KnownVec;
1224     if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO,
1225                              Depth + 1))
1226       return true;
1227 
1228     if (!!DemandedVecElts)
1229       Known = Known.intersectWith(KnownVec);
1230 
1231     return false;
1232   }
1233   case ISD::INSERT_SUBVECTOR: {
1234     if (VT.isScalableVector())
1235       return false;
1236     // Demand any elements from the subvector and the remainder from the src its
1237     // inserted into.
1238     SDValue Src = Op.getOperand(0);
1239     SDValue Sub = Op.getOperand(1);
1240     uint64_t Idx = Op.getConstantOperandVal(2);
1241     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1242     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1243     APInt DemandedSrcElts = DemandedElts;
1244     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
1245 
1246     KnownBits KnownSub, KnownSrc;
1247     if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO,
1248                              Depth + 1))
1249       return true;
1250     if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO,
1251                              Depth + 1))
1252       return true;
1253 
1254     Known.Zero.setAllBits();
1255     Known.One.setAllBits();
1256     if (!!DemandedSubElts)
1257       Known = Known.intersectWith(KnownSub);
1258     if (!!DemandedSrcElts)
1259       Known = Known.intersectWith(KnownSrc);
1260 
1261     // Attempt to avoid multi-use src if we don't need anything from it.
1262     if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() ||
1263         !DemandedSrcElts.isAllOnes()) {
1264       SDValue NewSub = SimplifyMultipleUseDemandedBits(
1265           Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1);
1266       SDValue NewSrc = SimplifyMultipleUseDemandedBits(
1267           Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1268       if (NewSub || NewSrc) {
1269         NewSub = NewSub ? NewSub : Sub;
1270         NewSrc = NewSrc ? NewSrc : Src;
1271         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub,
1272                                         Op.getOperand(2));
1273         return TLO.CombineTo(Op, NewOp);
1274       }
1275     }
1276     break;
1277   }
1278   case ISD::EXTRACT_SUBVECTOR: {
1279     if (VT.isScalableVector())
1280       return false;
1281     // Offset the demanded elts by the subvector index.
1282     SDValue Src = Op.getOperand(0);
1283     if (Src.getValueType().isScalableVector())
1284       break;
1285     uint64_t Idx = Op.getConstantOperandVal(1);
1286     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1287     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
1288 
1289     if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO,
1290                              Depth + 1))
1291       return true;
1292 
1293     // Attempt to avoid multi-use src if we don't need anything from it.
1294     if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
1295       SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
1296           Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1297       if (DemandedSrc) {
1298         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc,
1299                                         Op.getOperand(1));
1300         return TLO.CombineTo(Op, NewOp);
1301       }
1302     }
1303     break;
1304   }
1305   case ISD::CONCAT_VECTORS: {
1306     if (VT.isScalableVector())
1307       return false;
1308     Known.Zero.setAllBits();
1309     Known.One.setAllBits();
1310     EVT SubVT = Op.getOperand(0).getValueType();
1311     unsigned NumSubVecs = Op.getNumOperands();
1312     unsigned NumSubElts = SubVT.getVectorNumElements();
1313     for (unsigned i = 0; i != NumSubVecs; ++i) {
1314       APInt DemandedSubElts =
1315           DemandedElts.extractBits(NumSubElts, i * NumSubElts);
1316       if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
1317                                Known2, TLO, Depth + 1))
1318         return true;
1319       // Known bits are shared by every demanded subvector element.
1320       if (!!DemandedSubElts)
1321         Known = Known.intersectWith(Known2);
1322     }
1323     break;
1324   }
1325   case ISD::VECTOR_SHUFFLE: {
1326     assert(!VT.isScalableVector());
1327     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1328 
1329     // Collect demanded elements from shuffle operands..
1330     APInt DemandedLHS, DemandedRHS;
1331     if (!getShuffleDemandedElts(NumElts, ShuffleMask, DemandedElts, DemandedLHS,
1332                                 DemandedRHS))
1333       break;
1334 
1335     if (!!DemandedLHS || !!DemandedRHS) {
1336       SDValue Op0 = Op.getOperand(0);
1337       SDValue Op1 = Op.getOperand(1);
1338 
1339       Known.Zero.setAllBits();
1340       Known.One.setAllBits();
1341       if (!!DemandedLHS) {
1342         if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO,
1343                                  Depth + 1))
1344           return true;
1345         Known = Known.intersectWith(Known2);
1346       }
1347       if (!!DemandedRHS) {
1348         if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO,
1349                                  Depth + 1))
1350           return true;
1351         Known = Known.intersectWith(Known2);
1352       }
1353 
1354       // Attempt to avoid multi-use ops if we don't need anything from them.
1355       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1356           Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1);
1357       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1358           Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1);
1359       if (DemandedOp0 || DemandedOp1) {
1360         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1361         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1362         SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask);
1363         return TLO.CombineTo(Op, NewOp);
1364       }
1365     }
1366     break;
1367   }
1368   case ISD::AND: {
1369     SDValue Op0 = Op.getOperand(0);
1370     SDValue Op1 = Op.getOperand(1);
1371 
1372     // If the RHS is a constant, check to see if the LHS would be zero without
1373     // using the bits from the RHS.  Below, we use knowledge about the RHS to
1374     // simplify the LHS, here we're using information from the LHS to simplify
1375     // the RHS.
1376     if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) {
1377       // Do not increment Depth here; that can cause an infinite loop.
1378       KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
1379       // If the LHS already has zeros where RHSC does, this 'and' is dead.
1380       if ((LHSKnown.Zero & DemandedBits) ==
1381           (~RHSC->getAPIntValue() & DemandedBits))
1382         return TLO.CombineTo(Op, Op0);
1383 
1384       // If any of the set bits in the RHS are known zero on the LHS, shrink
1385       // the constant.
1386       if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits,
1387                                  DemandedElts, TLO))
1388         return true;
1389 
1390       // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
1391       // constant, but if this 'and' is only clearing bits that were just set by
1392       // the xor, then this 'and' can be eliminated by shrinking the mask of
1393       // the xor. For example, for a 32-bit X:
1394       // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
1395       if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
1396           LHSKnown.One == ~RHSC->getAPIntValue()) {
1397         SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
1398         return TLO.CombineTo(Op, Xor);
1399       }
1400     }
1401 
1402     // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I)
1403     // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits).
1404     if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR && !VT.isScalableVector() &&
1405         (Op0.getOperand(0).isUndef() ||
1406          ISD::isBuildVectorOfConstantSDNodes(Op0.getOperand(0).getNode())) &&
1407         Op0->hasOneUse()) {
1408       unsigned NumSubElts =
1409           Op0.getOperand(1).getValueType().getVectorNumElements();
1410       unsigned SubIdx = Op0.getConstantOperandVal(2);
1411       APInt DemandedSub =
1412           APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts);
1413       KnownBits KnownSubMask =
1414           TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1);
1415       if (DemandedBits.isSubsetOf(KnownSubMask.One)) {
1416         SDValue NewAnd =
1417             TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1);
1418         SDValue NewInsert =
1419             TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd,
1420                             Op0.getOperand(1), Op0.getOperand(2));
1421         return TLO.CombineTo(Op, NewInsert);
1422       }
1423     }
1424 
1425     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1426                              Depth + 1))
1427       return true;
1428     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1429     if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
1430                              Known2, TLO, Depth + 1))
1431       return true;
1432     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1433 
1434     // If all of the demanded bits are known one on one side, return the other.
1435     // These bits cannot contribute to the result of the 'and'.
1436     if (DemandedBits.isSubsetOf(Known2.Zero | Known.One))
1437       return TLO.CombineTo(Op, Op0);
1438     if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
1439       return TLO.CombineTo(Op, Op1);
1440     // If all of the demanded bits in the inputs are known zeros, return zero.
1441     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1442       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
1443     // If the RHS is a constant, see if we can simplify it.
1444     if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts,
1445                                TLO))
1446       return true;
1447     // If the operation can be done in a smaller type, do so.
1448     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1449       return true;
1450 
1451     // Attempt to avoid multi-use ops if we don't need anything from them.
1452     if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1453       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1454           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1455       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1456           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1457       if (DemandedOp0 || DemandedOp1) {
1458         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1459         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1460         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1461         return TLO.CombineTo(Op, NewOp);
1462       }
1463     }
1464 
1465     Known &= Known2;
1466     break;
1467   }
1468   case ISD::OR: {
1469     SDValue Op0 = Op.getOperand(0);
1470     SDValue Op1 = Op.getOperand(1);
1471 
1472     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1473                              Depth + 1))
1474       return true;
1475     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1476     if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
1477                              Known2, TLO, Depth + 1))
1478       return true;
1479     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1480 
1481     // If all of the demanded bits are known zero on one side, return the other.
1482     // These bits cannot contribute to the result of the 'or'.
1483     if (DemandedBits.isSubsetOf(Known2.One | Known.Zero))
1484       return TLO.CombineTo(Op, Op0);
1485     if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
1486       return TLO.CombineTo(Op, Op1);
1487     // If the RHS is a constant, see if we can simplify it.
1488     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1489       return true;
1490     // If the operation can be done in a smaller type, do so.
1491     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1492       return true;
1493 
1494     // Attempt to avoid multi-use ops if we don't need anything from them.
1495     if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1496       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1497           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1498       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1499           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1500       if (DemandedOp0 || DemandedOp1) {
1501         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1502         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1503         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1504         return TLO.CombineTo(Op, NewOp);
1505       }
1506     }
1507 
1508     // (or (and X, C1), (and (or X, Y), C2)) -> (or (and X, C1|C2), (and Y, C2))
1509     // TODO: Use SimplifyMultipleUseDemandedBits to peek through masks.
1510     if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::AND &&
1511         Op0->hasOneUse() && Op1->hasOneUse()) {
1512       // Attempt to match all commutations - m_c_Or would've been useful!
1513       for (int I = 0; I != 2; ++I) {
1514         SDValue X = Op.getOperand(I).getOperand(0);
1515         SDValue C1 = Op.getOperand(I).getOperand(1);
1516         SDValue Alt = Op.getOperand(1 - I).getOperand(0);
1517         SDValue C2 = Op.getOperand(1 - I).getOperand(1);
1518         if (Alt.getOpcode() == ISD::OR) {
1519           for (int J = 0; J != 2; ++J) {
1520             if (X == Alt.getOperand(J)) {
1521               SDValue Y = Alt.getOperand(1 - J);
1522               if (SDValue C12 = TLO.DAG.FoldConstantArithmetic(ISD::OR, dl, VT,
1523                                                                {C1, C2})) {
1524                 SDValue MaskX = TLO.DAG.getNode(ISD::AND, dl, VT, X, C12);
1525                 SDValue MaskY = TLO.DAG.getNode(ISD::AND, dl, VT, Y, C2);
1526                 return TLO.CombineTo(
1527                     Op, TLO.DAG.getNode(ISD::OR, dl, VT, MaskX, MaskY));
1528               }
1529             }
1530           }
1531         }
1532       }
1533     }
1534 
1535     Known |= Known2;
1536     break;
1537   }
1538   case ISD::XOR: {
1539     SDValue Op0 = Op.getOperand(0);
1540     SDValue Op1 = Op.getOperand(1);
1541 
1542     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1543                              Depth + 1))
1544       return true;
1545     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1546     if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
1547                              Depth + 1))
1548       return true;
1549     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1550 
1551     // If all of the demanded bits are known zero on one side, return the other.
1552     // These bits cannot contribute to the result of the 'xor'.
1553     if (DemandedBits.isSubsetOf(Known.Zero))
1554       return TLO.CombineTo(Op, Op0);
1555     if (DemandedBits.isSubsetOf(Known2.Zero))
1556       return TLO.CombineTo(Op, Op1);
1557     // If the operation can be done in a smaller type, do so.
1558     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1559       return true;
1560 
1561     // If all of the unknown bits are known to be zero on one side or the other
1562     // turn this into an *inclusive* or.
1563     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1564     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1565       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
1566 
1567     ConstantSDNode *C = isConstOrConstSplat(Op1, DemandedElts);
1568     if (C) {
1569       // If one side is a constant, and all of the set bits in the constant are
1570       // also known set on the other side, turn this into an AND, as we know
1571       // the bits will be cleared.
1572       //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1573       // NB: it is okay if more bits are known than are requested
1574       if (C->getAPIntValue() == Known2.One) {
1575         SDValue ANDC =
1576             TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
1577         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
1578       }
1579 
1580       // If the RHS is a constant, see if we can change it. Don't alter a -1
1581       // constant because that's a 'not' op, and that is better for combining
1582       // and codegen.
1583       if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) {
1584         // We're flipping all demanded bits. Flip the undemanded bits too.
1585         SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
1586         return TLO.CombineTo(Op, New);
1587       }
1588 
1589       unsigned Op0Opcode = Op0.getOpcode();
1590       if ((Op0Opcode == ISD::SRL || Op0Opcode == ISD::SHL) && Op0.hasOneUse()) {
1591         if (ConstantSDNode *ShiftC =
1592                 isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) {
1593           // Don't crash on an oversized shift. We can not guarantee that a
1594           // bogus shift has been simplified to undef.
1595           if (ShiftC->getAPIntValue().ult(BitWidth)) {
1596             uint64_t ShiftAmt = ShiftC->getZExtValue();
1597             APInt Ones = APInt::getAllOnes(BitWidth);
1598             Ones = Op0Opcode == ISD::SHL ? Ones.shl(ShiftAmt)
1599                                          : Ones.lshr(ShiftAmt);
1600             const TargetLowering &TLI = TLO.DAG.getTargetLoweringInfo();
1601             if ((DemandedBits & C->getAPIntValue()) == (DemandedBits & Ones) &&
1602                 TLI.isDesirableToCommuteXorWithShift(Op.getNode())) {
1603               // If the xor constant is a demanded mask, do a 'not' before the
1604               // shift:
1605               // xor (X << ShiftC), XorC --> (not X) << ShiftC
1606               // xor (X >> ShiftC), XorC --> (not X) >> ShiftC
1607               SDValue Not = TLO.DAG.getNOT(dl, Op0.getOperand(0), VT);
1608               return TLO.CombineTo(Op, TLO.DAG.getNode(Op0Opcode, dl, VT, Not,
1609                                                        Op0.getOperand(1)));
1610             }
1611           }
1612         }
1613       }
1614     }
1615 
1616     // If we can't turn this into a 'not', try to shrink the constant.
1617     if (!C || !C->isAllOnes())
1618       if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1619         return true;
1620 
1621     // Attempt to avoid multi-use ops if we don't need anything from them.
1622     if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1623       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1624           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1625       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1626           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1627       if (DemandedOp0 || DemandedOp1) {
1628         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1629         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1630         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1631         return TLO.CombineTo(Op, NewOp);
1632       }
1633     }
1634 
1635     Known ^= Known2;
1636     break;
1637   }
1638   case ISD::SELECT:
1639     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known, TLO,
1640                              Depth + 1))
1641       return true;
1642     if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, Known2, TLO,
1643                              Depth + 1))
1644       return true;
1645     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1646     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1647 
1648     // If the operands are constants, see if we can simplify them.
1649     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1650       return true;
1651 
1652     // Only known if known in both the LHS and RHS.
1653     Known = Known.intersectWith(Known2);
1654     break;
1655   case ISD::VSELECT:
1656     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1657                              Known, TLO, Depth + 1))
1658       return true;
1659     if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
1660                              Known2, TLO, Depth + 1))
1661       return true;
1662     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1663     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1664 
1665     // Only known if known in both the LHS and RHS.
1666     Known = Known.intersectWith(Known2);
1667     break;
1668   case ISD::SELECT_CC:
1669     if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, Known, TLO,
1670                              Depth + 1))
1671       return true;
1672     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, Known2, TLO,
1673                              Depth + 1))
1674       return true;
1675     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1676     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1677 
1678     // If the operands are constants, see if we can simplify them.
1679     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1680       return true;
1681 
1682     // Only known if known in both the LHS and RHS.
1683     Known = Known.intersectWith(Known2);
1684     break;
1685   case ISD::SETCC: {
1686     SDValue Op0 = Op.getOperand(0);
1687     SDValue Op1 = Op.getOperand(1);
1688     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1689     // If (1) we only need the sign-bit, (2) the setcc operands are the same
1690     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
1691     // -1, we may be able to bypass the setcc.
1692     if (DemandedBits.isSignMask() &&
1693         Op0.getScalarValueSizeInBits() == BitWidth &&
1694         getBooleanContents(Op0.getValueType()) ==
1695             BooleanContent::ZeroOrNegativeOneBooleanContent) {
1696       // If we're testing X < 0, then this compare isn't needed - just use X!
1697       // FIXME: We're limiting to integer types here, but this should also work
1698       // if we don't care about FP signed-zero. The use of SETLT with FP means
1699       // that we don't care about NaNs.
1700       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
1701           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
1702         return TLO.CombineTo(Op, Op0);
1703 
1704       // TODO: Should we check for other forms of sign-bit comparisons?
1705       // Examples: X <= -1, X >= 0
1706     }
1707     if (getBooleanContents(Op0.getValueType()) ==
1708             TargetLowering::ZeroOrOneBooleanContent &&
1709         BitWidth > 1)
1710       Known.Zero.setBitsFrom(1);
1711     break;
1712   }
1713   case ISD::SHL: {
1714     SDValue Op0 = Op.getOperand(0);
1715     SDValue Op1 = Op.getOperand(1);
1716     EVT ShiftVT = Op1.getValueType();
1717 
1718     if (const APInt *SA =
1719             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1720       unsigned ShAmt = SA->getZExtValue();
1721       if (ShAmt == 0)
1722         return TLO.CombineTo(Op, Op0);
1723 
1724       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1725       // single shift.  We can do this if the bottom bits (which are shifted
1726       // out) are never demanded.
1727       // TODO - support non-uniform vector amounts.
1728       if (Op0.getOpcode() == ISD::SRL) {
1729         if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) {
1730           if (const APInt *SA2 =
1731                   TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) {
1732             unsigned C1 = SA2->getZExtValue();
1733             unsigned Opc = ISD::SHL;
1734             int Diff = ShAmt - C1;
1735             if (Diff < 0) {
1736               Diff = -Diff;
1737               Opc = ISD::SRL;
1738             }
1739             SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1740             return TLO.CombineTo(
1741                 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1742           }
1743         }
1744       }
1745 
1746       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1747       // are not demanded. This will likely allow the anyext to be folded away.
1748       // TODO - support non-uniform vector amounts.
1749       if (Op0.getOpcode() == ISD::ANY_EXTEND) {
1750         SDValue InnerOp = Op0.getOperand(0);
1751         EVT InnerVT = InnerOp.getValueType();
1752         unsigned InnerBits = InnerVT.getScalarSizeInBits();
1753         if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
1754             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
1755           SDValue NarrowShl = TLO.DAG.getNode(
1756               ISD::SHL, dl, InnerVT, InnerOp,
1757               TLO.DAG.getShiftAmountConstant(ShAmt, InnerVT, dl));
1758           return TLO.CombineTo(
1759               Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
1760         }
1761 
1762         // Repeat the SHL optimization above in cases where an extension
1763         // intervenes: (shl (anyext (shr x, c1)), c2) to
1764         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
1765         // aren't demanded (as above) and that the shifted upper c1 bits of
1766         // x aren't demanded.
1767         // TODO - support non-uniform vector amounts.
1768         if (InnerOp.getOpcode() == ISD::SRL && Op0.hasOneUse() &&
1769             InnerOp.hasOneUse()) {
1770           if (const APInt *SA2 =
1771                   TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) {
1772             unsigned InnerShAmt = SA2->getZExtValue();
1773             if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
1774                 DemandedBits.getActiveBits() <=
1775                     (InnerBits - InnerShAmt + ShAmt) &&
1776                 DemandedBits.countr_zero() >= ShAmt) {
1777               SDValue NewSA =
1778                   TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT);
1779               SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
1780                                                InnerOp.getOperand(0));
1781               return TLO.CombineTo(
1782                   Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
1783             }
1784           }
1785         }
1786       }
1787 
1788       APInt InDemandedMask = DemandedBits.lshr(ShAmt);
1789       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1790                                Depth + 1)) {
1791         SDNodeFlags Flags = Op.getNode()->getFlags();
1792         if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
1793           // Disable the nsw and nuw flags. We can no longer guarantee that we
1794           // won't wrap after simplification.
1795           Flags.setNoSignedWrap(false);
1796           Flags.setNoUnsignedWrap(false);
1797           Op->setFlags(Flags);
1798         }
1799         return true;
1800       }
1801       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1802       Known.Zero <<= ShAmt;
1803       Known.One <<= ShAmt;
1804       // low bits known zero.
1805       Known.Zero.setLowBits(ShAmt);
1806 
1807       // Attempt to avoid multi-use ops if we don't need anything from them.
1808       if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
1809         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1810             Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
1811         if (DemandedOp0) {
1812           SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1);
1813           return TLO.CombineTo(Op, NewOp);
1814         }
1815       }
1816 
1817       // Try shrinking the operation as long as the shift amount will still be
1818       // in range.
1819       if ((ShAmt < DemandedBits.getActiveBits()) &&
1820           ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1821         return true;
1822 
1823       // Narrow shift to lower half - similar to ShrinkDemandedOp.
1824       // (shl i64:x, K) -> (i64 zero_extend (shl (i32 (trunc i64:x)), K))
1825       // Only do this if we demand the upper half so the knownbits are correct.
1826       unsigned HalfWidth = BitWidth / 2;
1827       if ((BitWidth % 2) == 0 && !VT.isVector() && ShAmt < HalfWidth &&
1828           DemandedBits.countLeadingOnes() >= HalfWidth) {
1829         EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), HalfWidth);
1830         if (isNarrowingProfitable(VT, HalfVT) &&
1831             isTypeDesirableForOp(ISD::SHL, HalfVT) &&
1832             isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
1833             (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, HalfVT))) {
1834           // If we're demanding the upper bits at all, we must ensure
1835           // that the upper bits of the shift result are known to be zero,
1836           // which is equivalent to the narrow shift being NUW.
1837           if (bool IsNUW = (Known.countMinLeadingZeros() >= HalfWidth)) {
1838             bool IsNSW = Known.countMinSignBits() > HalfWidth;
1839             SDNodeFlags Flags;
1840             Flags.setNoSignedWrap(IsNSW);
1841             Flags.setNoUnsignedWrap(IsNUW);
1842             SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
1843             SDValue NewShiftAmt = TLO.DAG.getShiftAmountConstant(
1844                 ShAmt, HalfVT, dl, TLO.LegalTypes());
1845             SDValue NewShift = TLO.DAG.getNode(ISD::SHL, dl, HalfVT, NewOp,
1846                                                NewShiftAmt, Flags);
1847             SDValue NewExt =
1848                 TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift);
1849             return TLO.CombineTo(Op, NewExt);
1850           }
1851         }
1852       }
1853     } else {
1854       // This is a variable shift, so we can't shift the demand mask by a known
1855       // amount. But if we are not demanding high bits, then we are not
1856       // demanding those bits from the pre-shifted operand either.
1857       if (unsigned CTLZ = DemandedBits.countl_zero()) {
1858         APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
1859         if (SimplifyDemandedBits(Op0, DemandedFromOp, DemandedElts, Known, TLO,
1860                                  Depth + 1)) {
1861           SDNodeFlags Flags = Op.getNode()->getFlags();
1862           if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
1863             // Disable the nsw and nuw flags. We can no longer guarantee that we
1864             // won't wrap after simplification.
1865             Flags.setNoSignedWrap(false);
1866             Flags.setNoUnsignedWrap(false);
1867             Op->setFlags(Flags);
1868           }
1869           return true;
1870         }
1871         Known.resetAll();
1872       }
1873     }
1874 
1875     // If we are only demanding sign bits then we can use the shift source
1876     // directly.
1877     if (const APInt *MaxSA =
1878             TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
1879       unsigned ShAmt = MaxSA->getZExtValue();
1880       unsigned NumSignBits =
1881           TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1882       unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
1883       if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
1884         return TLO.CombineTo(Op, Op0);
1885     }
1886     break;
1887   }
1888   case ISD::SRL: {
1889     SDValue Op0 = Op.getOperand(0);
1890     SDValue Op1 = Op.getOperand(1);
1891     EVT ShiftVT = Op1.getValueType();
1892 
1893     // Try to match AVG patterns.
1894     if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits,
1895                                         DemandedElts, Depth + 1))
1896       return TLO.CombineTo(Op, AVG);
1897 
1898     if (const APInt *SA =
1899             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1900       unsigned ShAmt = SA->getZExtValue();
1901       if (ShAmt == 0)
1902         return TLO.CombineTo(Op, Op0);
1903 
1904       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
1905       // single shift.  We can do this if the top bits (which are shifted out)
1906       // are never demanded.
1907       // TODO - support non-uniform vector amounts.
1908       if (Op0.getOpcode() == ISD::SHL) {
1909         if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
1910           if (const APInt *SA2 =
1911                   TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) {
1912             unsigned C1 = SA2->getZExtValue();
1913             unsigned Opc = ISD::SRL;
1914             int Diff = ShAmt - C1;
1915             if (Diff < 0) {
1916               Diff = -Diff;
1917               Opc = ISD::SHL;
1918             }
1919             SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1920             return TLO.CombineTo(
1921                 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1922           }
1923         }
1924       }
1925 
1926       APInt InDemandedMask = (DemandedBits << ShAmt);
1927 
1928       // If the shift is exact, then it does demand the low bits (and knows that
1929       // they are zero).
1930       if (Op->getFlags().hasExact())
1931         InDemandedMask.setLowBits(ShAmt);
1932 
1933       // Narrow shift to lower half - similar to ShrinkDemandedOp.
1934       // (srl i64:x, K) -> (i64 zero_extend (srl (i32 (trunc i64:x)), K))
1935       if ((BitWidth % 2) == 0 && !VT.isVector()) {
1936         APInt HiBits = APInt::getHighBitsSet(BitWidth, BitWidth / 2);
1937         EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), BitWidth / 2);
1938         if (isNarrowingProfitable(VT, HalfVT) &&
1939             isTypeDesirableForOp(ISD::SRL, HalfVT) &&
1940             isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
1941             (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, HalfVT)) &&
1942             ((InDemandedMask.countLeadingZeros() >= (BitWidth / 2)) ||
1943              TLO.DAG.MaskedValueIsZero(Op0, HiBits))) {
1944           SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
1945           SDValue NewShiftAmt = TLO.DAG.getShiftAmountConstant(
1946               ShAmt, HalfVT, dl, TLO.LegalTypes());
1947           SDValue NewShift =
1948               TLO.DAG.getNode(ISD::SRL, dl, HalfVT, NewOp, NewShiftAmt);
1949           return TLO.CombineTo(
1950               Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift));
1951         }
1952       }
1953 
1954       // Compute the new bits that are at the top now.
1955       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1956                                Depth + 1))
1957         return true;
1958       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1959       Known.Zero.lshrInPlace(ShAmt);
1960       Known.One.lshrInPlace(ShAmt);
1961       // High bits known zero.
1962       Known.Zero.setHighBits(ShAmt);
1963 
1964       // Attempt to avoid multi-use ops if we don't need anything from them.
1965       if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
1966         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1967             Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
1968         if (DemandedOp0) {
1969           SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, DemandedOp0, Op1);
1970           return TLO.CombineTo(Op, NewOp);
1971         }
1972       }
1973     } else {
1974       // Use generic knownbits computation as it has support for non-uniform
1975       // shift amounts.
1976       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1977     }
1978     break;
1979   }
1980   case ISD::SRA: {
1981     SDValue Op0 = Op.getOperand(0);
1982     SDValue Op1 = Op.getOperand(1);
1983     EVT ShiftVT = Op1.getValueType();
1984 
1985     // If we only want bits that already match the signbit then we don't need
1986     // to shift.
1987     unsigned NumHiDemandedBits = BitWidth - DemandedBits.countr_zero();
1988     if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >=
1989         NumHiDemandedBits)
1990       return TLO.CombineTo(Op, Op0);
1991 
1992     // If this is an arithmetic shift right and only the low-bit is set, we can
1993     // always convert this into a logical shr, even if the shift amount is
1994     // variable.  The low bit of the shift cannot be an input sign bit unless
1995     // the shift amount is >= the size of the datatype, which is undefined.
1996     if (DemandedBits.isOne())
1997       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
1998 
1999     // Try to match AVG patterns.
2000     if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits,
2001                                         DemandedElts, Depth + 1))
2002       return TLO.CombineTo(Op, AVG);
2003 
2004     if (const APInt *SA =
2005             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
2006       unsigned ShAmt = SA->getZExtValue();
2007       if (ShAmt == 0)
2008         return TLO.CombineTo(Op, Op0);
2009 
2010       // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target
2011       // supports sext_inreg.
2012       if (Op0.getOpcode() == ISD::SHL) {
2013         if (const APInt *InnerSA =
2014                 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) {
2015           unsigned LowBits = BitWidth - ShAmt;
2016           EVT ExtVT = EVT::getIntegerVT(*TLO.DAG.getContext(), LowBits);
2017           if (VT.isVector())
2018             ExtVT = EVT::getVectorVT(*TLO.DAG.getContext(), ExtVT,
2019                                      VT.getVectorElementCount());
2020 
2021           if (*InnerSA == ShAmt) {
2022             if (!TLO.LegalOperations() ||
2023                 getOperationAction(ISD::SIGN_EXTEND_INREG, ExtVT) == Legal)
2024               return TLO.CombineTo(
2025                   Op, TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
2026                                       Op0.getOperand(0),
2027                                       TLO.DAG.getValueType(ExtVT)));
2028 
2029             // Even if we can't convert to sext_inreg, we might be able to
2030             // remove this shift pair if the input is already sign extended.
2031             unsigned NumSignBits =
2032                 TLO.DAG.ComputeNumSignBits(Op0.getOperand(0), DemandedElts);
2033             if (NumSignBits > ShAmt)
2034               return TLO.CombineTo(Op, Op0.getOperand(0));
2035           }
2036         }
2037       }
2038 
2039       APInt InDemandedMask = (DemandedBits << ShAmt);
2040 
2041       // If the shift is exact, then it does demand the low bits (and knows that
2042       // they are zero).
2043       if (Op->getFlags().hasExact())
2044         InDemandedMask.setLowBits(ShAmt);
2045 
2046       // If any of the demanded bits are produced by the sign extension, we also
2047       // demand the input sign bit.
2048       if (DemandedBits.countl_zero() < ShAmt)
2049         InDemandedMask.setSignBit();
2050 
2051       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2052                                Depth + 1))
2053         return true;
2054       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2055       Known.Zero.lshrInPlace(ShAmt);
2056       Known.One.lshrInPlace(ShAmt);
2057 
2058       // If the input sign bit is known to be zero, or if none of the top bits
2059       // are demanded, turn this into an unsigned shift right.
2060       if (Known.Zero[BitWidth - ShAmt - 1] ||
2061           DemandedBits.countl_zero() >= ShAmt) {
2062         SDNodeFlags Flags;
2063         Flags.setExact(Op->getFlags().hasExact());
2064         return TLO.CombineTo(
2065             Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
2066       }
2067 
2068       int Log2 = DemandedBits.exactLogBase2();
2069       if (Log2 >= 0) {
2070         // The bit must come from the sign.
2071         SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT);
2072         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
2073       }
2074 
2075       if (Known.One[BitWidth - ShAmt - 1])
2076         // New bits are known one.
2077         Known.One.setHighBits(ShAmt);
2078 
2079       // Attempt to avoid multi-use ops if we don't need anything from them.
2080       if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2081         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
2082             Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2083         if (DemandedOp0) {
2084           SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1);
2085           return TLO.CombineTo(Op, NewOp);
2086         }
2087       }
2088     }
2089     break;
2090   }
2091   case ISD::FSHL:
2092   case ISD::FSHR: {
2093     SDValue Op0 = Op.getOperand(0);
2094     SDValue Op1 = Op.getOperand(1);
2095     SDValue Op2 = Op.getOperand(2);
2096     bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
2097 
2098     if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) {
2099       unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2100 
2101       // For fshl, 0-shift returns the 1st arg.
2102       // For fshr, 0-shift returns the 2nd arg.
2103       if (Amt == 0) {
2104         if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
2105                                  Known, TLO, Depth + 1))
2106           return true;
2107         break;
2108       }
2109 
2110       // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
2111       // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
2112       APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
2113       APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
2114       if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2115                                Depth + 1))
2116         return true;
2117       if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
2118                                Depth + 1))
2119         return true;
2120 
2121       Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt));
2122       Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt));
2123       Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
2124       Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
2125       Known = Known.unionWith(Known2);
2126 
2127       // Attempt to avoid multi-use ops if we don't need anything from them.
2128       if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() ||
2129           !DemandedElts.isAllOnes()) {
2130         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
2131             Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1);
2132         SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
2133             Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1);
2134         if (DemandedOp0 || DemandedOp1) {
2135           DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0;
2136           DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1;
2137           SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0,
2138                                           DemandedOp1, Op2);
2139           return TLO.CombineTo(Op, NewOp);
2140         }
2141       }
2142     }
2143 
2144     // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2145     if (isPowerOf2_32(BitWidth)) {
2146       APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1);
2147       if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts,
2148                                Known2, TLO, Depth + 1))
2149         return true;
2150     }
2151     break;
2152   }
2153   case ISD::ROTL:
2154   case ISD::ROTR: {
2155     SDValue Op0 = Op.getOperand(0);
2156     SDValue Op1 = Op.getOperand(1);
2157     bool IsROTL = (Op.getOpcode() == ISD::ROTL);
2158 
2159     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
2160     if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1))
2161       return TLO.CombineTo(Op, Op0);
2162 
2163     if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
2164       unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2165       unsigned RevAmt = BitWidth - Amt;
2166 
2167       // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt))
2168       // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt)
2169       APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt);
2170       if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2171                                Depth + 1))
2172         return true;
2173 
2174       // rot*(x, 0) --> x
2175       if (Amt == 0)
2176         return TLO.CombineTo(Op, Op0);
2177 
2178       // See if we don't demand either half of the rotated bits.
2179       if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) &&
2180           DemandedBits.countr_zero() >= (IsROTL ? Amt : RevAmt)) {
2181         Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType());
2182         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1));
2183       }
2184       if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) &&
2185           DemandedBits.countl_zero() >= (IsROTL ? RevAmt : Amt)) {
2186         Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType());
2187         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2188       }
2189     }
2190 
2191     // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2192     if (isPowerOf2_32(BitWidth)) {
2193       APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1);
2194       if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO,
2195                                Depth + 1))
2196         return true;
2197     }
2198     break;
2199   }
2200   case ISD::SMIN:
2201   case ISD::SMAX:
2202   case ISD::UMIN:
2203   case ISD::UMAX: {
2204     unsigned Opc = Op.getOpcode();
2205     SDValue Op0 = Op.getOperand(0);
2206     SDValue Op1 = Op.getOperand(1);
2207 
2208     // If we're only demanding signbits, then we can simplify to OR/AND node.
2209     unsigned BitOp =
2210         (Opc == ISD::SMIN || Opc == ISD::UMAX) ? ISD::OR : ISD::AND;
2211     unsigned NumSignBits =
2212         std::min(TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1),
2213                  TLO.DAG.ComputeNumSignBits(Op1, DemandedElts, Depth + 1));
2214     unsigned NumDemandedUpperBits = BitWidth - DemandedBits.countr_zero();
2215     if (NumSignBits >= NumDemandedUpperBits)
2216       return TLO.CombineTo(Op, TLO.DAG.getNode(BitOp, SDLoc(Op), VT, Op0, Op1));
2217 
2218     // Check if one arg is always less/greater than (or equal) to the other arg.
2219     KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
2220     KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
2221     switch (Opc) {
2222     case ISD::SMIN:
2223       if (std::optional<bool> IsSLE = KnownBits::sle(Known0, Known1))
2224         return TLO.CombineTo(Op, *IsSLE ? Op0 : Op1);
2225       if (std::optional<bool> IsSLT = KnownBits::slt(Known0, Known1))
2226         return TLO.CombineTo(Op, *IsSLT ? Op0 : Op1);
2227       Known = KnownBits::smin(Known0, Known1);
2228       break;
2229     case ISD::SMAX:
2230       if (std::optional<bool> IsSGE = KnownBits::sge(Known0, Known1))
2231         return TLO.CombineTo(Op, *IsSGE ? Op0 : Op1);
2232       if (std::optional<bool> IsSGT = KnownBits::sgt(Known0, Known1))
2233         return TLO.CombineTo(Op, *IsSGT ? Op0 : Op1);
2234       Known = KnownBits::smax(Known0, Known1);
2235       break;
2236     case ISD::UMIN:
2237       if (std::optional<bool> IsULE = KnownBits::ule(Known0, Known1))
2238         return TLO.CombineTo(Op, *IsULE ? Op0 : Op1);
2239       if (std::optional<bool> IsULT = KnownBits::ult(Known0, Known1))
2240         return TLO.CombineTo(Op, *IsULT ? Op0 : Op1);
2241       Known = KnownBits::umin(Known0, Known1);
2242       break;
2243     case ISD::UMAX:
2244       if (std::optional<bool> IsUGE = KnownBits::uge(Known0, Known1))
2245         return TLO.CombineTo(Op, *IsUGE ? Op0 : Op1);
2246       if (std::optional<bool> IsUGT = KnownBits::ugt(Known0, Known1))
2247         return TLO.CombineTo(Op, *IsUGT ? Op0 : Op1);
2248       Known = KnownBits::umax(Known0, Known1);
2249       break;
2250     }
2251     break;
2252   }
2253   case ISD::BITREVERSE: {
2254     SDValue Src = Op.getOperand(0);
2255     APInt DemandedSrcBits = DemandedBits.reverseBits();
2256     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2257                              Depth + 1))
2258       return true;
2259     Known.One = Known2.One.reverseBits();
2260     Known.Zero = Known2.Zero.reverseBits();
2261     break;
2262   }
2263   case ISD::BSWAP: {
2264     SDValue Src = Op.getOperand(0);
2265 
2266     // If the only bits demanded come from one byte of the bswap result,
2267     // just shift the input byte into position to eliminate the bswap.
2268     unsigned NLZ = DemandedBits.countl_zero();
2269     unsigned NTZ = DemandedBits.countr_zero();
2270 
2271     // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
2272     // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
2273     // have 14 leading zeros, round to 8.
2274     NLZ = alignDown(NLZ, 8);
2275     NTZ = alignDown(NTZ, 8);
2276     // If we need exactly one byte, we can do this transformation.
2277     if (BitWidth - NLZ - NTZ == 8) {
2278       // Replace this with either a left or right shift to get the byte into
2279       // the right place.
2280       unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL;
2281       if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) {
2282         EVT ShiftAmtTy = getShiftAmountTy(VT, DL);
2283         unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ;
2284         SDValue ShAmt = TLO.DAG.getConstant(ShiftAmount, dl, ShiftAmtTy);
2285         SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt);
2286         return TLO.CombineTo(Op, NewOp);
2287       }
2288     }
2289 
2290     APInt DemandedSrcBits = DemandedBits.byteSwap();
2291     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2292                              Depth + 1))
2293       return true;
2294     Known.One = Known2.One.byteSwap();
2295     Known.Zero = Known2.Zero.byteSwap();
2296     break;
2297   }
2298   case ISD::CTPOP: {
2299     // If only 1 bit is demanded, replace with PARITY as long as we're before
2300     // op legalization.
2301     // FIXME: Limit to scalars for now.
2302     if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector())
2303       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT,
2304                                                Op.getOperand(0)));
2305 
2306     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2307     break;
2308   }
2309   case ISD::SIGN_EXTEND_INREG: {
2310     SDValue Op0 = Op.getOperand(0);
2311     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2312     unsigned ExVTBits = ExVT.getScalarSizeInBits();
2313 
2314     // If we only care about the highest bit, don't bother shifting right.
2315     if (DemandedBits.isSignMask()) {
2316       unsigned MinSignedBits =
2317           TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1);
2318       bool AlreadySignExtended = ExVTBits >= MinSignedBits;
2319       // However if the input is already sign extended we expect the sign
2320       // extension to be dropped altogether later and do not simplify.
2321       if (!AlreadySignExtended) {
2322         // Compute the correct shift amount type, which must be getShiftAmountTy
2323         // for scalar types after legalization.
2324         SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ExVTBits, dl,
2325                                                getShiftAmountTy(VT, DL));
2326         return TLO.CombineTo(Op,
2327                              TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
2328       }
2329     }
2330 
2331     // If none of the extended bits are demanded, eliminate the sextinreg.
2332     if (DemandedBits.getActiveBits() <= ExVTBits)
2333       return TLO.CombineTo(Op, Op0);
2334 
2335     APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
2336 
2337     // Since the sign extended bits are demanded, we know that the sign
2338     // bit is demanded.
2339     InputDemandedBits.setBit(ExVTBits - 1);
2340 
2341     if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO,
2342                              Depth + 1))
2343       return true;
2344     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2345 
2346     // If the sign bit of the input is known set or clear, then we know the
2347     // top bits of the result.
2348 
2349     // If the input sign bit is known zero, convert this into a zero extension.
2350     if (Known.Zero[ExVTBits - 1])
2351       return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT));
2352 
2353     APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
2354     if (Known.One[ExVTBits - 1]) { // Input sign bit known set
2355       Known.One.setBitsFrom(ExVTBits);
2356       Known.Zero &= Mask;
2357     } else { // Input sign bit unknown
2358       Known.Zero &= Mask;
2359       Known.One &= Mask;
2360     }
2361     break;
2362   }
2363   case ISD::BUILD_PAIR: {
2364     EVT HalfVT = Op.getOperand(0).getValueType();
2365     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
2366 
2367     APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
2368     APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
2369 
2370     KnownBits KnownLo, KnownHi;
2371 
2372     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
2373       return true;
2374 
2375     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
2376       return true;
2377 
2378     Known = KnownHi.concat(KnownLo);
2379     break;
2380   }
2381   case ISD::ZERO_EXTEND_VECTOR_INREG:
2382     if (VT.isScalableVector())
2383       return false;
2384     [[fallthrough]];
2385   case ISD::ZERO_EXTEND: {
2386     SDValue Src = Op.getOperand(0);
2387     EVT SrcVT = Src.getValueType();
2388     unsigned InBits = SrcVT.getScalarSizeInBits();
2389     unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2390     bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
2391 
2392     // If none of the top bits are demanded, convert this into an any_extend.
2393     if (DemandedBits.getActiveBits() <= InBits) {
2394       // If we only need the non-extended bits of the bottom element
2395       // then we can just bitcast to the result.
2396       if (IsLE && IsVecInReg && DemandedElts == 1 &&
2397           VT.getSizeInBits() == SrcVT.getSizeInBits())
2398         return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2399 
2400       unsigned Opc =
2401           IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND;
2402       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2403         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2404     }
2405 
2406     SDNodeFlags Flags = Op->getFlags();
2407     APInt InDemandedBits = DemandedBits.trunc(InBits);
2408     APInt InDemandedElts = DemandedElts.zext(InElts);
2409     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2410                              Depth + 1)) {
2411       if (Flags.hasNonNeg()) {
2412         Flags.setNonNeg(false);
2413         Op->setFlags(Flags);
2414       }
2415       return true;
2416     }
2417     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2418     assert(Known.getBitWidth() == InBits && "Src width has changed?");
2419     Known = Known.zext(BitWidth);
2420 
2421     // Attempt to avoid multi-use ops if we don't need anything from them.
2422     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2423             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2424       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2425     break;
2426   }
2427   case ISD::SIGN_EXTEND_VECTOR_INREG:
2428     if (VT.isScalableVector())
2429       return false;
2430     [[fallthrough]];
2431   case ISD::SIGN_EXTEND: {
2432     SDValue Src = Op.getOperand(0);
2433     EVT SrcVT = Src.getValueType();
2434     unsigned InBits = SrcVT.getScalarSizeInBits();
2435     unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2436     bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
2437 
2438     // If none of the top bits are demanded, convert this into an any_extend.
2439     if (DemandedBits.getActiveBits() <= InBits) {
2440       // If we only need the non-extended bits of the bottom element
2441       // then we can just bitcast to the result.
2442       if (IsLE && IsVecInReg && DemandedElts == 1 &&
2443           VT.getSizeInBits() == SrcVT.getSizeInBits())
2444         return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2445 
2446       unsigned Opc =
2447           IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND;
2448       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2449         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2450     }
2451 
2452     APInt InDemandedBits = DemandedBits.trunc(InBits);
2453     APInt InDemandedElts = DemandedElts.zext(InElts);
2454 
2455     // Since some of the sign extended bits are demanded, we know that the sign
2456     // bit is demanded.
2457     InDemandedBits.setBit(InBits - 1);
2458 
2459     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2460                              Depth + 1))
2461       return true;
2462     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2463     assert(Known.getBitWidth() == InBits && "Src width has changed?");
2464 
2465     // If the sign bit is known one, the top bits match.
2466     Known = Known.sext(BitWidth);
2467 
2468     // If the sign bit is known zero, convert this to a zero extend.
2469     if (Known.isNonNegative()) {
2470       unsigned Opc =
2471           IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND;
2472       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2473         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2474     }
2475 
2476     // Attempt to avoid multi-use ops if we don't need anything from them.
2477     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2478             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2479       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2480     break;
2481   }
2482   case ISD::ANY_EXTEND_VECTOR_INREG:
2483     if (VT.isScalableVector())
2484       return false;
2485     [[fallthrough]];
2486   case ISD::ANY_EXTEND: {
2487     SDValue Src = Op.getOperand(0);
2488     EVT SrcVT = Src.getValueType();
2489     unsigned InBits = SrcVT.getScalarSizeInBits();
2490     unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2491     bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG;
2492 
2493     // If we only need the bottom element then we can just bitcast.
2494     // TODO: Handle ANY_EXTEND?
2495     if (IsLE && IsVecInReg && DemandedElts == 1 &&
2496         VT.getSizeInBits() == SrcVT.getSizeInBits())
2497       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2498 
2499     APInt InDemandedBits = DemandedBits.trunc(InBits);
2500     APInt InDemandedElts = DemandedElts.zext(InElts);
2501     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2502                              Depth + 1))
2503       return true;
2504     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2505     assert(Known.getBitWidth() == InBits && "Src width has changed?");
2506     Known = Known.anyext(BitWidth);
2507 
2508     // Attempt to avoid multi-use ops if we don't need anything from them.
2509     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2510             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2511       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2512     break;
2513   }
2514   case ISD::TRUNCATE: {
2515     SDValue Src = Op.getOperand(0);
2516 
2517     // Simplify the input, using demanded bit information, and compute the known
2518     // zero/one bits live out.
2519     unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
2520     APInt TruncMask = DemandedBits.zext(OperandBitWidth);
2521     if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO,
2522                              Depth + 1))
2523       return true;
2524     Known = Known.trunc(BitWidth);
2525 
2526     // Attempt to avoid multi-use ops if we don't need anything from them.
2527     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2528             Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1))
2529       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc));
2530 
2531     // If the input is only used by this truncate, see if we can shrink it based
2532     // on the known demanded bits.
2533     switch (Src.getOpcode()) {
2534     default:
2535       break;
2536     case ISD::SRL:
2537       // Shrink SRL by a constant if none of the high bits shifted in are
2538       // demanded.
2539       if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
2540         // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
2541         // undesirable.
2542         break;
2543 
2544       if (Src.getNode()->hasOneUse()) {
2545         const APInt *ShAmtC =
2546             TLO.DAG.getValidShiftAmountConstant(Src, DemandedElts);
2547         if (!ShAmtC || ShAmtC->uge(BitWidth))
2548           break;
2549         uint64_t ShVal = ShAmtC->getZExtValue();
2550 
2551         APInt HighBits =
2552             APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
2553         HighBits.lshrInPlace(ShVal);
2554         HighBits = HighBits.trunc(BitWidth);
2555 
2556         if (!(HighBits & DemandedBits)) {
2557           // None of the shifted in bits are needed.  Add a truncate of the
2558           // shift input, then shift it.
2559           SDValue NewShAmt = TLO.DAG.getConstant(
2560               ShVal, dl, getShiftAmountTy(VT, DL, TLO.LegalTypes()));
2561           SDValue NewTrunc =
2562               TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
2563           return TLO.CombineTo(
2564               Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt));
2565         }
2566       }
2567       break;
2568     }
2569 
2570     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2571     break;
2572   }
2573   case ISD::AssertZext: {
2574     // AssertZext demands all of the high bits, plus any of the low bits
2575     // demanded by its users.
2576     EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2577     APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits());
2578     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
2579                              TLO, Depth + 1))
2580       return true;
2581     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2582 
2583     Known.Zero |= ~InMask;
2584     Known.One &= (~Known.Zero);
2585     break;
2586   }
2587   case ISD::EXTRACT_VECTOR_ELT: {
2588     SDValue Src = Op.getOperand(0);
2589     SDValue Idx = Op.getOperand(1);
2590     ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount();
2591     unsigned EltBitWidth = Src.getScalarValueSizeInBits();
2592 
2593     if (SrcEltCnt.isScalable())
2594       return false;
2595 
2596     // Demand the bits from every vector element without a constant index.
2597     unsigned NumSrcElts = SrcEltCnt.getFixedValue();
2598     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
2599     if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
2600       if (CIdx->getAPIntValue().ult(NumSrcElts))
2601         DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
2602 
2603     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2604     // anything about the extended bits.
2605     APInt DemandedSrcBits = DemandedBits;
2606     if (BitWidth > EltBitWidth)
2607       DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
2608 
2609     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
2610                              Depth + 1))
2611       return true;
2612 
2613     // Attempt to avoid multi-use ops if we don't need anything from them.
2614     if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
2615       if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
2616               Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
2617         SDValue NewOp =
2618             TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx);
2619         return TLO.CombineTo(Op, NewOp);
2620       }
2621     }
2622 
2623     Known = Known2;
2624     if (BitWidth > EltBitWidth)
2625       Known = Known.anyext(BitWidth);
2626     break;
2627   }
2628   case ISD::BITCAST: {
2629     if (VT.isScalableVector())
2630       return false;
2631     SDValue Src = Op.getOperand(0);
2632     EVT SrcVT = Src.getValueType();
2633     unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
2634 
2635     // If this is an FP->Int bitcast and if the sign bit is the only
2636     // thing demanded, turn this into a FGETSIGN.
2637     if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
2638         DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
2639         SrcVT.isFloatingPoint()) {
2640       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT);
2641       bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
2642       if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 &&
2643           SrcVT != MVT::f128) {
2644         // Cannot eliminate/lower SHL for f128 yet.
2645         EVT Ty = OpVTLegal ? VT : MVT::i32;
2646         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
2647         // place.  We expect the SHL to be eliminated by other optimizations.
2648         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src);
2649         unsigned OpVTSizeInBits = Op.getValueSizeInBits();
2650         if (!OpVTLegal && OpVTSizeInBits > 32)
2651           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign);
2652         unsigned ShVal = Op.getValueSizeInBits() - 1;
2653         SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT);
2654         return TLO.CombineTo(Op,
2655                              TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
2656       }
2657     }
2658 
2659     // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
2660     // Demand the elt/bit if any of the original elts/bits are demanded.
2661     if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) {
2662       unsigned Scale = BitWidth / NumSrcEltBits;
2663       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2664       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2665       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
2666       for (unsigned i = 0; i != Scale; ++i) {
2667         unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
2668         unsigned BitOffset = EltOffset * NumSrcEltBits;
2669         APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset);
2670         if (!Sub.isZero()) {
2671           DemandedSrcBits |= Sub;
2672           for (unsigned j = 0; j != NumElts; ++j)
2673             if (DemandedElts[j])
2674               DemandedSrcElts.setBit((j * Scale) + i);
2675         }
2676       }
2677 
2678       APInt KnownSrcUndef, KnownSrcZero;
2679       if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2680                                      KnownSrcZero, TLO, Depth + 1))
2681         return true;
2682 
2683       KnownBits KnownSrcBits;
2684       if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2685                                KnownSrcBits, TLO, Depth + 1))
2686         return true;
2687     } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) {
2688       // TODO - bigendian once we have test coverage.
2689       unsigned Scale = NumSrcEltBits / BitWidth;
2690       unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2691       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2692       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
2693       for (unsigned i = 0; i != NumElts; ++i)
2694         if (DemandedElts[i]) {
2695           unsigned Offset = (i % Scale) * BitWidth;
2696           DemandedSrcBits.insertBits(DemandedBits, Offset);
2697           DemandedSrcElts.setBit(i / Scale);
2698         }
2699 
2700       if (SrcVT.isVector()) {
2701         APInt KnownSrcUndef, KnownSrcZero;
2702         if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2703                                        KnownSrcZero, TLO, Depth + 1))
2704           return true;
2705       }
2706 
2707       KnownBits KnownSrcBits;
2708       if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2709                                KnownSrcBits, TLO, Depth + 1))
2710         return true;
2711 
2712       // Attempt to avoid multi-use ops if we don't need anything from them.
2713       if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
2714         if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
2715                 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
2716           SDValue NewOp = TLO.DAG.getBitcast(VT, DemandedSrc);
2717           return TLO.CombineTo(Op, NewOp);
2718         }
2719       }
2720     }
2721 
2722     // If this is a bitcast, let computeKnownBits handle it.  Only do this on a
2723     // recursive call where Known may be useful to the caller.
2724     if (Depth > 0) {
2725       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2726       return false;
2727     }
2728     break;
2729   }
2730   case ISD::MUL:
2731     if (DemandedBits.isPowerOf2()) {
2732       // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
2733       // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
2734       // odd (has LSB set), then the left-shifted low bit of X is the answer.
2735       unsigned CTZ = DemandedBits.countr_zero();
2736       ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
2737       if (C && C->getAPIntValue().countr_zero() == CTZ) {
2738         EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout());
2739         SDValue AmtC = TLO.DAG.getConstant(CTZ, dl, ShiftAmtTy);
2740         SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC);
2741         return TLO.CombineTo(Op, Shl);
2742       }
2743     }
2744     // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
2745     // X * X is odd iff X is odd.
2746     // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
2747     if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) {
2748       SDValue One = TLO.DAG.getConstant(1, dl, VT);
2749       SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One);
2750       return TLO.CombineTo(Op, And1);
2751     }
2752     [[fallthrough]];
2753   case ISD::ADD:
2754   case ISD::SUB: {
2755     // Add, Sub, and Mul don't demand any bits in positions beyond that
2756     // of the highest bit demanded of them.
2757     SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
2758     SDNodeFlags Flags = Op.getNode()->getFlags();
2759     unsigned DemandedBitsLZ = DemandedBits.countl_zero();
2760     APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2761     KnownBits KnownOp0, KnownOp1;
2762     if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, KnownOp0, TLO,
2763                              Depth + 1) ||
2764         SimplifyDemandedBits(Op1, LoMask, DemandedElts, KnownOp1, TLO,
2765                              Depth + 1) ||
2766         // See if the operation should be performed at a smaller bit width.
2767         ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) {
2768       if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
2769         // Disable the nsw and nuw flags. We can no longer guarantee that we
2770         // won't wrap after simplification.
2771         Flags.setNoSignedWrap(false);
2772         Flags.setNoUnsignedWrap(false);
2773         Op->setFlags(Flags);
2774       }
2775       return true;
2776     }
2777 
2778     // neg x with only low bit demanded is simply x.
2779     if (Op.getOpcode() == ISD::SUB && DemandedBits.isOne() &&
2780         isNullConstant(Op0))
2781       return TLO.CombineTo(Op, Op1);
2782 
2783     // Attempt to avoid multi-use ops if we don't need anything from them.
2784     if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2785       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
2786           Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2787       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
2788           Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2789       if (DemandedOp0 || DemandedOp1) {
2790         Flags.setNoSignedWrap(false);
2791         Flags.setNoUnsignedWrap(false);
2792         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
2793         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
2794         SDValue NewOp =
2795             TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
2796         return TLO.CombineTo(Op, NewOp);
2797       }
2798     }
2799 
2800     // If we have a constant operand, we may be able to turn it into -1 if we
2801     // do not demand the high bits. This can make the constant smaller to
2802     // encode, allow more general folding, or match specialized instruction
2803     // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
2804     // is probably not useful (and could be detrimental).
2805     ConstantSDNode *C = isConstOrConstSplat(Op1);
2806     APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
2807     if (C && !C->isAllOnes() && !C->isOne() &&
2808         (C->getAPIntValue() | HighMask).isAllOnes()) {
2809       SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
2810       // Disable the nsw and nuw flags. We can no longer guarantee that we
2811       // won't wrap after simplification.
2812       Flags.setNoSignedWrap(false);
2813       Flags.setNoUnsignedWrap(false);
2814       SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags);
2815       return TLO.CombineTo(Op, NewOp);
2816     }
2817 
2818     // Match a multiply with a disguised negated-power-of-2 and convert to a
2819     // an equivalent shift-left amount.
2820     // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
2821     auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned {
2822       if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse())
2823         return 0;
2824 
2825       // Don't touch opaque constants. Also, ignore zero and power-of-2
2826       // multiplies. Those will get folded later.
2827       ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1));
2828       if (MulC && !MulC->isOpaque() && !MulC->isZero() &&
2829           !MulC->getAPIntValue().isPowerOf2()) {
2830         APInt UnmaskedC = MulC->getAPIntValue() | HighMask;
2831         if (UnmaskedC.isNegatedPowerOf2())
2832           return (-UnmaskedC).logBase2();
2833       }
2834       return 0;
2835     };
2836 
2837     auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y, unsigned ShlAmt) {
2838       EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout());
2839       SDValue ShlAmtC = TLO.DAG.getConstant(ShlAmt, dl, ShiftAmtTy);
2840       SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC);
2841       SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl);
2842       return TLO.CombineTo(Op, Res);
2843     };
2844 
2845     if (isOperationLegalOrCustom(ISD::SHL, VT)) {
2846       if (Op.getOpcode() == ISD::ADD) {
2847         // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
2848         if (unsigned ShAmt = getShiftLeftAmt(Op0))
2849           return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt);
2850         // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC))
2851         if (unsigned ShAmt = getShiftLeftAmt(Op1))
2852           return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt);
2853       }
2854       if (Op.getOpcode() == ISD::SUB) {
2855         // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC))
2856         if (unsigned ShAmt = getShiftLeftAmt(Op1))
2857           return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt);
2858       }
2859     }
2860 
2861     if (Op.getOpcode() == ISD::MUL) {
2862       Known = KnownBits::mul(KnownOp0, KnownOp1);
2863     } else { // Op.getOpcode() is either ISD::ADD or ISD::SUB.
2864       Known = KnownBits::computeForAddSub(Op.getOpcode() == ISD::ADD,
2865                                           Flags.hasNoSignedWrap(), KnownOp0,
2866                                           KnownOp1);
2867     }
2868     break;
2869   }
2870   default:
2871     // We also ask the target about intrinsics (which could be specific to it).
2872     if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2873         Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
2874       // TODO: Probably okay to remove after audit; here to reduce change size
2875       // in initial enablement patch for scalable vectors
2876       if (Op.getValueType().isScalableVector())
2877         break;
2878       if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts,
2879                                             Known, TLO, Depth))
2880         return true;
2881       break;
2882     }
2883 
2884     // Just use computeKnownBits to compute output bits.
2885     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2886     break;
2887   }
2888 
2889   // If we know the value of all of the demanded bits, return this as a
2890   // constant.
2891   if (!isTargetCanonicalConstantNode(Op) &&
2892       DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
2893     // Avoid folding to a constant if any OpaqueConstant is involved.
2894     const SDNode *N = Op.getNode();
2895     for (SDNode *Op :
2896          llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) {
2897       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
2898         if (C->isOpaque())
2899           return false;
2900     }
2901     if (VT.isInteger())
2902       return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
2903     if (VT.isFloatingPoint())
2904       return TLO.CombineTo(
2905           Op,
2906           TLO.DAG.getConstantFP(
2907               APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT));
2908   }
2909 
2910   // A multi use 'all demanded elts' simplify failed to find any knownbits.
2911   // Try again just for the original demanded elts.
2912   // Ensure we do this AFTER constant folding above.
2913   if (HasMultiUse && Known.isUnknown() && !OriginalDemandedElts.isAllOnes())
2914     Known = TLO.DAG.computeKnownBits(Op, OriginalDemandedElts, Depth);
2915 
2916   return false;
2917 }
2918 
2919 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op,
2920                                                 const APInt &DemandedElts,
2921                                                 DAGCombinerInfo &DCI) const {
2922   SelectionDAG &DAG = DCI.DAG;
2923   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
2924                         !DCI.isBeforeLegalizeOps());
2925 
2926   APInt KnownUndef, KnownZero;
2927   bool Simplified =
2928       SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
2929   if (Simplified) {
2930     DCI.AddToWorklist(Op.getNode());
2931     DCI.CommitTargetLoweringOpt(TLO);
2932   }
2933 
2934   return Simplified;
2935 }
2936 
2937 /// Given a vector binary operation and known undefined elements for each input
2938 /// operand, compute whether each element of the output is undefined.
2939 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG,
2940                                          const APInt &UndefOp0,
2941                                          const APInt &UndefOp1) {
2942   EVT VT = BO.getValueType();
2943   assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() &&
2944          "Vector binop only");
2945 
2946   EVT EltVT = VT.getVectorElementType();
2947   unsigned NumElts = VT.isFixedLengthVector() ? VT.getVectorNumElements() : 1;
2948   assert(UndefOp0.getBitWidth() == NumElts &&
2949          UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
2950 
2951   auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
2952                                    const APInt &UndefVals) {
2953     if (UndefVals[Index])
2954       return DAG.getUNDEF(EltVT);
2955 
2956     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2957       // Try hard to make sure that the getNode() call is not creating temporary
2958       // nodes. Ignore opaque integers because they do not constant fold.
2959       SDValue Elt = BV->getOperand(Index);
2960       auto *C = dyn_cast<ConstantSDNode>(Elt);
2961       if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
2962         return Elt;
2963     }
2964 
2965     return SDValue();
2966   };
2967 
2968   APInt KnownUndef = APInt::getZero(NumElts);
2969   for (unsigned i = 0; i != NumElts; ++i) {
2970     // If both inputs for this element are either constant or undef and match
2971     // the element type, compute the constant/undef result for this element of
2972     // the vector.
2973     // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
2974     // not handle FP constants. The code within getNode() should be refactored
2975     // to avoid the danger of creating a bogus temporary node here.
2976     SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
2977     SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
2978     if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
2979       if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
2980         KnownUndef.setBit(i);
2981   }
2982   return KnownUndef;
2983 }
2984 
2985 bool TargetLowering::SimplifyDemandedVectorElts(
2986     SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
2987     APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
2988     bool AssumeSingleUse) const {
2989   EVT VT = Op.getValueType();
2990   unsigned Opcode = Op.getOpcode();
2991   APInt DemandedElts = OriginalDemandedElts;
2992   unsigned NumElts = DemandedElts.getBitWidth();
2993   assert(VT.isVector() && "Expected vector op");
2994 
2995   KnownUndef = KnownZero = APInt::getZero(NumElts);
2996 
2997   const TargetLowering &TLI = TLO.DAG.getTargetLoweringInfo();
2998   if (!TLI.shouldSimplifyDemandedVectorElts(Op, TLO))
2999     return false;
3000 
3001   // TODO: For now we assume we know nothing about scalable vectors.
3002   if (VT.isScalableVector())
3003     return false;
3004 
3005   assert(VT.getVectorNumElements() == NumElts &&
3006          "Mask size mismatches value type element count!");
3007 
3008   // Undef operand.
3009   if (Op.isUndef()) {
3010     KnownUndef.setAllBits();
3011     return false;
3012   }
3013 
3014   // If Op has other users, assume that all elements are needed.
3015   if (!AssumeSingleUse && !Op.getNode()->hasOneUse())
3016     DemandedElts.setAllBits();
3017 
3018   // Not demanding any elements from Op.
3019   if (DemandedElts == 0) {
3020     KnownUndef.setAllBits();
3021     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3022   }
3023 
3024   // Limit search depth.
3025   if (Depth >= SelectionDAG::MaxRecursionDepth)
3026     return false;
3027 
3028   SDLoc DL(Op);
3029   unsigned EltSizeInBits = VT.getScalarSizeInBits();
3030   bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
3031 
3032   // Helper for demanding the specified elements and all the bits of both binary
3033   // operands.
3034   auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) {
3035     SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts,
3036                                                            TLO.DAG, Depth + 1);
3037     SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts,
3038                                                            TLO.DAG, Depth + 1);
3039     if (NewOp0 || NewOp1) {
3040       SDValue NewOp =
3041           TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0,
3042                           NewOp1 ? NewOp1 : Op1, Op->getFlags());
3043       return TLO.CombineTo(Op, NewOp);
3044     }
3045     return false;
3046   };
3047 
3048   switch (Opcode) {
3049   case ISD::SCALAR_TO_VECTOR: {
3050     if (!DemandedElts[0]) {
3051       KnownUndef.setAllBits();
3052       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3053     }
3054     SDValue ScalarSrc = Op.getOperand(0);
3055     if (ScalarSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
3056       SDValue Src = ScalarSrc.getOperand(0);
3057       SDValue Idx = ScalarSrc.getOperand(1);
3058       EVT SrcVT = Src.getValueType();
3059 
3060       ElementCount SrcEltCnt = SrcVT.getVectorElementCount();
3061 
3062       if (SrcEltCnt.isScalable())
3063         return false;
3064 
3065       unsigned NumSrcElts = SrcEltCnt.getFixedValue();
3066       if (isNullConstant(Idx)) {
3067         APInt SrcDemandedElts = APInt::getOneBitSet(NumSrcElts, 0);
3068         APInt SrcUndef = KnownUndef.zextOrTrunc(NumSrcElts);
3069         APInt SrcZero = KnownZero.zextOrTrunc(NumSrcElts);
3070         if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3071                                        TLO, Depth + 1))
3072           return true;
3073       }
3074     }
3075     KnownUndef.setHighBits(NumElts - 1);
3076     break;
3077   }
3078   case ISD::BITCAST: {
3079     SDValue Src = Op.getOperand(0);
3080     EVT SrcVT = Src.getValueType();
3081 
3082     // We only handle vectors here.
3083     // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits?
3084     if (!SrcVT.isVector())
3085       break;
3086 
3087     // Fast handling of 'identity' bitcasts.
3088     unsigned NumSrcElts = SrcVT.getVectorNumElements();
3089     if (NumSrcElts == NumElts)
3090       return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
3091                                         KnownZero, TLO, Depth + 1);
3092 
3093     APInt SrcDemandedElts, SrcZero, SrcUndef;
3094 
3095     // Bitcast from 'large element' src vector to 'small element' vector, we
3096     // must demand a source element if any DemandedElt maps to it.
3097     if ((NumElts % NumSrcElts) == 0) {
3098       unsigned Scale = NumElts / NumSrcElts;
3099       SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3100       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3101                                      TLO, Depth + 1))
3102         return true;
3103 
3104       // Try calling SimplifyDemandedBits, converting demanded elts to the bits
3105       // of the large element.
3106       // TODO - bigendian once we have test coverage.
3107       if (IsLE) {
3108         unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
3109         APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits);
3110         for (unsigned i = 0; i != NumElts; ++i)
3111           if (DemandedElts[i]) {
3112             unsigned Ofs = (i % Scale) * EltSizeInBits;
3113             SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
3114           }
3115 
3116         KnownBits Known;
3117         if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known,
3118                                  TLO, Depth + 1))
3119           return true;
3120 
3121         // The bitcast has split each wide element into a number of
3122         // narrow subelements. We have just computed the Known bits
3123         // for wide elements. See if element splitting results in
3124         // some subelements being zero. Only for demanded elements!
3125         for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) {
3126           if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits)
3127                    .isAllOnes())
3128             continue;
3129           for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) {
3130             unsigned Elt = Scale * SrcElt + SubElt;
3131             if (DemandedElts[Elt])
3132               KnownZero.setBit(Elt);
3133           }
3134         }
3135       }
3136 
3137       // If the src element is zero/undef then all the output elements will be -
3138       // only demanded elements are guaranteed to be correct.
3139       for (unsigned i = 0; i != NumSrcElts; ++i) {
3140         if (SrcDemandedElts[i]) {
3141           if (SrcZero[i])
3142             KnownZero.setBits(i * Scale, (i + 1) * Scale);
3143           if (SrcUndef[i])
3144             KnownUndef.setBits(i * Scale, (i + 1) * Scale);
3145         }
3146       }
3147     }
3148 
3149     // Bitcast from 'small element' src vector to 'large element' vector, we
3150     // demand all smaller source elements covered by the larger demanded element
3151     // of this vector.
3152     if ((NumSrcElts % NumElts) == 0) {
3153       unsigned Scale = NumSrcElts / NumElts;
3154       SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3155       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3156                                      TLO, Depth + 1))
3157         return true;
3158 
3159       // If all the src elements covering an output element are zero/undef, then
3160       // the output element will be as well, assuming it was demanded.
3161       for (unsigned i = 0; i != NumElts; ++i) {
3162         if (DemandedElts[i]) {
3163           if (SrcZero.extractBits(Scale, i * Scale).isAllOnes())
3164             KnownZero.setBit(i);
3165           if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes())
3166             KnownUndef.setBit(i);
3167         }
3168       }
3169     }
3170     break;
3171   }
3172   case ISD::BUILD_VECTOR: {
3173     // Check all elements and simplify any unused elements with UNDEF.
3174     if (!DemandedElts.isAllOnes()) {
3175       // Don't simplify BROADCASTS.
3176       if (llvm::any_of(Op->op_values(),
3177                        [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
3178         SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end());
3179         bool Updated = false;
3180         for (unsigned i = 0; i != NumElts; ++i) {
3181           if (!DemandedElts[i] && !Ops[i].isUndef()) {
3182             Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
3183             KnownUndef.setBit(i);
3184             Updated = true;
3185           }
3186         }
3187         if (Updated)
3188           return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
3189       }
3190     }
3191     for (unsigned i = 0; i != NumElts; ++i) {
3192       SDValue SrcOp = Op.getOperand(i);
3193       if (SrcOp.isUndef()) {
3194         KnownUndef.setBit(i);
3195       } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
3196                  (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) {
3197         KnownZero.setBit(i);
3198       }
3199     }
3200     break;
3201   }
3202   case ISD::CONCAT_VECTORS: {
3203     EVT SubVT = Op.getOperand(0).getValueType();
3204     unsigned NumSubVecs = Op.getNumOperands();
3205     unsigned NumSubElts = SubVT.getVectorNumElements();
3206     for (unsigned i = 0; i != NumSubVecs; ++i) {
3207       SDValue SubOp = Op.getOperand(i);
3208       APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3209       APInt SubUndef, SubZero;
3210       if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
3211                                      Depth + 1))
3212         return true;
3213       KnownUndef.insertBits(SubUndef, i * NumSubElts);
3214       KnownZero.insertBits(SubZero, i * NumSubElts);
3215     }
3216 
3217     // Attempt to avoid multi-use ops if we don't need anything from them.
3218     if (!DemandedElts.isAllOnes()) {
3219       bool FoundNewSub = false;
3220       SmallVector<SDValue, 2> DemandedSubOps;
3221       for (unsigned i = 0; i != NumSubVecs; ++i) {
3222         SDValue SubOp = Op.getOperand(i);
3223         APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3224         SDValue NewSubOp = SimplifyMultipleUseDemandedVectorElts(
3225             SubOp, SubElts, TLO.DAG, Depth + 1);
3226         DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp);
3227         FoundNewSub = NewSubOp ? true : FoundNewSub;
3228       }
3229       if (FoundNewSub) {
3230         SDValue NewOp =
3231             TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps);
3232         return TLO.CombineTo(Op, NewOp);
3233       }
3234     }
3235     break;
3236   }
3237   case ISD::INSERT_SUBVECTOR: {
3238     // Demand any elements from the subvector and the remainder from the src its
3239     // inserted into.
3240     SDValue Src = Op.getOperand(0);
3241     SDValue Sub = Op.getOperand(1);
3242     uint64_t Idx = Op.getConstantOperandVal(2);
3243     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3244     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3245     APInt DemandedSrcElts = DemandedElts;
3246     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3247 
3248     APInt SubUndef, SubZero;
3249     if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
3250                                    Depth + 1))
3251       return true;
3252 
3253     // If none of the src operand elements are demanded, replace it with undef.
3254     if (!DemandedSrcElts && !Src.isUndef())
3255       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
3256                                                TLO.DAG.getUNDEF(VT), Sub,
3257                                                Op.getOperand(2)));
3258 
3259     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
3260                                    TLO, Depth + 1))
3261       return true;
3262     KnownUndef.insertBits(SubUndef, Idx);
3263     KnownZero.insertBits(SubZero, Idx);
3264 
3265     // Attempt to avoid multi-use ops if we don't need anything from them.
3266     if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) {
3267       SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
3268           Src, DemandedSrcElts, TLO.DAG, Depth + 1);
3269       SDValue NewSub = SimplifyMultipleUseDemandedVectorElts(
3270           Sub, DemandedSubElts, TLO.DAG, Depth + 1);
3271       if (NewSrc || NewSub) {
3272         NewSrc = NewSrc ? NewSrc : Src;
3273         NewSub = NewSub ? NewSub : Sub;
3274         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3275                                         NewSub, Op.getOperand(2));
3276         return TLO.CombineTo(Op, NewOp);
3277       }
3278     }
3279     break;
3280   }
3281   case ISD::EXTRACT_SUBVECTOR: {
3282     // Offset the demanded elts by the subvector index.
3283     SDValue Src = Op.getOperand(0);
3284     if (Src.getValueType().isScalableVector())
3285       break;
3286     uint64_t Idx = Op.getConstantOperandVal(1);
3287     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3288     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3289 
3290     APInt SrcUndef, SrcZero;
3291     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3292                                    Depth + 1))
3293       return true;
3294     KnownUndef = SrcUndef.extractBits(NumElts, Idx);
3295     KnownZero = SrcZero.extractBits(NumElts, Idx);
3296 
3297     // Attempt to avoid multi-use ops if we don't need anything from them.
3298     if (!DemandedElts.isAllOnes()) {
3299       SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
3300           Src, DemandedSrcElts, TLO.DAG, Depth + 1);
3301       if (NewSrc) {
3302         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3303                                         Op.getOperand(1));
3304         return TLO.CombineTo(Op, NewOp);
3305       }
3306     }
3307     break;
3308   }
3309   case ISD::INSERT_VECTOR_ELT: {
3310     SDValue Vec = Op.getOperand(0);
3311     SDValue Scl = Op.getOperand(1);
3312     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3313 
3314     // For a legal, constant insertion index, if we don't need this insertion
3315     // then strip it, else remove it from the demanded elts.
3316     if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
3317       unsigned Idx = CIdx->getZExtValue();
3318       if (!DemandedElts[Idx])
3319         return TLO.CombineTo(Op, Vec);
3320 
3321       APInt DemandedVecElts(DemandedElts);
3322       DemandedVecElts.clearBit(Idx);
3323       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
3324                                      KnownZero, TLO, Depth + 1))
3325         return true;
3326 
3327       KnownUndef.setBitVal(Idx, Scl.isUndef());
3328 
3329       KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl));
3330       break;
3331     }
3332 
3333     APInt VecUndef, VecZero;
3334     if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
3335                                    Depth + 1))
3336       return true;
3337     // Without knowing the insertion index we can't set KnownUndef/KnownZero.
3338     break;
3339   }
3340   case ISD::VSELECT: {
3341     SDValue Sel = Op.getOperand(0);
3342     SDValue LHS = Op.getOperand(1);
3343     SDValue RHS = Op.getOperand(2);
3344 
3345     // Try to transform the select condition based on the current demanded
3346     // elements.
3347     APInt UndefSel, UndefZero;
3348     if (SimplifyDemandedVectorElts(Sel, DemandedElts, UndefSel, UndefZero, TLO,
3349                                    Depth + 1))
3350       return true;
3351 
3352     // See if we can simplify either vselect operand.
3353     APInt DemandedLHS(DemandedElts);
3354     APInt DemandedRHS(DemandedElts);
3355     APInt UndefLHS, ZeroLHS;
3356     APInt UndefRHS, ZeroRHS;
3357     if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3358                                    Depth + 1))
3359       return true;
3360     if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3361                                    Depth + 1))
3362       return true;
3363 
3364     KnownUndef = UndefLHS & UndefRHS;
3365     KnownZero = ZeroLHS & ZeroRHS;
3366 
3367     // If we know that the selected element is always zero, we don't need the
3368     // select value element.
3369     APInt DemandedSel = DemandedElts & ~KnownZero;
3370     if (DemandedSel != DemandedElts)
3371       if (SimplifyDemandedVectorElts(Sel, DemandedSel, UndefSel, UndefZero, TLO,
3372                                      Depth + 1))
3373         return true;
3374 
3375     break;
3376   }
3377   case ISD::VECTOR_SHUFFLE: {
3378     SDValue LHS = Op.getOperand(0);
3379     SDValue RHS = Op.getOperand(1);
3380     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
3381 
3382     // Collect demanded elements from shuffle operands..
3383     APInt DemandedLHS(NumElts, 0);
3384     APInt DemandedRHS(NumElts, 0);
3385     for (unsigned i = 0; i != NumElts; ++i) {
3386       int M = ShuffleMask[i];
3387       if (M < 0 || !DemandedElts[i])
3388         continue;
3389       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
3390       if (M < (int)NumElts)
3391         DemandedLHS.setBit(M);
3392       else
3393         DemandedRHS.setBit(M - NumElts);
3394     }
3395 
3396     // See if we can simplify either shuffle operand.
3397     APInt UndefLHS, ZeroLHS;
3398     APInt UndefRHS, ZeroRHS;
3399     if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3400                                    Depth + 1))
3401       return true;
3402     if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3403                                    Depth + 1))
3404       return true;
3405 
3406     // Simplify mask using undef elements from LHS/RHS.
3407     bool Updated = false;
3408     bool IdentityLHS = true, IdentityRHS = true;
3409     SmallVector<int, 32> NewMask(ShuffleMask);
3410     for (unsigned i = 0; i != NumElts; ++i) {
3411       int &M = NewMask[i];
3412       if (M < 0)
3413         continue;
3414       if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
3415           (M >= (int)NumElts && UndefRHS[M - NumElts])) {
3416         Updated = true;
3417         M = -1;
3418       }
3419       IdentityLHS &= (M < 0) || (M == (int)i);
3420       IdentityRHS &= (M < 0) || ((M - NumElts) == i);
3421     }
3422 
3423     // Update legal shuffle masks based on demanded elements if it won't reduce
3424     // to Identity which can cause premature removal of the shuffle mask.
3425     if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
3426       SDValue LegalShuffle =
3427           buildLegalVectorShuffle(VT, DL, LHS, RHS, NewMask, TLO.DAG);
3428       if (LegalShuffle)
3429         return TLO.CombineTo(Op, LegalShuffle);
3430     }
3431 
3432     // Propagate undef/zero elements from LHS/RHS.
3433     for (unsigned i = 0; i != NumElts; ++i) {
3434       int M = ShuffleMask[i];
3435       if (M < 0) {
3436         KnownUndef.setBit(i);
3437       } else if (M < (int)NumElts) {
3438         if (UndefLHS[M])
3439           KnownUndef.setBit(i);
3440         if (ZeroLHS[M])
3441           KnownZero.setBit(i);
3442       } else {
3443         if (UndefRHS[M - NumElts])
3444           KnownUndef.setBit(i);
3445         if (ZeroRHS[M - NumElts])
3446           KnownZero.setBit(i);
3447       }
3448     }
3449     break;
3450   }
3451   case ISD::ANY_EXTEND_VECTOR_INREG:
3452   case ISD::SIGN_EXTEND_VECTOR_INREG:
3453   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3454     APInt SrcUndef, SrcZero;
3455     SDValue Src = Op.getOperand(0);
3456     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3457     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3458     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3459                                    Depth + 1))
3460       return true;
3461     KnownZero = SrcZero.zextOrTrunc(NumElts);
3462     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
3463 
3464     if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
3465         Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
3466         DemandedSrcElts == 1) {
3467       // aext - if we just need the bottom element then we can bitcast.
3468       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
3469     }
3470 
3471     if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
3472       // zext(undef) upper bits are guaranteed to be zero.
3473       if (DemandedElts.isSubsetOf(KnownUndef))
3474         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3475       KnownUndef.clearAllBits();
3476 
3477       // zext - if we just need the bottom element then we can mask:
3478       // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and.
3479       if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND &&
3480           Op->isOnlyUserOf(Src.getNode()) &&
3481           Op.getValueSizeInBits() == Src.getValueSizeInBits()) {
3482         SDLoc DL(Op);
3483         EVT SrcVT = Src.getValueType();
3484         EVT SrcSVT = SrcVT.getScalarType();
3485         SmallVector<SDValue> MaskElts;
3486         MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT));
3487         MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT));
3488         SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts);
3489         if (SDValue Fold = TLO.DAG.FoldConstantArithmetic(
3490                 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) {
3491           Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold);
3492           return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold));
3493         }
3494       }
3495     }
3496     break;
3497   }
3498 
3499   // TODO: There are more binop opcodes that could be handled here - MIN,
3500   // MAX, saturated math, etc.
3501   case ISD::ADD: {
3502     SDValue Op0 = Op.getOperand(0);
3503     SDValue Op1 = Op.getOperand(1);
3504     if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) {
3505       APInt UndefLHS, ZeroLHS;
3506       if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3507                                      Depth + 1, /*AssumeSingleUse*/ true))
3508         return true;
3509     }
3510     [[fallthrough]];
3511   }
3512   case ISD::OR:
3513   case ISD::XOR:
3514   case ISD::SUB:
3515   case ISD::FADD:
3516   case ISD::FSUB:
3517   case ISD::FMUL:
3518   case ISD::FDIV:
3519   case ISD::FREM: {
3520     SDValue Op0 = Op.getOperand(0);
3521     SDValue Op1 = Op.getOperand(1);
3522 
3523     APInt UndefRHS, ZeroRHS;
3524     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3525                                    Depth + 1))
3526       return true;
3527     APInt UndefLHS, ZeroLHS;
3528     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3529                                    Depth + 1))
3530       return true;
3531 
3532     KnownZero = ZeroLHS & ZeroRHS;
3533     KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
3534 
3535     // Attempt to avoid multi-use ops if we don't need anything from them.
3536     // TODO - use KnownUndef to relax the demandedelts?
3537     if (!DemandedElts.isAllOnes())
3538       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3539         return true;
3540     break;
3541   }
3542   case ISD::SHL:
3543   case ISD::SRL:
3544   case ISD::SRA:
3545   case ISD::ROTL:
3546   case ISD::ROTR: {
3547     SDValue Op0 = Op.getOperand(0);
3548     SDValue Op1 = Op.getOperand(1);
3549 
3550     APInt UndefRHS, ZeroRHS;
3551     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3552                                    Depth + 1))
3553       return true;
3554     APInt UndefLHS, ZeroLHS;
3555     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3556                                    Depth + 1))
3557       return true;
3558 
3559     KnownZero = ZeroLHS;
3560     KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
3561 
3562     // Attempt to avoid multi-use ops if we don't need anything from them.
3563     // TODO - use KnownUndef to relax the demandedelts?
3564     if (!DemandedElts.isAllOnes())
3565       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3566         return true;
3567     break;
3568   }
3569   case ISD::MUL:
3570   case ISD::MULHU:
3571   case ISD::MULHS:
3572   case ISD::AND: {
3573     SDValue Op0 = Op.getOperand(0);
3574     SDValue Op1 = Op.getOperand(1);
3575 
3576     APInt SrcUndef, SrcZero;
3577     if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
3578                                    Depth + 1))
3579       return true;
3580     // If we know that a demanded element was zero in Op1 we don't need to
3581     // demand it in Op0 - its guaranteed to be zero.
3582     APInt DemandedElts0 = DemandedElts & ~SrcZero;
3583     if (SimplifyDemandedVectorElts(Op0, DemandedElts0, KnownUndef, KnownZero,
3584                                    TLO, Depth + 1))
3585       return true;
3586 
3587     KnownUndef &= DemandedElts0;
3588     KnownZero &= DemandedElts0;
3589 
3590     // If every element pair has a zero/undef then just fold to zero.
3591     // fold (and x, undef) -> 0  /  (and x, 0) -> 0
3592     // fold (mul x, undef) -> 0  /  (mul x, 0) -> 0
3593     if (DemandedElts.isSubsetOf(SrcZero | KnownZero | SrcUndef | KnownUndef))
3594       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3595 
3596     // If either side has a zero element, then the result element is zero, even
3597     // if the other is an UNDEF.
3598     // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
3599     // and then handle 'and' nodes with the rest of the binop opcodes.
3600     KnownZero |= SrcZero;
3601     KnownUndef &= SrcUndef;
3602     KnownUndef &= ~KnownZero;
3603 
3604     // Attempt to avoid multi-use ops if we don't need anything from them.
3605     if (!DemandedElts.isAllOnes())
3606       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3607         return true;
3608     break;
3609   }
3610   case ISD::TRUNCATE:
3611   case ISD::SIGN_EXTEND:
3612   case ISD::ZERO_EXTEND:
3613     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
3614                                    KnownZero, TLO, Depth + 1))
3615       return true;
3616 
3617     if (Op.getOpcode() == ISD::ZERO_EXTEND) {
3618       // zext(undef) upper bits are guaranteed to be zero.
3619       if (DemandedElts.isSubsetOf(KnownUndef))
3620         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3621       KnownUndef.clearAllBits();
3622     }
3623     break;
3624   default: {
3625     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
3626       if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
3627                                                   KnownZero, TLO, Depth))
3628         return true;
3629     } else {
3630       KnownBits Known;
3631       APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
3632       if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
3633                                TLO, Depth, AssumeSingleUse))
3634         return true;
3635     }
3636     break;
3637   }
3638   }
3639   assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
3640 
3641   // Constant fold all undef cases.
3642   // TODO: Handle zero cases as well.
3643   if (DemandedElts.isSubsetOf(KnownUndef))
3644     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3645 
3646   return false;
3647 }
3648 
3649 /// Determine which of the bits specified in Mask are known to be either zero or
3650 /// one and return them in the Known.
3651 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
3652                                                    KnownBits &Known,
3653                                                    const APInt &DemandedElts,
3654                                                    const SelectionDAG &DAG,
3655                                                    unsigned Depth) const {
3656   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3657           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3658           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3659           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3660          "Should use MaskedValueIsZero if you don't know whether Op"
3661          " is a target node!");
3662   Known.resetAll();
3663 }
3664 
3665 void TargetLowering::computeKnownBitsForTargetInstr(
3666     GISelKnownBits &Analysis, Register R, KnownBits &Known,
3667     const APInt &DemandedElts, const MachineRegisterInfo &MRI,
3668     unsigned Depth) const {
3669   Known.resetAll();
3670 }
3671 
3672 void TargetLowering::computeKnownBitsForFrameIndex(
3673   const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const {
3674   // The low bits are known zero if the pointer is aligned.
3675   Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx)));
3676 }
3677 
3678 Align TargetLowering::computeKnownAlignForTargetInstr(
3679   GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI,
3680   unsigned Depth) const {
3681   return Align(1);
3682 }
3683 
3684 /// This method can be implemented by targets that want to expose additional
3685 /// information about sign bits to the DAG Combiner.
3686 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
3687                                                          const APInt &,
3688                                                          const SelectionDAG &,
3689                                                          unsigned Depth) const {
3690   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3691           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3692           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3693           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3694          "Should use ComputeNumSignBits if you don't know whether Op"
3695          " is a target node!");
3696   return 1;
3697 }
3698 
3699 unsigned TargetLowering::computeNumSignBitsForTargetInstr(
3700   GISelKnownBits &Analysis, Register R, const APInt &DemandedElts,
3701   const MachineRegisterInfo &MRI, unsigned Depth) const {
3702   return 1;
3703 }
3704 
3705 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
3706     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
3707     TargetLoweringOpt &TLO, unsigned Depth) const {
3708   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3709           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3710           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3711           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3712          "Should use SimplifyDemandedVectorElts if you don't know whether Op"
3713          " is a target node!");
3714   return false;
3715 }
3716 
3717 bool TargetLowering::SimplifyDemandedBitsForTargetNode(
3718     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3719     KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
3720   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3721           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3722           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3723           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3724          "Should use SimplifyDemandedBits if you don't know whether Op"
3725          " is a target node!");
3726   computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
3727   return false;
3728 }
3729 
3730 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
3731     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3732     SelectionDAG &DAG, unsigned Depth) const {
3733   assert(
3734       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3735        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3736        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3737        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3738       "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
3739       " is a target node!");
3740   return SDValue();
3741 }
3742 
3743 SDValue
3744 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0,
3745                                         SDValue N1, MutableArrayRef<int> Mask,
3746                                         SelectionDAG &DAG) const {
3747   bool LegalMask = isShuffleMaskLegal(Mask, VT);
3748   if (!LegalMask) {
3749     std::swap(N0, N1);
3750     ShuffleVectorSDNode::commuteMask(Mask);
3751     LegalMask = isShuffleMaskLegal(Mask, VT);
3752   }
3753 
3754   if (!LegalMask)
3755     return SDValue();
3756 
3757   return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
3758 }
3759 
3760 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const {
3761   return nullptr;
3762 }
3763 
3764 bool TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode(
3765     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
3766     bool PoisonOnly, unsigned Depth) const {
3767   assert(
3768       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3769        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3770        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3771        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3772       "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op"
3773       " is a target node!");
3774   return false;
3775 }
3776 
3777 bool TargetLowering::canCreateUndefOrPoisonForTargetNode(
3778     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
3779     bool PoisonOnly, bool ConsiderFlags, unsigned Depth) const {
3780   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3781           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3782           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3783           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3784          "Should use canCreateUndefOrPoison if you don't know whether Op"
3785          " is a target node!");
3786   // Be conservative and return true.
3787   return true;
3788 }
3789 
3790 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
3791                                                   const SelectionDAG &DAG,
3792                                                   bool SNaN,
3793                                                   unsigned Depth) const {
3794   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3795           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3796           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3797           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3798          "Should use isKnownNeverNaN if you don't know whether Op"
3799          " is a target node!");
3800   return false;
3801 }
3802 
3803 bool TargetLowering::isSplatValueForTargetNode(SDValue Op,
3804                                                const APInt &DemandedElts,
3805                                                APInt &UndefElts,
3806                                                const SelectionDAG &DAG,
3807                                                unsigned Depth) const {
3808   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3809           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3810           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3811           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3812          "Should use isSplatValue if you don't know whether Op"
3813          " is a target node!");
3814   return false;
3815 }
3816 
3817 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
3818 // work with truncating build vectors and vectors with elements of less than
3819 // 8 bits.
3820 bool TargetLowering::isConstTrueVal(SDValue N) const {
3821   if (!N)
3822     return false;
3823 
3824   unsigned EltWidth;
3825   APInt CVal;
3826   if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false,
3827                                                /*AllowTruncation=*/true)) {
3828     CVal = CN->getAPIntValue();
3829     EltWidth = N.getValueType().getScalarSizeInBits();
3830   } else
3831     return false;
3832 
3833   // If this is a truncating splat, truncate the splat value.
3834   // Otherwise, we may fail to match the expected values below.
3835   if (EltWidth < CVal.getBitWidth())
3836     CVal = CVal.trunc(EltWidth);
3837 
3838   switch (getBooleanContents(N.getValueType())) {
3839   case UndefinedBooleanContent:
3840     return CVal[0];
3841   case ZeroOrOneBooleanContent:
3842     return CVal.isOne();
3843   case ZeroOrNegativeOneBooleanContent:
3844     return CVal.isAllOnes();
3845   }
3846 
3847   llvm_unreachable("Invalid boolean contents");
3848 }
3849 
3850 bool TargetLowering::isConstFalseVal(SDValue N) const {
3851   if (!N)
3852     return false;
3853 
3854   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
3855   if (!CN) {
3856     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
3857     if (!BV)
3858       return false;
3859 
3860     // Only interested in constant splats, we don't care about undef
3861     // elements in identifying boolean constants and getConstantSplatNode
3862     // returns NULL if all ops are undef;
3863     CN = BV->getConstantSplatNode();
3864     if (!CN)
3865       return false;
3866   }
3867 
3868   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
3869     return !CN->getAPIntValue()[0];
3870 
3871   return CN->isZero();
3872 }
3873 
3874 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
3875                                        bool SExt) const {
3876   if (VT == MVT::i1)
3877     return N->isOne();
3878 
3879   TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
3880   switch (Cnt) {
3881   case TargetLowering::ZeroOrOneBooleanContent:
3882     // An extended value of 1 is always true, unless its original type is i1,
3883     // in which case it will be sign extended to -1.
3884     return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
3885   case TargetLowering::UndefinedBooleanContent:
3886   case TargetLowering::ZeroOrNegativeOneBooleanContent:
3887     return N->isAllOnes() && SExt;
3888   }
3889   llvm_unreachable("Unexpected enumeration.");
3890 }
3891 
3892 /// This helper function of SimplifySetCC tries to optimize the comparison when
3893 /// either operand of the SetCC node is a bitwise-and instruction.
3894 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
3895                                          ISD::CondCode Cond, const SDLoc &DL,
3896                                          DAGCombinerInfo &DCI) const {
3897   if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
3898     std::swap(N0, N1);
3899 
3900   SelectionDAG &DAG = DCI.DAG;
3901   EVT OpVT = N0.getValueType();
3902   if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
3903       (Cond != ISD::SETEQ && Cond != ISD::SETNE))
3904     return SDValue();
3905 
3906   // (X & Y) != 0 --> zextOrTrunc(X & Y)
3907   // iff everything but LSB is known zero:
3908   if (Cond == ISD::SETNE && isNullConstant(N1) &&
3909       (getBooleanContents(OpVT) == TargetLowering::UndefinedBooleanContent ||
3910        getBooleanContents(OpVT) == TargetLowering::ZeroOrOneBooleanContent)) {
3911     unsigned NumEltBits = OpVT.getScalarSizeInBits();
3912     APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1);
3913     if (DAG.MaskedValueIsZero(N0, UpperBits))
3914       return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT);
3915   }
3916 
3917   // Try to eliminate a power-of-2 mask constant by converting to a signbit
3918   // test in a narrow type that we can truncate to with no cost. Examples:
3919   // (i32 X & 32768) == 0 --> (trunc X to i16) >= 0
3920   // (i32 X & 32768) != 0 --> (trunc X to i16) < 0
3921   // TODO: This conservatively checks for type legality on the source and
3922   //       destination types. That may inhibit optimizations, but it also
3923   //       allows setcc->shift transforms that may be more beneficial.
3924   auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3925   if (AndC && isNullConstant(N1) && AndC->getAPIntValue().isPowerOf2() &&
3926       isTypeLegal(OpVT) && N0.hasOneUse()) {
3927     EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(),
3928                                      AndC->getAPIntValue().getActiveBits());
3929     if (isTruncateFree(OpVT, NarrowVT) && isTypeLegal(NarrowVT)) {
3930       SDValue Trunc = DAG.getZExtOrTrunc(N0.getOperand(0), DL, NarrowVT);
3931       SDValue Zero = DAG.getConstant(0, DL, NarrowVT);
3932       return DAG.getSetCC(DL, VT, Trunc, Zero,
3933                           Cond == ISD::SETEQ ? ISD::SETGE : ISD::SETLT);
3934     }
3935   }
3936 
3937   // Match these patterns in any of their permutations:
3938   // (X & Y) == Y
3939   // (X & Y) != Y
3940   SDValue X, Y;
3941   if (N0.getOperand(0) == N1) {
3942     X = N0.getOperand(1);
3943     Y = N0.getOperand(0);
3944   } else if (N0.getOperand(1) == N1) {
3945     X = N0.getOperand(0);
3946     Y = N0.getOperand(1);
3947   } else {
3948     return SDValue();
3949   }
3950 
3951   // TODO: We should invert (X & Y) eq/ne 0 -> (X & Y) ne/eq Y if
3952   // `isXAndYEqZeroPreferableToXAndYEqY` is false. This is a bit difficult as
3953   // its liable to create and infinite loop.
3954   SDValue Zero = DAG.getConstant(0, DL, OpVT);
3955   if (isXAndYEqZeroPreferableToXAndYEqY(Cond, OpVT) &&
3956       DAG.isKnownToBeAPowerOfTwo(Y)) {
3957     // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
3958     // Note that where Y is variable and is known to have at most one bit set
3959     // (for example, if it is Z & 1) we cannot do this; the expressions are not
3960     // equivalent when Y == 0.
3961     assert(OpVT.isInteger());
3962     Cond = ISD::getSetCCInverse(Cond, OpVT);
3963     if (DCI.isBeforeLegalizeOps() ||
3964         isCondCodeLegal(Cond, N0.getSimpleValueType()))
3965       return DAG.getSetCC(DL, VT, N0, Zero, Cond);
3966   } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
3967     // If the target supports an 'and-not' or 'and-complement' logic operation,
3968     // try to use that to make a comparison operation more efficient.
3969     // But don't do this transform if the mask is a single bit because there are
3970     // more efficient ways to deal with that case (for example, 'bt' on x86 or
3971     // 'rlwinm' on PPC).
3972 
3973     // Bail out if the compare operand that we want to turn into a zero is
3974     // already a zero (otherwise, infinite loop).
3975     if (isNullConstant(Y))
3976       return SDValue();
3977 
3978     // Transform this into: ~X & Y == 0.
3979     SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
3980     SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
3981     return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
3982   }
3983 
3984   return SDValue();
3985 }
3986 
3987 /// There are multiple IR patterns that could be checking whether certain
3988 /// truncation of a signed number would be lossy or not. The pattern which is
3989 /// best at IR level, may not lower optimally. Thus, we want to unfold it.
3990 /// We are looking for the following pattern: (KeptBits is a constant)
3991 ///   (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
3992 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
3993 /// KeptBits also can't be 1, that would have been folded to  %x dstcond 0
3994 /// We will unfold it into the natural trunc+sext pattern:
3995 ///   ((%x << C) a>> C) dstcond %x
3996 /// Where  C = bitwidth(x) - KeptBits  and  C u< bitwidth(x)
3997 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
3998     EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
3999     const SDLoc &DL) const {
4000   // We must be comparing with a constant.
4001   ConstantSDNode *C1;
4002   if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
4003     return SDValue();
4004 
4005   // N0 should be:  add %x, (1 << (KeptBits-1))
4006   if (N0->getOpcode() != ISD::ADD)
4007     return SDValue();
4008 
4009   // And we must be 'add'ing a constant.
4010   ConstantSDNode *C01;
4011   if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
4012     return SDValue();
4013 
4014   SDValue X = N0->getOperand(0);
4015   EVT XVT = X.getValueType();
4016 
4017   // Validate constants ...
4018 
4019   APInt I1 = C1->getAPIntValue();
4020 
4021   ISD::CondCode NewCond;
4022   if (Cond == ISD::CondCode::SETULT) {
4023     NewCond = ISD::CondCode::SETEQ;
4024   } else if (Cond == ISD::CondCode::SETULE) {
4025     NewCond = ISD::CondCode::SETEQ;
4026     // But need to 'canonicalize' the constant.
4027     I1 += 1;
4028   } else if (Cond == ISD::CondCode::SETUGT) {
4029     NewCond = ISD::CondCode::SETNE;
4030     // But need to 'canonicalize' the constant.
4031     I1 += 1;
4032   } else if (Cond == ISD::CondCode::SETUGE) {
4033     NewCond = ISD::CondCode::SETNE;
4034   } else
4035     return SDValue();
4036 
4037   APInt I01 = C01->getAPIntValue();
4038 
4039   auto checkConstants = [&I1, &I01]() -> bool {
4040     // Both of them must be power-of-two, and the constant from setcc is bigger.
4041     return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
4042   };
4043 
4044   if (checkConstants()) {
4045     // Great, e.g. got  icmp ult i16 (add i16 %x, 128), 256
4046   } else {
4047     // What if we invert constants? (and the target predicate)
4048     I1.negate();
4049     I01.negate();
4050     assert(XVT.isInteger());
4051     NewCond = getSetCCInverse(NewCond, XVT);
4052     if (!checkConstants())
4053       return SDValue();
4054     // Great, e.g. got  icmp uge i16 (add i16 %x, -128), -256
4055   }
4056 
4057   // They are power-of-two, so which bit is set?
4058   const unsigned KeptBits = I1.logBase2();
4059   const unsigned KeptBitsMinusOne = I01.logBase2();
4060 
4061   // Magic!
4062   if (KeptBits != (KeptBitsMinusOne + 1))
4063     return SDValue();
4064   assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
4065 
4066   // We don't want to do this in every single case.
4067   SelectionDAG &DAG = DCI.DAG;
4068   if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck(
4069           XVT, KeptBits))
4070     return SDValue();
4071 
4072   const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits;
4073   assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable");
4074 
4075   // Unfold into:  ((%x << C) a>> C) cond %x
4076   // Where 'cond' will be either 'eq' or 'ne'.
4077   SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT);
4078   SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt);
4079   SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt);
4080   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond);
4081 
4082   return T2;
4083 }
4084 
4085 // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
4086 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
4087     EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
4088     DAGCombinerInfo &DCI, const SDLoc &DL) const {
4089   assert(isConstOrConstSplat(N1C) && isConstOrConstSplat(N1C)->isZero() &&
4090          "Should be a comparison with 0.");
4091   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4092          "Valid only for [in]equality comparisons.");
4093 
4094   unsigned NewShiftOpcode;
4095   SDValue X, C, Y;
4096 
4097   SelectionDAG &DAG = DCI.DAG;
4098   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4099 
4100   // Look for '(C l>>/<< Y)'.
4101   auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) {
4102     // The shift should be one-use.
4103     if (!V.hasOneUse())
4104       return false;
4105     unsigned OldShiftOpcode = V.getOpcode();
4106     switch (OldShiftOpcode) {
4107     case ISD::SHL:
4108       NewShiftOpcode = ISD::SRL;
4109       break;
4110     case ISD::SRL:
4111       NewShiftOpcode = ISD::SHL;
4112       break;
4113     default:
4114       return false; // must be a logical shift.
4115     }
4116     // We should be shifting a constant.
4117     // FIXME: best to use isConstantOrConstantVector().
4118     C = V.getOperand(0);
4119     ConstantSDNode *CC =
4120         isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4121     if (!CC)
4122       return false;
4123     Y = V.getOperand(1);
4124 
4125     ConstantSDNode *XC =
4126         isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4127     return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
4128         X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
4129   };
4130 
4131   // LHS of comparison should be an one-use 'and'.
4132   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
4133     return SDValue();
4134 
4135   X = N0.getOperand(0);
4136   SDValue Mask = N0.getOperand(1);
4137 
4138   // 'and' is commutative!
4139   if (!Match(Mask)) {
4140     std::swap(X, Mask);
4141     if (!Match(Mask))
4142       return SDValue();
4143   }
4144 
4145   EVT VT = X.getValueType();
4146 
4147   // Produce:
4148   // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
4149   SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
4150   SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
4151   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
4152   return T2;
4153 }
4154 
4155 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as
4156 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
4157 /// handle the commuted versions of these patterns.
4158 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
4159                                            ISD::CondCode Cond, const SDLoc &DL,
4160                                            DAGCombinerInfo &DCI) const {
4161   unsigned BOpcode = N0.getOpcode();
4162   assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
4163          "Unexpected binop");
4164   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
4165 
4166   // (X + Y) == X --> Y == 0
4167   // (X - Y) == X --> Y == 0
4168   // (X ^ Y) == X --> Y == 0
4169   SelectionDAG &DAG = DCI.DAG;
4170   EVT OpVT = N0.getValueType();
4171   SDValue X = N0.getOperand(0);
4172   SDValue Y = N0.getOperand(1);
4173   if (X == N1)
4174     return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
4175 
4176   if (Y != N1)
4177     return SDValue();
4178 
4179   // (X + Y) == Y --> X == 0
4180   // (X ^ Y) == Y --> X == 0
4181   if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
4182     return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
4183 
4184   // The shift would not be valid if the operands are boolean (i1).
4185   if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
4186     return SDValue();
4187 
4188   // (X - Y) == Y --> X == Y << 1
4189   EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(),
4190                                  !DCI.isBeforeLegalize());
4191   SDValue One = DAG.getConstant(1, DL, ShiftVT);
4192   SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
4193   if (!DCI.isCalledByLegalizer())
4194     DCI.AddToWorklist(YShl1.getNode());
4195   return DAG.getSetCC(DL, VT, X, YShl1, Cond);
4196 }
4197 
4198 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT,
4199                                       SDValue N0, const APInt &C1,
4200                                       ISD::CondCode Cond, const SDLoc &dl,
4201                                       SelectionDAG &DAG) {
4202   // Look through truncs that don't change the value of a ctpop.
4203   // FIXME: Add vector support? Need to be careful with setcc result type below.
4204   SDValue CTPOP = N0;
4205   if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
4206       N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits()))
4207     CTPOP = N0.getOperand(0);
4208 
4209   if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
4210     return SDValue();
4211 
4212   EVT CTVT = CTPOP.getValueType();
4213   SDValue CTOp = CTPOP.getOperand(0);
4214 
4215   // Expand a power-of-2-or-zero comparison based on ctpop:
4216   // (ctpop x) u< 2 -> (x & x-1) == 0
4217   // (ctpop x) u> 1 -> (x & x-1) != 0
4218   if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
4219     // Keep the CTPOP if it is a cheap vector op.
4220     if (CTVT.isVector() && TLI.isCtpopFast(CTVT))
4221       return SDValue();
4222 
4223     unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
4224     if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
4225       return SDValue();
4226     if (C1 == 0 && (Cond == ISD::SETULT))
4227       return SDValue(); // This is handled elsewhere.
4228 
4229     unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
4230 
4231     SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4232     SDValue Result = CTOp;
4233     for (unsigned i = 0; i < Passes; i++) {
4234       SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
4235       Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
4236     }
4237     ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
4238     return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
4239   }
4240 
4241   // Expand a power-of-2 comparison based on ctpop
4242   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
4243     // Keep the CTPOP if it is cheap.
4244     if (TLI.isCtpopFast(CTVT))
4245       return SDValue();
4246 
4247     SDValue Zero = DAG.getConstant(0, dl, CTVT);
4248     SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4249     assert(CTVT.isInteger());
4250     SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
4251 
4252     // Its not uncommon for known-never-zero X to exist in (ctpop X) eq/ne 1, so
4253     // check before emitting a potentially unnecessary op.
4254     if (DAG.isKnownNeverZero(CTOp)) {
4255       // (ctpop x) == 1 --> (x & x-1) == 0
4256       // (ctpop x) != 1 --> (x & x-1) != 0
4257       SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
4258       SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
4259       return RHS;
4260     }
4261 
4262     // (ctpop x) == 1 --> (x ^ x-1) >  x-1
4263     // (ctpop x) != 1 --> (x ^ x-1) <= x-1
4264     SDValue Xor = DAG.getNode(ISD::XOR, dl, CTVT, CTOp, Add);
4265     ISD::CondCode CmpCond = Cond == ISD::SETEQ ? ISD::SETUGT : ISD::SETULE;
4266     return DAG.getSetCC(dl, VT, Xor, Add, CmpCond);
4267   }
4268 
4269   return SDValue();
4270 }
4271 
4272 static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1,
4273                                    ISD::CondCode Cond, const SDLoc &dl,
4274                                    SelectionDAG &DAG) {
4275   if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4276     return SDValue();
4277 
4278   auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
4279   if (!C1 || !(C1->isZero() || C1->isAllOnes()))
4280     return SDValue();
4281 
4282   auto getRotateSource = [](SDValue X) {
4283     if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR)
4284       return X.getOperand(0);
4285     return SDValue();
4286   };
4287 
4288   // Peek through a rotated value compared against 0 or -1:
4289   // (rot X, Y) == 0/-1 --> X == 0/-1
4290   // (rot X, Y) != 0/-1 --> X != 0/-1
4291   if (SDValue R = getRotateSource(N0))
4292     return DAG.getSetCC(dl, VT, R, N1, Cond);
4293 
4294   // Peek through an 'or' of a rotated value compared against 0:
4295   // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0
4296   // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0
4297   //
4298   // TODO: Add the 'and' with -1 sibling.
4299   // TODO: Recurse through a series of 'or' ops to find the rotate.
4300   EVT OpVT = N0.getValueType();
4301   if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) {
4302     if (SDValue R = getRotateSource(N0.getOperand(0))) {
4303       SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1));
4304       return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4305     }
4306     if (SDValue R = getRotateSource(N0.getOperand(1))) {
4307       SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0));
4308       return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4309     }
4310   }
4311 
4312   return SDValue();
4313 }
4314 
4315 static SDValue foldSetCCWithFunnelShift(EVT VT, SDValue N0, SDValue N1,
4316                                         ISD::CondCode Cond, const SDLoc &dl,
4317                                         SelectionDAG &DAG) {
4318   // If we are testing for all-bits-clear, we might be able to do that with
4319   // less shifting since bit-order does not matter.
4320   if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4321     return SDValue();
4322 
4323   auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
4324   if (!C1 || !C1->isZero())
4325     return SDValue();
4326 
4327   if (!N0.hasOneUse() ||
4328       (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR))
4329     return SDValue();
4330 
4331   unsigned BitWidth = N0.getScalarValueSizeInBits();
4332   auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2));
4333   if (!ShAmtC || ShAmtC->getAPIntValue().uge(BitWidth))
4334     return SDValue();
4335 
4336   // Canonicalize fshr as fshl to reduce pattern-matching.
4337   unsigned ShAmt = ShAmtC->getZExtValue();
4338   if (N0.getOpcode() == ISD::FSHR)
4339     ShAmt = BitWidth - ShAmt;
4340 
4341   // Match an 'or' with a specific operand 'Other' in either commuted variant.
4342   SDValue X, Y;
4343   auto matchOr = [&X, &Y](SDValue Or, SDValue Other) {
4344     if (Or.getOpcode() != ISD::OR || !Or.hasOneUse())
4345       return false;
4346     if (Or.getOperand(0) == Other) {
4347       X = Or.getOperand(0);
4348       Y = Or.getOperand(1);
4349       return true;
4350     }
4351     if (Or.getOperand(1) == Other) {
4352       X = Or.getOperand(1);
4353       Y = Or.getOperand(0);
4354       return true;
4355     }
4356     return false;
4357   };
4358 
4359   EVT OpVT = N0.getValueType();
4360   EVT ShAmtVT = N0.getOperand(2).getValueType();
4361   SDValue F0 = N0.getOperand(0);
4362   SDValue F1 = N0.getOperand(1);
4363   if (matchOr(F0, F1)) {
4364     // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0
4365     SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT);
4366     SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt);
4367     SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4368     return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4369   }
4370   if (matchOr(F1, F0)) {
4371     // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0
4372     SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT);
4373     SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt);
4374     SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4375     return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4376   }
4377 
4378   return SDValue();
4379 }
4380 
4381 /// Try to simplify a setcc built with the specified operands and cc. If it is
4382 /// unable to simplify it, return a null SDValue.
4383 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
4384                                       ISD::CondCode Cond, bool foldBooleans,
4385                                       DAGCombinerInfo &DCI,
4386                                       const SDLoc &dl) const {
4387   SelectionDAG &DAG = DCI.DAG;
4388   const DataLayout &Layout = DAG.getDataLayout();
4389   EVT OpVT = N0.getValueType();
4390   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4391 
4392   // Constant fold or commute setcc.
4393   if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
4394     return Fold;
4395 
4396   bool N0ConstOrSplat =
4397       isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
4398   bool N1ConstOrSplat =
4399       isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
4400 
4401   // Canonicalize toward having the constant on the RHS.
4402   // TODO: Handle non-splat vector constants. All undef causes trouble.
4403   // FIXME: We can't yet fold constant scalable vector splats, so avoid an
4404   // infinite loop here when we encounter one.
4405   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
4406   if (N0ConstOrSplat && !N1ConstOrSplat &&
4407       (DCI.isBeforeLegalizeOps() ||
4408        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
4409     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
4410 
4411   // If we have a subtract with the same 2 non-constant operands as this setcc
4412   // -- but in reverse order -- then try to commute the operands of this setcc
4413   // to match. A matching pair of setcc (cmp) and sub may be combined into 1
4414   // instruction on some targets.
4415   if (!N0ConstOrSplat && !N1ConstOrSplat &&
4416       (DCI.isBeforeLegalizeOps() ||
4417        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
4418       DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
4419       !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
4420     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
4421 
4422   if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG))
4423     return V;
4424 
4425   if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG))
4426     return V;
4427 
4428   if (auto *N1C = isConstOrConstSplat(N1)) {
4429     const APInt &C1 = N1C->getAPIntValue();
4430 
4431     // Optimize some CTPOP cases.
4432     if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
4433       return V;
4434 
4435     // For equality to 0 of a no-wrap multiply, decompose and test each op:
4436     // X * Y == 0 --> (X == 0) || (Y == 0)
4437     // X * Y != 0 --> (X != 0) && (Y != 0)
4438     // TODO: This bails out if minsize is set, but if the target doesn't have a
4439     //       single instruction multiply for this type, it would likely be
4440     //       smaller to decompose.
4441     if (C1.isZero() && (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4442         N0.getOpcode() == ISD::MUL && N0.hasOneUse() &&
4443         (N0->getFlags().hasNoUnsignedWrap() ||
4444          N0->getFlags().hasNoSignedWrap()) &&
4445         !Attr.hasFnAttr(Attribute::MinSize)) {
4446       SDValue IsXZero = DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
4447       SDValue IsYZero = DAG.getSetCC(dl, VT, N0.getOperand(1), N1, Cond);
4448       unsigned LogicOp = Cond == ISD::SETEQ ? ISD::OR : ISD::AND;
4449       return DAG.getNode(LogicOp, dl, VT, IsXZero, IsYZero);
4450     }
4451 
4452     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
4453     // equality comparison, then we're just comparing whether X itself is
4454     // zero.
4455     if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) &&
4456         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
4457         llvm::has_single_bit<uint32_t>(N0.getScalarValueSizeInBits())) {
4458       if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
4459         if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4460             ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
4461           if ((C1 == 0) == (Cond == ISD::SETEQ)) {
4462             // (srl (ctlz x), 5) == 0  -> X != 0
4463             // (srl (ctlz x), 5) != 1  -> X != 0
4464             Cond = ISD::SETNE;
4465           } else {
4466             // (srl (ctlz x), 5) != 0  -> X == 0
4467             // (srl (ctlz x), 5) == 1  -> X == 0
4468             Cond = ISD::SETEQ;
4469           }
4470           SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
4471           return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
4472                               Cond);
4473         }
4474       }
4475     }
4476   }
4477 
4478   // FIXME: Support vectors.
4479   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
4480     const APInt &C1 = N1C->getAPIntValue();
4481 
4482     // (zext x) == C --> x == (trunc C)
4483     // (sext x) == C --> x == (trunc C)
4484     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4485         DCI.isBeforeLegalize() && N0->hasOneUse()) {
4486       unsigned MinBits = N0.getValueSizeInBits();
4487       SDValue PreExt;
4488       bool Signed = false;
4489       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
4490         // ZExt
4491         MinBits = N0->getOperand(0).getValueSizeInBits();
4492         PreExt = N0->getOperand(0);
4493       } else if (N0->getOpcode() == ISD::AND) {
4494         // DAGCombine turns costly ZExts into ANDs
4495         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
4496           if ((C->getAPIntValue()+1).isPowerOf2()) {
4497             MinBits = C->getAPIntValue().countr_one();
4498             PreExt = N0->getOperand(0);
4499           }
4500       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
4501         // SExt
4502         MinBits = N0->getOperand(0).getValueSizeInBits();
4503         PreExt = N0->getOperand(0);
4504         Signed = true;
4505       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
4506         // ZEXTLOAD / SEXTLOAD
4507         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
4508           MinBits = LN0->getMemoryVT().getSizeInBits();
4509           PreExt = N0;
4510         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
4511           Signed = true;
4512           MinBits = LN0->getMemoryVT().getSizeInBits();
4513           PreExt = N0;
4514         }
4515       }
4516 
4517       // Figure out how many bits we need to preserve this constant.
4518       unsigned ReqdBits = Signed ? C1.getSignificantBits() : C1.getActiveBits();
4519 
4520       // Make sure we're not losing bits from the constant.
4521       if (MinBits > 0 &&
4522           MinBits < C1.getBitWidth() &&
4523           MinBits >= ReqdBits) {
4524         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
4525         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
4526           // Will get folded away.
4527           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
4528           if (MinBits == 1 && C1 == 1)
4529             // Invert the condition.
4530             return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
4531                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4532           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
4533           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
4534         }
4535 
4536         // If truncating the setcc operands is not desirable, we can still
4537         // simplify the expression in some cases:
4538         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
4539         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
4540         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
4541         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
4542         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
4543         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
4544         SDValue TopSetCC = N0->getOperand(0);
4545         unsigned N0Opc = N0->getOpcode();
4546         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
4547         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
4548             TopSetCC.getOpcode() == ISD::SETCC &&
4549             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
4550             (isConstFalseVal(N1) ||
4551              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
4552 
4553           bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) ||
4554                          (!N1C->isZero() && Cond == ISD::SETNE);
4555 
4556           if (!Inverse)
4557             return TopSetCC;
4558 
4559           ISD::CondCode InvCond = ISD::getSetCCInverse(
4560               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
4561               TopSetCC.getOperand(0).getValueType());
4562           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
4563                                       TopSetCC.getOperand(1),
4564                                       InvCond);
4565         }
4566       }
4567     }
4568 
4569     // If the LHS is '(and load, const)', the RHS is 0, the test is for
4570     // equality or unsigned, and all 1 bits of the const are in the same
4571     // partial word, see if we can shorten the load.
4572     if (DCI.isBeforeLegalize() &&
4573         !ISD::isSignedIntSetCC(Cond) &&
4574         N0.getOpcode() == ISD::AND && C1 == 0 &&
4575         N0.getNode()->hasOneUse() &&
4576         isa<LoadSDNode>(N0.getOperand(0)) &&
4577         N0.getOperand(0).getNode()->hasOneUse() &&
4578         isa<ConstantSDNode>(N0.getOperand(1))) {
4579       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
4580       APInt bestMask;
4581       unsigned bestWidth = 0, bestOffset = 0;
4582       if (Lod->isSimple() && Lod->isUnindexed()) {
4583         unsigned origWidth = N0.getValueSizeInBits();
4584         unsigned maskWidth = origWidth;
4585         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
4586         // 8 bits, but have to be careful...
4587         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
4588           origWidth = Lod->getMemoryVT().getSizeInBits();
4589         const APInt &Mask = N0.getConstantOperandAPInt(1);
4590         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
4591           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
4592           for (unsigned offset=0; offset<origWidth/width; offset++) {
4593             if (Mask.isSubsetOf(newMask)) {
4594               if (Layout.isLittleEndian())
4595                 bestOffset = (uint64_t)offset * (width/8);
4596               else
4597                 bestOffset = (origWidth/width - offset - 1) * (width/8);
4598               bestMask = Mask.lshr(offset * (width/8) * 8);
4599               bestWidth = width;
4600               break;
4601             }
4602             newMask <<= width;
4603           }
4604         }
4605       }
4606       if (bestWidth) {
4607         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
4608         if (newVT.isRound() &&
4609             shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) {
4610           SDValue Ptr = Lod->getBasePtr();
4611           if (bestOffset != 0)
4612             Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::getFixed(bestOffset),
4613                                            dl);
4614           SDValue NewLoad =
4615               DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
4616                           Lod->getPointerInfo().getWithOffset(bestOffset),
4617                           Lod->getOriginalAlign());
4618           return DAG.getSetCC(dl, VT,
4619                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
4620                                       DAG.getConstant(bestMask.trunc(bestWidth),
4621                                                       dl, newVT)),
4622                               DAG.getConstant(0LL, dl, newVT), Cond);
4623         }
4624       }
4625     }
4626 
4627     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
4628     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
4629       unsigned InSize = N0.getOperand(0).getValueSizeInBits();
4630 
4631       // If the comparison constant has bits in the upper part, the
4632       // zero-extended value could never match.
4633       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
4634                                               C1.getBitWidth() - InSize))) {
4635         switch (Cond) {
4636         case ISD::SETUGT:
4637         case ISD::SETUGE:
4638         case ISD::SETEQ:
4639           return DAG.getConstant(0, dl, VT);
4640         case ISD::SETULT:
4641         case ISD::SETULE:
4642         case ISD::SETNE:
4643           return DAG.getConstant(1, dl, VT);
4644         case ISD::SETGT:
4645         case ISD::SETGE:
4646           // True if the sign bit of C1 is set.
4647           return DAG.getConstant(C1.isNegative(), dl, VT);
4648         case ISD::SETLT:
4649         case ISD::SETLE:
4650           // True if the sign bit of C1 isn't set.
4651           return DAG.getConstant(C1.isNonNegative(), dl, VT);
4652         default:
4653           break;
4654         }
4655       }
4656 
4657       // Otherwise, we can perform the comparison with the low bits.
4658       switch (Cond) {
4659       case ISD::SETEQ:
4660       case ISD::SETNE:
4661       case ISD::SETUGT:
4662       case ISD::SETUGE:
4663       case ISD::SETULT:
4664       case ISD::SETULE: {
4665         EVT newVT = N0.getOperand(0).getValueType();
4666         if (DCI.isBeforeLegalizeOps() ||
4667             (isOperationLegal(ISD::SETCC, newVT) &&
4668              isCondCodeLegal(Cond, newVT.getSimpleVT()))) {
4669           EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
4670           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
4671 
4672           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
4673                                           NewConst, Cond);
4674           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
4675         }
4676         break;
4677       }
4678       default:
4679         break; // todo, be more careful with signed comparisons
4680       }
4681     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4682                (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4683                !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(),
4684                                       OpVT)) {
4685       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
4686       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
4687       EVT ExtDstTy = N0.getValueType();
4688       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
4689 
4690       // If the constant doesn't fit into the number of bits for the source of
4691       // the sign extension, it is impossible for both sides to be equal.
4692       if (C1.getSignificantBits() > ExtSrcTyBits)
4693         return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
4694 
4695       assert(ExtDstTy == N0.getOperand(0).getValueType() &&
4696              ExtDstTy != ExtSrcTy && "Unexpected types!");
4697       APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
4698       SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
4699                                    DAG.getConstant(Imm, dl, ExtDstTy));
4700       if (!DCI.isCalledByLegalizer())
4701         DCI.AddToWorklist(ZextOp.getNode());
4702       // Otherwise, make this a use of a zext.
4703       return DAG.getSetCC(dl, VT, ZextOp,
4704                           DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
4705     } else if ((N1C->isZero() || N1C->isOne()) &&
4706                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4707       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
4708       if (N0.getOpcode() == ISD::SETCC &&
4709           isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
4710           (N0.getValueType() == MVT::i1 ||
4711            getBooleanContents(N0.getOperand(0).getValueType()) ==
4712                        ZeroOrOneBooleanContent)) {
4713         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
4714         if (TrueWhenTrue)
4715           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
4716         // Invert the condition.
4717         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4718         CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType());
4719         if (DCI.isBeforeLegalizeOps() ||
4720             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
4721           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
4722       }
4723 
4724       if ((N0.getOpcode() == ISD::XOR ||
4725            (N0.getOpcode() == ISD::AND &&
4726             N0.getOperand(0).getOpcode() == ISD::XOR &&
4727             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
4728           isOneConstant(N0.getOperand(1))) {
4729         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
4730         // can only do this if the top bits are known zero.
4731         unsigned BitWidth = N0.getValueSizeInBits();
4732         if (DAG.MaskedValueIsZero(N0,
4733                                   APInt::getHighBitsSet(BitWidth,
4734                                                         BitWidth-1))) {
4735           // Okay, get the un-inverted input value.
4736           SDValue Val;
4737           if (N0.getOpcode() == ISD::XOR) {
4738             Val = N0.getOperand(0);
4739           } else {
4740             assert(N0.getOpcode() == ISD::AND &&
4741                     N0.getOperand(0).getOpcode() == ISD::XOR);
4742             // ((X^1)&1)^1 -> X & 1
4743             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
4744                               N0.getOperand(0).getOperand(0),
4745                               N0.getOperand(1));
4746           }
4747 
4748           return DAG.getSetCC(dl, VT, Val, N1,
4749                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4750         }
4751       } else if (N1C->isOne()) {
4752         SDValue Op0 = N0;
4753         if (Op0.getOpcode() == ISD::TRUNCATE)
4754           Op0 = Op0.getOperand(0);
4755 
4756         if ((Op0.getOpcode() == ISD::XOR) &&
4757             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
4758             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
4759           SDValue XorLHS = Op0.getOperand(0);
4760           SDValue XorRHS = Op0.getOperand(1);
4761           // Ensure that the input setccs return an i1 type or 0/1 value.
4762           if (Op0.getValueType() == MVT::i1 ||
4763               (getBooleanContents(XorLHS.getOperand(0).getValueType()) ==
4764                       ZeroOrOneBooleanContent &&
4765                getBooleanContents(XorRHS.getOperand(0).getValueType()) ==
4766                         ZeroOrOneBooleanContent)) {
4767             // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
4768             Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
4769             return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
4770           }
4771         }
4772         if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
4773           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
4774           if (Op0.getValueType().bitsGT(VT))
4775             Op0 = DAG.getNode(ISD::AND, dl, VT,
4776                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
4777                           DAG.getConstant(1, dl, VT));
4778           else if (Op0.getValueType().bitsLT(VT))
4779             Op0 = DAG.getNode(ISD::AND, dl, VT,
4780                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
4781                         DAG.getConstant(1, dl, VT));
4782 
4783           return DAG.getSetCC(dl, VT, Op0,
4784                               DAG.getConstant(0, dl, Op0.getValueType()),
4785                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4786         }
4787         if (Op0.getOpcode() == ISD::AssertZext &&
4788             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
4789           return DAG.getSetCC(dl, VT, Op0,
4790                               DAG.getConstant(0, dl, Op0.getValueType()),
4791                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4792       }
4793     }
4794 
4795     // Given:
4796     //   icmp eq/ne (urem %x, %y), 0
4797     // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
4798     //   icmp eq/ne %x, 0
4799     if (N0.getOpcode() == ISD::UREM && N1C->isZero() &&
4800         (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4801       KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
4802       KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
4803       if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
4804         return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
4805     }
4806 
4807     // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0
4808     //  and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0
4809     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4810         N0.getOpcode() == ISD::SRA && isa<ConstantSDNode>(N0.getOperand(1)) &&
4811         N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 &&
4812         N1C && N1C->isAllOnes()) {
4813       return DAG.getSetCC(dl, VT, N0.getOperand(0),
4814                           DAG.getConstant(0, dl, OpVT),
4815                           Cond == ISD::SETEQ ? ISD::SETLT : ISD::SETGE);
4816     }
4817 
4818     if (SDValue V =
4819             optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
4820       return V;
4821   }
4822 
4823   // These simplifications apply to splat vectors as well.
4824   // TODO: Handle more splat vector cases.
4825   if (auto *N1C = isConstOrConstSplat(N1)) {
4826     const APInt &C1 = N1C->getAPIntValue();
4827 
4828     APInt MinVal, MaxVal;
4829     unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
4830     if (ISD::isSignedIntSetCC(Cond)) {
4831       MinVal = APInt::getSignedMinValue(OperandBitSize);
4832       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
4833     } else {
4834       MinVal = APInt::getMinValue(OperandBitSize);
4835       MaxVal = APInt::getMaxValue(OperandBitSize);
4836     }
4837 
4838     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
4839     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
4840       // X >= MIN --> true
4841       if (C1 == MinVal)
4842         return DAG.getBoolConstant(true, dl, VT, OpVT);
4843 
4844       if (!VT.isVector()) { // TODO: Support this for vectors.
4845         // X >= C0 --> X > (C0 - 1)
4846         APInt C = C1 - 1;
4847         ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
4848         if ((DCI.isBeforeLegalizeOps() ||
4849              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
4850             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
4851                                   isLegalICmpImmediate(C.getSExtValue())))) {
4852           return DAG.getSetCC(dl, VT, N0,
4853                               DAG.getConstant(C, dl, N1.getValueType()),
4854                               NewCC);
4855         }
4856       }
4857     }
4858 
4859     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
4860       // X <= MAX --> true
4861       if (C1 == MaxVal)
4862         return DAG.getBoolConstant(true, dl, VT, OpVT);
4863 
4864       // X <= C0 --> X < (C0 + 1)
4865       if (!VT.isVector()) { // TODO: Support this for vectors.
4866         APInt C = C1 + 1;
4867         ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
4868         if ((DCI.isBeforeLegalizeOps() ||
4869              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
4870             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
4871                                   isLegalICmpImmediate(C.getSExtValue())))) {
4872           return DAG.getSetCC(dl, VT, N0,
4873                               DAG.getConstant(C, dl, N1.getValueType()),
4874                               NewCC);
4875         }
4876       }
4877     }
4878 
4879     if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
4880       if (C1 == MinVal)
4881         return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
4882 
4883       // TODO: Support this for vectors after legalize ops.
4884       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4885         // Canonicalize setlt X, Max --> setne X, Max
4886         if (C1 == MaxVal)
4887           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
4888 
4889         // If we have setult X, 1, turn it into seteq X, 0
4890         if (C1 == MinVal+1)
4891           return DAG.getSetCC(dl, VT, N0,
4892                               DAG.getConstant(MinVal, dl, N0.getValueType()),
4893                               ISD::SETEQ);
4894       }
4895     }
4896 
4897     if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
4898       if (C1 == MaxVal)
4899         return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
4900 
4901       // TODO: Support this for vectors after legalize ops.
4902       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4903         // Canonicalize setgt X, Min --> setne X, Min
4904         if (C1 == MinVal)
4905           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
4906 
4907         // If we have setugt X, Max-1, turn it into seteq X, Max
4908         if (C1 == MaxVal-1)
4909           return DAG.getSetCC(dl, VT, N0,
4910                               DAG.getConstant(MaxVal, dl, N0.getValueType()),
4911                               ISD::SETEQ);
4912       }
4913     }
4914 
4915     if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
4916       // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
4917       if (C1.isZero())
4918         if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
4919                 VT, N0, N1, Cond, DCI, dl))
4920           return CC;
4921 
4922       // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
4923       // For example, when high 32-bits of i64 X are known clear:
4924       // all bits clear: (X | (Y<<32)) ==  0 --> (X | Y) ==  0
4925       // all bits set:   (X | (Y<<32)) == -1 --> (X & Y) == -1
4926       bool CmpZero = N1C->isZero();
4927       bool CmpNegOne = N1C->isAllOnes();
4928       if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
4929         // Match or(lo,shl(hi,bw/2)) pattern.
4930         auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
4931           unsigned EltBits = V.getScalarValueSizeInBits();
4932           if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
4933             return false;
4934           SDValue LHS = V.getOperand(0);
4935           SDValue RHS = V.getOperand(1);
4936           APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
4937           // Unshifted element must have zero upperbits.
4938           if (RHS.getOpcode() == ISD::SHL &&
4939               isa<ConstantSDNode>(RHS.getOperand(1)) &&
4940               RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
4941               DAG.MaskedValueIsZero(LHS, HiBits)) {
4942             Lo = LHS;
4943             Hi = RHS.getOperand(0);
4944             return true;
4945           }
4946           if (LHS.getOpcode() == ISD::SHL &&
4947               isa<ConstantSDNode>(LHS.getOperand(1)) &&
4948               LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
4949               DAG.MaskedValueIsZero(RHS, HiBits)) {
4950             Lo = RHS;
4951             Hi = LHS.getOperand(0);
4952             return true;
4953           }
4954           return false;
4955         };
4956 
4957         auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
4958           unsigned EltBits = N0.getScalarValueSizeInBits();
4959           unsigned HalfBits = EltBits / 2;
4960           APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
4961           SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
4962           SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
4963           SDValue NewN0 =
4964               DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
4965           SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
4966           return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
4967         };
4968 
4969         SDValue Lo, Hi;
4970         if (IsConcat(N0, Lo, Hi))
4971           return MergeConcat(Lo, Hi);
4972 
4973         if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
4974           SDValue Lo0, Lo1, Hi0, Hi1;
4975           if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
4976               IsConcat(N0.getOperand(1), Lo1, Hi1)) {
4977             return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
4978                                DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
4979           }
4980         }
4981       }
4982     }
4983 
4984     // If we have "setcc X, C0", check to see if we can shrink the immediate
4985     // by changing cc.
4986     // TODO: Support this for vectors after legalize ops.
4987     if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4988       // SETUGT X, SINTMAX  -> SETLT X, 0
4989       // SETUGE X, SINTMIN -> SETLT X, 0
4990       if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
4991           (Cond == ISD::SETUGE && C1.isMinSignedValue()))
4992         return DAG.getSetCC(dl, VT, N0,
4993                             DAG.getConstant(0, dl, N1.getValueType()),
4994                             ISD::SETLT);
4995 
4996       // SETULT X, SINTMIN  -> SETGT X, -1
4997       // SETULE X, SINTMAX  -> SETGT X, -1
4998       if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
4999           (Cond == ISD::SETULE && C1.isMaxSignedValue()))
5000         return DAG.getSetCC(dl, VT, N0,
5001                             DAG.getAllOnesConstant(dl, N1.getValueType()),
5002                             ISD::SETGT);
5003     }
5004   }
5005 
5006   // Back to non-vector simplifications.
5007   // TODO: Can we do these for vector splats?
5008   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5009     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5010     const APInt &C1 = N1C->getAPIntValue();
5011     EVT ShValTy = N0.getValueType();
5012 
5013     // Fold bit comparisons when we can. This will result in an
5014     // incorrect value when boolean false is negative one, unless
5015     // the bitsize is 1 in which case the false value is the same
5016     // in practice regardless of the representation.
5017     if ((VT.getSizeInBits() == 1 ||
5018          getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) &&
5019         (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5020         (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
5021         N0.getOpcode() == ISD::AND) {
5022       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5023         EVT ShiftTy =
5024             getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
5025         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
5026           // Perform the xform if the AND RHS is a single bit.
5027           unsigned ShCt = AndRHS->getAPIntValue().logBase2();
5028           if (AndRHS->getAPIntValue().isPowerOf2() &&
5029               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
5030             return DAG.getNode(ISD::TRUNCATE, dl, VT,
5031                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5032                                            DAG.getConstant(ShCt, dl, ShiftTy)));
5033           }
5034         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
5035           // (X & 8) == 8  -->  (X & 8) >> 3
5036           // Perform the xform if C1 is a single bit.
5037           unsigned ShCt = C1.logBase2();
5038           if (C1.isPowerOf2() &&
5039               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
5040             return DAG.getNode(ISD::TRUNCATE, dl, VT,
5041                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5042                                            DAG.getConstant(ShCt, dl, ShiftTy)));
5043           }
5044         }
5045       }
5046     }
5047 
5048     if (C1.getSignificantBits() <= 64 &&
5049         !isLegalICmpImmediate(C1.getSExtValue())) {
5050       EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
5051       // (X & -256) == 256 -> (X >> 8) == 1
5052       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5053           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
5054         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5055           const APInt &AndRHSC = AndRHS->getAPIntValue();
5056           if (AndRHSC.isNegatedPowerOf2() && (AndRHSC & C1) == C1) {
5057             unsigned ShiftBits = AndRHSC.countr_zero();
5058             if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5059               SDValue Shift =
5060                 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0),
5061                             DAG.getConstant(ShiftBits, dl, ShiftTy));
5062               SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy);
5063               return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5064             }
5065           }
5066         }
5067       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
5068                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
5069         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
5070         // X <  0x100000000 -> (X >> 32) <  1
5071         // X >= 0x100000000 -> (X >> 32) >= 1
5072         // X <= 0x0ffffffff -> (X >> 32) <  1
5073         // X >  0x0ffffffff -> (X >> 32) >= 1
5074         unsigned ShiftBits;
5075         APInt NewC = C1;
5076         ISD::CondCode NewCond = Cond;
5077         if (AdjOne) {
5078           ShiftBits = C1.countr_one();
5079           NewC = NewC + 1;
5080           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
5081         } else {
5082           ShiftBits = C1.countr_zero();
5083         }
5084         NewC.lshrInPlace(ShiftBits);
5085         if (ShiftBits && NewC.getSignificantBits() <= 64 &&
5086             isLegalICmpImmediate(NewC.getSExtValue()) &&
5087             !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5088           SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5089                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
5090           SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5091           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
5092         }
5093       }
5094     }
5095   }
5096 
5097   if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) {
5098     auto *CFP = cast<ConstantFPSDNode>(N1);
5099     assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
5100 
5101     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
5102     // constant if knowing that the operand is non-nan is enough.  We prefer to
5103     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
5104     // materialize 0.0.
5105     if (Cond == ISD::SETO || Cond == ISD::SETUO)
5106       return DAG.getSetCC(dl, VT, N0, N0, Cond);
5107 
5108     // setcc (fneg x), C -> setcc swap(pred) x, -C
5109     if (N0.getOpcode() == ISD::FNEG) {
5110       ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
5111       if (DCI.isBeforeLegalizeOps() ||
5112           isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
5113         SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
5114         return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
5115       }
5116     }
5117 
5118     // setueq/setoeq X, (fabs Inf) -> is_fpclass X, fcInf
5119     if (isOperationLegalOrCustom(ISD::IS_FPCLASS, N0.getValueType()) &&
5120         !isFPImmLegal(CFP->getValueAPF(), CFP->getValueType(0))) {
5121       bool IsFabs = N0.getOpcode() == ISD::FABS;
5122       SDValue Op = IsFabs ? N0.getOperand(0) : N0;
5123       if ((Cond == ISD::SETOEQ || Cond == ISD::SETUEQ) && CFP->isInfinity()) {
5124         FPClassTest Flag = CFP->isNegative() ? (IsFabs ? fcNone : fcNegInf)
5125                                              : (IsFabs ? fcInf : fcPosInf);
5126         if (Cond == ISD::SETUEQ)
5127           Flag |= fcNan;
5128         return DAG.getNode(ISD::IS_FPCLASS, dl, VT, Op,
5129                            DAG.getTargetConstant(Flag, dl, MVT::i32));
5130       }
5131     }
5132 
5133     // If the condition is not legal, see if we can find an equivalent one
5134     // which is legal.
5135     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
5136       // If the comparison was an awkward floating-point == or != and one of
5137       // the comparison operands is infinity or negative infinity, convert the
5138       // condition to a less-awkward <= or >=.
5139       if (CFP->getValueAPF().isInfinity()) {
5140         bool IsNegInf = CFP->getValueAPF().isNegative();
5141         ISD::CondCode NewCond = ISD::SETCC_INVALID;
5142         switch (Cond) {
5143         case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
5144         case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
5145         case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
5146         case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
5147         default: break;
5148         }
5149         if (NewCond != ISD::SETCC_INVALID &&
5150             isCondCodeLegal(NewCond, N0.getSimpleValueType()))
5151           return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5152       }
5153     }
5154   }
5155 
5156   if (N0 == N1) {
5157     // The sext(setcc()) => setcc() optimization relies on the appropriate
5158     // constant being emitted.
5159     assert(!N0.getValueType().isInteger() &&
5160            "Integer types should be handled by FoldSetCC");
5161 
5162     bool EqTrue = ISD::isTrueWhenEqual(Cond);
5163     unsigned UOF = ISD::getUnorderedFlavor(Cond);
5164     if (UOF == 2) // FP operators that are undefined on NaNs.
5165       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5166     if (UOF == unsigned(EqTrue))
5167       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5168     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
5169     // if it is not already.
5170     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
5171     if (NewCond != Cond &&
5172         (DCI.isBeforeLegalizeOps() ||
5173                             isCondCodeLegal(NewCond, N0.getSimpleValueType())))
5174       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5175   }
5176 
5177   // ~X > ~Y --> Y > X
5178   // ~X < ~Y --> Y < X
5179   // ~X < C --> X > ~C
5180   // ~X > C --> X < ~C
5181   if ((isSignedIntSetCC(Cond) || isUnsignedIntSetCC(Cond)) &&
5182       N0.getValueType().isInteger()) {
5183     if (isBitwiseNot(N0)) {
5184       if (isBitwiseNot(N1))
5185         return DAG.getSetCC(dl, VT, N1.getOperand(0), N0.getOperand(0), Cond);
5186 
5187       if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
5188           !DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(0))) {
5189         SDValue Not = DAG.getNOT(dl, N1, OpVT);
5190         return DAG.getSetCC(dl, VT, Not, N0.getOperand(0), Cond);
5191       }
5192     }
5193   }
5194 
5195   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5196       N0.getValueType().isInteger()) {
5197     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
5198         N0.getOpcode() == ISD::XOR) {
5199       // Simplify (X+Y) == (X+Z) -->  Y == Z
5200       if (N0.getOpcode() == N1.getOpcode()) {
5201         if (N0.getOperand(0) == N1.getOperand(0))
5202           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
5203         if (N0.getOperand(1) == N1.getOperand(1))
5204           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
5205         if (isCommutativeBinOp(N0.getOpcode())) {
5206           // If X op Y == Y op X, try other combinations.
5207           if (N0.getOperand(0) == N1.getOperand(1))
5208             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
5209                                 Cond);
5210           if (N0.getOperand(1) == N1.getOperand(0))
5211             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
5212                                 Cond);
5213         }
5214       }
5215 
5216       // If RHS is a legal immediate value for a compare instruction, we need
5217       // to be careful about increasing register pressure needlessly.
5218       bool LegalRHSImm = false;
5219 
5220       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
5221         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5222           // Turn (X+C1) == C2 --> X == C2-C1
5223           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse())
5224             return DAG.getSetCC(
5225                 dl, VT, N0.getOperand(0),
5226                 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(),
5227                                 dl, N0.getValueType()),
5228                 Cond);
5229 
5230           // Turn (X^C1) == C2 --> X == C1^C2
5231           if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse())
5232             return DAG.getSetCC(
5233                 dl, VT, N0.getOperand(0),
5234                 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(),
5235                                 dl, N0.getValueType()),
5236                 Cond);
5237         }
5238 
5239         // Turn (C1-X) == C2 --> X == C1-C2
5240         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
5241           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse())
5242             return DAG.getSetCC(
5243                 dl, VT, N0.getOperand(1),
5244                 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(),
5245                                 dl, N0.getValueType()),
5246                 Cond);
5247 
5248         // Could RHSC fold directly into a compare?
5249         if (RHSC->getValueType(0).getSizeInBits() <= 64)
5250           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
5251       }
5252 
5253       // (X+Y) == X --> Y == 0 and similar folds.
5254       // Don't do this if X is an immediate that can fold into a cmp
5255       // instruction and X+Y has other uses. It could be an induction variable
5256       // chain, and the transform would increase register pressure.
5257       if (!LegalRHSImm || N0.hasOneUse())
5258         if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
5259           return V;
5260     }
5261 
5262     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
5263         N1.getOpcode() == ISD::XOR)
5264       if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
5265         return V;
5266 
5267     if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
5268       return V;
5269   }
5270 
5271   // Fold remainder of division by a constant.
5272   if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
5273       N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5274     // When division is cheap or optimizing for minimum size,
5275     // fall through to DIVREM creation by skipping this fold.
5276     if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) {
5277       if (N0.getOpcode() == ISD::UREM) {
5278         if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
5279           return Folded;
5280       } else if (N0.getOpcode() == ISD::SREM) {
5281         if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
5282           return Folded;
5283       }
5284     }
5285   }
5286 
5287   // Fold away ALL boolean setcc's.
5288   if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
5289     SDValue Temp;
5290     switch (Cond) {
5291     default: llvm_unreachable("Unknown integer setcc!");
5292     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
5293       Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
5294       N0 = DAG.getNOT(dl, Temp, OpVT);
5295       if (!DCI.isCalledByLegalizer())
5296         DCI.AddToWorklist(Temp.getNode());
5297       break;
5298     case ISD::SETNE:  // X != Y   -->  (X^Y)
5299       N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
5300       break;
5301     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
5302     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
5303       Temp = DAG.getNOT(dl, N0, OpVT);
5304       N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
5305       if (!DCI.isCalledByLegalizer())
5306         DCI.AddToWorklist(Temp.getNode());
5307       break;
5308     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
5309     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
5310       Temp = DAG.getNOT(dl, N1, OpVT);
5311       N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
5312       if (!DCI.isCalledByLegalizer())
5313         DCI.AddToWorklist(Temp.getNode());
5314       break;
5315     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
5316     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
5317       Temp = DAG.getNOT(dl, N0, OpVT);
5318       N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
5319       if (!DCI.isCalledByLegalizer())
5320         DCI.AddToWorklist(Temp.getNode());
5321       break;
5322     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
5323     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
5324       Temp = DAG.getNOT(dl, N1, OpVT);
5325       N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
5326       break;
5327     }
5328     if (VT.getScalarType() != MVT::i1) {
5329       if (!DCI.isCalledByLegalizer())
5330         DCI.AddToWorklist(N0.getNode());
5331       // FIXME: If running after legalize, we probably can't do this.
5332       ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT));
5333       N0 = DAG.getNode(ExtendCode, dl, VT, N0);
5334     }
5335     return N0;
5336   }
5337 
5338   // Could not fold it.
5339   return SDValue();
5340 }
5341 
5342 /// Returns true (and the GlobalValue and the offset) if the node is a
5343 /// GlobalAddress + offset.
5344 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA,
5345                                     int64_t &Offset) const {
5346 
5347   SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
5348 
5349   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
5350     GA = GASD->getGlobal();
5351     Offset += GASD->getOffset();
5352     return true;
5353   }
5354 
5355   if (N->getOpcode() == ISD::ADD) {
5356     SDValue N1 = N->getOperand(0);
5357     SDValue N2 = N->getOperand(1);
5358     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
5359       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
5360         Offset += V->getSExtValue();
5361         return true;
5362       }
5363     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
5364       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
5365         Offset += V->getSExtValue();
5366         return true;
5367       }
5368     }
5369   }
5370 
5371   return false;
5372 }
5373 
5374 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
5375                                           DAGCombinerInfo &DCI) const {
5376   // Default implementation: no optimization.
5377   return SDValue();
5378 }
5379 
5380 //===----------------------------------------------------------------------===//
5381 //  Inline Assembler Implementation Methods
5382 //===----------------------------------------------------------------------===//
5383 
5384 TargetLowering::ConstraintType
5385 TargetLowering::getConstraintType(StringRef Constraint) const {
5386   unsigned S = Constraint.size();
5387 
5388   if (S == 1) {
5389     switch (Constraint[0]) {
5390     default: break;
5391     case 'r':
5392       return C_RegisterClass;
5393     case 'm': // memory
5394     case 'o': // offsetable
5395     case 'V': // not offsetable
5396       return C_Memory;
5397     case 'p': // Address.
5398       return C_Address;
5399     case 'n': // Simple Integer
5400     case 'E': // Floating Point Constant
5401     case 'F': // Floating Point Constant
5402       return C_Immediate;
5403     case 'i': // Simple Integer or Relocatable Constant
5404     case 's': // Relocatable Constant
5405     case 'X': // Allow ANY value.
5406     case 'I': // Target registers.
5407     case 'J':
5408     case 'K':
5409     case 'L':
5410     case 'M':
5411     case 'N':
5412     case 'O':
5413     case 'P':
5414     case '<':
5415     case '>':
5416       return C_Other;
5417     }
5418   }
5419 
5420   if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
5421     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
5422       return C_Memory;
5423     return C_Register;
5424   }
5425   return C_Unknown;
5426 }
5427 
5428 /// Try to replace an X constraint, which matches anything, with another that
5429 /// has more specific requirements based on the type of the corresponding
5430 /// operand.
5431 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5432   if (ConstraintVT.isInteger())
5433     return "r";
5434   if (ConstraintVT.isFloatingPoint())
5435     return "f"; // works for many targets
5436   return nullptr;
5437 }
5438 
5439 SDValue TargetLowering::LowerAsmOutputForConstraint(
5440     SDValue &Chain, SDValue &Glue, const SDLoc &DL,
5441     const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
5442   return SDValue();
5443 }
5444 
5445 /// Lower the specified operand into the Ops vector.
5446 /// If it is invalid, don't add anything to Ops.
5447 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
5448                                                   StringRef Constraint,
5449                                                   std::vector<SDValue> &Ops,
5450                                                   SelectionDAG &DAG) const {
5451 
5452   if (Constraint.size() > 1)
5453     return;
5454 
5455   char ConstraintLetter = Constraint[0];
5456   switch (ConstraintLetter) {
5457   default: break;
5458   case 'X':    // Allows any operand
5459   case 'i':    // Simple Integer or Relocatable Constant
5460   case 'n':    // Simple Integer
5461   case 's': {  // Relocatable Constant
5462 
5463     ConstantSDNode *C;
5464     uint64_t Offset = 0;
5465 
5466     // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
5467     // etc., since getelementpointer is variadic. We can't use
5468     // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
5469     // while in this case the GA may be furthest from the root node which is
5470     // likely an ISD::ADD.
5471     while (true) {
5472       if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
5473         // gcc prints these as sign extended.  Sign extend value to 64 bits
5474         // now; without this it would get ZExt'd later in
5475         // ScheduleDAGSDNodes::EmitNode, which is very generic.
5476         bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
5477         BooleanContent BCont = getBooleanContents(MVT::i64);
5478         ISD::NodeType ExtOpc =
5479             IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
5480         int64_t ExtVal =
5481             ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
5482         Ops.push_back(
5483             DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
5484         return;
5485       }
5486       if (ConstraintLetter != 'n') {
5487         if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5488           Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5489                                                    GA->getValueType(0),
5490                                                    Offset + GA->getOffset()));
5491           return;
5492         }
5493         if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
5494           Ops.push_back(DAG.getTargetBlockAddress(
5495               BA->getBlockAddress(), BA->getValueType(0),
5496               Offset + BA->getOffset(), BA->getTargetFlags()));
5497           return;
5498         }
5499         if (isa<BasicBlockSDNode>(Op)) {
5500           Ops.push_back(Op);
5501           return;
5502         }
5503       }
5504       const unsigned OpCode = Op.getOpcode();
5505       if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
5506         if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
5507           Op = Op.getOperand(1);
5508         // Subtraction is not commutative.
5509         else if (OpCode == ISD::ADD &&
5510                  (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
5511           Op = Op.getOperand(0);
5512         else
5513           return;
5514         Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
5515         continue;
5516       }
5517       return;
5518     }
5519     break;
5520   }
5521   }
5522 }
5523 
5524 void TargetLowering::CollectTargetIntrinsicOperands(
5525     const CallInst &I, SmallVectorImpl<SDValue> &Ops, SelectionDAG &DAG) const {
5526 }
5527 
5528 std::pair<unsigned, const TargetRegisterClass *>
5529 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
5530                                              StringRef Constraint,
5531                                              MVT VT) const {
5532   if (Constraint.empty() || Constraint[0] != '{')
5533     return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
5534   assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
5535 
5536   // Remove the braces from around the name.
5537   StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
5538 
5539   std::pair<unsigned, const TargetRegisterClass *> R =
5540       std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
5541 
5542   // Figure out which register class contains this reg.
5543   for (const TargetRegisterClass *RC : RI->regclasses()) {
5544     // If none of the value types for this register class are valid, we
5545     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
5546     if (!isLegalRC(*RI, *RC))
5547       continue;
5548 
5549     for (const MCPhysReg &PR : *RC) {
5550       if (RegName.equals_insensitive(RI->getRegAsmName(PR))) {
5551         std::pair<unsigned, const TargetRegisterClass *> S =
5552             std::make_pair(PR, RC);
5553 
5554         // If this register class has the requested value type, return it,
5555         // otherwise keep searching and return the first class found
5556         // if no other is found which explicitly has the requested type.
5557         if (RI->isTypeLegalForClass(*RC, VT))
5558           return S;
5559         if (!R.second)
5560           R = S;
5561       }
5562     }
5563   }
5564 
5565   return R;
5566 }
5567 
5568 //===----------------------------------------------------------------------===//
5569 // Constraint Selection.
5570 
5571 /// Return true of this is an input operand that is a matching constraint like
5572 /// "4".
5573 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
5574   assert(!ConstraintCode.empty() && "No known constraint!");
5575   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
5576 }
5577 
5578 /// If this is an input matching constraint, this method returns the output
5579 /// operand it matches.
5580 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
5581   assert(!ConstraintCode.empty() && "No known constraint!");
5582   return atoi(ConstraintCode.c_str());
5583 }
5584 
5585 /// Split up the constraint string from the inline assembly value into the
5586 /// specific constraints and their prefixes, and also tie in the associated
5587 /// operand values.
5588 /// If this returns an empty vector, and if the constraint string itself
5589 /// isn't empty, there was an error parsing.
5590 TargetLowering::AsmOperandInfoVector
5591 TargetLowering::ParseConstraints(const DataLayout &DL,
5592                                  const TargetRegisterInfo *TRI,
5593                                  const CallBase &Call) const {
5594   /// Information about all of the constraints.
5595   AsmOperandInfoVector ConstraintOperands;
5596   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
5597   unsigned maCount = 0; // Largest number of multiple alternative constraints.
5598 
5599   // Do a prepass over the constraints, canonicalizing them, and building up the
5600   // ConstraintOperands list.
5601   unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5602   unsigned ResNo = 0; // ResNo - The result number of the next output.
5603   unsigned LabelNo = 0; // LabelNo - CallBr indirect dest number.
5604 
5605   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
5606     ConstraintOperands.emplace_back(std::move(CI));
5607     AsmOperandInfo &OpInfo = ConstraintOperands.back();
5608 
5609     // Update multiple alternative constraint count.
5610     if (OpInfo.multipleAlternatives.size() > maCount)
5611       maCount = OpInfo.multipleAlternatives.size();
5612 
5613     OpInfo.ConstraintVT = MVT::Other;
5614 
5615     // Compute the value type for each operand.
5616     switch (OpInfo.Type) {
5617     case InlineAsm::isOutput:
5618       // Indirect outputs just consume an argument.
5619       if (OpInfo.isIndirect) {
5620         OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
5621         break;
5622       }
5623 
5624       // The return value of the call is this value.  As such, there is no
5625       // corresponding argument.
5626       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
5627       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
5628         OpInfo.ConstraintVT =
5629             getSimpleValueType(DL, STy->getElementType(ResNo));
5630       } else {
5631         assert(ResNo == 0 && "Asm only has one result!");
5632         OpInfo.ConstraintVT =
5633             getAsmOperandValueType(DL, Call.getType()).getSimpleVT();
5634       }
5635       ++ResNo;
5636       break;
5637     case InlineAsm::isInput:
5638       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
5639       break;
5640     case InlineAsm::isLabel:
5641       OpInfo.CallOperandVal = cast<CallBrInst>(&Call)->getIndirectDest(LabelNo);
5642       ++LabelNo;
5643       continue;
5644     case InlineAsm::isClobber:
5645       // Nothing to do.
5646       break;
5647     }
5648 
5649     if (OpInfo.CallOperandVal) {
5650       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
5651       if (OpInfo.isIndirect) {
5652         OpTy = Call.getParamElementType(ArgNo);
5653         assert(OpTy && "Indirect operand must have elementtype attribute");
5654       }
5655 
5656       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
5657       if (StructType *STy = dyn_cast<StructType>(OpTy))
5658         if (STy->getNumElements() == 1)
5659           OpTy = STy->getElementType(0);
5660 
5661       // If OpTy is not a single value, it may be a struct/union that we
5662       // can tile with integers.
5663       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5664         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
5665         switch (BitSize) {
5666         default: break;
5667         case 1:
5668         case 8:
5669         case 16:
5670         case 32:
5671         case 64:
5672         case 128:
5673           OpTy = IntegerType::get(OpTy->getContext(), BitSize);
5674           break;
5675         }
5676       }
5677 
5678       EVT VT = getAsmOperandValueType(DL, OpTy, true);
5679       OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
5680       ArgNo++;
5681     }
5682   }
5683 
5684   // If we have multiple alternative constraints, select the best alternative.
5685   if (!ConstraintOperands.empty()) {
5686     if (maCount) {
5687       unsigned bestMAIndex = 0;
5688       int bestWeight = -1;
5689       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
5690       int weight = -1;
5691       unsigned maIndex;
5692       // Compute the sums of the weights for each alternative, keeping track
5693       // of the best (highest weight) one so far.
5694       for (maIndex = 0; maIndex < maCount; ++maIndex) {
5695         int weightSum = 0;
5696         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
5697              cIndex != eIndex; ++cIndex) {
5698           AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
5699           if (OpInfo.Type == InlineAsm::isClobber)
5700             continue;
5701 
5702           // If this is an output operand with a matching input operand,
5703           // look up the matching input. If their types mismatch, e.g. one
5704           // is an integer, the other is floating point, or their sizes are
5705           // different, flag it as an maCantMatch.
5706           if (OpInfo.hasMatchingInput()) {
5707             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5708             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5709               if ((OpInfo.ConstraintVT.isInteger() !=
5710                    Input.ConstraintVT.isInteger()) ||
5711                   (OpInfo.ConstraintVT.getSizeInBits() !=
5712                    Input.ConstraintVT.getSizeInBits())) {
5713                 weightSum = -1; // Can't match.
5714                 break;
5715               }
5716             }
5717           }
5718           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
5719           if (weight == -1) {
5720             weightSum = -1;
5721             break;
5722           }
5723           weightSum += weight;
5724         }
5725         // Update best.
5726         if (weightSum > bestWeight) {
5727           bestWeight = weightSum;
5728           bestMAIndex = maIndex;
5729         }
5730       }
5731 
5732       // Now select chosen alternative in each constraint.
5733       for (AsmOperandInfo &cInfo : ConstraintOperands)
5734         if (cInfo.Type != InlineAsm::isClobber)
5735           cInfo.selectAlternative(bestMAIndex);
5736     }
5737   }
5738 
5739   // Check and hook up tied operands, choose constraint code to use.
5740   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
5741        cIndex != eIndex; ++cIndex) {
5742     AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
5743 
5744     // If this is an output operand with a matching input operand, look up the
5745     // matching input. If their types mismatch, e.g. one is an integer, the
5746     // other is floating point, or their sizes are different, flag it as an
5747     // error.
5748     if (OpInfo.hasMatchingInput()) {
5749       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5750 
5751       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5752         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
5753             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
5754                                          OpInfo.ConstraintVT);
5755         std::pair<unsigned, const TargetRegisterClass *> InputRC =
5756             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
5757                                          Input.ConstraintVT);
5758         if ((OpInfo.ConstraintVT.isInteger() !=
5759              Input.ConstraintVT.isInteger()) ||
5760             (MatchRC.second != InputRC.second)) {
5761           report_fatal_error("Unsupported asm: input constraint"
5762                              " with a matching output constraint of"
5763                              " incompatible type!");
5764         }
5765       }
5766     }
5767   }
5768 
5769   return ConstraintOperands;
5770 }
5771 
5772 /// Return a number indicating our preference for chosing a type of constraint
5773 /// over another, for the purpose of sorting them. Immediates are almost always
5774 /// preferrable (when they can be emitted). A higher return value means a
5775 /// stronger preference for one constraint type relative to another.
5776 /// FIXME: We should prefer registers over memory but doing so may lead to
5777 /// unrecoverable register exhaustion later.
5778 /// https://github.com/llvm/llvm-project/issues/20571
5779 static unsigned getConstraintPiority(TargetLowering::ConstraintType CT) {
5780   switch (CT) {
5781   case TargetLowering::C_Immediate:
5782   case TargetLowering::C_Other:
5783     return 4;
5784   case TargetLowering::C_Memory:
5785   case TargetLowering::C_Address:
5786     return 3;
5787   case TargetLowering::C_RegisterClass:
5788     return 2;
5789   case TargetLowering::C_Register:
5790     return 1;
5791   case TargetLowering::C_Unknown:
5792     return 0;
5793   }
5794   llvm_unreachable("Invalid constraint type");
5795 }
5796 
5797 /// Examine constraint type and operand type and determine a weight value.
5798 /// This object must already have been set up with the operand type
5799 /// and the current alternative constraint selected.
5800 TargetLowering::ConstraintWeight
5801   TargetLowering::getMultipleConstraintMatchWeight(
5802     AsmOperandInfo &info, int maIndex) const {
5803   InlineAsm::ConstraintCodeVector *rCodes;
5804   if (maIndex >= (int)info.multipleAlternatives.size())
5805     rCodes = &info.Codes;
5806   else
5807     rCodes = &info.multipleAlternatives[maIndex].Codes;
5808   ConstraintWeight BestWeight = CW_Invalid;
5809 
5810   // Loop over the options, keeping track of the most general one.
5811   for (const std::string &rCode : *rCodes) {
5812     ConstraintWeight weight =
5813         getSingleConstraintMatchWeight(info, rCode.c_str());
5814     if (weight > BestWeight)
5815       BestWeight = weight;
5816   }
5817 
5818   return BestWeight;
5819 }
5820 
5821 /// Examine constraint type and operand type and determine a weight value.
5822 /// This object must already have been set up with the operand type
5823 /// and the current alternative constraint selected.
5824 TargetLowering::ConstraintWeight
5825   TargetLowering::getSingleConstraintMatchWeight(
5826     AsmOperandInfo &info, const char *constraint) const {
5827   ConstraintWeight weight = CW_Invalid;
5828   Value *CallOperandVal = info.CallOperandVal;
5829     // If we don't have a value, we can't do a match,
5830     // but allow it at the lowest weight.
5831   if (!CallOperandVal)
5832     return CW_Default;
5833   // Look at the constraint type.
5834   switch (*constraint) {
5835     case 'i': // immediate integer.
5836     case 'n': // immediate integer with a known value.
5837       if (isa<ConstantInt>(CallOperandVal))
5838         weight = CW_Constant;
5839       break;
5840     case 's': // non-explicit intregal immediate.
5841       if (isa<GlobalValue>(CallOperandVal))
5842         weight = CW_Constant;
5843       break;
5844     case 'E': // immediate float if host format.
5845     case 'F': // immediate float.
5846       if (isa<ConstantFP>(CallOperandVal))
5847         weight = CW_Constant;
5848       break;
5849     case '<': // memory operand with autodecrement.
5850     case '>': // memory operand with autoincrement.
5851     case 'm': // memory operand.
5852     case 'o': // offsettable memory operand
5853     case 'V': // non-offsettable memory operand
5854       weight = CW_Memory;
5855       break;
5856     case 'r': // general register.
5857     case 'g': // general register, memory operand or immediate integer.
5858               // note: Clang converts "g" to "imr".
5859       if (CallOperandVal->getType()->isIntegerTy())
5860         weight = CW_Register;
5861       break;
5862     case 'X': // any operand.
5863   default:
5864     weight = CW_Default;
5865     break;
5866   }
5867   return weight;
5868 }
5869 
5870 /// If there are multiple different constraints that we could pick for this
5871 /// operand (e.g. "imr") try to pick the 'best' one.
5872 /// This is somewhat tricky: constraints (TargetLowering::ConstraintType) fall
5873 /// into seven classes:
5874 ///    Register      -> one specific register
5875 ///    RegisterClass -> a group of regs
5876 ///    Memory        -> memory
5877 ///    Address       -> a symbolic memory reference
5878 ///    Immediate     -> immediate values
5879 ///    Other         -> magic values (such as "Flag Output Operands")
5880 ///    Unknown       -> something we don't recognize yet and can't handle
5881 /// Ideally, we would pick the most specific constraint possible: if we have
5882 /// something that fits into a register, we would pick it.  The problem here
5883 /// is that if we have something that could either be in a register or in
5884 /// memory that use of the register could cause selection of *other*
5885 /// operands to fail: they might only succeed if we pick memory.  Because of
5886 /// this the heuristic we use is:
5887 ///
5888 ///  1) If there is an 'other' constraint, and if the operand is valid for
5889 ///     that constraint, use it.  This makes us take advantage of 'i'
5890 ///     constraints when available.
5891 ///  2) Otherwise, pick the most general constraint present.  This prefers
5892 ///     'm' over 'r', for example.
5893 ///
5894 TargetLowering::ConstraintGroup TargetLowering::getConstraintPreferences(
5895     TargetLowering::AsmOperandInfo &OpInfo) const {
5896   ConstraintGroup Ret;
5897 
5898   Ret.reserve(OpInfo.Codes.size());
5899   for (StringRef Code : OpInfo.Codes) {
5900     TargetLowering::ConstraintType CType = getConstraintType(Code);
5901 
5902     // Indirect 'other' or 'immediate' constraints are not allowed.
5903     if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
5904                                CType == TargetLowering::C_Register ||
5905                                CType == TargetLowering::C_RegisterClass))
5906       continue;
5907 
5908     // Things with matching constraints can only be registers, per gcc
5909     // documentation.  This mainly affects "g" constraints.
5910     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
5911       continue;
5912 
5913     Ret.emplace_back(Code, CType);
5914   }
5915 
5916   std::stable_sort(
5917       Ret.begin(), Ret.end(), [](ConstraintPair a, ConstraintPair b) {
5918         return getConstraintPiority(a.second) > getConstraintPiority(b.second);
5919       });
5920 
5921   return Ret;
5922 }
5923 
5924 /// If we have an immediate, see if we can lower it. Return true if we can,
5925 /// false otherwise.
5926 static bool lowerImmediateIfPossible(TargetLowering::ConstraintPair &P,
5927                                      SDValue Op, SelectionDAG *DAG,
5928                                      const TargetLowering &TLI) {
5929 
5930   assert((P.second == TargetLowering::C_Other ||
5931           P.second == TargetLowering::C_Immediate) &&
5932          "need immediate or other");
5933 
5934   if (!Op.getNode())
5935     return false;
5936 
5937   std::vector<SDValue> ResultOps;
5938   TLI.LowerAsmOperandForConstraint(Op, P.first, ResultOps, *DAG);
5939   return !ResultOps.empty();
5940 }
5941 
5942 /// Determines the constraint code and constraint type to use for the specific
5943 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
5944 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
5945                                             SDValue Op,
5946                                             SelectionDAG *DAG) const {
5947   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
5948 
5949   // Single-letter constraints ('r') are very common.
5950   if (OpInfo.Codes.size() == 1) {
5951     OpInfo.ConstraintCode = OpInfo.Codes[0];
5952     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
5953   } else {
5954     ConstraintGroup G = getConstraintPreferences(OpInfo);
5955     if (G.empty())
5956       return;
5957 
5958     unsigned BestIdx = 0;
5959     for (const unsigned E = G.size();
5960          BestIdx < E && (G[BestIdx].second == TargetLowering::C_Other ||
5961                          G[BestIdx].second == TargetLowering::C_Immediate);
5962          ++BestIdx) {
5963       if (lowerImmediateIfPossible(G[BestIdx], Op, DAG, *this))
5964         break;
5965       // If we're out of constraints, just pick the first one.
5966       if (BestIdx + 1 == E) {
5967         BestIdx = 0;
5968         break;
5969       }
5970     }
5971 
5972     OpInfo.ConstraintCode = G[BestIdx].first;
5973     OpInfo.ConstraintType = G[BestIdx].second;
5974   }
5975 
5976   // 'X' matches anything.
5977   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
5978     // Constants are handled elsewhere.  For Functions, the type here is the
5979     // type of the result, which is not what we want to look at; leave them
5980     // alone.
5981     Value *v = OpInfo.CallOperandVal;
5982     if (isa<ConstantInt>(v) || isa<Function>(v)) {
5983       return;
5984     }
5985 
5986     if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) {
5987       OpInfo.ConstraintCode = "i";
5988       return;
5989     }
5990 
5991     // Otherwise, try to resolve it to something we know about by looking at
5992     // the actual operand type.
5993     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
5994       OpInfo.ConstraintCode = Repl;
5995       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
5996     }
5997   }
5998 }
5999 
6000 /// Given an exact SDIV by a constant, create a multiplication
6001 /// with the multiplicative inverse of the constant.
6002 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N,
6003                               const SDLoc &dl, SelectionDAG &DAG,
6004                               SmallVectorImpl<SDNode *> &Created) {
6005   SDValue Op0 = N->getOperand(0);
6006   SDValue Op1 = N->getOperand(1);
6007   EVT VT = N->getValueType(0);
6008   EVT SVT = VT.getScalarType();
6009   EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6010   EVT ShSVT = ShVT.getScalarType();
6011 
6012   bool UseSRA = false;
6013   SmallVector<SDValue, 16> Shifts, Factors;
6014 
6015   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6016     if (C->isZero())
6017       return false;
6018     APInt Divisor = C->getAPIntValue();
6019     unsigned Shift = Divisor.countr_zero();
6020     if (Shift) {
6021       Divisor.ashrInPlace(Shift);
6022       UseSRA = true;
6023     }
6024     // Calculate the multiplicative inverse, using Newton's method.
6025     APInt t;
6026     APInt Factor = Divisor;
6027     while ((t = Divisor * Factor) != 1)
6028       Factor *= APInt(Divisor.getBitWidth(), 2) - t;
6029     Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6030     Factors.push_back(DAG.getConstant(Factor, dl, SVT));
6031     return true;
6032   };
6033 
6034   // Collect all magic values from the build vector.
6035   if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
6036     return SDValue();
6037 
6038   SDValue Shift, Factor;
6039   if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6040     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6041     Factor = DAG.getBuildVector(VT, dl, Factors);
6042   } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6043     assert(Shifts.size() == 1 && Factors.size() == 1 &&
6044            "Expected matchUnaryPredicate to return one element for scalable "
6045            "vectors");
6046     Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6047     Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6048   } else {
6049     assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6050     Shift = Shifts[0];
6051     Factor = Factors[0];
6052   }
6053 
6054   SDValue Res = Op0;
6055 
6056   // Shift the value upfront if it is even, so the LSB is one.
6057   if (UseSRA) {
6058     // TODO: For UDIV use SRL instead of SRA.
6059     SDNodeFlags Flags;
6060     Flags.setExact(true);
6061     Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags);
6062     Created.push_back(Res.getNode());
6063   }
6064 
6065   return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6066 }
6067 
6068 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
6069                               SelectionDAG &DAG,
6070                               SmallVectorImpl<SDNode *> &Created) const {
6071   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
6072   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6073   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
6074     return SDValue(N, 0); // Lower SDIV as SDIV
6075   return SDValue();
6076 }
6077 
6078 SDValue
6079 TargetLowering::BuildSREMPow2(SDNode *N, const APInt &Divisor,
6080                               SelectionDAG &DAG,
6081                               SmallVectorImpl<SDNode *> &Created) const {
6082   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
6083   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6084   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
6085     return SDValue(N, 0); // Lower SREM as SREM
6086   return SDValue();
6087 }
6088 
6089 /// Build sdiv by power-of-2 with conditional move instructions
6090 /// Ref: "Hacker's Delight" by Henry Warren 10-1
6091 /// If conditional move/branch is preferred, we lower sdiv x, +/-2**k into:
6092 ///   bgez x, label
6093 ///   add x, x, 2**k-1
6094 /// label:
6095 ///   sra res, x, k
6096 ///   neg res, res (when the divisor is negative)
6097 SDValue TargetLowering::buildSDIVPow2WithCMov(
6098     SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
6099     SmallVectorImpl<SDNode *> &Created) const {
6100   unsigned Lg2 = Divisor.countr_zero();
6101   EVT VT = N->getValueType(0);
6102 
6103   SDLoc DL(N);
6104   SDValue N0 = N->getOperand(0);
6105   SDValue Zero = DAG.getConstant(0, DL, VT);
6106   APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
6107   SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
6108 
6109   // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
6110   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6111   SDValue Cmp = DAG.getSetCC(DL, CCVT, N0, Zero, ISD::SETLT);
6112   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
6113   SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
6114 
6115   Created.push_back(Cmp.getNode());
6116   Created.push_back(Add.getNode());
6117   Created.push_back(CMov.getNode());
6118 
6119   // Divide by pow2.
6120   SDValue SRA =
6121       DAG.getNode(ISD::SRA, DL, VT, CMov, DAG.getConstant(Lg2, DL, VT));
6122 
6123   // If we're dividing by a positive value, we're done.  Otherwise, we must
6124   // negate the result.
6125   if (Divisor.isNonNegative())
6126     return SRA;
6127 
6128   Created.push_back(SRA.getNode());
6129   return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
6130 }
6131 
6132 /// Given an ISD::SDIV node expressing a divide by constant,
6133 /// return a DAG expression to select that will generate the same value by
6134 /// multiplying by a magic number.
6135 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
6136 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
6137                                   bool IsAfterLegalization,
6138                                   SmallVectorImpl<SDNode *> &Created) const {
6139   SDLoc dl(N);
6140   EVT VT = N->getValueType(0);
6141   EVT SVT = VT.getScalarType();
6142   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
6143   EVT ShSVT = ShVT.getScalarType();
6144   unsigned EltBits = VT.getScalarSizeInBits();
6145   EVT MulVT;
6146 
6147   // Check to see if we can do this.
6148   // FIXME: We should be more aggressive here.
6149   if (!isTypeLegal(VT)) {
6150     // Limit this to simple scalars for now.
6151     if (VT.isVector() || !VT.isSimple())
6152       return SDValue();
6153 
6154     // If this type will be promoted to a large enough type with a legal
6155     // multiply operation, we can go ahead and do this transform.
6156     if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger)
6157       return SDValue();
6158 
6159     MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
6160     if (MulVT.getSizeInBits() < (2 * EltBits) ||
6161         !isOperationLegal(ISD::MUL, MulVT))
6162       return SDValue();
6163   }
6164 
6165   // If the sdiv has an 'exact' bit we can use a simpler lowering.
6166   if (N->getFlags().hasExact())
6167     return BuildExactSDIV(*this, N, dl, DAG, Created);
6168 
6169   SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
6170 
6171   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6172     if (C->isZero())
6173       return false;
6174 
6175     const APInt &Divisor = C->getAPIntValue();
6176     SignedDivisionByConstantInfo magics = SignedDivisionByConstantInfo::get(Divisor);
6177     int NumeratorFactor = 0;
6178     int ShiftMask = -1;
6179 
6180     if (Divisor.isOne() || Divisor.isAllOnes()) {
6181       // If d is +1/-1, we just multiply the numerator by +1/-1.
6182       NumeratorFactor = Divisor.getSExtValue();
6183       magics.Magic = 0;
6184       magics.ShiftAmount = 0;
6185       ShiftMask = 0;
6186     } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) {
6187       // If d > 0 and m < 0, add the numerator.
6188       NumeratorFactor = 1;
6189     } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) {
6190       // If d < 0 and m > 0, subtract the numerator.
6191       NumeratorFactor = -1;
6192     }
6193 
6194     MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT));
6195     Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT));
6196     Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT));
6197     ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT));
6198     return true;
6199   };
6200 
6201   SDValue N0 = N->getOperand(0);
6202   SDValue N1 = N->getOperand(1);
6203 
6204   // Collect the shifts / magic values from each element.
6205   if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern))
6206     return SDValue();
6207 
6208   SDValue MagicFactor, Factor, Shift, ShiftMask;
6209   if (N1.getOpcode() == ISD::BUILD_VECTOR) {
6210     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
6211     Factor = DAG.getBuildVector(VT, dl, Factors);
6212     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6213     ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
6214   } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
6215     assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
6216            Shifts.size() == 1 && ShiftMasks.size() == 1 &&
6217            "Expected matchUnaryPredicate to return one element for scalable "
6218            "vectors");
6219     MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
6220     Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6221     Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6222     ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
6223   } else {
6224     assert(isa<ConstantSDNode>(N1) && "Expected a constant");
6225     MagicFactor = MagicFactors[0];
6226     Factor = Factors[0];
6227     Shift = Shifts[0];
6228     ShiftMask = ShiftMasks[0];
6229   }
6230 
6231   // Multiply the numerator (operand 0) by the magic value.
6232   // FIXME: We should support doing a MUL in a wider type.
6233   auto GetMULHS = [&](SDValue X, SDValue Y) {
6234     // If the type isn't legal, use a wider mul of the type calculated
6235     // earlier.
6236     if (!isTypeLegal(VT)) {
6237       X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
6238       Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
6239       Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
6240       Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
6241                       DAG.getShiftAmountConstant(EltBits, MulVT, dl));
6242       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
6243     }
6244 
6245     if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization))
6246       return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
6247     if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) {
6248       SDValue LoHi =
6249           DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
6250       return SDValue(LoHi.getNode(), 1);
6251     }
6252     // If type twice as wide legal, widen and use a mul plus a shift.
6253     unsigned Size = VT.getScalarSizeInBits();
6254     EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), Size * 2);
6255     if (VT.isVector())
6256       WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT,
6257                                 VT.getVectorElementCount());
6258     if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
6259       X = DAG.getNode(ISD::SIGN_EXTEND, dl, WideVT, X);
6260       Y = DAG.getNode(ISD::SIGN_EXTEND, dl, WideVT, Y);
6261       Y = DAG.getNode(ISD::MUL, dl, WideVT, X, Y);
6262       Y = DAG.getNode(ISD::SRL, dl, WideVT, Y,
6263                       DAG.getShiftAmountConstant(EltBits, WideVT, dl));
6264       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
6265     }
6266     return SDValue();
6267   };
6268 
6269   SDValue Q = GetMULHS(N0, MagicFactor);
6270   if (!Q)
6271     return SDValue();
6272 
6273   Created.push_back(Q.getNode());
6274 
6275   // (Optionally) Add/subtract the numerator using Factor.
6276   Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
6277   Created.push_back(Factor.getNode());
6278   Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
6279   Created.push_back(Q.getNode());
6280 
6281   // Shift right algebraic by shift value.
6282   Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
6283   Created.push_back(Q.getNode());
6284 
6285   // Extract the sign bit, mask it and add it to the quotient.
6286   SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
6287   SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
6288   Created.push_back(T.getNode());
6289   T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
6290   Created.push_back(T.getNode());
6291   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
6292 }
6293 
6294 /// Given an ISD::UDIV node expressing a divide by constant,
6295 /// return a DAG expression to select that will generate the same value by
6296 /// multiplying by a magic number.
6297 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
6298 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
6299                                   bool IsAfterLegalization,
6300                                   SmallVectorImpl<SDNode *> &Created) const {
6301   SDLoc dl(N);
6302   EVT VT = N->getValueType(0);
6303   EVT SVT = VT.getScalarType();
6304   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
6305   EVT ShSVT = ShVT.getScalarType();
6306   unsigned EltBits = VT.getScalarSizeInBits();
6307   EVT MulVT;
6308 
6309   // Check to see if we can do this.
6310   // FIXME: We should be more aggressive here.
6311   if (!isTypeLegal(VT)) {
6312     // Limit this to simple scalars for now.
6313     if (VT.isVector() || !VT.isSimple())
6314       return SDValue();
6315 
6316     // If this type will be promoted to a large enough type with a legal
6317     // multiply operation, we can go ahead and do this transform.
6318     if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger)
6319       return SDValue();
6320 
6321     MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
6322     if (MulVT.getSizeInBits() < (2 * EltBits) ||
6323         !isOperationLegal(ISD::MUL, MulVT))
6324       return SDValue();
6325   }
6326 
6327   SDValue N0 = N->getOperand(0);
6328   SDValue N1 = N->getOperand(1);
6329 
6330   // Try to use leading zeros of the dividend to reduce the multiplier and
6331   // avoid expensive fixups.
6332   // TODO: Support vectors.
6333   unsigned LeadingZeros = 0;
6334   if (!VT.isVector() && isa<ConstantSDNode>(N1)) {
6335     assert(!isOneConstant(N1) && "Unexpected divisor");
6336     LeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
6337     // UnsignedDivisionByConstantInfo doesn't work correctly if leading zeros in
6338     // the dividend exceeds the leading zeros for the divisor.
6339     LeadingZeros = std::min(
6340         LeadingZeros, cast<ConstantSDNode>(N1)->getAPIntValue().countl_zero());
6341   }
6342 
6343   bool UseNPQ = false, UsePreShift = false, UsePostShift = false;
6344   SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
6345 
6346   auto BuildUDIVPattern = [&](ConstantSDNode *C) {
6347     if (C->isZero())
6348       return false;
6349     const APInt& Divisor = C->getAPIntValue();
6350 
6351     SDValue PreShift, MagicFactor, NPQFactor, PostShift;
6352 
6353     // Magic algorithm doesn't work for division by 1. We need to emit a select
6354     // at the end.
6355     if (Divisor.isOne()) {
6356       PreShift = PostShift = DAG.getUNDEF(ShSVT);
6357       MagicFactor = NPQFactor = DAG.getUNDEF(SVT);
6358     } else {
6359       UnsignedDivisionByConstantInfo magics =
6360           UnsignedDivisionByConstantInfo::get(Divisor, LeadingZeros);
6361 
6362       MagicFactor = DAG.getConstant(magics.Magic, dl, SVT);
6363 
6364       assert(magics.PreShift < Divisor.getBitWidth() &&
6365              "We shouldn't generate an undefined shift!");
6366       assert(magics.PostShift < Divisor.getBitWidth() &&
6367              "We shouldn't generate an undefined shift!");
6368       assert((!magics.IsAdd || magics.PreShift == 0) &&
6369              "Unexpected pre-shift");
6370       PreShift = DAG.getConstant(magics.PreShift, dl, ShSVT);
6371       PostShift = DAG.getConstant(magics.PostShift, dl, ShSVT);
6372       NPQFactor = DAG.getConstant(
6373           magics.IsAdd ? APInt::getOneBitSet(EltBits, EltBits - 1)
6374                        : APInt::getZero(EltBits),
6375           dl, SVT);
6376       UseNPQ |= magics.IsAdd;
6377       UsePreShift |= magics.PreShift != 0;
6378       UsePostShift |= magics.PostShift != 0;
6379     }
6380 
6381     PreShifts.push_back(PreShift);
6382     MagicFactors.push_back(MagicFactor);
6383     NPQFactors.push_back(NPQFactor);
6384     PostShifts.push_back(PostShift);
6385     return true;
6386   };
6387 
6388   // Collect the shifts/magic values from each element.
6389   if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern))
6390     return SDValue();
6391 
6392   SDValue PreShift, PostShift, MagicFactor, NPQFactor;
6393   if (N1.getOpcode() == ISD::BUILD_VECTOR) {
6394     PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
6395     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
6396     NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
6397     PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
6398   } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
6399     assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
6400            NPQFactors.size() == 1 && PostShifts.size() == 1 &&
6401            "Expected matchUnaryPredicate to return one for scalable vectors");
6402     PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
6403     MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
6404     NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
6405     PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
6406   } else {
6407     assert(isa<ConstantSDNode>(N1) && "Expected a constant");
6408     PreShift = PreShifts[0];
6409     MagicFactor = MagicFactors[0];
6410     PostShift = PostShifts[0];
6411   }
6412 
6413   SDValue Q = N0;
6414   if (UsePreShift) {
6415     Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
6416     Created.push_back(Q.getNode());
6417   }
6418 
6419   // FIXME: We should support doing a MUL in a wider type.
6420   auto GetMULHU = [&](SDValue X, SDValue Y) {
6421     // If the type isn't legal, use a wider mul of the type calculated
6422     // earlier.
6423     if (!isTypeLegal(VT)) {
6424       X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
6425       Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
6426       Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
6427       Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
6428                       DAG.getShiftAmountConstant(EltBits, MulVT, dl));
6429       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
6430     }
6431 
6432     if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization))
6433       return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
6434     if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) {
6435       SDValue LoHi =
6436           DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
6437       return SDValue(LoHi.getNode(), 1);
6438     }
6439     // If type twice as wide legal, widen and use a mul plus a shift.
6440     unsigned Size = VT.getScalarSizeInBits();
6441     EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), Size * 2);
6442     if (VT.isVector())
6443       WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT,
6444                                 VT.getVectorElementCount());
6445     if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
6446       X = DAG.getNode(ISD::ZERO_EXTEND, dl, WideVT, X);
6447       Y = DAG.getNode(ISD::ZERO_EXTEND, dl, WideVT, Y);
6448       Y = DAG.getNode(ISD::MUL, dl, WideVT, X, Y);
6449       Y = DAG.getNode(ISD::SRL, dl, WideVT, Y,
6450                       DAG.getShiftAmountConstant(EltBits, WideVT, dl));
6451       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
6452     }
6453     return SDValue(); // No mulhu or equivalent
6454   };
6455 
6456   // Multiply the numerator (operand 0) by the magic value.
6457   Q = GetMULHU(Q, MagicFactor);
6458   if (!Q)
6459     return SDValue();
6460 
6461   Created.push_back(Q.getNode());
6462 
6463   if (UseNPQ) {
6464     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
6465     Created.push_back(NPQ.getNode());
6466 
6467     // For vectors we might have a mix of non-NPQ/NPQ paths, so use
6468     // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
6469     if (VT.isVector())
6470       NPQ = GetMULHU(NPQ, NPQFactor);
6471     else
6472       NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
6473 
6474     Created.push_back(NPQ.getNode());
6475 
6476     Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
6477     Created.push_back(Q.getNode());
6478   }
6479 
6480   if (UsePostShift) {
6481     Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
6482     Created.push_back(Q.getNode());
6483   }
6484 
6485   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6486 
6487   SDValue One = DAG.getConstant(1, dl, VT);
6488   SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
6489   return DAG.getSelect(dl, VT, IsOne, N0, Q);
6490 }
6491 
6492 /// If all values in Values that *don't* match the predicate are same 'splat'
6493 /// value, then replace all values with that splat value.
6494 /// Else, if AlternativeReplacement was provided, then replace all values that
6495 /// do match predicate with AlternativeReplacement value.
6496 static void
6497 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values,
6498                           std::function<bool(SDValue)> Predicate,
6499                           SDValue AlternativeReplacement = SDValue()) {
6500   SDValue Replacement;
6501   // Is there a value for which the Predicate does *NOT* match? What is it?
6502   auto SplatValue = llvm::find_if_not(Values, Predicate);
6503   if (SplatValue != Values.end()) {
6504     // Does Values consist only of SplatValue's and values matching Predicate?
6505     if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
6506           return Value == *SplatValue || Predicate(Value);
6507         })) // Then we shall replace values matching predicate with SplatValue.
6508       Replacement = *SplatValue;
6509   }
6510   if (!Replacement) {
6511     // Oops, we did not find the "baseline" splat value.
6512     if (!AlternativeReplacement)
6513       return; // Nothing to do.
6514     // Let's replace with provided value then.
6515     Replacement = AlternativeReplacement;
6516   }
6517   std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
6518 }
6519 
6520 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
6521 /// where the divisor is constant and the comparison target is zero,
6522 /// return a DAG expression that will generate the same comparison result
6523 /// using only multiplications, additions and shifts/rotations.
6524 /// Ref: "Hacker's Delight" 10-17.
6525 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
6526                                         SDValue CompTargetNode,
6527                                         ISD::CondCode Cond,
6528                                         DAGCombinerInfo &DCI,
6529                                         const SDLoc &DL) const {
6530   SmallVector<SDNode *, 5> Built;
6531   if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
6532                                          DCI, DL, Built)) {
6533     for (SDNode *N : Built)
6534       DCI.AddToWorklist(N);
6535     return Folded;
6536   }
6537 
6538   return SDValue();
6539 }
6540 
6541 SDValue
6542 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
6543                                   SDValue CompTargetNode, ISD::CondCode Cond,
6544                                   DAGCombinerInfo &DCI, const SDLoc &DL,
6545                                   SmallVectorImpl<SDNode *> &Created) const {
6546   // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q)
6547   // - D must be constant, with D = D0 * 2^K where D0 is odd
6548   // - P is the multiplicative inverse of D0 modulo 2^W
6549   // - Q = floor(((2^W) - 1) / D)
6550   // where W is the width of the common type of N and D.
6551   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
6552          "Only applicable for (in)equality comparisons.");
6553 
6554   SelectionDAG &DAG = DCI.DAG;
6555 
6556   EVT VT = REMNode.getValueType();
6557   EVT SVT = VT.getScalarType();
6558   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize());
6559   EVT ShSVT = ShVT.getScalarType();
6560 
6561   // If MUL is unavailable, we cannot proceed in any case.
6562   if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
6563     return SDValue();
6564 
6565   bool ComparingWithAllZeros = true;
6566   bool AllComparisonsWithNonZerosAreTautological = true;
6567   bool HadTautologicalLanes = false;
6568   bool AllLanesAreTautological = true;
6569   bool HadEvenDivisor = false;
6570   bool AllDivisorsArePowerOfTwo = true;
6571   bool HadTautologicalInvertedLanes = false;
6572   SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts;
6573 
6574   auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
6575     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
6576     if (CDiv->isZero())
6577       return false;
6578 
6579     const APInt &D = CDiv->getAPIntValue();
6580     const APInt &Cmp = CCmp->getAPIntValue();
6581 
6582     ComparingWithAllZeros &= Cmp.isZero();
6583 
6584     // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
6585     // if C2 is not less than C1, the comparison is always false.
6586     // But we will only be able to produce the comparison that will give the
6587     // opposive tautological answer. So this lane would need to be fixed up.
6588     bool TautologicalInvertedLane = D.ule(Cmp);
6589     HadTautologicalInvertedLanes |= TautologicalInvertedLane;
6590 
6591     // If all lanes are tautological (either all divisors are ones, or divisor
6592     // is not greater than the constant we are comparing with),
6593     // we will prefer to avoid the fold.
6594     bool TautologicalLane = D.isOne() || TautologicalInvertedLane;
6595     HadTautologicalLanes |= TautologicalLane;
6596     AllLanesAreTautological &= TautologicalLane;
6597 
6598     // If we are comparing with non-zero, we need'll need  to subtract said
6599     // comparison value from the LHS. But there is no point in doing that if
6600     // every lane where we are comparing with non-zero is tautological..
6601     if (!Cmp.isZero())
6602       AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
6603 
6604     // Decompose D into D0 * 2^K
6605     unsigned K = D.countr_zero();
6606     assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
6607     APInt D0 = D.lshr(K);
6608 
6609     // D is even if it has trailing zeros.
6610     HadEvenDivisor |= (K != 0);
6611     // D is a power-of-two if D0 is one.
6612     // If all divisors are power-of-two, we will prefer to avoid the fold.
6613     AllDivisorsArePowerOfTwo &= D0.isOne();
6614 
6615     // P = inv(D0, 2^W)
6616     // 2^W requires W + 1 bits, so we have to extend and then truncate.
6617     unsigned W = D.getBitWidth();
6618     APInt P = D0.zext(W + 1)
6619                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
6620                   .trunc(W);
6621     assert(!P.isZero() && "No multiplicative inverse!"); // unreachable
6622     assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
6623 
6624     // Q = floor((2^W - 1) u/ D)
6625     // R = ((2^W - 1) u% D)
6626     APInt Q, R;
6627     APInt::udivrem(APInt::getAllOnes(W), D, Q, R);
6628 
6629     // If we are comparing with zero, then that comparison constant is okay,
6630     // else it may need to be one less than that.
6631     if (Cmp.ugt(R))
6632       Q -= 1;
6633 
6634     assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) &&
6635            "We are expecting that K is always less than all-ones for ShSVT");
6636 
6637     // If the lane is tautological the result can be constant-folded.
6638     if (TautologicalLane) {
6639       // Set P and K amount to a bogus values so we can try to splat them.
6640       P = 0;
6641       K = -1;
6642       // And ensure that comparison constant is tautological,
6643       // it will always compare true/false.
6644       Q = -1;
6645     }
6646 
6647     PAmts.push_back(DAG.getConstant(P, DL, SVT));
6648     KAmts.push_back(
6649         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
6650     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
6651     return true;
6652   };
6653 
6654   SDValue N = REMNode.getOperand(0);
6655   SDValue D = REMNode.getOperand(1);
6656 
6657   // Collect the values from each element.
6658   if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
6659     return SDValue();
6660 
6661   // If all lanes are tautological, the result can be constant-folded.
6662   if (AllLanesAreTautological)
6663     return SDValue();
6664 
6665   // If this is a urem by a powers-of-two, avoid the fold since it can be
6666   // best implemented as a bit test.
6667   if (AllDivisorsArePowerOfTwo)
6668     return SDValue();
6669 
6670   SDValue PVal, KVal, QVal;
6671   if (D.getOpcode() == ISD::BUILD_VECTOR) {
6672     if (HadTautologicalLanes) {
6673       // Try to turn PAmts into a splat, since we don't care about the values
6674       // that are currently '0'. If we can't, just keep '0'`s.
6675       turnVectorIntoSplatVector(PAmts, isNullConstant);
6676       // Try to turn KAmts into a splat, since we don't care about the values
6677       // that are currently '-1'. If we can't, change them to '0'`s.
6678       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
6679                                 DAG.getConstant(0, DL, ShSVT));
6680     }
6681 
6682     PVal = DAG.getBuildVector(VT, DL, PAmts);
6683     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
6684     QVal = DAG.getBuildVector(VT, DL, QAmts);
6685   } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
6686     assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 &&
6687            "Expected matchBinaryPredicate to return one element for "
6688            "SPLAT_VECTORs");
6689     PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
6690     KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
6691     QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
6692   } else {
6693     PVal = PAmts[0];
6694     KVal = KAmts[0];
6695     QVal = QAmts[0];
6696   }
6697 
6698   if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
6699     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
6700       return SDValue(); // FIXME: Could/should use `ISD::ADD`?
6701     assert(CompTargetNode.getValueType() == N.getValueType() &&
6702            "Expecting that the types on LHS and RHS of comparisons match.");
6703     N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
6704   }
6705 
6706   // (mul N, P)
6707   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
6708   Created.push_back(Op0.getNode());
6709 
6710   // Rotate right only if any divisor was even. We avoid rotates for all-odd
6711   // divisors as a performance improvement, since rotating by 0 is a no-op.
6712   if (HadEvenDivisor) {
6713     // We need ROTR to do this.
6714     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
6715       return SDValue();
6716     // UREM: (rotr (mul N, P), K)
6717     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
6718     Created.push_back(Op0.getNode());
6719   }
6720 
6721   // UREM: (setule/setugt (rotr (mul N, P), K), Q)
6722   SDValue NewCC =
6723       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
6724                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
6725   if (!HadTautologicalInvertedLanes)
6726     return NewCC;
6727 
6728   // If any lanes previously compared always-false, the NewCC will give
6729   // always-true result for them, so we need to fixup those lanes.
6730   // Or the other way around for inequality predicate.
6731   assert(VT.isVector() && "Can/should only get here for vectors.");
6732   Created.push_back(NewCC.getNode());
6733 
6734   // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
6735   // if C2 is not less than C1, the comparison is always false.
6736   // But we have produced the comparison that will give the
6737   // opposive tautological answer. So these lanes would need to be fixed up.
6738   SDValue TautologicalInvertedChannels =
6739       DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
6740   Created.push_back(TautologicalInvertedChannels.getNode());
6741 
6742   // NOTE: we avoid letting illegal types through even if we're before legalize
6743   // ops – legalization has a hard time producing good code for this.
6744   if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
6745     // If we have a vector select, let's replace the comparison results in the
6746     // affected lanes with the correct tautological result.
6747     SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
6748                                               DL, SETCCVT, SETCCVT);
6749     return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
6750                        Replacement, NewCC);
6751   }
6752 
6753   // Else, we can just invert the comparison result in the appropriate lanes.
6754   //
6755   // NOTE: see the note above VSELECT above.
6756   if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
6757     return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
6758                        TautologicalInvertedChannels);
6759 
6760   return SDValue(); // Don't know how to lower.
6761 }
6762 
6763 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
6764 /// where the divisor is constant and the comparison target is zero,
6765 /// return a DAG expression that will generate the same comparison result
6766 /// using only multiplications, additions and shifts/rotations.
6767 /// Ref: "Hacker's Delight" 10-17.
6768 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
6769                                         SDValue CompTargetNode,
6770                                         ISD::CondCode Cond,
6771                                         DAGCombinerInfo &DCI,
6772                                         const SDLoc &DL) const {
6773   SmallVector<SDNode *, 7> Built;
6774   if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
6775                                          DCI, DL, Built)) {
6776     assert(Built.size() <= 7 && "Max size prediction failed.");
6777     for (SDNode *N : Built)
6778       DCI.AddToWorklist(N);
6779     return Folded;
6780   }
6781 
6782   return SDValue();
6783 }
6784 
6785 SDValue
6786 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
6787                                   SDValue CompTargetNode, ISD::CondCode Cond,
6788                                   DAGCombinerInfo &DCI, const SDLoc &DL,
6789                                   SmallVectorImpl<SDNode *> &Created) const {
6790   // Fold:
6791   //   (seteq/ne (srem N, D), 0)
6792   // To:
6793   //   (setule/ugt (rotr (add (mul N, P), A), K), Q)
6794   //
6795   // - D must be constant, with D = D0 * 2^K where D0 is odd
6796   // - P is the multiplicative inverse of D0 modulo 2^W
6797   // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
6798   // - Q = floor((2 * A) / (2^K))
6799   // where W is the width of the common type of N and D.
6800   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
6801          "Only applicable for (in)equality comparisons.");
6802 
6803   SelectionDAG &DAG = DCI.DAG;
6804 
6805   EVT VT = REMNode.getValueType();
6806   EVT SVT = VT.getScalarType();
6807   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize());
6808   EVT ShSVT = ShVT.getScalarType();
6809 
6810   // If we are after ops legalization, and MUL is unavailable, we can not
6811   // proceed.
6812   if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
6813     return SDValue();
6814 
6815   // TODO: Could support comparing with non-zero too.
6816   ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
6817   if (!CompTarget || !CompTarget->isZero())
6818     return SDValue();
6819 
6820   bool HadIntMinDivisor = false;
6821   bool HadOneDivisor = false;
6822   bool AllDivisorsAreOnes = true;
6823   bool HadEvenDivisor = false;
6824   bool NeedToApplyOffset = false;
6825   bool AllDivisorsArePowerOfTwo = true;
6826   SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
6827 
6828   auto BuildSREMPattern = [&](ConstantSDNode *C) {
6829     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
6830     if (C->isZero())
6831       return false;
6832 
6833     // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
6834 
6835     // WARNING: this fold is only valid for positive divisors!
6836     APInt D = C->getAPIntValue();
6837     if (D.isNegative())
6838       D.negate(); //  `rem %X, -C` is equivalent to `rem %X, C`
6839 
6840     HadIntMinDivisor |= D.isMinSignedValue();
6841 
6842     // If all divisors are ones, we will prefer to avoid the fold.
6843     HadOneDivisor |= D.isOne();
6844     AllDivisorsAreOnes &= D.isOne();
6845 
6846     // Decompose D into D0 * 2^K
6847     unsigned K = D.countr_zero();
6848     assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
6849     APInt D0 = D.lshr(K);
6850 
6851     if (!D.isMinSignedValue()) {
6852       // D is even if it has trailing zeros; unless it's INT_MIN, in which case
6853       // we don't care about this lane in this fold, we'll special-handle it.
6854       HadEvenDivisor |= (K != 0);
6855     }
6856 
6857     // D is a power-of-two if D0 is one. This includes INT_MIN.
6858     // If all divisors are power-of-two, we will prefer to avoid the fold.
6859     AllDivisorsArePowerOfTwo &= D0.isOne();
6860 
6861     // P = inv(D0, 2^W)
6862     // 2^W requires W + 1 bits, so we have to extend and then truncate.
6863     unsigned W = D.getBitWidth();
6864     APInt P = D0.zext(W + 1)
6865                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
6866                   .trunc(W);
6867     assert(!P.isZero() && "No multiplicative inverse!"); // unreachable
6868     assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
6869 
6870     // A = floor((2^(W - 1) - 1) / D0) & -2^K
6871     APInt A = APInt::getSignedMaxValue(W).udiv(D0);
6872     A.clearLowBits(K);
6873 
6874     if (!D.isMinSignedValue()) {
6875       // If divisor INT_MIN, then we don't care about this lane in this fold,
6876       // we'll special-handle it.
6877       NeedToApplyOffset |= A != 0;
6878     }
6879 
6880     // Q = floor((2 * A) / (2^K))
6881     APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
6882 
6883     assert(APInt::getAllOnes(SVT.getSizeInBits()).ugt(A) &&
6884            "We are expecting that A is always less than all-ones for SVT");
6885     assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) &&
6886            "We are expecting that K is always less than all-ones for ShSVT");
6887 
6888     // If the divisor is 1 the result can be constant-folded. Likewise, we
6889     // don't care about INT_MIN lanes, those can be set to undef if appropriate.
6890     if (D.isOne()) {
6891       // Set P, A and K to a bogus values so we can try to splat them.
6892       P = 0;
6893       A = -1;
6894       K = -1;
6895 
6896       // x ?% 1 == 0  <-->  true  <-->  x u<= -1
6897       Q = -1;
6898     }
6899 
6900     PAmts.push_back(DAG.getConstant(P, DL, SVT));
6901     AAmts.push_back(DAG.getConstant(A, DL, SVT));
6902     KAmts.push_back(
6903         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
6904     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
6905     return true;
6906   };
6907 
6908   SDValue N = REMNode.getOperand(0);
6909   SDValue D = REMNode.getOperand(1);
6910 
6911   // Collect the values from each element.
6912   if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
6913     return SDValue();
6914 
6915   // If this is a srem by a one, avoid the fold since it can be constant-folded.
6916   if (AllDivisorsAreOnes)
6917     return SDValue();
6918 
6919   // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
6920   // since it can be best implemented as a bit test.
6921   if (AllDivisorsArePowerOfTwo)
6922     return SDValue();
6923 
6924   SDValue PVal, AVal, KVal, QVal;
6925   if (D.getOpcode() == ISD::BUILD_VECTOR) {
6926     if (HadOneDivisor) {
6927       // Try to turn PAmts into a splat, since we don't care about the values
6928       // that are currently '0'. If we can't, just keep '0'`s.
6929       turnVectorIntoSplatVector(PAmts, isNullConstant);
6930       // Try to turn AAmts into a splat, since we don't care about the
6931       // values that are currently '-1'. If we can't, change them to '0'`s.
6932       turnVectorIntoSplatVector(AAmts, isAllOnesConstant,
6933                                 DAG.getConstant(0, DL, SVT));
6934       // Try to turn KAmts into a splat, since we don't care about the values
6935       // that are currently '-1'. If we can't, change them to '0'`s.
6936       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
6937                                 DAG.getConstant(0, DL, ShSVT));
6938     }
6939 
6940     PVal = DAG.getBuildVector(VT, DL, PAmts);
6941     AVal = DAG.getBuildVector(VT, DL, AAmts);
6942     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
6943     QVal = DAG.getBuildVector(VT, DL, QAmts);
6944   } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
6945     assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
6946            QAmts.size() == 1 &&
6947            "Expected matchUnaryPredicate to return one element for scalable "
6948            "vectors");
6949     PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
6950     AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
6951     KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
6952     QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
6953   } else {
6954     assert(isa<ConstantSDNode>(D) && "Expected a constant");
6955     PVal = PAmts[0];
6956     AVal = AAmts[0];
6957     KVal = KAmts[0];
6958     QVal = QAmts[0];
6959   }
6960 
6961   // (mul N, P)
6962   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
6963   Created.push_back(Op0.getNode());
6964 
6965   if (NeedToApplyOffset) {
6966     // We need ADD to do this.
6967     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
6968       return SDValue();
6969 
6970     // (add (mul N, P), A)
6971     Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
6972     Created.push_back(Op0.getNode());
6973   }
6974 
6975   // Rotate right only if any divisor was even. We avoid rotates for all-odd
6976   // divisors as a performance improvement, since rotating by 0 is a no-op.
6977   if (HadEvenDivisor) {
6978     // We need ROTR to do this.
6979     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
6980       return SDValue();
6981     // SREM: (rotr (add (mul N, P), A), K)
6982     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
6983     Created.push_back(Op0.getNode());
6984   }
6985 
6986   // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
6987   SDValue Fold =
6988       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
6989                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
6990 
6991   // If we didn't have lanes with INT_MIN divisor, then we're done.
6992   if (!HadIntMinDivisor)
6993     return Fold;
6994 
6995   // That fold is only valid for positive divisors. Which effectively means,
6996   // it is invalid for INT_MIN divisors. So if we have such a lane,
6997   // we must fix-up results for said lanes.
6998   assert(VT.isVector() && "Can/should only get here for vectors.");
6999 
7000   // NOTE: we avoid letting illegal types through even if we're before legalize
7001   // ops – legalization has a hard time producing good code for the code that
7002   // follows.
7003   if (!isOperationLegalOrCustom(ISD::SETCC, SETCCVT) ||
7004       !isOperationLegalOrCustom(ISD::AND, VT) ||
7005       !isCondCodeLegalOrCustom(Cond, VT.getSimpleVT()) ||
7006       !isOperationLegalOrCustom(ISD::VSELECT, SETCCVT))
7007     return SDValue();
7008 
7009   Created.push_back(Fold.getNode());
7010 
7011   SDValue IntMin = DAG.getConstant(
7012       APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT);
7013   SDValue IntMax = DAG.getConstant(
7014       APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT);
7015   SDValue Zero =
7016       DAG.getConstant(APInt::getZero(SVT.getScalarSizeInBits()), DL, VT);
7017 
7018   // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded.
7019   SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ);
7020   Created.push_back(DivisorIsIntMin.getNode());
7021 
7022   // (N s% INT_MIN) ==/!= 0  <-->  (N & INT_MAX) ==/!= 0
7023   SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax);
7024   Created.push_back(Masked.getNode());
7025   SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond);
7026   Created.push_back(MaskedIsZero.getNode());
7027 
7028   // To produce final result we need to blend 2 vectors: 'SetCC' and
7029   // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick
7030   // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is
7031   // constant-folded, select can get lowered to a shuffle with constant mask.
7032   SDValue Blended = DAG.getNode(ISD::VSELECT, DL, SETCCVT, DivisorIsIntMin,
7033                                 MaskedIsZero, Fold);
7034 
7035   return Blended;
7036 }
7037 
7038 bool TargetLowering::
7039 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
7040   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
7041     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
7042                                 "be a constant integer");
7043     return true;
7044   }
7045 
7046   return false;
7047 }
7048 
7049 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
7050                                          const DenormalMode &Mode) const {
7051   SDLoc DL(Op);
7052   EVT VT = Op.getValueType();
7053   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7054   SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
7055 
7056   // This is specifically a check for the handling of denormal inputs, not the
7057   // result.
7058   if (Mode.Input == DenormalMode::PreserveSign ||
7059       Mode.Input == DenormalMode::PositiveZero) {
7060     // Test = X == 0.0
7061     return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
7062   }
7063 
7064   // Testing it with denormal inputs to avoid wrong estimate.
7065   //
7066   // Test = fabs(X) < SmallestNormal
7067   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
7068   APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
7069   SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
7070   SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op);
7071   return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT);
7072 }
7073 
7074 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
7075                                              bool LegalOps, bool OptForSize,
7076                                              NegatibleCost &Cost,
7077                                              unsigned Depth) const {
7078   // fneg is removable even if it has multiple uses.
7079   if (Op.getOpcode() == ISD::FNEG || Op.getOpcode() == ISD::VP_FNEG) {
7080     Cost = NegatibleCost::Cheaper;
7081     return Op.getOperand(0);
7082   }
7083 
7084   // Don't recurse exponentially.
7085   if (Depth > SelectionDAG::MaxRecursionDepth)
7086     return SDValue();
7087 
7088   // Pre-increment recursion depth for use in recursive calls.
7089   ++Depth;
7090   const SDNodeFlags Flags = Op->getFlags();
7091   const TargetOptions &Options = DAG.getTarget().Options;
7092   EVT VT = Op.getValueType();
7093   unsigned Opcode = Op.getOpcode();
7094 
7095   // Don't allow anything with multiple uses unless we know it is free.
7096   if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
7097     bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
7098                         isFPExtFree(VT, Op.getOperand(0).getValueType());
7099     if (!IsFreeExtend)
7100       return SDValue();
7101   }
7102 
7103   auto RemoveDeadNode = [&](SDValue N) {
7104     if (N && N.getNode()->use_empty())
7105       DAG.RemoveDeadNode(N.getNode());
7106   };
7107 
7108   SDLoc DL(Op);
7109 
7110   // Because getNegatedExpression can delete nodes we need a handle to keep
7111   // temporary nodes alive in case the recursion manages to create an identical
7112   // node.
7113   std::list<HandleSDNode> Handles;
7114 
7115   switch (Opcode) {
7116   case ISD::ConstantFP: {
7117     // Don't invert constant FP values after legalization unless the target says
7118     // the negated constant is legal.
7119     bool IsOpLegal =
7120         isOperationLegal(ISD::ConstantFP, VT) ||
7121         isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
7122                      OptForSize);
7123 
7124     if (LegalOps && !IsOpLegal)
7125       break;
7126 
7127     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
7128     V.changeSign();
7129     SDValue CFP = DAG.getConstantFP(V, DL, VT);
7130 
7131     // If we already have the use of the negated floating constant, it is free
7132     // to negate it even it has multiple uses.
7133     if (!Op.hasOneUse() && CFP.use_empty())
7134       break;
7135     Cost = NegatibleCost::Neutral;
7136     return CFP;
7137   }
7138   case ISD::BUILD_VECTOR: {
7139     // Only permit BUILD_VECTOR of constants.
7140     if (llvm::any_of(Op->op_values(), [&](SDValue N) {
7141           return !N.isUndef() && !isa<ConstantFPSDNode>(N);
7142         }))
7143       break;
7144 
7145     bool IsOpLegal =
7146         (isOperationLegal(ISD::ConstantFP, VT) &&
7147          isOperationLegal(ISD::BUILD_VECTOR, VT)) ||
7148         llvm::all_of(Op->op_values(), [&](SDValue N) {
7149           return N.isUndef() ||
7150                  isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
7151                               OptForSize);
7152         });
7153 
7154     if (LegalOps && !IsOpLegal)
7155       break;
7156 
7157     SmallVector<SDValue, 4> Ops;
7158     for (SDValue C : Op->op_values()) {
7159       if (C.isUndef()) {
7160         Ops.push_back(C);
7161         continue;
7162       }
7163       APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
7164       V.changeSign();
7165       Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
7166     }
7167     Cost = NegatibleCost::Neutral;
7168     return DAG.getBuildVector(VT, DL, Ops);
7169   }
7170   case ISD::FADD: {
7171     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
7172       break;
7173 
7174     // After operation legalization, it might not be legal to create new FSUBs.
7175     if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
7176       break;
7177     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
7178 
7179     // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
7180     NegatibleCost CostX = NegatibleCost::Expensive;
7181     SDValue NegX =
7182         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
7183     // Prevent this node from being deleted by the next call.
7184     if (NegX)
7185       Handles.emplace_back(NegX);
7186 
7187     // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
7188     NegatibleCost CostY = NegatibleCost::Expensive;
7189     SDValue NegY =
7190         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
7191 
7192     // We're done with the handles.
7193     Handles.clear();
7194 
7195     // Negate the X if its cost is less or equal than Y.
7196     if (NegX && (CostX <= CostY)) {
7197       Cost = CostX;
7198       SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
7199       if (NegY != N)
7200         RemoveDeadNode(NegY);
7201       return N;
7202     }
7203 
7204     // Negate the Y if it is not expensive.
7205     if (NegY) {
7206       Cost = CostY;
7207       SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
7208       if (NegX != N)
7209         RemoveDeadNode(NegX);
7210       return N;
7211     }
7212     break;
7213   }
7214   case ISD::FSUB: {
7215     // We can't turn -(A-B) into B-A when we honor signed zeros.
7216     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
7217       break;
7218 
7219     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
7220     // fold (fneg (fsub 0, Y)) -> Y
7221     if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
7222       if (C->isZero()) {
7223         Cost = NegatibleCost::Cheaper;
7224         return Y;
7225       }
7226 
7227     // fold (fneg (fsub X, Y)) -> (fsub Y, X)
7228     Cost = NegatibleCost::Neutral;
7229     return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
7230   }
7231   case ISD::FMUL:
7232   case ISD::FDIV: {
7233     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
7234 
7235     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
7236     NegatibleCost CostX = NegatibleCost::Expensive;
7237     SDValue NegX =
7238         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
7239     // Prevent this node from being deleted by the next call.
7240     if (NegX)
7241       Handles.emplace_back(NegX);
7242 
7243     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
7244     NegatibleCost CostY = NegatibleCost::Expensive;
7245     SDValue NegY =
7246         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
7247 
7248     // We're done with the handles.
7249     Handles.clear();
7250 
7251     // Negate the X if its cost is less or equal than Y.
7252     if (NegX && (CostX <= CostY)) {
7253       Cost = CostX;
7254       SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
7255       if (NegY != N)
7256         RemoveDeadNode(NegY);
7257       return N;
7258     }
7259 
7260     // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
7261     if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
7262       if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
7263         break;
7264 
7265     // Negate the Y if it is not expensive.
7266     if (NegY) {
7267       Cost = CostY;
7268       SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
7269       if (NegX != N)
7270         RemoveDeadNode(NegX);
7271       return N;
7272     }
7273     break;
7274   }
7275   case ISD::FMA:
7276   case ISD::FMAD: {
7277     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
7278       break;
7279 
7280     SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
7281     NegatibleCost CostZ = NegatibleCost::Expensive;
7282     SDValue NegZ =
7283         getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
7284     // Give up if fail to negate the Z.
7285     if (!NegZ)
7286       break;
7287 
7288     // Prevent this node from being deleted by the next two calls.
7289     Handles.emplace_back(NegZ);
7290 
7291     // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
7292     NegatibleCost CostX = NegatibleCost::Expensive;
7293     SDValue NegX =
7294         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
7295     // Prevent this node from being deleted by the next call.
7296     if (NegX)
7297       Handles.emplace_back(NegX);
7298 
7299     // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
7300     NegatibleCost CostY = NegatibleCost::Expensive;
7301     SDValue NegY =
7302         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
7303 
7304     // We're done with the handles.
7305     Handles.clear();
7306 
7307     // Negate the X if its cost is less or equal than Y.
7308     if (NegX && (CostX <= CostY)) {
7309       Cost = std::min(CostX, CostZ);
7310       SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
7311       if (NegY != N)
7312         RemoveDeadNode(NegY);
7313       return N;
7314     }
7315 
7316     // Negate the Y if it is not expensive.
7317     if (NegY) {
7318       Cost = std::min(CostY, CostZ);
7319       SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
7320       if (NegX != N)
7321         RemoveDeadNode(NegX);
7322       return N;
7323     }
7324     break;
7325   }
7326 
7327   case ISD::FP_EXTEND:
7328   case ISD::FSIN:
7329     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
7330                                             OptForSize, Cost, Depth))
7331       return DAG.getNode(Opcode, DL, VT, NegV);
7332     break;
7333   case ISD::FP_ROUND:
7334     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
7335                                             OptForSize, Cost, Depth))
7336       return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
7337     break;
7338   case ISD::SELECT:
7339   case ISD::VSELECT: {
7340     // fold (fneg (select C, LHS, RHS)) -> (select C, (fneg LHS), (fneg RHS))
7341     // iff at least one cost is cheaper and the other is neutral/cheaper
7342     SDValue LHS = Op.getOperand(1);
7343     NegatibleCost CostLHS = NegatibleCost::Expensive;
7344     SDValue NegLHS =
7345         getNegatedExpression(LHS, DAG, LegalOps, OptForSize, CostLHS, Depth);
7346     if (!NegLHS || CostLHS > NegatibleCost::Neutral) {
7347       RemoveDeadNode(NegLHS);
7348       break;
7349     }
7350 
7351     // Prevent this node from being deleted by the next call.
7352     Handles.emplace_back(NegLHS);
7353 
7354     SDValue RHS = Op.getOperand(2);
7355     NegatibleCost CostRHS = NegatibleCost::Expensive;
7356     SDValue NegRHS =
7357         getNegatedExpression(RHS, DAG, LegalOps, OptForSize, CostRHS, Depth);
7358 
7359     // We're done with the handles.
7360     Handles.clear();
7361 
7362     if (!NegRHS || CostRHS > NegatibleCost::Neutral ||
7363         (CostLHS != NegatibleCost::Cheaper &&
7364          CostRHS != NegatibleCost::Cheaper)) {
7365       RemoveDeadNode(NegLHS);
7366       RemoveDeadNode(NegRHS);
7367       break;
7368     }
7369 
7370     Cost = std::min(CostLHS, CostRHS);
7371     return DAG.getSelect(DL, VT, Op.getOperand(0), NegLHS, NegRHS);
7372   }
7373   }
7374 
7375   return SDValue();
7376 }
7377 
7378 //===----------------------------------------------------------------------===//
7379 // Legalization Utilities
7380 //===----------------------------------------------------------------------===//
7381 
7382 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
7383                                     SDValue LHS, SDValue RHS,
7384                                     SmallVectorImpl<SDValue> &Result,
7385                                     EVT HiLoVT, SelectionDAG &DAG,
7386                                     MulExpansionKind Kind, SDValue LL,
7387                                     SDValue LH, SDValue RL, SDValue RH) const {
7388   assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
7389          Opcode == ISD::SMUL_LOHI);
7390 
7391   bool HasMULHS = (Kind == MulExpansionKind::Always) ||
7392                   isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
7393   bool HasMULHU = (Kind == MulExpansionKind::Always) ||
7394                   isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
7395   bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
7396                       isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
7397   bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
7398                       isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
7399 
7400   if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
7401     return false;
7402 
7403   unsigned OuterBitSize = VT.getScalarSizeInBits();
7404   unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
7405 
7406   // LL, LH, RL, and RH must be either all NULL or all set to a value.
7407   assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
7408          (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
7409 
7410   SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
7411   auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
7412                           bool Signed) -> bool {
7413     if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
7414       Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
7415       Hi = SDValue(Lo.getNode(), 1);
7416       return true;
7417     }
7418     if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
7419       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
7420       Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
7421       return true;
7422     }
7423     return false;
7424   };
7425 
7426   SDValue Lo, Hi;
7427 
7428   if (!LL.getNode() && !RL.getNode() &&
7429       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
7430     LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
7431     RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
7432   }
7433 
7434   if (!LL.getNode())
7435     return false;
7436 
7437   APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
7438   if (DAG.MaskedValueIsZero(LHS, HighMask) &&
7439       DAG.MaskedValueIsZero(RHS, HighMask)) {
7440     // The inputs are both zero-extended.
7441     if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
7442       Result.push_back(Lo);
7443       Result.push_back(Hi);
7444       if (Opcode != ISD::MUL) {
7445         SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
7446         Result.push_back(Zero);
7447         Result.push_back(Zero);
7448       }
7449       return true;
7450     }
7451   }
7452 
7453   if (!VT.isVector() && Opcode == ISD::MUL &&
7454       DAG.ComputeMaxSignificantBits(LHS) <= InnerBitSize &&
7455       DAG.ComputeMaxSignificantBits(RHS) <= InnerBitSize) {
7456     // The input values are both sign-extended.
7457     // TODO non-MUL case?
7458     if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
7459       Result.push_back(Lo);
7460       Result.push_back(Hi);
7461       return true;
7462     }
7463   }
7464 
7465   unsigned ShiftAmount = OuterBitSize - InnerBitSize;
7466   SDValue Shift = DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
7467 
7468   if (!LH.getNode() && !RH.getNode() &&
7469       isOperationLegalOrCustom(ISD::SRL, VT) &&
7470       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
7471     LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
7472     LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
7473     RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
7474     RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
7475   }
7476 
7477   if (!LH.getNode())
7478     return false;
7479 
7480   if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
7481     return false;
7482 
7483   Result.push_back(Lo);
7484 
7485   if (Opcode == ISD::MUL) {
7486     RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
7487     LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
7488     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
7489     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
7490     Result.push_back(Hi);
7491     return true;
7492   }
7493 
7494   // Compute the full width result.
7495   auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
7496     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
7497     Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
7498     Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
7499     return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
7500   };
7501 
7502   SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
7503   if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
7504     return false;
7505 
7506   // This is effectively the add part of a multiply-add of half-sized operands,
7507   // so it cannot overflow.
7508   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
7509 
7510   if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
7511     return false;
7512 
7513   SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
7514   EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7515 
7516   bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
7517                   isOperationLegalOrCustom(ISD::ADDE, VT));
7518   if (UseGlue)
7519     Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
7520                        Merge(Lo, Hi));
7521   else
7522     Next = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(VT, BoolType), Next,
7523                        Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
7524 
7525   SDValue Carry = Next.getValue(1);
7526   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
7527   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
7528 
7529   if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
7530     return false;
7531 
7532   if (UseGlue)
7533     Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
7534                      Carry);
7535   else
7536     Hi = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
7537                      Zero, Carry);
7538 
7539   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
7540 
7541   if (Opcode == ISD::SMUL_LOHI) {
7542     SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
7543                                   DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
7544     Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
7545 
7546     NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
7547                           DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
7548     Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
7549   }
7550 
7551   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
7552   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
7553   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
7554   return true;
7555 }
7556 
7557 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
7558                                SelectionDAG &DAG, MulExpansionKind Kind,
7559                                SDValue LL, SDValue LH, SDValue RL,
7560                                SDValue RH) const {
7561   SmallVector<SDValue, 2> Result;
7562   bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
7563                            N->getOperand(0), N->getOperand(1), Result, HiLoVT,
7564                            DAG, Kind, LL, LH, RL, RH);
7565   if (Ok) {
7566     assert(Result.size() == 2);
7567     Lo = Result[0];
7568     Hi = Result[1];
7569   }
7570   return Ok;
7571 }
7572 
7573 // Optimize unsigned division or remainder by constants for types twice as large
7574 // as a legal VT.
7575 //
7576 // If (1 << (BitWidth / 2)) % Constant == 1, then the remainder
7577 // can be computed
7578 // as:
7579 //   Sum += __builtin_uadd_overflow(Lo, High, &Sum);
7580 //   Remainder = Sum % Constant
7581 // This is based on "Remainder by Summing Digits" from Hacker's Delight.
7582 //
7583 // For division, we can compute the remainder using the algorithm described
7584 // above, subtract it from the dividend to get an exact multiple of Constant.
7585 // Then multiply that extact multiply by the multiplicative inverse modulo
7586 // (1 << (BitWidth / 2)) to get the quotient.
7587 
7588 // If Constant is even, we can shift right the dividend and the divisor by the
7589 // number of trailing zeros in Constant before applying the remainder algorithm.
7590 // If we're after the quotient, we can subtract this value from the shifted
7591 // dividend and multiply by the multiplicative inverse of the shifted divisor.
7592 // If we want the remainder, we shift the value left by the number of trailing
7593 // zeros and add the bits that were shifted out of the dividend.
7594 bool TargetLowering::expandDIVREMByConstant(SDNode *N,
7595                                             SmallVectorImpl<SDValue> &Result,
7596                                             EVT HiLoVT, SelectionDAG &DAG,
7597                                             SDValue LL, SDValue LH) const {
7598   unsigned Opcode = N->getOpcode();
7599   EVT VT = N->getValueType(0);
7600 
7601   // TODO: Support signed division/remainder.
7602   if (Opcode == ISD::SREM || Opcode == ISD::SDIV || Opcode == ISD::SDIVREM)
7603     return false;
7604   assert(
7605       (Opcode == ISD::UREM || Opcode == ISD::UDIV || Opcode == ISD::UDIVREM) &&
7606       "Unexpected opcode");
7607 
7608   auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(1));
7609   if (!CN)
7610     return false;
7611 
7612   APInt Divisor = CN->getAPIntValue();
7613   unsigned BitWidth = Divisor.getBitWidth();
7614   unsigned HBitWidth = BitWidth / 2;
7615   assert(VT.getScalarSizeInBits() == BitWidth &&
7616          HiLoVT.getScalarSizeInBits() == HBitWidth && "Unexpected VTs");
7617 
7618   // Divisor needs to less than (1 << HBitWidth).
7619   APInt HalfMaxPlus1 = APInt::getOneBitSet(BitWidth, HBitWidth);
7620   if (Divisor.uge(HalfMaxPlus1))
7621     return false;
7622 
7623   // We depend on the UREM by constant optimization in DAGCombiner that requires
7624   // high multiply.
7625   if (!isOperationLegalOrCustom(ISD::MULHU, HiLoVT) &&
7626       !isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT))
7627     return false;
7628 
7629   // Don't expand if optimizing for size.
7630   if (DAG.shouldOptForSize())
7631     return false;
7632 
7633   // Early out for 0 or 1 divisors.
7634   if (Divisor.ule(1))
7635     return false;
7636 
7637   // If the divisor is even, shift it until it becomes odd.
7638   unsigned TrailingZeros = 0;
7639   if (!Divisor[0]) {
7640     TrailingZeros = Divisor.countr_zero();
7641     Divisor.lshrInPlace(TrailingZeros);
7642   }
7643 
7644   SDLoc dl(N);
7645   SDValue Sum;
7646   SDValue PartialRem;
7647 
7648   // If (1 << HBitWidth) % divisor == 1, we can add the two halves together and
7649   // then add in the carry.
7650   // TODO: If we can't split it in half, we might be able to split into 3 or
7651   // more pieces using a smaller bit width.
7652   if (HalfMaxPlus1.urem(Divisor).isOne()) {
7653     assert(!LL == !LH && "Expected both input halves or no input halves!");
7654     if (!LL)
7655       std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT);
7656 
7657     // Shift the input by the number of TrailingZeros in the divisor. The
7658     // shifted out bits will be added to the remainder later.
7659     if (TrailingZeros) {
7660       // Save the shifted off bits if we need the remainder.
7661       if (Opcode != ISD::UDIV) {
7662         APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
7663         PartialRem = DAG.getNode(ISD::AND, dl, HiLoVT, LL,
7664                                  DAG.getConstant(Mask, dl, HiLoVT));
7665       }
7666 
7667       LL = DAG.getNode(
7668           ISD::OR, dl, HiLoVT,
7669           DAG.getNode(ISD::SRL, dl, HiLoVT, LL,
7670                       DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl)),
7671           DAG.getNode(ISD::SHL, dl, HiLoVT, LH,
7672                       DAG.getShiftAmountConstant(HBitWidth - TrailingZeros,
7673                                                  HiLoVT, dl)));
7674       LH = DAG.getNode(ISD::SRL, dl, HiLoVT, LH,
7675                        DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
7676     }
7677 
7678     // Use uaddo_carry if we can, otherwise use a compare to detect overflow.
7679     EVT SetCCType =
7680         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), HiLoVT);
7681     if (isOperationLegalOrCustom(ISD::UADDO_CARRY, HiLoVT)) {
7682       SDVTList VTList = DAG.getVTList(HiLoVT, SetCCType);
7683       Sum = DAG.getNode(ISD::UADDO, dl, VTList, LL, LH);
7684       Sum = DAG.getNode(ISD::UADDO_CARRY, dl, VTList, Sum,
7685                         DAG.getConstant(0, dl, HiLoVT), Sum.getValue(1));
7686     } else {
7687       Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, LL, LH);
7688       SDValue Carry = DAG.getSetCC(dl, SetCCType, Sum, LL, ISD::SETULT);
7689       // If the boolean for the target is 0 or 1, we can add the setcc result
7690       // directly.
7691       if (getBooleanContents(HiLoVT) ==
7692           TargetLoweringBase::ZeroOrOneBooleanContent)
7693         Carry = DAG.getZExtOrTrunc(Carry, dl, HiLoVT);
7694       else
7695         Carry = DAG.getSelect(dl, HiLoVT, Carry, DAG.getConstant(1, dl, HiLoVT),
7696                               DAG.getConstant(0, dl, HiLoVT));
7697       Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, Carry);
7698     }
7699   }
7700 
7701   // If we didn't find a sum, we can't do the expansion.
7702   if (!Sum)
7703     return false;
7704 
7705   // Perform a HiLoVT urem on the Sum using truncated divisor.
7706   SDValue RemL =
7707       DAG.getNode(ISD::UREM, dl, HiLoVT, Sum,
7708                   DAG.getConstant(Divisor.trunc(HBitWidth), dl, HiLoVT));
7709   SDValue RemH = DAG.getConstant(0, dl, HiLoVT);
7710 
7711   if (Opcode != ISD::UREM) {
7712     // Subtract the remainder from the shifted dividend.
7713     SDValue Dividend = DAG.getNode(ISD::BUILD_PAIR, dl, VT, LL, LH);
7714     SDValue Rem = DAG.getNode(ISD::BUILD_PAIR, dl, VT, RemL, RemH);
7715 
7716     Dividend = DAG.getNode(ISD::SUB, dl, VT, Dividend, Rem);
7717 
7718     // Multiply by the multiplicative inverse of the divisor modulo
7719     // (1 << BitWidth).
7720     APInt Mod = APInt::getSignedMinValue(BitWidth + 1);
7721     APInt MulFactor = Divisor.zext(BitWidth + 1);
7722     MulFactor = MulFactor.multiplicativeInverse(Mod);
7723     MulFactor = MulFactor.trunc(BitWidth);
7724 
7725     SDValue Quotient = DAG.getNode(ISD::MUL, dl, VT, Dividend,
7726                                    DAG.getConstant(MulFactor, dl, VT));
7727 
7728     // Split the quotient into low and high parts.
7729     SDValue QuotL, QuotH;
7730     std::tie(QuotL, QuotH) = DAG.SplitScalar(Quotient, dl, HiLoVT, HiLoVT);
7731     Result.push_back(QuotL);
7732     Result.push_back(QuotH);
7733   }
7734 
7735   if (Opcode != ISD::UDIV) {
7736     // If we shifted the input, shift the remainder left and add the bits we
7737     // shifted off the input.
7738     if (TrailingZeros) {
7739       APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
7740       RemL = DAG.getNode(ISD::SHL, dl, HiLoVT, RemL,
7741                          DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
7742       RemL = DAG.getNode(ISD::ADD, dl, HiLoVT, RemL, PartialRem);
7743     }
7744     Result.push_back(RemL);
7745     Result.push_back(DAG.getConstant(0, dl, HiLoVT));
7746   }
7747 
7748   return true;
7749 }
7750 
7751 // Check that (every element of) Z is undef or not an exact multiple of BW.
7752 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
7753   return ISD::matchUnaryPredicate(
7754       Z,
7755       [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
7756       true);
7757 }
7758 
7759 static SDValue expandVPFunnelShift(SDNode *Node, SelectionDAG &DAG) {
7760   EVT VT = Node->getValueType(0);
7761   SDValue ShX, ShY;
7762   SDValue ShAmt, InvShAmt;
7763   SDValue X = Node->getOperand(0);
7764   SDValue Y = Node->getOperand(1);
7765   SDValue Z = Node->getOperand(2);
7766   SDValue Mask = Node->getOperand(3);
7767   SDValue VL = Node->getOperand(4);
7768 
7769   unsigned BW = VT.getScalarSizeInBits();
7770   bool IsFSHL = Node->getOpcode() == ISD::VP_FSHL;
7771   SDLoc DL(SDValue(Node, 0));
7772 
7773   EVT ShVT = Z.getValueType();
7774   if (isNonZeroModBitWidthOrUndef(Z, BW)) {
7775     // fshl: X << C | Y >> (BW - C)
7776     // fshr: X << (BW - C) | Y >> C
7777     // where C = Z % BW is not zero
7778     SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
7779     ShAmt = DAG.getNode(ISD::VP_UREM, DL, ShVT, Z, BitWidthC, Mask, VL);
7780     InvShAmt = DAG.getNode(ISD::VP_SUB, DL, ShVT, BitWidthC, ShAmt, Mask, VL);
7781     ShX = DAG.getNode(ISD::VP_SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt, Mask,
7782                       VL);
7783     ShY = DAG.getNode(ISD::VP_LSHR, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt, Mask,
7784                       VL);
7785   } else {
7786     // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
7787     // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
7788     SDValue BitMask = DAG.getConstant(BW - 1, DL, ShVT);
7789     if (isPowerOf2_32(BW)) {
7790       // Z % BW -> Z & (BW - 1)
7791       ShAmt = DAG.getNode(ISD::VP_AND, DL, ShVT, Z, BitMask, Mask, VL);
7792       // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
7793       SDValue NotZ = DAG.getNode(ISD::VP_XOR, DL, ShVT, Z,
7794                                  DAG.getAllOnesConstant(DL, ShVT), Mask, VL);
7795       InvShAmt = DAG.getNode(ISD::VP_AND, DL, ShVT, NotZ, BitMask, Mask, VL);
7796     } else {
7797       SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
7798       ShAmt = DAG.getNode(ISD::VP_UREM, DL, ShVT, Z, BitWidthC, Mask, VL);
7799       InvShAmt = DAG.getNode(ISD::VP_SUB, DL, ShVT, BitMask, ShAmt, Mask, VL);
7800     }
7801 
7802     SDValue One = DAG.getConstant(1, DL, ShVT);
7803     if (IsFSHL) {
7804       ShX = DAG.getNode(ISD::VP_SHL, DL, VT, X, ShAmt, Mask, VL);
7805       SDValue ShY1 = DAG.getNode(ISD::VP_LSHR, DL, VT, Y, One, Mask, VL);
7806       ShY = DAG.getNode(ISD::VP_LSHR, DL, VT, ShY1, InvShAmt, Mask, VL);
7807     } else {
7808       SDValue ShX1 = DAG.getNode(ISD::VP_SHL, DL, VT, X, One, Mask, VL);
7809       ShX = DAG.getNode(ISD::VP_SHL, DL, VT, ShX1, InvShAmt, Mask, VL);
7810       ShY = DAG.getNode(ISD::VP_LSHR, DL, VT, Y, ShAmt, Mask, VL);
7811     }
7812   }
7813   return DAG.getNode(ISD::VP_OR, DL, VT, ShX, ShY, Mask, VL);
7814 }
7815 
7816 SDValue TargetLowering::expandFunnelShift(SDNode *Node,
7817                                           SelectionDAG &DAG) const {
7818   if (Node->isVPOpcode())
7819     return expandVPFunnelShift(Node, DAG);
7820 
7821   EVT VT = Node->getValueType(0);
7822 
7823   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
7824                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
7825                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
7826                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
7827     return SDValue();
7828 
7829   SDValue X = Node->getOperand(0);
7830   SDValue Y = Node->getOperand(1);
7831   SDValue Z = Node->getOperand(2);
7832 
7833   unsigned BW = VT.getScalarSizeInBits();
7834   bool IsFSHL = Node->getOpcode() == ISD::FSHL;
7835   SDLoc DL(SDValue(Node, 0));
7836 
7837   EVT ShVT = Z.getValueType();
7838 
7839   // If a funnel shift in the other direction is more supported, use it.
7840   unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
7841   if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
7842       isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
7843     if (isNonZeroModBitWidthOrUndef(Z, BW)) {
7844       // fshl X, Y, Z -> fshr X, Y, -Z
7845       // fshr X, Y, Z -> fshl X, Y, -Z
7846       SDValue Zero = DAG.getConstant(0, DL, ShVT);
7847       Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z);
7848     } else {
7849       // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
7850       // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
7851       SDValue One = DAG.getConstant(1, DL, ShVT);
7852       if (IsFSHL) {
7853         Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
7854         X = DAG.getNode(ISD::SRL, DL, VT, X, One);
7855       } else {
7856         X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
7857         Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
7858       }
7859       Z = DAG.getNOT(DL, Z, ShVT);
7860     }
7861     return DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
7862   }
7863 
7864   SDValue ShX, ShY;
7865   SDValue ShAmt, InvShAmt;
7866   if (isNonZeroModBitWidthOrUndef(Z, BW)) {
7867     // fshl: X << C | Y >> (BW - C)
7868     // fshr: X << (BW - C) | Y >> C
7869     // where C = Z % BW is not zero
7870     SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
7871     ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
7872     InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
7873     ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
7874     ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
7875   } else {
7876     // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
7877     // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
7878     SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
7879     if (isPowerOf2_32(BW)) {
7880       // Z % BW -> Z & (BW - 1)
7881       ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
7882       // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
7883       InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
7884     } else {
7885       SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
7886       ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
7887       InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
7888     }
7889 
7890     SDValue One = DAG.getConstant(1, DL, ShVT);
7891     if (IsFSHL) {
7892       ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
7893       SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
7894       ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
7895     } else {
7896       SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
7897       ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
7898       ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
7899     }
7900   }
7901   return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
7902 }
7903 
7904 // TODO: Merge with expandFunnelShift.
7905 SDValue TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps,
7906                                   SelectionDAG &DAG) const {
7907   EVT VT = Node->getValueType(0);
7908   unsigned EltSizeInBits = VT.getScalarSizeInBits();
7909   bool IsLeft = Node->getOpcode() == ISD::ROTL;
7910   SDValue Op0 = Node->getOperand(0);
7911   SDValue Op1 = Node->getOperand(1);
7912   SDLoc DL(SDValue(Node, 0));
7913 
7914   EVT ShVT = Op1.getValueType();
7915   SDValue Zero = DAG.getConstant(0, DL, ShVT);
7916 
7917   // If a rotate in the other direction is more supported, use it.
7918   unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
7919   if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
7920       isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
7921     SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
7922     return DAG.getNode(RevRot, DL, VT, Op0, Sub);
7923   }
7924 
7925   if (!AllowVectorOps && VT.isVector() &&
7926       (!isOperationLegalOrCustom(ISD::SHL, VT) ||
7927        !isOperationLegalOrCustom(ISD::SRL, VT) ||
7928        !isOperationLegalOrCustom(ISD::SUB, VT) ||
7929        !isOperationLegalOrCustomOrPromote(ISD::OR, VT) ||
7930        !isOperationLegalOrCustomOrPromote(ISD::AND, VT)))
7931     return SDValue();
7932 
7933   unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
7934   unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
7935   SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
7936   SDValue ShVal;
7937   SDValue HsVal;
7938   if (isPowerOf2_32(EltSizeInBits)) {
7939     // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
7940     // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
7941     SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
7942     SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
7943     ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
7944     SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
7945     HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
7946   } else {
7947     // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
7948     // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
7949     SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
7950     SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
7951     ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
7952     SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
7953     SDValue One = DAG.getConstant(1, DL, ShVT);
7954     HsVal =
7955         DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
7956   }
7957   return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
7958 }
7959 
7960 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi,
7961                                       SelectionDAG &DAG) const {
7962   assert(Node->getNumOperands() == 3 && "Not a double-shift!");
7963   EVT VT = Node->getValueType(0);
7964   unsigned VTBits = VT.getScalarSizeInBits();
7965   assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
7966 
7967   bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
7968   bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
7969   SDValue ShOpLo = Node->getOperand(0);
7970   SDValue ShOpHi = Node->getOperand(1);
7971   SDValue ShAmt = Node->getOperand(2);
7972   EVT ShAmtVT = ShAmt.getValueType();
7973   EVT ShAmtCCVT =
7974       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
7975   SDLoc dl(Node);
7976 
7977   // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
7978   // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
7979   // away during isel.
7980   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
7981                                   DAG.getConstant(VTBits - 1, dl, ShAmtVT));
7982   SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7983                                      DAG.getConstant(VTBits - 1, dl, ShAmtVT))
7984                        : DAG.getConstant(0, dl, VT);
7985 
7986   SDValue Tmp2, Tmp3;
7987   if (IsSHL) {
7988     Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
7989     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
7990   } else {
7991     Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
7992     Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
7993   }
7994 
7995   // If the shift amount is larger or equal than the width of a part we don't
7996   // use the result from the FSHL/FSHR. Insert a test and select the appropriate
7997   // values for large shift amounts.
7998   SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
7999                                 DAG.getConstant(VTBits, dl, ShAmtVT));
8000   SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
8001                               DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
8002 
8003   if (IsSHL) {
8004     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
8005     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
8006   } else {
8007     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
8008     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
8009   }
8010 }
8011 
8012 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
8013                                       SelectionDAG &DAG) const {
8014   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
8015   SDValue Src = Node->getOperand(OpNo);
8016   EVT SrcVT = Src.getValueType();
8017   EVT DstVT = Node->getValueType(0);
8018   SDLoc dl(SDValue(Node, 0));
8019 
8020   // FIXME: Only f32 to i64 conversions are supported.
8021   if (SrcVT != MVT::f32 || DstVT != MVT::i64)
8022     return false;
8023 
8024   if (Node->isStrictFPOpcode())
8025     // When a NaN is converted to an integer a trap is allowed. We can't
8026     // use this expansion here because it would eliminate that trap. Other
8027     // traps are also allowed and cannot be eliminated. See
8028     // IEEE 754-2008 sec 5.8.
8029     return false;
8030 
8031   // Expand f32 -> i64 conversion
8032   // This algorithm comes from compiler-rt's implementation of fixsfdi:
8033   // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
8034   unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
8035   EVT IntVT = SrcVT.changeTypeToInteger();
8036   EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
8037 
8038   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
8039   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
8040   SDValue Bias = DAG.getConstant(127, dl, IntVT);
8041   SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
8042   SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
8043   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
8044 
8045   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
8046 
8047   SDValue ExponentBits = DAG.getNode(
8048       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
8049       DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
8050   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
8051 
8052   SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
8053                              DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
8054                              DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
8055   Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
8056 
8057   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
8058                           DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
8059                           DAG.getConstant(0x00800000, dl, IntVT));
8060 
8061   R = DAG.getZExtOrTrunc(R, dl, DstVT);
8062 
8063   R = DAG.getSelectCC(
8064       dl, Exponent, ExponentLoBit,
8065       DAG.getNode(ISD::SHL, dl, DstVT, R,
8066                   DAG.getZExtOrTrunc(
8067                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
8068                       dl, IntShVT)),
8069       DAG.getNode(ISD::SRL, dl, DstVT, R,
8070                   DAG.getZExtOrTrunc(
8071                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
8072                       dl, IntShVT)),
8073       ISD::SETGT);
8074 
8075   SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
8076                             DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
8077 
8078   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
8079                            DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
8080   return true;
8081 }
8082 
8083 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result,
8084                                       SDValue &Chain,
8085                                       SelectionDAG &DAG) const {
8086   SDLoc dl(SDValue(Node, 0));
8087   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
8088   SDValue Src = Node->getOperand(OpNo);
8089 
8090   EVT SrcVT = Src.getValueType();
8091   EVT DstVT = Node->getValueType(0);
8092   EVT SetCCVT =
8093       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8094   EVT DstSetCCVT =
8095       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8096 
8097   // Only expand vector types if we have the appropriate vector bit operations.
8098   unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
8099                                                    ISD::FP_TO_SINT;
8100   if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
8101                            !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT)))
8102     return false;
8103 
8104   // If the maximum float value is smaller then the signed integer range,
8105   // the destination signmask can't be represented by the float, so we can
8106   // just use FP_TO_SINT directly.
8107   const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT);
8108   APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
8109   APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
8110   if (APFloat::opOverflow &
8111       APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
8112     if (Node->isStrictFPOpcode()) {
8113       Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
8114                            { Node->getOperand(0), Src });
8115       Chain = Result.getValue(1);
8116     } else
8117       Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
8118     return true;
8119   }
8120 
8121   // Don't expand it if there isn't cheap fsub instruction.
8122   if (!isOperationLegalOrCustom(
8123           Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
8124     return false;
8125 
8126   SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8127   SDValue Sel;
8128 
8129   if (Node->isStrictFPOpcode()) {
8130     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8131                        Node->getOperand(0), /*IsSignaling*/ true);
8132     Chain = Sel.getValue(1);
8133   } else {
8134     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
8135   }
8136 
8137   bool Strict = Node->isStrictFPOpcode() ||
8138                 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
8139 
8140   if (Strict) {
8141     // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
8142     // signmask then offset (the result of which should be fully representable).
8143     // Sel = Src < 0x8000000000000000
8144     // FltOfs = select Sel, 0, 0x8000000000000000
8145     // IntOfs = select Sel, 0, 0x8000000000000000
8146     // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8147 
8148     // TODO: Should any fast-math-flags be set for the FSUB?
8149     SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
8150                                    DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8151     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8152     SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
8153                                    DAG.getConstant(0, dl, DstVT),
8154                                    DAG.getConstant(SignMask, dl, DstVT));
8155     SDValue SInt;
8156     if (Node->isStrictFPOpcode()) {
8157       SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
8158                                 { Chain, Src, FltOfs });
8159       SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
8160                          { Val.getValue(1), Val });
8161       Chain = SInt.getValue(1);
8162     } else {
8163       SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
8164       SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
8165     }
8166     Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8167   } else {
8168     // Expand based on maximum range of FP_TO_SINT:
8169     // True = fp_to_sint(Src)
8170     // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
8171     // Result = select (Src < 0x8000000000000000), True, False
8172 
8173     SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
8174     // TODO: Should any fast-math-flags be set for the FSUB?
8175     SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
8176                                 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
8177     False = DAG.getNode(ISD::XOR, dl, DstVT, False,
8178                         DAG.getConstant(SignMask, dl, DstVT));
8179     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8180     Result = DAG.getSelect(dl, DstVT, Sel, True, False);
8181   }
8182   return true;
8183 }
8184 
8185 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result,
8186                                       SDValue &Chain,
8187                                       SelectionDAG &DAG) const {
8188   // This transform is not correct for converting 0 when rounding mode is set
8189   // to round toward negative infinity which will produce -0.0. So disable under
8190   // strictfp.
8191   if (Node->isStrictFPOpcode())
8192     return false;
8193 
8194   SDValue Src = Node->getOperand(0);
8195   EVT SrcVT = Src.getValueType();
8196   EVT DstVT = Node->getValueType(0);
8197 
8198   if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
8199     return false;
8200 
8201   // Only expand vector types if we have the appropriate vector bit operations.
8202   if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
8203                            !isOperationLegalOrCustom(ISD::FADD, DstVT) ||
8204                            !isOperationLegalOrCustom(ISD::FSUB, DstVT) ||
8205                            !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) ||
8206                            !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT)))
8207     return false;
8208 
8209   SDLoc dl(SDValue(Node, 0));
8210   EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout());
8211 
8212   // Implementation of unsigned i64 to f64 following the algorithm in
8213   // __floatundidf in compiler_rt.  This implementation performs rounding
8214   // correctly in all rounding modes with the exception of converting 0
8215   // when rounding toward negative infinity. In that case the fsub will produce
8216   // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect.
8217   SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
8218   SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
8219       llvm::bit_cast<double>(UINT64_C(0x4530000000100000)), dl, DstVT);
8220   SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
8221   SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
8222   SDValue HiShift = DAG.getConstant(32, dl, ShiftVT);
8223 
8224   SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
8225   SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
8226   SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
8227   SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
8228   SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
8229   SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
8230   SDValue HiSub =
8231       DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
8232   Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
8233   return true;
8234 }
8235 
8236 SDValue
8237 TargetLowering::createSelectForFMINNUM_FMAXNUM(SDNode *Node,
8238                                                SelectionDAG &DAG) const {
8239   unsigned Opcode = Node->getOpcode();
8240   assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM ||
8241           Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) &&
8242          "Wrong opcode");
8243 
8244   if (Node->getFlags().hasNoNaNs()) {
8245     ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
8246     SDValue Op1 = Node->getOperand(0);
8247     SDValue Op2 = Node->getOperand(1);
8248     SDValue SelCC = DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred);
8249     // Copy FMF flags, but always set the no-signed-zeros flag
8250     // as this is implied by the FMINNUM/FMAXNUM semantics.
8251     SDNodeFlags Flags = Node->getFlags();
8252     Flags.setNoSignedZeros(true);
8253     SelCC->setFlags(Flags);
8254     return SelCC;
8255   }
8256 
8257   return SDValue();
8258 }
8259 
8260 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node,
8261                                               SelectionDAG &DAG) const {
8262   SDLoc dl(Node);
8263   unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ?
8264     ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
8265   EVT VT = Node->getValueType(0);
8266 
8267   if (VT.isScalableVector())
8268     report_fatal_error(
8269         "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
8270 
8271   if (isOperationLegalOrCustom(NewOp, VT)) {
8272     SDValue Quiet0 = Node->getOperand(0);
8273     SDValue Quiet1 = Node->getOperand(1);
8274 
8275     if (!Node->getFlags().hasNoNaNs()) {
8276       // Insert canonicalizes if it's possible we need to quiet to get correct
8277       // sNaN behavior.
8278       if (!DAG.isKnownNeverSNaN(Quiet0)) {
8279         Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
8280                              Node->getFlags());
8281       }
8282       if (!DAG.isKnownNeverSNaN(Quiet1)) {
8283         Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
8284                              Node->getFlags());
8285       }
8286     }
8287 
8288     return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
8289   }
8290 
8291   // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
8292   // instead if there are no NaNs and there can't be an incompatible zero
8293   // compare: at least one operand isn't +/-0, or there are no signed-zeros.
8294   if ((Node->getFlags().hasNoNaNs() ||
8295        (DAG.isKnownNeverNaN(Node->getOperand(0)) &&
8296         DAG.isKnownNeverNaN(Node->getOperand(1)))) &&
8297       (Node->getFlags().hasNoSignedZeros() ||
8298        DAG.isKnownNeverZeroFloat(Node->getOperand(0)) ||
8299        DAG.isKnownNeverZeroFloat(Node->getOperand(1)))) {
8300     unsigned IEEE2018Op =
8301         Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
8302     if (isOperationLegalOrCustom(IEEE2018Op, VT))
8303       return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
8304                          Node->getOperand(1), Node->getFlags());
8305   }
8306 
8307   if (SDValue SelCC = createSelectForFMINNUM_FMAXNUM(Node, DAG))
8308     return SelCC;
8309 
8310   return SDValue();
8311 }
8312 
8313 /// Returns a true value if if this FPClassTest can be performed with an ordered
8314 /// fcmp to 0, and a false value if it's an unordered fcmp to 0. Returns
8315 /// std::nullopt if it cannot be performed as a compare with 0.
8316 static std::optional<bool> isFCmpEqualZero(FPClassTest Test,
8317                                            const fltSemantics &Semantics,
8318                                            const MachineFunction &MF) {
8319   FPClassTest OrderedMask = Test & ~fcNan;
8320   FPClassTest NanTest = Test & fcNan;
8321   bool IsOrdered = NanTest == fcNone;
8322   bool IsUnordered = NanTest == fcNan;
8323 
8324   // Skip cases that are testing for only a qnan or snan.
8325   if (!IsOrdered && !IsUnordered)
8326     return std::nullopt;
8327 
8328   if (OrderedMask == fcZero &&
8329       MF.getDenormalMode(Semantics).Input == DenormalMode::IEEE)
8330     return IsOrdered;
8331   if (OrderedMask == (fcZero | fcSubnormal) &&
8332       MF.getDenormalMode(Semantics).inputsAreZero())
8333     return IsOrdered;
8334   return std::nullopt;
8335 }
8336 
8337 SDValue TargetLowering::expandIS_FPCLASS(EVT ResultVT, SDValue Op,
8338                                          FPClassTest Test, SDNodeFlags Flags,
8339                                          const SDLoc &DL,
8340                                          SelectionDAG &DAG) const {
8341   EVT OperandVT = Op.getValueType();
8342   assert(OperandVT.isFloatingPoint());
8343 
8344   // Degenerated cases.
8345   if (Test == fcNone)
8346     return DAG.getBoolConstant(false, DL, ResultVT, OperandVT);
8347   if ((Test & fcAllFlags) == fcAllFlags)
8348     return DAG.getBoolConstant(true, DL, ResultVT, OperandVT);
8349 
8350   // PPC double double is a pair of doubles, of which the higher part determines
8351   // the value class.
8352   if (OperandVT == MVT::ppcf128) {
8353     Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op,
8354                      DAG.getConstant(1, DL, MVT::i32));
8355     OperandVT = MVT::f64;
8356   }
8357 
8358   // Some checks may be represented as inversion of simpler check, for example
8359   // "inf|normal|subnormal|zero" => !"nan".
8360   bool IsInverted = false;
8361   if (FPClassTest InvertedCheck = invertFPClassTestIfSimpler(Test)) {
8362     IsInverted = true;
8363     Test = InvertedCheck;
8364   }
8365 
8366   // Floating-point type properties.
8367   EVT ScalarFloatVT = OperandVT.getScalarType();
8368   const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext());
8369   const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics();
8370   bool IsF80 = (ScalarFloatVT == MVT::f80);
8371 
8372   // Some checks can be implemented using float comparisons, if floating point
8373   // exceptions are ignored.
8374   if (Flags.hasNoFPExcept() &&
8375       isOperationLegalOrCustom(ISD::SETCC, OperandVT.getScalarType())) {
8376     ISD::CondCode OrderedCmpOpcode = IsInverted ? ISD::SETUNE : ISD::SETOEQ;
8377     ISD::CondCode UnorderedCmpOpcode = IsInverted ? ISD::SETONE : ISD::SETUEQ;
8378 
8379     if (std::optional<bool> IsCmp0 =
8380             isFCmpEqualZero(Test, Semantics, DAG.getMachineFunction());
8381         IsCmp0 && (isCondCodeLegalOrCustom(
8382                       *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode,
8383                       OperandVT.getScalarType().getSimpleVT()))) {
8384 
8385       // If denormals could be implicitly treated as 0, this is not equivalent
8386       // to a compare with 0 since it will also be true for denormals.
8387       return DAG.getSetCC(DL, ResultVT, Op,
8388                           DAG.getConstantFP(0.0, DL, OperandVT),
8389                           *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode);
8390     }
8391 
8392     if (Test == fcNan &&
8393         isCondCodeLegalOrCustom(IsInverted ? ISD::SETO : ISD::SETUO,
8394                                 OperandVT.getScalarType().getSimpleVT())) {
8395       return DAG.getSetCC(DL, ResultVT, Op, Op,
8396                           IsInverted ? ISD::SETO : ISD::SETUO);
8397     }
8398 
8399     if (Test == fcInf &&
8400         isCondCodeLegalOrCustom(IsInverted ? ISD::SETUNE : ISD::SETOEQ,
8401                                 OperandVT.getScalarType().getSimpleVT()) &&
8402         isOperationLegalOrCustom(ISD::FABS, OperandVT.getScalarType())) {
8403       // isinf(x) --> fabs(x) == inf
8404       SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
8405       SDValue Inf =
8406           DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
8407       return DAG.getSetCC(DL, ResultVT, Abs, Inf,
8408                           IsInverted ? ISD::SETUNE : ISD::SETOEQ);
8409     }
8410   }
8411 
8412   // In the general case use integer operations.
8413   unsigned BitSize = OperandVT.getScalarSizeInBits();
8414   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), BitSize);
8415   if (OperandVT.isVector())
8416     IntVT = EVT::getVectorVT(*DAG.getContext(), IntVT,
8417                              OperandVT.getVectorElementCount());
8418   SDValue OpAsInt = DAG.getBitcast(IntVT, Op);
8419 
8420   // Various masks.
8421   APInt SignBit = APInt::getSignMask(BitSize);
8422   APInt ValueMask = APInt::getSignedMaxValue(BitSize);     // All bits but sign.
8423   APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit.
8424   const unsigned ExplicitIntBitInF80 = 63;
8425   APInt ExpMask = Inf;
8426   if (IsF80)
8427     ExpMask.clearBit(ExplicitIntBitInF80);
8428   APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf;
8429   APInt QNaNBitMask =
8430       APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1);
8431   APInt InvertionMask = APInt::getAllOnes(ResultVT.getScalarSizeInBits());
8432 
8433   SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT);
8434   SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT);
8435   SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT);
8436   SDValue ZeroV = DAG.getConstant(0, DL, IntVT);
8437   SDValue InfV = DAG.getConstant(Inf, DL, IntVT);
8438   SDValue ResultInvertionMask = DAG.getConstant(InvertionMask, DL, ResultVT);
8439 
8440   SDValue Res;
8441   const auto appendResult = [&](SDValue PartialRes) {
8442     if (PartialRes) {
8443       if (Res)
8444         Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes);
8445       else
8446         Res = PartialRes;
8447     }
8448   };
8449 
8450   SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set.
8451   const auto getIntBitIsSet = [&]() -> SDValue {
8452     if (!IntBitIsSetV) {
8453       APInt IntBitMask(BitSize, 0);
8454       IntBitMask.setBit(ExplicitIntBitInF80);
8455       SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT);
8456       SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV);
8457       IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE);
8458     }
8459     return IntBitIsSetV;
8460   };
8461 
8462   // Split the value into sign bit and absolute value.
8463   SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV);
8464   SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt,
8465                                DAG.getConstant(0.0, DL, IntVT), ISD::SETLT);
8466 
8467   // Tests that involve more than one class should be processed first.
8468   SDValue PartialRes;
8469 
8470   if (IsF80)
8471     ; // Detect finite numbers of f80 by checking individual classes because
8472       // they have different settings of the explicit integer bit.
8473   else if ((Test & fcFinite) == fcFinite) {
8474     // finite(V) ==> abs(V) < exp_mask
8475     PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
8476     Test &= ~fcFinite;
8477   } else if ((Test & fcFinite) == fcPosFinite) {
8478     // finite(V) && V > 0 ==> V < exp_mask
8479     PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT);
8480     Test &= ~fcPosFinite;
8481   } else if ((Test & fcFinite) == fcNegFinite) {
8482     // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1
8483     PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
8484     PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
8485     Test &= ~fcNegFinite;
8486   }
8487   appendResult(PartialRes);
8488 
8489   if (FPClassTest PartialCheck = Test & (fcZero | fcSubnormal)) {
8490     // fcZero | fcSubnormal => test all exponent bits are 0
8491     // TODO: Handle sign bit specific cases
8492     if (PartialCheck == (fcZero | fcSubnormal)) {
8493       SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ExpMaskV);
8494       SDValue ExpIsZero =
8495           DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
8496       appendResult(ExpIsZero);
8497       Test &= ~PartialCheck & fcAllFlags;
8498     }
8499   }
8500 
8501   // Check for individual classes.
8502 
8503   if (unsigned PartialCheck = Test & fcZero) {
8504     if (PartialCheck == fcPosZero)
8505       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ);
8506     else if (PartialCheck == fcZero)
8507       PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ);
8508     else // ISD::fcNegZero
8509       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ);
8510     appendResult(PartialRes);
8511   }
8512 
8513   if (unsigned PartialCheck = Test & fcSubnormal) {
8514     // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set)
8515     // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set)
8516     SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV;
8517     SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT);
8518     SDValue VMinusOneV =
8519         DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT));
8520     PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT);
8521     if (PartialCheck == fcNegSubnormal)
8522       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
8523     appendResult(PartialRes);
8524   }
8525 
8526   if (unsigned PartialCheck = Test & fcInf) {
8527     if (PartialCheck == fcPosInf)
8528       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ);
8529     else if (PartialCheck == fcInf)
8530       PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ);
8531     else { // ISD::fcNegInf
8532       APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt();
8533       SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT);
8534       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ);
8535     }
8536     appendResult(PartialRes);
8537   }
8538 
8539   if (unsigned PartialCheck = Test & fcNan) {
8540     APInt InfWithQnanBit = Inf | QNaNBitMask;
8541     SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT);
8542     if (PartialCheck == fcNan) {
8543       // isnan(V) ==> abs(V) > int(inf)
8544       PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
8545       if (IsF80) {
8546         // Recognize unsupported values as NaNs for compatibility with glibc.
8547         // In them (exp(V)==0) == int_bit.
8548         SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV);
8549         SDValue ExpIsZero =
8550             DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
8551         SDValue IsPseudo =
8552             DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ);
8553         PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo);
8554       }
8555     } else if (PartialCheck == fcQNan) {
8556       // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit)
8557       PartialRes =
8558           DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE);
8559     } else { // ISD::fcSNan
8560       // issignaling(V) ==> abs(V) > unsigned(Inf) &&
8561       //                    abs(V) < (unsigned(Inf) | quiet_bit)
8562       SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
8563       SDValue IsNotQnan =
8564           DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT);
8565       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan);
8566     }
8567     appendResult(PartialRes);
8568   }
8569 
8570   if (unsigned PartialCheck = Test & fcNormal) {
8571     // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1))
8572     APInt ExpLSB = ExpMask & ~(ExpMask.shl(1));
8573     SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT);
8574     SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV);
8575     APInt ExpLimit = ExpMask - ExpLSB;
8576     SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT);
8577     PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT);
8578     if (PartialCheck == fcNegNormal)
8579       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
8580     else if (PartialCheck == fcPosNormal) {
8581       SDValue PosSignV =
8582           DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInvertionMask);
8583       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV);
8584     }
8585     if (IsF80)
8586       PartialRes =
8587           DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet());
8588     appendResult(PartialRes);
8589   }
8590 
8591   if (!Res)
8592     return DAG.getConstant(IsInverted, DL, ResultVT);
8593   if (IsInverted)
8594     Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInvertionMask);
8595   return Res;
8596 }
8597 
8598 // Only expand vector types if we have the appropriate vector bit operations.
8599 static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) {
8600   assert(VT.isVector() && "Expected vector type");
8601   unsigned Len = VT.getScalarSizeInBits();
8602   return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
8603          TLI.isOperationLegalOrCustom(ISD::SUB, VT) &&
8604          TLI.isOperationLegalOrCustom(ISD::SRL, VT) &&
8605          (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
8606          TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT);
8607 }
8608 
8609 SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &DAG) const {
8610   SDLoc dl(Node);
8611   EVT VT = Node->getValueType(0);
8612   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
8613   SDValue Op = Node->getOperand(0);
8614   unsigned Len = VT.getScalarSizeInBits();
8615   assert(VT.isInteger() && "CTPOP not implemented for this type.");
8616 
8617   // TODO: Add support for irregular type lengths.
8618   if (!(Len <= 128 && Len % 8 == 0))
8619     return SDValue();
8620 
8621   // Only expand vector types if we have the appropriate vector bit operations.
8622   if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
8623     return SDValue();
8624 
8625   // This is the "best" algorithm from
8626   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
8627   SDValue Mask55 =
8628       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
8629   SDValue Mask33 =
8630       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
8631   SDValue Mask0F =
8632       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
8633 
8634   // v = v - ((v >> 1) & 0x55555555...)
8635   Op = DAG.getNode(ISD::SUB, dl, VT, Op,
8636                    DAG.getNode(ISD::AND, dl, VT,
8637                                DAG.getNode(ISD::SRL, dl, VT, Op,
8638                                            DAG.getConstant(1, dl, ShVT)),
8639                                Mask55));
8640   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
8641   Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
8642                    DAG.getNode(ISD::AND, dl, VT,
8643                                DAG.getNode(ISD::SRL, dl, VT, Op,
8644                                            DAG.getConstant(2, dl, ShVT)),
8645                                Mask33));
8646   // v = (v + (v >> 4)) & 0x0F0F0F0F...
8647   Op = DAG.getNode(ISD::AND, dl, VT,
8648                    DAG.getNode(ISD::ADD, dl, VT, Op,
8649                                DAG.getNode(ISD::SRL, dl, VT, Op,
8650                                            DAG.getConstant(4, dl, ShVT))),
8651                    Mask0F);
8652 
8653   if (Len <= 8)
8654     return Op;
8655 
8656   // Avoid the multiply if we only have 2 bytes to add.
8657   // TODO: Only doing this for scalars because vectors weren't as obviously
8658   // improved.
8659   if (Len == 16 && !VT.isVector()) {
8660     // v = (v + (v >> 8)) & 0x00FF;
8661     return DAG.getNode(ISD::AND, dl, VT,
8662                      DAG.getNode(ISD::ADD, dl, VT, Op,
8663                                  DAG.getNode(ISD::SRL, dl, VT, Op,
8664                                              DAG.getConstant(8, dl, ShVT))),
8665                      DAG.getConstant(0xFF, dl, VT));
8666   }
8667 
8668   // v = (v * 0x01010101...) >> (Len - 8)
8669   SDValue Mask01 =
8670       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
8671   return DAG.getNode(ISD::SRL, dl, VT,
8672                      DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
8673                      DAG.getConstant(Len - 8, dl, ShVT));
8674 }
8675 
8676 SDValue TargetLowering::expandVPCTPOP(SDNode *Node, SelectionDAG &DAG) const {
8677   SDLoc dl(Node);
8678   EVT VT = Node->getValueType(0);
8679   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
8680   SDValue Op = Node->getOperand(0);
8681   SDValue Mask = Node->getOperand(1);
8682   SDValue VL = Node->getOperand(2);
8683   unsigned Len = VT.getScalarSizeInBits();
8684   assert(VT.isInteger() && "VP_CTPOP not implemented for this type.");
8685 
8686   // TODO: Add support for irregular type lengths.
8687   if (!(Len <= 128 && Len % 8 == 0))
8688     return SDValue();
8689 
8690   // This is same algorithm of expandCTPOP from
8691   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
8692   SDValue Mask55 =
8693       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
8694   SDValue Mask33 =
8695       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
8696   SDValue Mask0F =
8697       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
8698 
8699   SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5;
8700 
8701   // v = v - ((v >> 1) & 0x55555555...)
8702   Tmp1 = DAG.getNode(ISD::VP_AND, dl, VT,
8703                      DAG.getNode(ISD::VP_LSHR, dl, VT, Op,
8704                                  DAG.getConstant(1, dl, ShVT), Mask, VL),
8705                      Mask55, Mask, VL);
8706   Op = DAG.getNode(ISD::VP_SUB, dl, VT, Op, Tmp1, Mask, VL);
8707 
8708   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
8709   Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Op, Mask33, Mask, VL);
8710   Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT,
8711                      DAG.getNode(ISD::VP_LSHR, dl, VT, Op,
8712                                  DAG.getConstant(2, dl, ShVT), Mask, VL),
8713                      Mask33, Mask, VL);
8714   Op = DAG.getNode(ISD::VP_ADD, dl, VT, Tmp2, Tmp3, Mask, VL);
8715 
8716   // v = (v + (v >> 4)) & 0x0F0F0F0F...
8717   Tmp4 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(4, dl, ShVT),
8718                      Mask, VL),
8719   Tmp5 = DAG.getNode(ISD::VP_ADD, dl, VT, Op, Tmp4, Mask, VL);
8720   Op = DAG.getNode(ISD::VP_AND, dl, VT, Tmp5, Mask0F, Mask, VL);
8721 
8722   if (Len <= 8)
8723     return Op;
8724 
8725   // v = (v * 0x01010101...) >> (Len - 8)
8726   SDValue Mask01 =
8727       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
8728   return DAG.getNode(ISD::VP_LSHR, dl, VT,
8729                      DAG.getNode(ISD::VP_MUL, dl, VT, Op, Mask01, Mask, VL),
8730                      DAG.getConstant(Len - 8, dl, ShVT), Mask, VL);
8731 }
8732 
8733 SDValue TargetLowering::expandCTLZ(SDNode *Node, SelectionDAG &DAG) const {
8734   SDLoc dl(Node);
8735   EVT VT = Node->getValueType(0);
8736   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
8737   SDValue Op = Node->getOperand(0);
8738   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
8739 
8740   // If the non-ZERO_UNDEF version is supported we can use that instead.
8741   if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF &&
8742       isOperationLegalOrCustom(ISD::CTLZ, VT))
8743     return DAG.getNode(ISD::CTLZ, dl, VT, Op);
8744 
8745   // If the ZERO_UNDEF version is supported use that and handle the zero case.
8746   if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) {
8747     EVT SetCCVT =
8748         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8749     SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op);
8750     SDValue Zero = DAG.getConstant(0, dl, VT);
8751     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
8752     return DAG.getSelect(dl, VT, SrcIsZero,
8753                          DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
8754   }
8755 
8756   // Only expand vector types if we have the appropriate vector bit operations.
8757   // This includes the operations needed to expand CTPOP if it isn't supported.
8758   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
8759                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
8760                          !canExpandVectorCTPOP(*this, VT)) ||
8761                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
8762                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
8763     return SDValue();
8764 
8765   // for now, we do this:
8766   // x = x | (x >> 1);
8767   // x = x | (x >> 2);
8768   // ...
8769   // x = x | (x >>16);
8770   // x = x | (x >>32); // for 64-bit input
8771   // return popcount(~x);
8772   //
8773   // Ref: "Hacker's Delight" by Henry Warren
8774   for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) {
8775     SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
8776     Op = DAG.getNode(ISD::OR, dl, VT, Op,
8777                      DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
8778   }
8779   Op = DAG.getNOT(dl, Op, VT);
8780   return DAG.getNode(ISD::CTPOP, dl, VT, Op);
8781 }
8782 
8783 SDValue TargetLowering::expandVPCTLZ(SDNode *Node, SelectionDAG &DAG) const {
8784   SDLoc dl(Node);
8785   EVT VT = Node->getValueType(0);
8786   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
8787   SDValue Op = Node->getOperand(0);
8788   SDValue Mask = Node->getOperand(1);
8789   SDValue VL = Node->getOperand(2);
8790   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
8791 
8792   // do this:
8793   // x = x | (x >> 1);
8794   // x = x | (x >> 2);
8795   // ...
8796   // x = x | (x >>16);
8797   // x = x | (x >>32); // for 64-bit input
8798   // return popcount(~x);
8799   for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) {
8800     SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
8801     Op = DAG.getNode(ISD::VP_OR, dl, VT, Op,
8802                      DAG.getNode(ISD::VP_LSHR, dl, VT, Op, Tmp, Mask, VL), Mask,
8803                      VL);
8804   }
8805   Op = DAG.getNode(ISD::VP_XOR, dl, VT, Op, DAG.getConstant(-1, dl, VT), Mask,
8806                    VL);
8807   return DAG.getNode(ISD::VP_CTPOP, dl, VT, Op, Mask, VL);
8808 }
8809 
8810 SDValue TargetLowering::CTTZTableLookup(SDNode *Node, SelectionDAG &DAG,
8811                                         const SDLoc &DL, EVT VT, SDValue Op,
8812                                         unsigned BitWidth) const {
8813   if (BitWidth != 32 && BitWidth != 64)
8814     return SDValue();
8815   APInt DeBruijn = BitWidth == 32 ? APInt(32, 0x077CB531U)
8816                                   : APInt(64, 0x0218A392CD3D5DBFULL);
8817   const DataLayout &TD = DAG.getDataLayout();
8818   MachinePointerInfo PtrInfo =
8819       MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
8820   unsigned ShiftAmt = BitWidth - Log2_32(BitWidth);
8821   SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
8822   SDValue Lookup = DAG.getNode(
8823       ISD::SRL, DL, VT,
8824       DAG.getNode(ISD::MUL, DL, VT, DAG.getNode(ISD::AND, DL, VT, Op, Neg),
8825                   DAG.getConstant(DeBruijn, DL, VT)),
8826       DAG.getConstant(ShiftAmt, DL, VT));
8827   Lookup = DAG.getSExtOrTrunc(Lookup, DL, getPointerTy(TD));
8828 
8829   SmallVector<uint8_t> Table(BitWidth, 0);
8830   for (unsigned i = 0; i < BitWidth; i++) {
8831     APInt Shl = DeBruijn.shl(i);
8832     APInt Lshr = Shl.lshr(ShiftAmt);
8833     Table[Lshr.getZExtValue()] = i;
8834   }
8835 
8836   // Create a ConstantArray in Constant Pool
8837   auto *CA = ConstantDataArray::get(*DAG.getContext(), Table);
8838   SDValue CPIdx = DAG.getConstantPool(CA, getPointerTy(TD),
8839                                       TD.getPrefTypeAlign(CA->getType()));
8840   SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getEntryNode(),
8841                                    DAG.getMemBasePlusOffset(CPIdx, Lookup, DL),
8842                                    PtrInfo, MVT::i8);
8843   if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF)
8844     return ExtLoad;
8845 
8846   EVT SetCCVT =
8847       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8848   SDValue Zero = DAG.getConstant(0, DL, VT);
8849   SDValue SrcIsZero = DAG.getSetCC(DL, SetCCVT, Op, Zero, ISD::SETEQ);
8850   return DAG.getSelect(DL, VT, SrcIsZero,
8851                        DAG.getConstant(BitWidth, DL, VT), ExtLoad);
8852 }
8853 
8854 SDValue TargetLowering::expandCTTZ(SDNode *Node, SelectionDAG &DAG) const {
8855   SDLoc dl(Node);
8856   EVT VT = Node->getValueType(0);
8857   SDValue Op = Node->getOperand(0);
8858   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
8859 
8860   // If the non-ZERO_UNDEF version is supported we can use that instead.
8861   if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
8862       isOperationLegalOrCustom(ISD::CTTZ, VT))
8863     return DAG.getNode(ISD::CTTZ, dl, VT, Op);
8864 
8865   // If the ZERO_UNDEF version is supported use that and handle the zero case.
8866   if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) {
8867     EVT SetCCVT =
8868         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8869     SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op);
8870     SDValue Zero = DAG.getConstant(0, dl, VT);
8871     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
8872     return DAG.getSelect(dl, VT, SrcIsZero,
8873                          DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
8874   }
8875 
8876   // Only expand vector types if we have the appropriate vector bit operations.
8877   // This includes the operations needed to expand CTPOP if it isn't supported.
8878   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
8879                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
8880                          !isOperationLegalOrCustom(ISD::CTLZ, VT) &&
8881                          !canExpandVectorCTPOP(*this, VT)) ||
8882                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
8883                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
8884                         !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
8885     return SDValue();
8886 
8887   // Emit Table Lookup if ISD::CTLZ and ISD::CTPOP are not legal.
8888   if (!VT.isVector() && isOperationExpand(ISD::CTPOP, VT) &&
8889       !isOperationLegal(ISD::CTLZ, VT))
8890     if (SDValue V = CTTZTableLookup(Node, DAG, dl, VT, Op, NumBitsPerElt))
8891       return V;
8892 
8893   // for now, we use: { return popcount(~x & (x - 1)); }
8894   // unless the target has ctlz but not ctpop, in which case we use:
8895   // { return 32 - nlz(~x & (x-1)); }
8896   // Ref: "Hacker's Delight" by Henry Warren
8897   SDValue Tmp = DAG.getNode(
8898       ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
8899       DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
8900 
8901   // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
8902   if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) {
8903     return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
8904                        DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
8905   }
8906 
8907   return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
8908 }
8909 
8910 SDValue TargetLowering::expandVPCTTZ(SDNode *Node, SelectionDAG &DAG) const {
8911   SDValue Op = Node->getOperand(0);
8912   SDValue Mask = Node->getOperand(1);
8913   SDValue VL = Node->getOperand(2);
8914   SDLoc dl(Node);
8915   EVT VT = Node->getValueType(0);
8916 
8917   // Same as the vector part of expandCTTZ, use: popcount(~x & (x - 1))
8918   SDValue Not = DAG.getNode(ISD::VP_XOR, dl, VT, Op,
8919                             DAG.getConstant(-1, dl, VT), Mask, VL);
8920   SDValue MinusOne = DAG.getNode(ISD::VP_SUB, dl, VT, Op,
8921                                  DAG.getConstant(1, dl, VT), Mask, VL);
8922   SDValue Tmp = DAG.getNode(ISD::VP_AND, dl, VT, Not, MinusOne, Mask, VL);
8923   return DAG.getNode(ISD::VP_CTPOP, dl, VT, Tmp, Mask, VL);
8924 }
8925 
8926 SDValue TargetLowering::expandABS(SDNode *N, SelectionDAG &DAG,
8927                                   bool IsNegative) const {
8928   SDLoc dl(N);
8929   EVT VT = N->getValueType(0);
8930   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
8931   SDValue Op = N->getOperand(0);
8932 
8933   // abs(x) -> smax(x,sub(0,x))
8934   if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
8935       isOperationLegal(ISD::SMAX, VT)) {
8936     SDValue Zero = DAG.getConstant(0, dl, VT);
8937     return DAG.getNode(ISD::SMAX, dl, VT, Op,
8938                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
8939   }
8940 
8941   // abs(x) -> umin(x,sub(0,x))
8942   if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
8943       isOperationLegal(ISD::UMIN, VT)) {
8944     SDValue Zero = DAG.getConstant(0, dl, VT);
8945     Op = DAG.getFreeze(Op);
8946     return DAG.getNode(ISD::UMIN, dl, VT, Op,
8947                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
8948   }
8949 
8950   // 0 - abs(x) -> smin(x, sub(0,x))
8951   if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
8952       isOperationLegal(ISD::SMIN, VT)) {
8953     Op = DAG.getFreeze(Op);
8954     SDValue Zero = DAG.getConstant(0, dl, VT);
8955     return DAG.getNode(ISD::SMIN, dl, VT, Op,
8956                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
8957   }
8958 
8959   // Only expand vector types if we have the appropriate vector operations.
8960   if (VT.isVector() &&
8961       (!isOperationLegalOrCustom(ISD::SRA, VT) ||
8962        (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
8963        (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
8964        !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
8965     return SDValue();
8966 
8967   Op = DAG.getFreeze(Op);
8968   SDValue Shift =
8969       DAG.getNode(ISD::SRA, dl, VT, Op,
8970                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT));
8971   SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
8972 
8973   // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
8974   if (!IsNegative)
8975     return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift);
8976 
8977   // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
8978   return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
8979 }
8980 
8981 SDValue TargetLowering::expandABD(SDNode *N, SelectionDAG &DAG) const {
8982   SDLoc dl(N);
8983   EVT VT = N->getValueType(0);
8984   SDValue LHS = DAG.getFreeze(N->getOperand(0));
8985   SDValue RHS = DAG.getFreeze(N->getOperand(1));
8986   bool IsSigned = N->getOpcode() == ISD::ABDS;
8987 
8988   // abds(lhs, rhs) -> sub(smax(lhs,rhs), smin(lhs,rhs))
8989   // abdu(lhs, rhs) -> sub(umax(lhs,rhs), umin(lhs,rhs))
8990   unsigned MaxOpc = IsSigned ? ISD::SMAX : ISD::UMAX;
8991   unsigned MinOpc = IsSigned ? ISD::SMIN : ISD::UMIN;
8992   if (isOperationLegal(MaxOpc, VT) && isOperationLegal(MinOpc, VT)) {
8993     SDValue Max = DAG.getNode(MaxOpc, dl, VT, LHS, RHS);
8994     SDValue Min = DAG.getNode(MinOpc, dl, VT, LHS, RHS);
8995     return DAG.getNode(ISD::SUB, dl, VT, Max, Min);
8996   }
8997 
8998   // abdu(lhs, rhs) -> or(usubsat(lhs,rhs), usubsat(rhs,lhs))
8999   if (!IsSigned && isOperationLegal(ISD::USUBSAT, VT))
9000     return DAG.getNode(ISD::OR, dl, VT,
9001                        DAG.getNode(ISD::USUBSAT, dl, VT, LHS, RHS),
9002                        DAG.getNode(ISD::USUBSAT, dl, VT, RHS, LHS));
9003 
9004   // abds(lhs, rhs) -> select(sgt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
9005   // abdu(lhs, rhs) -> select(ugt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
9006   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
9007   ISD::CondCode CC = IsSigned ? ISD::CondCode::SETGT : ISD::CondCode::SETUGT;
9008   SDValue Cmp = DAG.getSetCC(dl, CCVT, LHS, RHS, CC);
9009   return DAG.getSelect(dl, VT, Cmp, DAG.getNode(ISD::SUB, dl, VT, LHS, RHS),
9010                        DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
9011 }
9012 
9013 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const {
9014   SDLoc dl(N);
9015   EVT VT = N->getValueType(0);
9016   SDValue Op = N->getOperand(0);
9017 
9018   if (!VT.isSimple())
9019     return SDValue();
9020 
9021   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
9022   SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
9023   switch (VT.getSimpleVT().getScalarType().SimpleTy) {
9024   default:
9025     return SDValue();
9026   case MVT::i16:
9027     // Use a rotate by 8. This can be further expanded if necessary.
9028     return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
9029   case MVT::i32:
9030     Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
9031     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Op,
9032                        DAG.getConstant(0xFF00, dl, VT));
9033     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT));
9034     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
9035     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
9036     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
9037     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
9038     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
9039     return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
9040   case MVT::i64:
9041     Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
9042     Tmp7 = DAG.getNode(ISD::AND, dl, VT, Op,
9043                        DAG.getConstant(255ULL<<8, dl, VT));
9044     Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT));
9045     Tmp6 = DAG.getNode(ISD::AND, dl, VT, Op,
9046                        DAG.getConstant(255ULL<<16, dl, VT));
9047     Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT));
9048     Tmp5 = DAG.getNode(ISD::AND, dl, VT, Op,
9049                        DAG.getConstant(255ULL<<24, dl, VT));
9050     Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT));
9051     Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
9052     Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
9053                        DAG.getConstant(255ULL<<24, dl, VT));
9054     Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
9055     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
9056                        DAG.getConstant(255ULL<<16, dl, VT));
9057     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
9058     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
9059                        DAG.getConstant(255ULL<<8, dl, VT));
9060     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
9061     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
9062     Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
9063     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
9064     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
9065     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
9066     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
9067     return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
9068   }
9069 }
9070 
9071 SDValue TargetLowering::expandVPBSWAP(SDNode *N, SelectionDAG &DAG) const {
9072   SDLoc dl(N);
9073   EVT VT = N->getValueType(0);
9074   SDValue Op = N->getOperand(0);
9075   SDValue Mask = N->getOperand(1);
9076   SDValue EVL = N->getOperand(2);
9077 
9078   if (!VT.isSimple())
9079     return SDValue();
9080 
9081   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
9082   SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
9083   switch (VT.getSimpleVT().getScalarType().SimpleTy) {
9084   default:
9085     return SDValue();
9086   case MVT::i16:
9087     Tmp1 = DAG.getNode(ISD::VP_SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT),
9088                        Mask, EVL);
9089     Tmp2 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(8, dl, SHVT),
9090                        Mask, EVL);
9091     return DAG.getNode(ISD::VP_OR, dl, VT, Tmp1, Tmp2, Mask, EVL);
9092   case MVT::i32:
9093     Tmp4 = DAG.getNode(ISD::VP_SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT),
9094                        Mask, EVL);
9095     Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Op, DAG.getConstant(0xFF00, dl, VT),
9096                        Mask, EVL);
9097     Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT),
9098                        Mask, EVL);
9099     Tmp2 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(8, dl, SHVT),
9100                        Mask, EVL);
9101     Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2,
9102                        DAG.getConstant(0xFF00, dl, VT), Mask, EVL);
9103     Tmp1 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(24, dl, SHVT),
9104                        Mask, EVL);
9105     Tmp4 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp3, Mask, EVL);
9106     Tmp2 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp1, Mask, EVL);
9107     return DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp2, Mask, EVL);
9108   case MVT::i64:
9109     Tmp8 = DAG.getNode(ISD::VP_SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT),
9110                        Mask, EVL);
9111     Tmp7 = DAG.getNode(ISD::VP_AND, dl, VT, Op,
9112                        DAG.getConstant(255ULL << 8, dl, VT), Mask, EVL);
9113     Tmp7 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT),
9114                        Mask, EVL);
9115     Tmp6 = DAG.getNode(ISD::VP_AND, dl, VT, Op,
9116                        DAG.getConstant(255ULL << 16, dl, VT), Mask, EVL);
9117     Tmp6 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT),
9118                        Mask, EVL);
9119     Tmp5 = DAG.getNode(ISD::VP_AND, dl, VT, Op,
9120                        DAG.getConstant(255ULL << 24, dl, VT), Mask, EVL);
9121     Tmp5 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT),
9122                        Mask, EVL);
9123     Tmp4 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(8, dl, SHVT),
9124                        Mask, EVL);
9125     Tmp4 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp4,
9126                        DAG.getConstant(255ULL << 24, dl, VT), Mask, EVL);
9127     Tmp3 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(24, dl, SHVT),
9128                        Mask, EVL);
9129     Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp3,
9130                        DAG.getConstant(255ULL << 16, dl, VT), Mask, EVL);
9131     Tmp2 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(40, dl, SHVT),
9132                        Mask, EVL);
9133     Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2,
9134                        DAG.getConstant(255ULL << 8, dl, VT), Mask, EVL);
9135     Tmp1 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(56, dl, SHVT),
9136                        Mask, EVL);
9137     Tmp8 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp8, Tmp7, Mask, EVL);
9138     Tmp6 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp6, Tmp5, Mask, EVL);
9139     Tmp4 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp3, Mask, EVL);
9140     Tmp2 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp1, Mask, EVL);
9141     Tmp8 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp8, Tmp6, Mask, EVL);
9142     Tmp4 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp2, Mask, EVL);
9143     return DAG.getNode(ISD::VP_OR, dl, VT, Tmp8, Tmp4, Mask, EVL);
9144   }
9145 }
9146 
9147 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const {
9148   SDLoc dl(N);
9149   EVT VT = N->getValueType(0);
9150   SDValue Op = N->getOperand(0);
9151   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
9152   unsigned Sz = VT.getScalarSizeInBits();
9153 
9154   SDValue Tmp, Tmp2, Tmp3;
9155 
9156   // If we can, perform BSWAP first and then the mask+swap the i4, then i2
9157   // and finally the i1 pairs.
9158   // TODO: We can easily support i4/i2 legal types if any target ever does.
9159   if (Sz >= 8 && isPowerOf2_32(Sz)) {
9160     // Create the masks - repeating the pattern every byte.
9161     APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
9162     APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
9163     APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
9164 
9165     // BSWAP if the type is wider than a single byte.
9166     Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
9167 
9168     // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
9169     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
9170     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
9171     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
9172     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
9173     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
9174 
9175     // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
9176     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
9177     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
9178     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
9179     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
9180     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
9181 
9182     // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
9183     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
9184     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
9185     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
9186     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
9187     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
9188     return Tmp;
9189   }
9190 
9191   Tmp = DAG.getConstant(0, dl, VT);
9192   for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
9193     if (I < J)
9194       Tmp2 =
9195           DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
9196     else
9197       Tmp2 =
9198           DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
9199 
9200     APInt Shift = APInt::getOneBitSet(Sz, J);
9201     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
9202     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
9203   }
9204 
9205   return Tmp;
9206 }
9207 
9208 SDValue TargetLowering::expandVPBITREVERSE(SDNode *N, SelectionDAG &DAG) const {
9209   assert(N->getOpcode() == ISD::VP_BITREVERSE);
9210 
9211   SDLoc dl(N);
9212   EVT VT = N->getValueType(0);
9213   SDValue Op = N->getOperand(0);
9214   SDValue Mask = N->getOperand(1);
9215   SDValue EVL = N->getOperand(2);
9216   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
9217   unsigned Sz = VT.getScalarSizeInBits();
9218 
9219   SDValue Tmp, Tmp2, Tmp3;
9220 
9221   // If we can, perform BSWAP first and then the mask+swap the i4, then i2
9222   // and finally the i1 pairs.
9223   // TODO: We can easily support i4/i2 legal types if any target ever does.
9224   if (Sz >= 8 && isPowerOf2_32(Sz)) {
9225     // Create the masks - repeating the pattern every byte.
9226     APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
9227     APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
9228     APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
9229 
9230     // BSWAP if the type is wider than a single byte.
9231     Tmp = (Sz > 8 ? DAG.getNode(ISD::VP_BSWAP, dl, VT, Op, Mask, EVL) : Op);
9232 
9233     // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
9234     Tmp2 = DAG.getNode(ISD::VP_LSHR, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT),
9235                        Mask, EVL);
9236     Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2,
9237                        DAG.getConstant(Mask4, dl, VT), Mask, EVL);
9238     Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT),
9239                        Mask, EVL);
9240     Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT),
9241                        Mask, EVL);
9242     Tmp = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp3, Mask, EVL);
9243 
9244     // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
9245     Tmp2 = DAG.getNode(ISD::VP_LSHR, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT),
9246                        Mask, EVL);
9247     Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2,
9248                        DAG.getConstant(Mask2, dl, VT), Mask, EVL);
9249     Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT),
9250                        Mask, EVL);
9251     Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT),
9252                        Mask, EVL);
9253     Tmp = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp3, Mask, EVL);
9254 
9255     // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
9256     Tmp2 = DAG.getNode(ISD::VP_LSHR, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT),
9257                        Mask, EVL);
9258     Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2,
9259                        DAG.getConstant(Mask1, dl, VT), Mask, EVL);
9260     Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT),
9261                        Mask, EVL);
9262     Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT),
9263                        Mask, EVL);
9264     Tmp = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp3, Mask, EVL);
9265     return Tmp;
9266   }
9267   return SDValue();
9268 }
9269 
9270 std::pair<SDValue, SDValue>
9271 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
9272                                     SelectionDAG &DAG) const {
9273   SDLoc SL(LD);
9274   SDValue Chain = LD->getChain();
9275   SDValue BasePTR = LD->getBasePtr();
9276   EVT SrcVT = LD->getMemoryVT();
9277   EVT DstVT = LD->getValueType(0);
9278   ISD::LoadExtType ExtType = LD->getExtensionType();
9279 
9280   if (SrcVT.isScalableVector())
9281     report_fatal_error("Cannot scalarize scalable vector loads");
9282 
9283   unsigned NumElem = SrcVT.getVectorNumElements();
9284 
9285   EVT SrcEltVT = SrcVT.getScalarType();
9286   EVT DstEltVT = DstVT.getScalarType();
9287 
9288   // A vector must always be stored in memory as-is, i.e. without any padding
9289   // between the elements, since various code depend on it, e.g. in the
9290   // handling of a bitcast of a vector type to int, which may be done with a
9291   // vector store followed by an integer load. A vector that does not have
9292   // elements that are byte-sized must therefore be stored as an integer
9293   // built out of the extracted vector elements.
9294   if (!SrcEltVT.isByteSized()) {
9295     unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
9296     EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
9297 
9298     unsigned NumSrcBits = SrcVT.getSizeInBits();
9299     EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
9300 
9301     unsigned SrcEltBits = SrcEltVT.getSizeInBits();
9302     SDValue SrcEltBitMask = DAG.getConstant(
9303         APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
9304 
9305     // Load the whole vector and avoid masking off the top bits as it makes
9306     // the codegen worse.
9307     SDValue Load =
9308         DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR,
9309                        LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(),
9310                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
9311 
9312     SmallVector<SDValue, 8> Vals;
9313     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
9314       unsigned ShiftIntoIdx =
9315           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
9316       SDValue ShiftAmount =
9317           DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(),
9318                                      LoadVT, SL, /*LegalTypes=*/false);
9319       SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
9320       SDValue Elt =
9321           DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
9322       SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
9323 
9324       if (ExtType != ISD::NON_EXTLOAD) {
9325         unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
9326         Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
9327       }
9328 
9329       Vals.push_back(Scalar);
9330     }
9331 
9332     SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
9333     return std::make_pair(Value, Load.getValue(1));
9334   }
9335 
9336   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
9337   assert(SrcEltVT.isByteSized());
9338 
9339   SmallVector<SDValue, 8> Vals;
9340   SmallVector<SDValue, 8> LoadChains;
9341 
9342   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
9343     SDValue ScalarLoad =
9344         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
9345                        LD->getPointerInfo().getWithOffset(Idx * Stride),
9346                        SrcEltVT, LD->getOriginalAlign(),
9347                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
9348 
9349     BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::getFixed(Stride));
9350 
9351     Vals.push_back(ScalarLoad.getValue(0));
9352     LoadChains.push_back(ScalarLoad.getValue(1));
9353   }
9354 
9355   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
9356   SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
9357 
9358   return std::make_pair(Value, NewChain);
9359 }
9360 
9361 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
9362                                              SelectionDAG &DAG) const {
9363   SDLoc SL(ST);
9364 
9365   SDValue Chain = ST->getChain();
9366   SDValue BasePtr = ST->getBasePtr();
9367   SDValue Value = ST->getValue();
9368   EVT StVT = ST->getMemoryVT();
9369 
9370   if (StVT.isScalableVector())
9371     report_fatal_error("Cannot scalarize scalable vector stores");
9372 
9373   // The type of the data we want to save
9374   EVT RegVT = Value.getValueType();
9375   EVT RegSclVT = RegVT.getScalarType();
9376 
9377   // The type of data as saved in memory.
9378   EVT MemSclVT = StVT.getScalarType();
9379 
9380   unsigned NumElem = StVT.getVectorNumElements();
9381 
9382   // A vector must always be stored in memory as-is, i.e. without any padding
9383   // between the elements, since various code depend on it, e.g. in the
9384   // handling of a bitcast of a vector type to int, which may be done with a
9385   // vector store followed by an integer load. A vector that does not have
9386   // elements that are byte-sized must therefore be stored as an integer
9387   // built out of the extracted vector elements.
9388   if (!MemSclVT.isByteSized()) {
9389     unsigned NumBits = StVT.getSizeInBits();
9390     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
9391 
9392     SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
9393 
9394     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
9395       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
9396                                 DAG.getVectorIdxConstant(Idx, SL));
9397       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
9398       SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
9399       unsigned ShiftIntoIdx =
9400           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
9401       SDValue ShiftAmount =
9402           DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
9403       SDValue ShiftedElt =
9404           DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
9405       CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
9406     }
9407 
9408     return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
9409                         ST->getOriginalAlign(), ST->getMemOperand()->getFlags(),
9410                         ST->getAAInfo());
9411   }
9412 
9413   // Store Stride in bytes
9414   unsigned Stride = MemSclVT.getSizeInBits() / 8;
9415   assert(Stride && "Zero stride!");
9416   // Extract each of the elements from the original vector and save them into
9417   // memory individually.
9418   SmallVector<SDValue, 8> Stores;
9419   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
9420     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
9421                               DAG.getVectorIdxConstant(Idx, SL));
9422 
9423     SDValue Ptr =
9424         DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Idx * Stride));
9425 
9426     // This scalar TruncStore may be illegal, but we legalize it later.
9427     SDValue Store = DAG.getTruncStore(
9428         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
9429         MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(),
9430         ST->getAAInfo());
9431 
9432     Stores.push_back(Store);
9433   }
9434 
9435   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
9436 }
9437 
9438 std::pair<SDValue, SDValue>
9439 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
9440   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
9441          "unaligned indexed loads not implemented!");
9442   SDValue Chain = LD->getChain();
9443   SDValue Ptr = LD->getBasePtr();
9444   EVT VT = LD->getValueType(0);
9445   EVT LoadedVT = LD->getMemoryVT();
9446   SDLoc dl(LD);
9447   auto &MF = DAG.getMachineFunction();
9448 
9449   if (VT.isFloatingPoint() || VT.isVector()) {
9450     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
9451     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
9452       if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
9453           LoadedVT.isVector()) {
9454         // Scalarize the load and let the individual components be handled.
9455         return scalarizeVectorLoad(LD, DAG);
9456       }
9457 
9458       // Expand to a (misaligned) integer load of the same size,
9459       // then bitconvert to floating point or vector.
9460       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
9461                                     LD->getMemOperand());
9462       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
9463       if (LoadedVT != VT)
9464         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
9465                              ISD::ANY_EXTEND, dl, VT, Result);
9466 
9467       return std::make_pair(Result, newLoad.getValue(1));
9468     }
9469 
9470     // Copy the value to a (aligned) stack slot using (unaligned) integer
9471     // loads and stores, then do a (aligned) load from the stack slot.
9472     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
9473     unsigned LoadedBytes = LoadedVT.getStoreSize();
9474     unsigned RegBytes = RegVT.getSizeInBits() / 8;
9475     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
9476 
9477     // Make sure the stack slot is also aligned for the register type.
9478     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
9479     auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
9480     SmallVector<SDValue, 8> Stores;
9481     SDValue StackPtr = StackBase;
9482     unsigned Offset = 0;
9483 
9484     EVT PtrVT = Ptr.getValueType();
9485     EVT StackPtrVT = StackPtr.getValueType();
9486 
9487     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
9488     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
9489 
9490     // Do all but one copies using the full register width.
9491     for (unsigned i = 1; i < NumRegs; i++) {
9492       // Load one integer register's worth from the original location.
9493       SDValue Load = DAG.getLoad(
9494           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
9495           LD->getOriginalAlign(), LD->getMemOperand()->getFlags(),
9496           LD->getAAInfo());
9497       // Follow the load with a store to the stack slot.  Remember the store.
9498       Stores.push_back(DAG.getStore(
9499           Load.getValue(1), dl, Load, StackPtr,
9500           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
9501       // Increment the pointers.
9502       Offset += RegBytes;
9503 
9504       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
9505       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
9506     }
9507 
9508     // The last copy may be partial.  Do an extending load.
9509     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
9510                                   8 * (LoadedBytes - Offset));
9511     SDValue Load =
9512         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
9513                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
9514                        LD->getOriginalAlign(), LD->getMemOperand()->getFlags(),
9515                        LD->getAAInfo());
9516     // Follow the load with a store to the stack slot.  Remember the store.
9517     // On big-endian machines this requires a truncating store to ensure
9518     // that the bits end up in the right place.
9519     Stores.push_back(DAG.getTruncStore(
9520         Load.getValue(1), dl, Load, StackPtr,
9521         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
9522 
9523     // The order of the stores doesn't matter - say it with a TokenFactor.
9524     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9525 
9526     // Finally, perform the original load only redirected to the stack slot.
9527     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
9528                           MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
9529                           LoadedVT);
9530 
9531     // Callers expect a MERGE_VALUES node.
9532     return std::make_pair(Load, TF);
9533   }
9534 
9535   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
9536          "Unaligned load of unsupported type.");
9537 
9538   // Compute the new VT that is half the size of the old one.  This is an
9539   // integer MVT.
9540   unsigned NumBits = LoadedVT.getSizeInBits();
9541   EVT NewLoadedVT;
9542   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
9543   NumBits >>= 1;
9544 
9545   Align Alignment = LD->getOriginalAlign();
9546   unsigned IncrementSize = NumBits / 8;
9547   ISD::LoadExtType HiExtType = LD->getExtensionType();
9548 
9549   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
9550   if (HiExtType == ISD::NON_EXTLOAD)
9551     HiExtType = ISD::ZEXTLOAD;
9552 
9553   // Load the value in two parts
9554   SDValue Lo, Hi;
9555   if (DAG.getDataLayout().isLittleEndian()) {
9556     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
9557                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
9558                         LD->getAAInfo());
9559 
9560     Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
9561     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
9562                         LD->getPointerInfo().getWithOffset(IncrementSize),
9563                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
9564                         LD->getAAInfo());
9565   } else {
9566     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
9567                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
9568                         LD->getAAInfo());
9569 
9570     Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
9571     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
9572                         LD->getPointerInfo().getWithOffset(IncrementSize),
9573                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
9574                         LD->getAAInfo());
9575   }
9576 
9577   // aggregate the two parts
9578   SDValue ShiftAmount =
9579       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
9580                                                     DAG.getDataLayout()));
9581   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
9582   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
9583 
9584   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
9585                              Hi.getValue(1));
9586 
9587   return std::make_pair(Result, TF);
9588 }
9589 
9590 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
9591                                              SelectionDAG &DAG) const {
9592   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
9593          "unaligned indexed stores not implemented!");
9594   SDValue Chain = ST->getChain();
9595   SDValue Ptr = ST->getBasePtr();
9596   SDValue Val = ST->getValue();
9597   EVT VT = Val.getValueType();
9598   Align Alignment = ST->getOriginalAlign();
9599   auto &MF = DAG.getMachineFunction();
9600   EVT StoreMemVT = ST->getMemoryVT();
9601 
9602   SDLoc dl(ST);
9603   if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
9604     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9605     if (isTypeLegal(intVT)) {
9606       if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
9607           StoreMemVT.isVector()) {
9608         // Scalarize the store and let the individual components be handled.
9609         SDValue Result = scalarizeVectorStore(ST, DAG);
9610         return Result;
9611       }
9612       // Expand to a bitconvert of the value to the integer type of the
9613       // same size, then a (misaligned) int store.
9614       // FIXME: Does not handle truncating floating point stores!
9615       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
9616       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
9617                             Alignment, ST->getMemOperand()->getFlags());
9618       return Result;
9619     }
9620     // Do a (aligned) store to a stack slot, then copy from the stack slot
9621     // to the final destination using (unaligned) integer loads and stores.
9622     MVT RegVT = getRegisterType(
9623         *DAG.getContext(),
9624         EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
9625     EVT PtrVT = Ptr.getValueType();
9626     unsigned StoredBytes = StoreMemVT.getStoreSize();
9627     unsigned RegBytes = RegVT.getSizeInBits() / 8;
9628     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
9629 
9630     // Make sure the stack slot is also aligned for the register type.
9631     SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
9632     auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
9633 
9634     // Perform the original store, only redirected to the stack slot.
9635     SDValue Store = DAG.getTruncStore(
9636         Chain, dl, Val, StackPtr,
9637         MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
9638 
9639     EVT StackPtrVT = StackPtr.getValueType();
9640 
9641     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
9642     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
9643     SmallVector<SDValue, 8> Stores;
9644     unsigned Offset = 0;
9645 
9646     // Do all but one copies using the full register width.
9647     for (unsigned i = 1; i < NumRegs; i++) {
9648       // Load one integer register's worth from the stack slot.
9649       SDValue Load = DAG.getLoad(
9650           RegVT, dl, Store, StackPtr,
9651           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
9652       // Store it to the final location.  Remember the store.
9653       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
9654                                     ST->getPointerInfo().getWithOffset(Offset),
9655                                     ST->getOriginalAlign(),
9656                                     ST->getMemOperand()->getFlags()));
9657       // Increment the pointers.
9658       Offset += RegBytes;
9659       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
9660       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
9661     }
9662 
9663     // The last store may be partial.  Do a truncating store.  On big-endian
9664     // machines this requires an extending load from the stack slot to ensure
9665     // that the bits are in the right place.
9666     EVT LoadMemVT =
9667         EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
9668 
9669     // Load from the stack slot.
9670     SDValue Load = DAG.getExtLoad(
9671         ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
9672         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
9673 
9674     Stores.push_back(
9675         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
9676                           ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
9677                           ST->getOriginalAlign(),
9678                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
9679     // The order of the stores doesn't matter - say it with a TokenFactor.
9680     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9681     return Result;
9682   }
9683 
9684   assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
9685          "Unaligned store of unknown type.");
9686   // Get the half-size VT
9687   EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
9688   unsigned NumBits = NewStoredVT.getFixedSizeInBits();
9689   unsigned IncrementSize = NumBits / 8;
9690 
9691   // Divide the stored value in two parts.
9692   SDValue ShiftAmount = DAG.getConstant(
9693       NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout()));
9694   SDValue Lo = Val;
9695   // If Val is a constant, replace the upper bits with 0. The SRL will constant
9696   // fold and not use the upper bits. A smaller constant may be easier to
9697   // materialize.
9698   if (auto *C = dyn_cast<ConstantSDNode>(Lo); C && !C->isOpaque())
9699     Lo = DAG.getNode(
9700         ISD::AND, dl, VT, Lo,
9701         DAG.getConstant(APInt::getLowBitsSet(VT.getSizeInBits(), NumBits), dl,
9702                         VT));
9703   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
9704 
9705   // Store the two parts
9706   SDValue Store1, Store2;
9707   Store1 = DAG.getTruncStore(Chain, dl,
9708                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
9709                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
9710                              ST->getMemOperand()->getFlags());
9711 
9712   Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
9713   Store2 = DAG.getTruncStore(
9714       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
9715       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
9716       ST->getMemOperand()->getFlags(), ST->getAAInfo());
9717 
9718   SDValue Result =
9719       DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
9720   return Result;
9721 }
9722 
9723 SDValue
9724 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
9725                                        const SDLoc &DL, EVT DataVT,
9726                                        SelectionDAG &DAG,
9727                                        bool IsCompressedMemory) const {
9728   SDValue Increment;
9729   EVT AddrVT = Addr.getValueType();
9730   EVT MaskVT = Mask.getValueType();
9731   assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
9732          "Incompatible types of Data and Mask");
9733   if (IsCompressedMemory) {
9734     if (DataVT.isScalableVector())
9735       report_fatal_error(
9736           "Cannot currently handle compressed memory with scalable vectors");
9737     // Incrementing the pointer according to number of '1's in the mask.
9738     EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
9739     SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
9740     if (MaskIntVT.getSizeInBits() < 32) {
9741       MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
9742       MaskIntVT = MVT::i32;
9743     }
9744 
9745     // Count '1's with POPCNT.
9746     Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
9747     Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
9748     // Scale is an element size in bytes.
9749     SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
9750                                     AddrVT);
9751     Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
9752   } else if (DataVT.isScalableVector()) {
9753     Increment = DAG.getVScale(DL, AddrVT,
9754                               APInt(AddrVT.getFixedSizeInBits(),
9755                                     DataVT.getStoreSize().getKnownMinValue()));
9756   } else
9757     Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT);
9758 
9759   return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
9760 }
9761 
9762 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx,
9763                                        EVT VecVT, const SDLoc &dl,
9764                                        ElementCount SubEC) {
9765   assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
9766          "Cannot index a scalable vector within a fixed-width vector");
9767 
9768   unsigned NElts = VecVT.getVectorMinNumElements();
9769   unsigned NumSubElts = SubEC.getKnownMinValue();
9770   EVT IdxVT = Idx.getValueType();
9771 
9772   if (VecVT.isScalableVector() && !SubEC.isScalable()) {
9773     // If this is a constant index and we know the value plus the number of the
9774     // elements in the subvector minus one is less than the minimum number of
9775     // elements then it's safe to return Idx.
9776     if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx))
9777       if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts)
9778         return Idx;
9779     SDValue VS =
9780         DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts));
9781     unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT;
9782     SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS,
9783                               DAG.getConstant(NumSubElts, dl, IdxVT));
9784     return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub);
9785   }
9786   if (isPowerOf2_32(NElts) && NumSubElts == 1) {
9787     APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts));
9788     return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
9789                        DAG.getConstant(Imm, dl, IdxVT));
9790   }
9791   unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0;
9792   return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
9793                      DAG.getConstant(MaxIndex, dl, IdxVT));
9794 }
9795 
9796 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
9797                                                 SDValue VecPtr, EVT VecVT,
9798                                                 SDValue Index) const {
9799   return getVectorSubVecPointer(
9800       DAG, VecPtr, VecVT,
9801       EVT::getVectorVT(*DAG.getContext(), VecVT.getVectorElementType(), 1),
9802       Index);
9803 }
9804 
9805 SDValue TargetLowering::getVectorSubVecPointer(SelectionDAG &DAG,
9806                                                SDValue VecPtr, EVT VecVT,
9807                                                EVT SubVecVT,
9808                                                SDValue Index) const {
9809   SDLoc dl(Index);
9810   // Make sure the index type is big enough to compute in.
9811   Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
9812 
9813   EVT EltVT = VecVT.getVectorElementType();
9814 
9815   // Calculate the element offset and add it to the pointer.
9816   unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
9817   assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
9818          "Converting bits to bytes lost precision");
9819   assert(SubVecVT.getVectorElementType() == EltVT &&
9820          "Sub-vector must be a vector with matching element type");
9821   Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
9822                                   SubVecVT.getVectorElementCount());
9823 
9824   EVT IdxVT = Index.getValueType();
9825   if (SubVecVT.isScalableVector())
9826     Index =
9827         DAG.getNode(ISD::MUL, dl, IdxVT, Index,
9828                     DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1)));
9829 
9830   Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
9831                       DAG.getConstant(EltSize, dl, IdxVT));
9832   return DAG.getMemBasePlusOffset(VecPtr, Index, dl);
9833 }
9834 
9835 //===----------------------------------------------------------------------===//
9836 // Implementation of Emulated TLS Model
9837 //===----------------------------------------------------------------------===//
9838 
9839 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
9840                                                 SelectionDAG &DAG) const {
9841   // Access to address of TLS varialbe xyz is lowered to a function call:
9842   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
9843   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9844   PointerType *VoidPtrType = PointerType::get(*DAG.getContext(), 0);
9845   SDLoc dl(GA);
9846 
9847   ArgListTy Args;
9848   ArgListEntry Entry;
9849   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
9850   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
9851   StringRef EmuTlsVarName(NameString);
9852   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
9853   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
9854   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
9855   Entry.Ty = VoidPtrType;
9856   Args.push_back(Entry);
9857 
9858   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
9859 
9860   TargetLowering::CallLoweringInfo CLI(DAG);
9861   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
9862   CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
9863   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
9864 
9865   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
9866   // At last for X86 targets, maybe good for other targets too?
9867   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9868   MFI.setAdjustsStack(true); // Is this only for X86 target?
9869   MFI.setHasCalls(true);
9870 
9871   assert((GA->getOffset() == 0) &&
9872          "Emulated TLS must have zero offset in GlobalAddressSDNode");
9873   return CallResult.first;
9874 }
9875 
9876 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
9877                                                 SelectionDAG &DAG) const {
9878   assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
9879   if (!isCtlzFast())
9880     return SDValue();
9881   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9882   SDLoc dl(Op);
9883   if (isNullConstant(Op.getOperand(1)) && CC == ISD::SETEQ) {
9884     EVT VT = Op.getOperand(0).getValueType();
9885     SDValue Zext = Op.getOperand(0);
9886     if (VT.bitsLT(MVT::i32)) {
9887       VT = MVT::i32;
9888       Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
9889     }
9890     unsigned Log2b = Log2_32(VT.getSizeInBits());
9891     SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
9892     SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
9893                               DAG.getConstant(Log2b, dl, MVT::i32));
9894     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
9895   }
9896   return SDValue();
9897 }
9898 
9899 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const {
9900   SDValue Op0 = Node->getOperand(0);
9901   SDValue Op1 = Node->getOperand(1);
9902   EVT VT = Op0.getValueType();
9903   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
9904   unsigned Opcode = Node->getOpcode();
9905   SDLoc DL(Node);
9906 
9907   // umax(x,1) --> sub(x,cmpeq(x,0)) iff cmp result is allbits
9908   if (Opcode == ISD::UMAX && llvm::isOneOrOneSplat(Op1, true) && BoolVT == VT &&
9909       getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
9910     Op0 = DAG.getFreeze(Op0);
9911     SDValue Zero = DAG.getConstant(0, DL, VT);
9912     return DAG.getNode(ISD::SUB, DL, VT, Op0,
9913                        DAG.getSetCC(DL, VT, Op0, Zero, ISD::SETEQ));
9914   }
9915 
9916   // umin(x,y) -> sub(x,usubsat(x,y))
9917   // TODO: Missing freeze(Op0)?
9918   if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
9919       isOperationLegal(ISD::USUBSAT, VT)) {
9920     return DAG.getNode(ISD::SUB, DL, VT, Op0,
9921                        DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
9922   }
9923 
9924   // umax(x,y) -> add(x,usubsat(y,x))
9925   // TODO: Missing freeze(Op0)?
9926   if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
9927       isOperationLegal(ISD::USUBSAT, VT)) {
9928     return DAG.getNode(ISD::ADD, DL, VT, Op0,
9929                        DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
9930   }
9931 
9932   // FIXME: Should really try to split the vector in case it's legal on a
9933   // subvector.
9934   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
9935     return DAG.UnrollVectorOp(Node);
9936 
9937   // Attempt to find an existing SETCC node that we can reuse.
9938   // TODO: Do we need a generic doesSETCCNodeExist?
9939   // TODO: Missing freeze(Op0)/freeze(Op1)?
9940   auto buildMinMax = [&](ISD::CondCode PrefCC, ISD::CondCode AltCC,
9941                          ISD::CondCode PrefCommuteCC,
9942                          ISD::CondCode AltCommuteCC) {
9943     SDVTList BoolVTList = DAG.getVTList(BoolVT);
9944     for (ISD::CondCode CC : {PrefCC, AltCC}) {
9945       if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
9946                             {Op0, Op1, DAG.getCondCode(CC)})) {
9947         SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
9948         return DAG.getSelect(DL, VT, Cond, Op0, Op1);
9949       }
9950     }
9951     for (ISD::CondCode CC : {PrefCommuteCC, AltCommuteCC}) {
9952       if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
9953                             {Op0, Op1, DAG.getCondCode(CC)})) {
9954         SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
9955         return DAG.getSelect(DL, VT, Cond, Op1, Op0);
9956       }
9957     }
9958     SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, PrefCC);
9959     return DAG.getSelect(DL, VT, Cond, Op0, Op1);
9960   };
9961 
9962   // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
9963   //                      -> Y = (A < B) ? B : A
9964   //                      -> Y = (A >= B) ? A : B
9965   //                      -> Y = (A <= B) ? B : A
9966   switch (Opcode) {
9967   case ISD::SMAX:
9968     return buildMinMax(ISD::SETGT, ISD::SETGE, ISD::SETLT, ISD::SETLE);
9969   case ISD::SMIN:
9970     return buildMinMax(ISD::SETLT, ISD::SETLE, ISD::SETGT, ISD::SETGE);
9971   case ISD::UMAX:
9972     return buildMinMax(ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE);
9973   case ISD::UMIN:
9974     return buildMinMax(ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE);
9975   }
9976 
9977   llvm_unreachable("How did we get here?");
9978 }
9979 
9980 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const {
9981   unsigned Opcode = Node->getOpcode();
9982   SDValue LHS = Node->getOperand(0);
9983   SDValue RHS = Node->getOperand(1);
9984   EVT VT = LHS.getValueType();
9985   SDLoc dl(Node);
9986 
9987   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
9988   assert(VT.isInteger() && "Expected operands to be integers");
9989 
9990   // usub.sat(a, b) -> umax(a, b) - b
9991   if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
9992     SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
9993     return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
9994   }
9995 
9996   // uadd.sat(a, b) -> umin(a, ~b) + b
9997   if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
9998     SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
9999     SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
10000     return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
10001   }
10002 
10003   unsigned OverflowOp;
10004   switch (Opcode) {
10005   case ISD::SADDSAT:
10006     OverflowOp = ISD::SADDO;
10007     break;
10008   case ISD::UADDSAT:
10009     OverflowOp = ISD::UADDO;
10010     break;
10011   case ISD::SSUBSAT:
10012     OverflowOp = ISD::SSUBO;
10013     break;
10014   case ISD::USUBSAT:
10015     OverflowOp = ISD::USUBO;
10016     break;
10017   default:
10018     llvm_unreachable("Expected method to receive signed or unsigned saturation "
10019                      "addition or subtraction node.");
10020   }
10021 
10022   // FIXME: Should really try to split the vector in case it's legal on a
10023   // subvector.
10024   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
10025     return DAG.UnrollVectorOp(Node);
10026 
10027   unsigned BitWidth = LHS.getScalarValueSizeInBits();
10028   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10029   SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
10030   SDValue SumDiff = Result.getValue(0);
10031   SDValue Overflow = Result.getValue(1);
10032   SDValue Zero = DAG.getConstant(0, dl, VT);
10033   SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
10034 
10035   if (Opcode == ISD::UADDSAT) {
10036     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
10037       // (LHS + RHS) | OverflowMask
10038       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
10039       return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
10040     }
10041     // Overflow ? 0xffff.... : (LHS + RHS)
10042     return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
10043   }
10044 
10045   if (Opcode == ISD::USUBSAT) {
10046     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
10047       // (LHS - RHS) & ~OverflowMask
10048       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
10049       SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
10050       return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
10051     }
10052     // Overflow ? 0 : (LHS - RHS)
10053     return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
10054   }
10055 
10056   if (Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) {
10057     APInt MinVal = APInt::getSignedMinValue(BitWidth);
10058     APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
10059 
10060     KnownBits KnownLHS = DAG.computeKnownBits(LHS);
10061     KnownBits KnownRHS = DAG.computeKnownBits(RHS);
10062 
10063     // If either of the operand signs are known, then they are guaranteed to
10064     // only saturate in one direction. If non-negative they will saturate
10065     // towards SIGNED_MAX, if negative they will saturate towards SIGNED_MIN.
10066     //
10067     // In the case of ISD::SSUBSAT, 'x - y' is equivalent to 'x + (-y)', so the
10068     // sign of 'y' has to be flipped.
10069 
10070     bool LHSIsNonNegative = KnownLHS.isNonNegative();
10071     bool RHSIsNonNegative = Opcode == ISD::SADDSAT ? KnownRHS.isNonNegative()
10072                                                    : KnownRHS.isNegative();
10073     if (LHSIsNonNegative || RHSIsNonNegative) {
10074       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
10075       return DAG.getSelect(dl, VT, Overflow, SatMax, SumDiff);
10076     }
10077 
10078     bool LHSIsNegative = KnownLHS.isNegative();
10079     bool RHSIsNegative = Opcode == ISD::SADDSAT ? KnownRHS.isNegative()
10080                                                 : KnownRHS.isNonNegative();
10081     if (LHSIsNegative || RHSIsNegative) {
10082       SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
10083       return DAG.getSelect(dl, VT, Overflow, SatMin, SumDiff);
10084     }
10085   }
10086 
10087   // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
10088   APInt MinVal = APInt::getSignedMinValue(BitWidth);
10089   SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
10090   SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
10091                               DAG.getConstant(BitWidth - 1, dl, VT));
10092   Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
10093   return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
10094 }
10095 
10096 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const {
10097   unsigned Opcode = Node->getOpcode();
10098   bool IsSigned = Opcode == ISD::SSHLSAT;
10099   SDValue LHS = Node->getOperand(0);
10100   SDValue RHS = Node->getOperand(1);
10101   EVT VT = LHS.getValueType();
10102   SDLoc dl(Node);
10103 
10104   assert((Node->getOpcode() == ISD::SSHLSAT ||
10105           Node->getOpcode() == ISD::USHLSAT) &&
10106           "Expected a SHLSAT opcode");
10107   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
10108   assert(VT.isInteger() && "Expected operands to be integers");
10109 
10110   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
10111     return DAG.UnrollVectorOp(Node);
10112 
10113   // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
10114 
10115   unsigned BW = VT.getScalarSizeInBits();
10116   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10117   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
10118   SDValue Orig =
10119       DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
10120 
10121   SDValue SatVal;
10122   if (IsSigned) {
10123     SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
10124     SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
10125     SDValue Cond =
10126         DAG.getSetCC(dl, BoolVT, LHS, DAG.getConstant(0, dl, VT), ISD::SETLT);
10127     SatVal = DAG.getSelect(dl, VT, Cond, SatMin, SatMax);
10128   } else {
10129     SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
10130   }
10131   SDValue Cond = DAG.getSetCC(dl, BoolVT, LHS, Orig, ISD::SETNE);
10132   return DAG.getSelect(dl, VT, Cond, SatVal, Result);
10133 }
10134 
10135 SDValue
10136 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const {
10137   assert((Node->getOpcode() == ISD::SMULFIX ||
10138           Node->getOpcode() == ISD::UMULFIX ||
10139           Node->getOpcode() == ISD::SMULFIXSAT ||
10140           Node->getOpcode() == ISD::UMULFIXSAT) &&
10141          "Expected a fixed point multiplication opcode");
10142 
10143   SDLoc dl(Node);
10144   SDValue LHS = Node->getOperand(0);
10145   SDValue RHS = Node->getOperand(1);
10146   EVT VT = LHS.getValueType();
10147   unsigned Scale = Node->getConstantOperandVal(2);
10148   bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
10149                      Node->getOpcode() == ISD::UMULFIXSAT);
10150   bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
10151                  Node->getOpcode() == ISD::SMULFIXSAT);
10152   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10153   unsigned VTSize = VT.getScalarSizeInBits();
10154 
10155   if (!Scale) {
10156     // [us]mul.fix(a, b, 0) -> mul(a, b)
10157     if (!Saturating) {
10158       if (isOperationLegalOrCustom(ISD::MUL, VT))
10159         return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
10160     } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
10161       SDValue Result =
10162           DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
10163       SDValue Product = Result.getValue(0);
10164       SDValue Overflow = Result.getValue(1);
10165       SDValue Zero = DAG.getConstant(0, dl, VT);
10166 
10167       APInt MinVal = APInt::getSignedMinValue(VTSize);
10168       APInt MaxVal = APInt::getSignedMaxValue(VTSize);
10169       SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
10170       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
10171       // Xor the inputs, if resulting sign bit is 0 the product will be
10172       // positive, else negative.
10173       SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
10174       SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
10175       Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
10176       return DAG.getSelect(dl, VT, Overflow, Result, Product);
10177     } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
10178       SDValue Result =
10179           DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
10180       SDValue Product = Result.getValue(0);
10181       SDValue Overflow = Result.getValue(1);
10182 
10183       APInt MaxVal = APInt::getMaxValue(VTSize);
10184       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
10185       return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
10186     }
10187   }
10188 
10189   assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
10190          "Expected scale to be less than the number of bits if signed or at "
10191          "most the number of bits if unsigned.");
10192   assert(LHS.getValueType() == RHS.getValueType() &&
10193          "Expected both operands to be the same type");
10194 
10195   // Get the upper and lower bits of the result.
10196   SDValue Lo, Hi;
10197   unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
10198   unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
10199   if (isOperationLegalOrCustom(LoHiOp, VT)) {
10200     SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
10201     Lo = Result.getValue(0);
10202     Hi = Result.getValue(1);
10203   } else if (isOperationLegalOrCustom(HiOp, VT)) {
10204     Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
10205     Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
10206   } else if (VT.isVector()) {
10207     return SDValue();
10208   } else {
10209     report_fatal_error("Unable to expand fixed point multiplication.");
10210   }
10211 
10212   if (Scale == VTSize)
10213     // Result is just the top half since we'd be shifting by the width of the
10214     // operand. Overflow impossible so this works for both UMULFIX and
10215     // UMULFIXSAT.
10216     return Hi;
10217 
10218   // The result will need to be shifted right by the scale since both operands
10219   // are scaled. The result is given to us in 2 halves, so we only want part of
10220   // both in the result.
10221   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
10222   SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
10223                                DAG.getConstant(Scale, dl, ShiftTy));
10224   if (!Saturating)
10225     return Result;
10226 
10227   if (!Signed) {
10228     // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
10229     // widened multiplication) aren't all zeroes.
10230 
10231     // Saturate to max if ((Hi >> Scale) != 0),
10232     // which is the same as if (Hi > ((1 << Scale) - 1))
10233     APInt MaxVal = APInt::getMaxValue(VTSize);
10234     SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale),
10235                                       dl, VT);
10236     Result = DAG.getSelectCC(dl, Hi, LowMask,
10237                              DAG.getConstant(MaxVal, dl, VT), Result,
10238                              ISD::SETUGT);
10239 
10240     return Result;
10241   }
10242 
10243   // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
10244   // widened multiplication) aren't all ones or all zeroes.
10245 
10246   SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
10247   SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
10248 
10249   if (Scale == 0) {
10250     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
10251                                DAG.getConstant(VTSize - 1, dl, ShiftTy));
10252     SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
10253     // Saturated to SatMin if wide product is negative, and SatMax if wide
10254     // product is positive ...
10255     SDValue Zero = DAG.getConstant(0, dl, VT);
10256     SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax,
10257                                                ISD::SETLT);
10258     // ... but only if we overflowed.
10259     return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
10260   }
10261 
10262   //  We handled Scale==0 above so all the bits to examine is in Hi.
10263 
10264   // Saturate to max if ((Hi >> (Scale - 1)) > 0),
10265   // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
10266   SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1),
10267                                     dl, VT);
10268   Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT);
10269   // Saturate to min if (Hi >> (Scale - 1)) < -1),
10270   // which is the same as if (HI < (-1 << (Scale - 1))
10271   SDValue HighMask =
10272       DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1),
10273                       dl, VT);
10274   Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT);
10275   return Result;
10276 }
10277 
10278 SDValue
10279 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl,
10280                                     SDValue LHS, SDValue RHS,
10281                                     unsigned Scale, SelectionDAG &DAG) const {
10282   assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
10283           Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
10284          "Expected a fixed point division opcode");
10285 
10286   EVT VT = LHS.getValueType();
10287   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
10288   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
10289   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10290 
10291   // If there is enough room in the type to upscale the LHS or downscale the
10292   // RHS before the division, we can perform it in this type without having to
10293   // resize. For signed operations, the LHS headroom is the number of
10294   // redundant sign bits, and for unsigned ones it is the number of zeroes.
10295   // The headroom for the RHS is the number of trailing zeroes.
10296   unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
10297                             : DAG.computeKnownBits(LHS).countMinLeadingZeros();
10298   unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
10299 
10300   // For signed saturating operations, we need to be able to detect true integer
10301   // division overflow; that is, when you have MIN / -EPS. However, this
10302   // is undefined behavior and if we emit divisions that could take such
10303   // values it may cause undesired behavior (arithmetic exceptions on x86, for
10304   // example).
10305   // Avoid this by requiring an extra bit so that we never get this case.
10306   // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
10307   // signed saturating division, we need to emit a whopping 32-bit division.
10308   if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
10309     return SDValue();
10310 
10311   unsigned LHSShift = std::min(LHSLead, Scale);
10312   unsigned RHSShift = Scale - LHSShift;
10313 
10314   // At this point, we know that if we shift the LHS up by LHSShift and the
10315   // RHS down by RHSShift, we can emit a regular division with a final scaling
10316   // factor of Scale.
10317 
10318   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
10319   if (LHSShift)
10320     LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
10321                       DAG.getConstant(LHSShift, dl, ShiftTy));
10322   if (RHSShift)
10323     RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
10324                       DAG.getConstant(RHSShift, dl, ShiftTy));
10325 
10326   SDValue Quot;
10327   if (Signed) {
10328     // For signed operations, if the resulting quotient is negative and the
10329     // remainder is nonzero, subtract 1 from the quotient to round towards
10330     // negative infinity.
10331     SDValue Rem;
10332     // FIXME: Ideally we would always produce an SDIVREM here, but if the
10333     // type isn't legal, SDIVREM cannot be expanded. There is no reason why
10334     // we couldn't just form a libcall, but the type legalizer doesn't do it.
10335     if (isTypeLegal(VT) &&
10336         isOperationLegalOrCustom(ISD::SDIVREM, VT)) {
10337       Quot = DAG.getNode(ISD::SDIVREM, dl,
10338                          DAG.getVTList(VT, VT),
10339                          LHS, RHS);
10340       Rem = Quot.getValue(1);
10341       Quot = Quot.getValue(0);
10342     } else {
10343       Quot = DAG.getNode(ISD::SDIV, dl, VT,
10344                          LHS, RHS);
10345       Rem = DAG.getNode(ISD::SREM, dl, VT,
10346                         LHS, RHS);
10347     }
10348     SDValue Zero = DAG.getConstant(0, dl, VT);
10349     SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
10350     SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
10351     SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
10352     SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
10353     SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
10354                                DAG.getConstant(1, dl, VT));
10355     Quot = DAG.getSelect(dl, VT,
10356                          DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
10357                          Sub1, Quot);
10358   } else
10359     Quot = DAG.getNode(ISD::UDIV, dl, VT,
10360                        LHS, RHS);
10361 
10362   return Quot;
10363 }
10364 
10365 void TargetLowering::expandUADDSUBO(
10366     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
10367   SDLoc dl(Node);
10368   SDValue LHS = Node->getOperand(0);
10369   SDValue RHS = Node->getOperand(1);
10370   bool IsAdd = Node->getOpcode() == ISD::UADDO;
10371 
10372   // If UADDO_CARRY/SUBO_CARRY is legal, use that instead.
10373   unsigned OpcCarry = IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
10374   if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
10375     SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
10376     SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
10377                                     { LHS, RHS, CarryIn });
10378     Result = SDValue(NodeCarry.getNode(), 0);
10379     Overflow = SDValue(NodeCarry.getNode(), 1);
10380     return;
10381   }
10382 
10383   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
10384                             LHS.getValueType(), LHS, RHS);
10385 
10386   EVT ResultType = Node->getValueType(1);
10387   EVT SetCCType = getSetCCResultType(
10388       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
10389   SDValue SetCC;
10390   if (IsAdd && isOneConstant(RHS)) {
10391     // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces
10392     // the live range of X. We assume comparing with 0 is cheap.
10393     // The general case (X + C) < C is not necessarily beneficial. Although we
10394     // reduce the live range of X, we may introduce the materialization of
10395     // constant C.
10396     SetCC =
10397         DAG.getSetCC(dl, SetCCType, Result,
10398                      DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ);
10399   } else if (IsAdd && isAllOnesConstant(RHS)) {
10400     // Special case: uaddo X, -1 overflows if X != 0.
10401     SetCC =
10402         DAG.getSetCC(dl, SetCCType, LHS,
10403                      DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETNE);
10404   } else {
10405     ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
10406     SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
10407   }
10408   Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
10409 }
10410 
10411 void TargetLowering::expandSADDSUBO(
10412     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
10413   SDLoc dl(Node);
10414   SDValue LHS = Node->getOperand(0);
10415   SDValue RHS = Node->getOperand(1);
10416   bool IsAdd = Node->getOpcode() == ISD::SADDO;
10417 
10418   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
10419                             LHS.getValueType(), LHS, RHS);
10420 
10421   EVT ResultType = Node->getValueType(1);
10422   EVT OType = getSetCCResultType(
10423       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
10424 
10425   // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
10426   unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
10427   if (isOperationLegal(OpcSat, LHS.getValueType())) {
10428     SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
10429     SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
10430     Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
10431     return;
10432   }
10433 
10434   SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
10435 
10436   // For an addition, the result should be less than one of the operands (LHS)
10437   // if and only if the other operand (RHS) is negative, otherwise there will
10438   // be overflow.
10439   // For a subtraction, the result should be less than one of the operands
10440   // (LHS) if and only if the other operand (RHS) is (non-zero) positive,
10441   // otherwise there will be overflow.
10442   SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
10443   SDValue ConditionRHS =
10444       DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT);
10445 
10446   Overflow = DAG.getBoolExtOrTrunc(
10447       DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl,
10448       ResultType, ResultType);
10449 }
10450 
10451 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result,
10452                                 SDValue &Overflow, SelectionDAG &DAG) const {
10453   SDLoc dl(Node);
10454   EVT VT = Node->getValueType(0);
10455   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10456   SDValue LHS = Node->getOperand(0);
10457   SDValue RHS = Node->getOperand(1);
10458   bool isSigned = Node->getOpcode() == ISD::SMULO;
10459 
10460   // For power-of-two multiplications we can use a simpler shift expansion.
10461   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
10462     const APInt &C = RHSC->getAPIntValue();
10463     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
10464     if (C.isPowerOf2()) {
10465       // smulo(x, signed_min) is same as umulo(x, signed_min).
10466       bool UseArithShift = isSigned && !C.isMinSignedValue();
10467       EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout());
10468       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy);
10469       Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
10470       Overflow = DAG.getSetCC(dl, SetCCVT,
10471           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
10472                       dl, VT, Result, ShiftAmt),
10473           LHS, ISD::SETNE);
10474       return true;
10475     }
10476   }
10477 
10478   EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2);
10479   if (VT.isVector())
10480     WideVT =
10481         EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount());
10482 
10483   SDValue BottomHalf;
10484   SDValue TopHalf;
10485   static const unsigned Ops[2][3] =
10486       { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
10487         { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
10488   if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
10489     BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
10490     TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
10491   } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
10492     BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
10493                              RHS);
10494     TopHalf = BottomHalf.getValue(1);
10495   } else if (isTypeLegal(WideVT)) {
10496     LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
10497     RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
10498     SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
10499     BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
10500     SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl,
10501         getShiftAmountTy(WideVT, DAG.getDataLayout()));
10502     TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
10503                           DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
10504   } else {
10505     if (VT.isVector())
10506       return false;
10507 
10508     // We can fall back to a libcall with an illegal type for the MUL if we
10509     // have a libcall big enough.
10510     // Also, we can fall back to a division in some cases, but that's a big
10511     // performance hit in the general case.
10512     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
10513     if (WideVT == MVT::i16)
10514       LC = RTLIB::MUL_I16;
10515     else if (WideVT == MVT::i32)
10516       LC = RTLIB::MUL_I32;
10517     else if (WideVT == MVT::i64)
10518       LC = RTLIB::MUL_I64;
10519     else if (WideVT == MVT::i128)
10520       LC = RTLIB::MUL_I128;
10521     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
10522 
10523     SDValue HiLHS;
10524     SDValue HiRHS;
10525     if (isSigned) {
10526       // The high part is obtained by SRA'ing all but one of the bits of low
10527       // part.
10528       unsigned LoSize = VT.getFixedSizeInBits();
10529       HiLHS =
10530           DAG.getNode(ISD::SRA, dl, VT, LHS,
10531                       DAG.getConstant(LoSize - 1, dl,
10532                                       getPointerTy(DAG.getDataLayout())));
10533       HiRHS =
10534           DAG.getNode(ISD::SRA, dl, VT, RHS,
10535                       DAG.getConstant(LoSize - 1, dl,
10536                                       getPointerTy(DAG.getDataLayout())));
10537     } else {
10538         HiLHS = DAG.getConstant(0, dl, VT);
10539         HiRHS = DAG.getConstant(0, dl, VT);
10540     }
10541 
10542     // Here we're passing the 2 arguments explicitly as 4 arguments that are
10543     // pre-lowered to the correct types. This all depends upon WideVT not
10544     // being a legal type for the architecture and thus has to be split to
10545     // two arguments.
10546     SDValue Ret;
10547     TargetLowering::MakeLibCallOptions CallOptions;
10548     CallOptions.setSExt(isSigned);
10549     CallOptions.setIsPostTypeLegalization(true);
10550     if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) {
10551       // Halves of WideVT are packed into registers in different order
10552       // depending on platform endianness. This is usually handled by
10553       // the C calling convention, but we can't defer to it in
10554       // the legalizer.
10555       SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
10556       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
10557     } else {
10558       SDValue Args[] = { HiLHS, LHS, HiRHS, RHS };
10559       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
10560     }
10561     assert(Ret.getOpcode() == ISD::MERGE_VALUES &&
10562            "Ret value is a collection of constituent nodes holding result.");
10563     if (DAG.getDataLayout().isLittleEndian()) {
10564       // Same as above.
10565       BottomHalf = Ret.getOperand(0);
10566       TopHalf = Ret.getOperand(1);
10567     } else {
10568       BottomHalf = Ret.getOperand(1);
10569       TopHalf = Ret.getOperand(0);
10570     }
10571   }
10572 
10573   Result = BottomHalf;
10574   if (isSigned) {
10575     SDValue ShiftAmt = DAG.getConstant(
10576         VT.getScalarSizeInBits() - 1, dl,
10577         getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout()));
10578     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
10579     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
10580   } else {
10581     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
10582                             DAG.getConstant(0, dl, VT), ISD::SETNE);
10583   }
10584 
10585   // Truncate the result if SetCC returns a larger type than needed.
10586   EVT RType = Node->getValueType(1);
10587   if (RType.bitsLT(Overflow.getValueType()))
10588     Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
10589 
10590   assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
10591          "Unexpected result type for S/UMULO legalization");
10592   return true;
10593 }
10594 
10595 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const {
10596   SDLoc dl(Node);
10597   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
10598   SDValue Op = Node->getOperand(0);
10599   EVT VT = Op.getValueType();
10600 
10601   if (VT.isScalableVector())
10602     report_fatal_error(
10603         "Expanding reductions for scalable vectors is undefined.");
10604 
10605   // Try to use a shuffle reduction for power of two vectors.
10606   if (VT.isPow2VectorType()) {
10607     while (VT.getVectorNumElements() > 1) {
10608       EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
10609       if (!isOperationLegalOrCustom(BaseOpcode, HalfVT))
10610         break;
10611 
10612       SDValue Lo, Hi;
10613       std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
10614       Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi);
10615       VT = HalfVT;
10616     }
10617   }
10618 
10619   EVT EltVT = VT.getVectorElementType();
10620   unsigned NumElts = VT.getVectorNumElements();
10621 
10622   SmallVector<SDValue, 8> Ops;
10623   DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
10624 
10625   SDValue Res = Ops[0];
10626   for (unsigned i = 1; i < NumElts; i++)
10627     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags());
10628 
10629   // Result type may be wider than element type.
10630   if (EltVT != Node->getValueType(0))
10631     Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
10632   return Res;
10633 }
10634 
10635 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const {
10636   SDLoc dl(Node);
10637   SDValue AccOp = Node->getOperand(0);
10638   SDValue VecOp = Node->getOperand(1);
10639   SDNodeFlags Flags = Node->getFlags();
10640 
10641   EVT VT = VecOp.getValueType();
10642   EVT EltVT = VT.getVectorElementType();
10643 
10644   if (VT.isScalableVector())
10645     report_fatal_error(
10646         "Expanding reductions for scalable vectors is undefined.");
10647 
10648   unsigned NumElts = VT.getVectorNumElements();
10649 
10650   SmallVector<SDValue, 8> Ops;
10651   DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
10652 
10653   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
10654 
10655   SDValue Res = AccOp;
10656   for (unsigned i = 0; i < NumElts; i++)
10657     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
10658 
10659   return Res;
10660 }
10661 
10662 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result,
10663                                SelectionDAG &DAG) const {
10664   EVT VT = Node->getValueType(0);
10665   SDLoc dl(Node);
10666   bool isSigned = Node->getOpcode() == ISD::SREM;
10667   unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
10668   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
10669   SDValue Dividend = Node->getOperand(0);
10670   SDValue Divisor = Node->getOperand(1);
10671   if (isOperationLegalOrCustom(DivRemOpc, VT)) {
10672     SDVTList VTs = DAG.getVTList(VT, VT);
10673     Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
10674     return true;
10675   }
10676   if (isOperationLegalOrCustom(DivOpc, VT)) {
10677     // X % Y -> X-X/Y*Y
10678     SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
10679     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
10680     Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
10681     return true;
10682   }
10683   return false;
10684 }
10685 
10686 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node,
10687                                             SelectionDAG &DAG) const {
10688   bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
10689   SDLoc dl(SDValue(Node, 0));
10690   SDValue Src = Node->getOperand(0);
10691 
10692   // DstVT is the result type, while SatVT is the size to which we saturate
10693   EVT SrcVT = Src.getValueType();
10694   EVT DstVT = Node->getValueType(0);
10695 
10696   EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10697   unsigned SatWidth = SatVT.getScalarSizeInBits();
10698   unsigned DstWidth = DstVT.getScalarSizeInBits();
10699   assert(SatWidth <= DstWidth &&
10700          "Expected saturation width smaller than result width");
10701 
10702   // Determine minimum and maximum integer values and their corresponding
10703   // floating-point values.
10704   APInt MinInt, MaxInt;
10705   if (IsSigned) {
10706     MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
10707     MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
10708   } else {
10709     MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
10710     MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
10711   }
10712 
10713   // We cannot risk emitting FP_TO_XINT nodes with a source VT of [b]f16, as
10714   // libcall emission cannot handle this. Large result types will fail.
10715   if (SrcVT == MVT::f16 || SrcVT == MVT::bf16) {
10716     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
10717     SrcVT = Src.getValueType();
10718   }
10719 
10720   APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT));
10721   APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT));
10722 
10723   APFloat::opStatus MinStatus =
10724       MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
10725   APFloat::opStatus MaxStatus =
10726       MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
10727   bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
10728                              !(MaxStatus & APFloat::opStatus::opInexact);
10729 
10730   SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
10731   SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
10732 
10733   // If the integer bounds are exactly representable as floats and min/max are
10734   // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
10735   // of comparisons and selects.
10736   bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) &&
10737                      isOperationLegal(ISD::FMAXNUM, SrcVT);
10738   if (AreExactFloatBounds && MinMaxLegal) {
10739     SDValue Clamped = Src;
10740 
10741     // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat.
10742     Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode);
10743     // Clamp by MaxFloat from above. NaN cannot occur.
10744     Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode);
10745     // Convert clamped value to integer.
10746     SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
10747                                   dl, DstVT, Clamped);
10748 
10749     // In the unsigned case we're done, because we mapped NaN to MinFloat,
10750     // which will cast to zero.
10751     if (!IsSigned)
10752       return FpToInt;
10753 
10754     // Otherwise, select 0 if Src is NaN.
10755     SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
10756     EVT SetCCVT =
10757         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
10758     SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
10759     return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, FpToInt);
10760   }
10761 
10762   SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
10763   SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
10764 
10765   // Result of direct conversion. The assumption here is that the operation is
10766   // non-trapping and it's fine to apply it to an out-of-range value if we
10767   // select it away later.
10768   SDValue FpToInt =
10769       DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
10770 
10771   SDValue Select = FpToInt;
10772 
10773   EVT SetCCVT =
10774       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
10775 
10776   // If Src ULT MinFloat, select MinInt. In particular, this also selects
10777   // MinInt if Src is NaN.
10778   SDValue ULT = DAG.getSetCC(dl, SetCCVT, Src, MinFloatNode, ISD::SETULT);
10779   Select = DAG.getSelect(dl, DstVT, ULT, MinIntNode, Select);
10780   // If Src OGT MaxFloat, select MaxInt.
10781   SDValue OGT = DAG.getSetCC(dl, SetCCVT, Src, MaxFloatNode, ISD::SETOGT);
10782   Select = DAG.getSelect(dl, DstVT, OGT, MaxIntNode, Select);
10783 
10784   // In the unsigned case we are done, because we mapped NaN to MinInt, which
10785   // is already zero.
10786   if (!IsSigned)
10787     return Select;
10788 
10789   // Otherwise, select 0 if Src is NaN.
10790   SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
10791   SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
10792   return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, Select);
10793 }
10794 
10795 SDValue TargetLowering::expandVectorSplice(SDNode *Node,
10796                                            SelectionDAG &DAG) const {
10797   assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!");
10798   assert(Node->getValueType(0).isScalableVector() &&
10799          "Fixed length vector types expected to use SHUFFLE_VECTOR!");
10800 
10801   EVT VT = Node->getValueType(0);
10802   SDValue V1 = Node->getOperand(0);
10803   SDValue V2 = Node->getOperand(1);
10804   int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue();
10805   SDLoc DL(Node);
10806 
10807   // Expand through memory thusly:
10808   //  Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
10809   //  Store V1, Ptr
10810   //  Store V2, Ptr + sizeof(V1)
10811   //  If (Imm < 0)
10812   //    TrailingElts = -Imm
10813   //    Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt))
10814   //  else
10815   //    Ptr = Ptr + (Imm * sizeof(VT.Elt))
10816   //  Res = Load Ptr
10817 
10818   Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
10819 
10820   EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
10821                                VT.getVectorElementCount() * 2);
10822   SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
10823   EVT PtrVT = StackPtr.getValueType();
10824   auto &MF = DAG.getMachineFunction();
10825   auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
10826   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
10827 
10828   // Store the lo part of CONCAT_VECTORS(V1, V2)
10829   SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo);
10830   // Store the hi part of CONCAT_VECTORS(V1, V2)
10831   SDValue OffsetToV2 = DAG.getVScale(
10832       DL, PtrVT,
10833       APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinValue()));
10834   SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2);
10835   SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo);
10836 
10837   if (Imm >= 0) {
10838     // Load back the required element. getVectorElementPointer takes care of
10839     // clamping the index if it's out-of-bounds.
10840     StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2));
10841     // Load the spliced result
10842     return DAG.getLoad(VT, DL, StoreV2, StackPtr,
10843                        MachinePointerInfo::getUnknownStack(MF));
10844   }
10845 
10846   uint64_t TrailingElts = -Imm;
10847 
10848   // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2.
10849   TypeSize EltByteSize = VT.getVectorElementType().getStoreSize();
10850   SDValue TrailingBytes =
10851       DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT);
10852 
10853   if (TrailingElts > VT.getVectorMinNumElements()) {
10854     SDValue VLBytes =
10855         DAG.getVScale(DL, PtrVT,
10856                       APInt(PtrVT.getFixedSizeInBits(),
10857                             VT.getStoreSize().getKnownMinValue()));
10858     TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes);
10859   }
10860 
10861   // Calculate the start address of the spliced result.
10862   StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
10863 
10864   // Load the spliced result
10865   return DAG.getLoad(VT, DL, StoreV2, StackPtr2,
10866                      MachinePointerInfo::getUnknownStack(MF));
10867 }
10868 
10869 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT,
10870                                            SDValue &LHS, SDValue &RHS,
10871                                            SDValue &CC, SDValue Mask,
10872                                            SDValue EVL, bool &NeedInvert,
10873                                            const SDLoc &dl, SDValue &Chain,
10874                                            bool IsSignaling) const {
10875   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10876   MVT OpVT = LHS.getSimpleValueType();
10877   ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
10878   NeedInvert = false;
10879   assert(!EVL == !Mask && "VP Mask and EVL must either both be set or unset");
10880   bool IsNonVP = !EVL;
10881   switch (TLI.getCondCodeAction(CCCode, OpVT)) {
10882   default:
10883     llvm_unreachable("Unknown condition code action!");
10884   case TargetLowering::Legal:
10885     // Nothing to do.
10886     break;
10887   case TargetLowering::Expand: {
10888     ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode);
10889     if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
10890       std::swap(LHS, RHS);
10891       CC = DAG.getCondCode(InvCC);
10892       return true;
10893     }
10894     // Swapping operands didn't work. Try inverting the condition.
10895     bool NeedSwap = false;
10896     InvCC = getSetCCInverse(CCCode, OpVT);
10897     if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
10898       // If inverting the condition is not enough, try swapping operands
10899       // on top of it.
10900       InvCC = ISD::getSetCCSwappedOperands(InvCC);
10901       NeedSwap = true;
10902     }
10903     if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
10904       CC = DAG.getCondCode(InvCC);
10905       NeedInvert = true;
10906       if (NeedSwap)
10907         std::swap(LHS, RHS);
10908       return true;
10909     }
10910 
10911     ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
10912     unsigned Opc = 0;
10913     switch (CCCode) {
10914     default:
10915       llvm_unreachable("Don't know how to expand this condition!");
10916     case ISD::SETUO:
10917       if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) {
10918         CC1 = ISD::SETUNE;
10919         CC2 = ISD::SETUNE;
10920         Opc = ISD::OR;
10921         break;
10922       }
10923       assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) &&
10924              "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
10925       NeedInvert = true;
10926       [[fallthrough]];
10927     case ISD::SETO:
10928       assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) &&
10929              "If SETO is expanded, SETOEQ must be legal!");
10930       CC1 = ISD::SETOEQ;
10931       CC2 = ISD::SETOEQ;
10932       Opc = ISD::AND;
10933       break;
10934     case ISD::SETONE:
10935     case ISD::SETUEQ:
10936       // If the SETUO or SETO CC isn't legal, we might be able to use
10937       // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
10938       // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
10939       // the operands.
10940       CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
10941       if (!TLI.isCondCodeLegal(CC2, OpVT) &&
10942           (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) ||
10943            TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) {
10944         CC1 = ISD::SETOGT;
10945         CC2 = ISD::SETOLT;
10946         Opc = ISD::OR;
10947         NeedInvert = ((unsigned)CCCode & 0x8U);
10948         break;
10949       }
10950       [[fallthrough]];
10951     case ISD::SETOEQ:
10952     case ISD::SETOGT:
10953     case ISD::SETOGE:
10954     case ISD::SETOLT:
10955     case ISD::SETOLE:
10956     case ISD::SETUNE:
10957     case ISD::SETUGT:
10958     case ISD::SETUGE:
10959     case ISD::SETULT:
10960     case ISD::SETULE:
10961       // If we are floating point, assign and break, otherwise fall through.
10962       if (!OpVT.isInteger()) {
10963         // We can use the 4th bit to tell if we are the unordered
10964         // or ordered version of the opcode.
10965         CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
10966         Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
10967         CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
10968         break;
10969       }
10970       // Fallthrough if we are unsigned integer.
10971       [[fallthrough]];
10972     case ISD::SETLE:
10973     case ISD::SETGT:
10974     case ISD::SETGE:
10975     case ISD::SETLT:
10976     case ISD::SETNE:
10977     case ISD::SETEQ:
10978       // If all combinations of inverting the condition and swapping operands
10979       // didn't work then we have no means to expand the condition.
10980       llvm_unreachable("Don't know how to expand this condition!");
10981     }
10982 
10983     SDValue SetCC1, SetCC2;
10984     if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
10985       // If we aren't the ordered or unorder operation,
10986       // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
10987       if (IsNonVP) {
10988         SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
10989         SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
10990       } else {
10991         SetCC1 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC1, Mask, EVL);
10992         SetCC2 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC2, Mask, EVL);
10993       }
10994     } else {
10995       // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
10996       if (IsNonVP) {
10997         SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
10998         SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
10999       } else {
11000         SetCC1 = DAG.getSetCCVP(dl, VT, LHS, LHS, CC1, Mask, EVL);
11001         SetCC2 = DAG.getSetCCVP(dl, VT, RHS, RHS, CC2, Mask, EVL);
11002       }
11003     }
11004     if (Chain)
11005       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
11006                           SetCC2.getValue(1));
11007     if (IsNonVP)
11008       LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
11009     else {
11010       // Transform the binary opcode to the VP equivalent.
11011       assert((Opc == ISD::OR || Opc == ISD::AND) && "Unexpected opcode");
11012       Opc = Opc == ISD::OR ? ISD::VP_OR : ISD::VP_AND;
11013       LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2, Mask, EVL);
11014     }
11015     RHS = SDValue();
11016     CC = SDValue();
11017     return true;
11018   }
11019   }
11020   return false;
11021 }
11022