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.getExtOrTrunc(IsSigned, ExtOpA, DL, NVT),
1068                   DAG.getExtOrTrunc(IsSigned, ExtOpB, DL, NVT));
1069   return DAG.getExtOrTrunc(IsSigned, ResultAVG, DL, VT);
1070 }
1071 
1072 /// Look at Op. At this point, we know that only the OriginalDemandedBits of the
1073 /// result of Op are ever used downstream. If we can use this information to
1074 /// simplify Op, create a new simplified DAG node and return true, returning the
1075 /// original and new nodes in Old and New. Otherwise, analyze the expression and
1076 /// return a mask of Known bits for the expression (used to simplify the
1077 /// caller).  The Known bits may only be accurate for those bits in the
1078 /// OriginalDemandedBits and OriginalDemandedElts.
1079 bool TargetLowering::SimplifyDemandedBits(
1080     SDValue Op, const APInt &OriginalDemandedBits,
1081     const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
1082     unsigned Depth, bool AssumeSingleUse) const {
1083   unsigned BitWidth = OriginalDemandedBits.getBitWidth();
1084   assert(Op.getScalarValueSizeInBits() == BitWidth &&
1085          "Mask size mismatches value type size!");
1086 
1087   // Don't know anything.
1088   Known = KnownBits(BitWidth);
1089 
1090   EVT VT = Op.getValueType();
1091   bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
1092   unsigned NumElts = OriginalDemandedElts.getBitWidth();
1093   assert((!VT.isFixedLengthVector() || NumElts == VT.getVectorNumElements()) &&
1094          "Unexpected vector size");
1095 
1096   APInt DemandedBits = OriginalDemandedBits;
1097   APInt DemandedElts = OriginalDemandedElts;
1098   SDLoc dl(Op);
1099   auto &DL = TLO.DAG.getDataLayout();
1100 
1101   // Undef operand.
1102   if (Op.isUndef())
1103     return false;
1104 
1105   // We can't simplify target constants.
1106   if (Op.getOpcode() == ISD::TargetConstant)
1107     return false;
1108 
1109   if (Op.getOpcode() == ISD::Constant) {
1110     // We know all of the bits for a constant!
1111     Known = KnownBits::makeConstant(Op->getAsAPIntVal());
1112     return false;
1113   }
1114 
1115   if (Op.getOpcode() == ISD::ConstantFP) {
1116     // We know all of the bits for a floating point constant!
1117     Known = KnownBits::makeConstant(
1118         cast<ConstantFPSDNode>(Op)->getValueAPF().bitcastToAPInt());
1119     return false;
1120   }
1121 
1122   // Other users may use these bits.
1123   bool HasMultiUse = false;
1124   if (!AssumeSingleUse && !Op.getNode()->hasOneUse()) {
1125     if (Depth >= SelectionDAG::MaxRecursionDepth) {
1126       // Limit search depth.
1127       return false;
1128     }
1129     // Allow multiple uses, just set the DemandedBits/Elts to all bits.
1130     DemandedBits = APInt::getAllOnes(BitWidth);
1131     DemandedElts = APInt::getAllOnes(NumElts);
1132     HasMultiUse = true;
1133   } else if (OriginalDemandedBits == 0 || OriginalDemandedElts == 0) {
1134     // Not demanding any bits/elts from Op.
1135     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1136   } else if (Depth >= SelectionDAG::MaxRecursionDepth) {
1137     // Limit search depth.
1138     return false;
1139   }
1140 
1141   KnownBits Known2;
1142   switch (Op.getOpcode()) {
1143   case ISD::SCALAR_TO_VECTOR: {
1144     if (VT.isScalableVector())
1145       return false;
1146     if (!DemandedElts[0])
1147       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
1148 
1149     KnownBits SrcKnown;
1150     SDValue Src = Op.getOperand(0);
1151     unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
1152     APInt SrcDemandedBits = DemandedBits.zext(SrcBitWidth);
1153     if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcKnown, TLO, Depth + 1))
1154       return true;
1155 
1156     // Upper elements are undef, so only get the knownbits if we just demand
1157     // the bottom element.
1158     if (DemandedElts == 1)
1159       Known = SrcKnown.anyextOrTrunc(BitWidth);
1160     break;
1161   }
1162   case ISD::BUILD_VECTOR:
1163     // Collect the known bits that are shared by every demanded element.
1164     // TODO: Call SimplifyDemandedBits for non-constant demanded elements.
1165     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1166     return false; // Don't fall through, will infinitely loop.
1167   case ISD::SPLAT_VECTOR: {
1168     SDValue Scl = Op.getOperand(0);
1169     APInt DemandedSclBits = DemandedBits.zextOrTrunc(Scl.getValueSizeInBits());
1170     KnownBits KnownScl;
1171     if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1172       return true;
1173 
1174     // Implicitly truncate the bits to match the official semantics of
1175     // SPLAT_VECTOR.
1176     Known = KnownScl.trunc(BitWidth);
1177     break;
1178   }
1179   case ISD::LOAD: {
1180     auto *LD = cast<LoadSDNode>(Op);
1181     if (getTargetConstantFromLoad(LD)) {
1182       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1183       return false; // Don't fall through, will infinitely loop.
1184     }
1185     if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
1186       // If this is a ZEXTLoad and we are looking at the loaded value.
1187       EVT MemVT = LD->getMemoryVT();
1188       unsigned MemBits = MemVT.getScalarSizeInBits();
1189       Known.Zero.setBitsFrom(MemBits);
1190       return false; // Don't fall through, will infinitely loop.
1191     }
1192     break;
1193   }
1194   case ISD::INSERT_VECTOR_ELT: {
1195     if (VT.isScalableVector())
1196       return false;
1197     SDValue Vec = Op.getOperand(0);
1198     SDValue Scl = Op.getOperand(1);
1199     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
1200     EVT VecVT = Vec.getValueType();
1201 
1202     // If index isn't constant, assume we need all vector elements AND the
1203     // inserted element.
1204     APInt DemandedVecElts(DemandedElts);
1205     if (CIdx && CIdx->getAPIntValue().ult(VecVT.getVectorNumElements())) {
1206       unsigned Idx = CIdx->getZExtValue();
1207       DemandedVecElts.clearBit(Idx);
1208 
1209       // Inserted element is not required.
1210       if (!DemandedElts[Idx])
1211         return TLO.CombineTo(Op, Vec);
1212     }
1213 
1214     KnownBits KnownScl;
1215     unsigned NumSclBits = Scl.getScalarValueSizeInBits();
1216     APInt DemandedSclBits = DemandedBits.zextOrTrunc(NumSclBits);
1217     if (SimplifyDemandedBits(Scl, DemandedSclBits, KnownScl, TLO, Depth + 1))
1218       return true;
1219 
1220     Known = KnownScl.anyextOrTrunc(BitWidth);
1221 
1222     KnownBits KnownVec;
1223     if (SimplifyDemandedBits(Vec, DemandedBits, DemandedVecElts, KnownVec, TLO,
1224                              Depth + 1))
1225       return true;
1226 
1227     if (!!DemandedVecElts)
1228       Known = Known.intersectWith(KnownVec);
1229 
1230     return false;
1231   }
1232   case ISD::INSERT_SUBVECTOR: {
1233     if (VT.isScalableVector())
1234       return false;
1235     // Demand any elements from the subvector and the remainder from the src its
1236     // inserted into.
1237     SDValue Src = Op.getOperand(0);
1238     SDValue Sub = Op.getOperand(1);
1239     uint64_t Idx = Op.getConstantOperandVal(2);
1240     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
1241     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
1242     APInt DemandedSrcElts = DemandedElts;
1243     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
1244 
1245     KnownBits KnownSub, KnownSrc;
1246     if (SimplifyDemandedBits(Sub, DemandedBits, DemandedSubElts, KnownSub, TLO,
1247                              Depth + 1))
1248       return true;
1249     if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, KnownSrc, TLO,
1250                              Depth + 1))
1251       return true;
1252 
1253     Known.Zero.setAllBits();
1254     Known.One.setAllBits();
1255     if (!!DemandedSubElts)
1256       Known = Known.intersectWith(KnownSub);
1257     if (!!DemandedSrcElts)
1258       Known = Known.intersectWith(KnownSrc);
1259 
1260     // Attempt to avoid multi-use src if we don't need anything from it.
1261     if (!DemandedBits.isAllOnes() || !DemandedSubElts.isAllOnes() ||
1262         !DemandedSrcElts.isAllOnes()) {
1263       SDValue NewSub = SimplifyMultipleUseDemandedBits(
1264           Sub, DemandedBits, DemandedSubElts, TLO.DAG, Depth + 1);
1265       SDValue NewSrc = SimplifyMultipleUseDemandedBits(
1266           Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1267       if (NewSub || NewSrc) {
1268         NewSub = NewSub ? NewSub : Sub;
1269         NewSrc = NewSrc ? NewSrc : Src;
1270         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc, NewSub,
1271                                         Op.getOperand(2));
1272         return TLO.CombineTo(Op, NewOp);
1273       }
1274     }
1275     break;
1276   }
1277   case ISD::EXTRACT_SUBVECTOR: {
1278     if (VT.isScalableVector())
1279       return false;
1280     // Offset the demanded elts by the subvector index.
1281     SDValue Src = Op.getOperand(0);
1282     if (Src.getValueType().isScalableVector())
1283       break;
1284     uint64_t Idx = Op.getConstantOperandVal(1);
1285     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
1286     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
1287 
1288     if (SimplifyDemandedBits(Src, DemandedBits, DemandedSrcElts, Known, TLO,
1289                              Depth + 1))
1290       return true;
1291 
1292     // Attempt to avoid multi-use src if we don't need anything from it.
1293     if (!DemandedBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
1294       SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
1295           Src, DemandedBits, DemandedSrcElts, TLO.DAG, Depth + 1);
1296       if (DemandedSrc) {
1297         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc,
1298                                         Op.getOperand(1));
1299         return TLO.CombineTo(Op, NewOp);
1300       }
1301     }
1302     break;
1303   }
1304   case ISD::CONCAT_VECTORS: {
1305     if (VT.isScalableVector())
1306       return false;
1307     Known.Zero.setAllBits();
1308     Known.One.setAllBits();
1309     EVT SubVT = Op.getOperand(0).getValueType();
1310     unsigned NumSubVecs = Op.getNumOperands();
1311     unsigned NumSubElts = SubVT.getVectorNumElements();
1312     for (unsigned i = 0; i != NumSubVecs; ++i) {
1313       APInt DemandedSubElts =
1314           DemandedElts.extractBits(NumSubElts, i * NumSubElts);
1315       if (SimplifyDemandedBits(Op.getOperand(i), DemandedBits, DemandedSubElts,
1316                                Known2, TLO, Depth + 1))
1317         return true;
1318       // Known bits are shared by every demanded subvector element.
1319       if (!!DemandedSubElts)
1320         Known = Known.intersectWith(Known2);
1321     }
1322     break;
1323   }
1324   case ISD::VECTOR_SHUFFLE: {
1325     assert(!VT.isScalableVector());
1326     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
1327 
1328     // Collect demanded elements from shuffle operands..
1329     APInt DemandedLHS, DemandedRHS;
1330     if (!getShuffleDemandedElts(NumElts, ShuffleMask, DemandedElts, DemandedLHS,
1331                                 DemandedRHS))
1332       break;
1333 
1334     if (!!DemandedLHS || !!DemandedRHS) {
1335       SDValue Op0 = Op.getOperand(0);
1336       SDValue Op1 = Op.getOperand(1);
1337 
1338       Known.Zero.setAllBits();
1339       Known.One.setAllBits();
1340       if (!!DemandedLHS) {
1341         if (SimplifyDemandedBits(Op0, DemandedBits, DemandedLHS, Known2, TLO,
1342                                  Depth + 1))
1343           return true;
1344         Known = Known.intersectWith(Known2);
1345       }
1346       if (!!DemandedRHS) {
1347         if (SimplifyDemandedBits(Op1, DemandedBits, DemandedRHS, Known2, TLO,
1348                                  Depth + 1))
1349           return true;
1350         Known = Known.intersectWith(Known2);
1351       }
1352 
1353       // Attempt to avoid multi-use ops if we don't need anything from them.
1354       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1355           Op0, DemandedBits, DemandedLHS, TLO.DAG, Depth + 1);
1356       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1357           Op1, DemandedBits, DemandedRHS, TLO.DAG, Depth + 1);
1358       if (DemandedOp0 || DemandedOp1) {
1359         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1360         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1361         SDValue NewOp = TLO.DAG.getVectorShuffle(VT, dl, Op0, Op1, ShuffleMask);
1362         return TLO.CombineTo(Op, NewOp);
1363       }
1364     }
1365     break;
1366   }
1367   case ISD::AND: {
1368     SDValue Op0 = Op.getOperand(0);
1369     SDValue Op1 = Op.getOperand(1);
1370 
1371     // If the RHS is a constant, check to see if the LHS would be zero without
1372     // using the bits from the RHS.  Below, we use knowledge about the RHS to
1373     // simplify the LHS, here we're using information from the LHS to simplify
1374     // the RHS.
1375     if (ConstantSDNode *RHSC = isConstOrConstSplat(Op1)) {
1376       // Do not increment Depth here; that can cause an infinite loop.
1377       KnownBits LHSKnown = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth);
1378       // If the LHS already has zeros where RHSC does, this 'and' is dead.
1379       if ((LHSKnown.Zero & DemandedBits) ==
1380           (~RHSC->getAPIntValue() & DemandedBits))
1381         return TLO.CombineTo(Op, Op0);
1382 
1383       // If any of the set bits in the RHS are known zero on the LHS, shrink
1384       // the constant.
1385       if (ShrinkDemandedConstant(Op, ~LHSKnown.Zero & DemandedBits,
1386                                  DemandedElts, TLO))
1387         return true;
1388 
1389       // Bitwise-not (xor X, -1) is a special case: we don't usually shrink its
1390       // constant, but if this 'and' is only clearing bits that were just set by
1391       // the xor, then this 'and' can be eliminated by shrinking the mask of
1392       // the xor. For example, for a 32-bit X:
1393       // and (xor (srl X, 31), -1), 1 --> xor (srl X, 31), 1
1394       if (isBitwiseNot(Op0) && Op0.hasOneUse() &&
1395           LHSKnown.One == ~RHSC->getAPIntValue()) {
1396         SDValue Xor = TLO.DAG.getNode(ISD::XOR, dl, VT, Op0.getOperand(0), Op1);
1397         return TLO.CombineTo(Op, Xor);
1398       }
1399     }
1400 
1401     // AND(INSERT_SUBVECTOR(C,X,I),M) -> INSERT_SUBVECTOR(AND(C,M),X,I)
1402     // iff 'C' is Undef/Constant and AND(X,M) == X (for DemandedBits).
1403     if (Op0.getOpcode() == ISD::INSERT_SUBVECTOR && !VT.isScalableVector() &&
1404         (Op0.getOperand(0).isUndef() ||
1405          ISD::isBuildVectorOfConstantSDNodes(Op0.getOperand(0).getNode())) &&
1406         Op0->hasOneUse()) {
1407       unsigned NumSubElts =
1408           Op0.getOperand(1).getValueType().getVectorNumElements();
1409       unsigned SubIdx = Op0.getConstantOperandVal(2);
1410       APInt DemandedSub =
1411           APInt::getBitsSet(NumElts, SubIdx, SubIdx + NumSubElts);
1412       KnownBits KnownSubMask =
1413           TLO.DAG.computeKnownBits(Op1, DemandedSub & DemandedElts, Depth + 1);
1414       if (DemandedBits.isSubsetOf(KnownSubMask.One)) {
1415         SDValue NewAnd =
1416             TLO.DAG.getNode(ISD::AND, dl, VT, Op0.getOperand(0), Op1);
1417         SDValue NewInsert =
1418             TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, dl, VT, NewAnd,
1419                             Op0.getOperand(1), Op0.getOperand(2));
1420         return TLO.CombineTo(Op, NewInsert);
1421       }
1422     }
1423 
1424     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1425                              Depth + 1))
1426       return true;
1427     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1428     if (SimplifyDemandedBits(Op0, ~Known.Zero & DemandedBits, DemandedElts,
1429                              Known2, TLO, Depth + 1))
1430       return true;
1431     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1432 
1433     // If all of the demanded bits are known one on one side, return the other.
1434     // These bits cannot contribute to the result of the 'and'.
1435     if (DemandedBits.isSubsetOf(Known2.Zero | Known.One))
1436       return TLO.CombineTo(Op, Op0);
1437     if (DemandedBits.isSubsetOf(Known.Zero | Known2.One))
1438       return TLO.CombineTo(Op, Op1);
1439     // If all of the demanded bits in the inputs are known zeros, return zero.
1440     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1441       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, dl, VT));
1442     // If the RHS is a constant, see if we can simplify it.
1443     if (ShrinkDemandedConstant(Op, ~Known2.Zero & DemandedBits, DemandedElts,
1444                                TLO))
1445       return true;
1446     // If the operation can be done in a smaller type, do so.
1447     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1448       return true;
1449 
1450     // Attempt to avoid multi-use ops if we don't need anything from them.
1451     if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1452       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1453           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1454       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1455           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1456       if (DemandedOp0 || DemandedOp1) {
1457         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1458         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1459         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1460         return TLO.CombineTo(Op, NewOp);
1461       }
1462     }
1463 
1464     Known &= Known2;
1465     break;
1466   }
1467   case ISD::OR: {
1468     SDValue Op0 = Op.getOperand(0);
1469     SDValue Op1 = Op.getOperand(1);
1470     SDNodeFlags Flags = Op.getNode()->getFlags();
1471     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1472                              Depth + 1)) {
1473       if (Flags.hasDisjoint()) {
1474         Flags.setDisjoint(false);
1475         Op->setFlags(Flags);
1476       }
1477       return true;
1478     }
1479     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1480     if (SimplifyDemandedBits(Op0, ~Known.One & DemandedBits, DemandedElts,
1481                              Known2, TLO, Depth + 1)) {
1482       if (Flags.hasDisjoint()) {
1483         Flags.setDisjoint(false);
1484         Op->setFlags(Flags);
1485       }
1486       return true;
1487     }
1488     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1489 
1490     // If all of the demanded bits are known zero on one side, return the other.
1491     // These bits cannot contribute to the result of the 'or'.
1492     if (DemandedBits.isSubsetOf(Known2.One | Known.Zero))
1493       return TLO.CombineTo(Op, Op0);
1494     if (DemandedBits.isSubsetOf(Known.One | Known2.Zero))
1495       return TLO.CombineTo(Op, Op1);
1496     // If the RHS is a constant, see if we can simplify it.
1497     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1498       return true;
1499     // If the operation can be done in a smaller type, do so.
1500     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1501       return true;
1502 
1503     // Attempt to avoid multi-use ops if we don't need anything from them.
1504     if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1505       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1506           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1507       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1508           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1509       if (DemandedOp0 || DemandedOp1) {
1510         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1511         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1512         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1513         return TLO.CombineTo(Op, NewOp);
1514       }
1515     }
1516 
1517     // (or (and X, C1), (and (or X, Y), C2)) -> (or (and X, C1|C2), (and Y, C2))
1518     // TODO: Use SimplifyMultipleUseDemandedBits to peek through masks.
1519     if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::AND &&
1520         Op0->hasOneUse() && Op1->hasOneUse()) {
1521       // Attempt to match all commutations - m_c_Or would've been useful!
1522       for (int I = 0; I != 2; ++I) {
1523         SDValue X = Op.getOperand(I).getOperand(0);
1524         SDValue C1 = Op.getOperand(I).getOperand(1);
1525         SDValue Alt = Op.getOperand(1 - I).getOperand(0);
1526         SDValue C2 = Op.getOperand(1 - I).getOperand(1);
1527         if (Alt.getOpcode() == ISD::OR) {
1528           for (int J = 0; J != 2; ++J) {
1529             if (X == Alt.getOperand(J)) {
1530               SDValue Y = Alt.getOperand(1 - J);
1531               if (SDValue C12 = TLO.DAG.FoldConstantArithmetic(ISD::OR, dl, VT,
1532                                                                {C1, C2})) {
1533                 SDValue MaskX = TLO.DAG.getNode(ISD::AND, dl, VT, X, C12);
1534                 SDValue MaskY = TLO.DAG.getNode(ISD::AND, dl, VT, Y, C2);
1535                 return TLO.CombineTo(
1536                     Op, TLO.DAG.getNode(ISD::OR, dl, VT, MaskX, MaskY));
1537               }
1538             }
1539           }
1540         }
1541       }
1542     }
1543 
1544     Known |= Known2;
1545     break;
1546   }
1547   case ISD::XOR: {
1548     SDValue Op0 = Op.getOperand(0);
1549     SDValue Op1 = Op.getOperand(1);
1550 
1551     if (SimplifyDemandedBits(Op1, DemandedBits, DemandedElts, Known, TLO,
1552                              Depth + 1))
1553       return true;
1554     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1555     if (SimplifyDemandedBits(Op0, DemandedBits, DemandedElts, Known2, TLO,
1556                              Depth + 1))
1557       return true;
1558     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1559 
1560     // If all of the demanded bits are known zero on one side, return the other.
1561     // These bits cannot contribute to the result of the 'xor'.
1562     if (DemandedBits.isSubsetOf(Known.Zero))
1563       return TLO.CombineTo(Op, Op0);
1564     if (DemandedBits.isSubsetOf(Known2.Zero))
1565       return TLO.CombineTo(Op, Op1);
1566     // If the operation can be done in a smaller type, do so.
1567     if (ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1568       return true;
1569 
1570     // If all of the unknown bits are known to be zero on one side or the other
1571     // turn this into an *inclusive* or.
1572     //    e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1573     if (DemandedBits.isSubsetOf(Known.Zero | Known2.Zero))
1574       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::OR, dl, VT, Op0, Op1));
1575 
1576     ConstantSDNode *C = isConstOrConstSplat(Op1, DemandedElts);
1577     if (C) {
1578       // If one side is a constant, and all of the set bits in the constant are
1579       // also known set on the other side, turn this into an AND, as we know
1580       // the bits will be cleared.
1581       //    e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1582       // NB: it is okay if more bits are known than are requested
1583       if (C->getAPIntValue() == Known2.One) {
1584         SDValue ANDC =
1585             TLO.DAG.getConstant(~C->getAPIntValue() & DemandedBits, dl, VT);
1586         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::AND, dl, VT, Op0, ANDC));
1587       }
1588 
1589       // If the RHS is a constant, see if we can change it. Don't alter a -1
1590       // constant because that's a 'not' op, and that is better for combining
1591       // and codegen.
1592       if (!C->isAllOnes() && DemandedBits.isSubsetOf(C->getAPIntValue())) {
1593         // We're flipping all demanded bits. Flip the undemanded bits too.
1594         SDValue New = TLO.DAG.getNOT(dl, Op0, VT);
1595         return TLO.CombineTo(Op, New);
1596       }
1597 
1598       unsigned Op0Opcode = Op0.getOpcode();
1599       if ((Op0Opcode == ISD::SRL || Op0Opcode == ISD::SHL) && Op0.hasOneUse()) {
1600         if (ConstantSDNode *ShiftC =
1601                 isConstOrConstSplat(Op0.getOperand(1), DemandedElts)) {
1602           // Don't crash on an oversized shift. We can not guarantee that a
1603           // bogus shift has been simplified to undef.
1604           if (ShiftC->getAPIntValue().ult(BitWidth)) {
1605             uint64_t ShiftAmt = ShiftC->getZExtValue();
1606             APInt Ones = APInt::getAllOnes(BitWidth);
1607             Ones = Op0Opcode == ISD::SHL ? Ones.shl(ShiftAmt)
1608                                          : Ones.lshr(ShiftAmt);
1609             const TargetLowering &TLI = TLO.DAG.getTargetLoweringInfo();
1610             if ((DemandedBits & C->getAPIntValue()) == (DemandedBits & Ones) &&
1611                 TLI.isDesirableToCommuteXorWithShift(Op.getNode())) {
1612               // If the xor constant is a demanded mask, do a 'not' before the
1613               // shift:
1614               // xor (X << ShiftC), XorC --> (not X) << ShiftC
1615               // xor (X >> ShiftC), XorC --> (not X) >> ShiftC
1616               SDValue Not = TLO.DAG.getNOT(dl, Op0.getOperand(0), VT);
1617               return TLO.CombineTo(Op, TLO.DAG.getNode(Op0Opcode, dl, VT, Not,
1618                                                        Op0.getOperand(1)));
1619             }
1620           }
1621         }
1622       }
1623     }
1624 
1625     // If we can't turn this into a 'not', try to shrink the constant.
1626     if (!C || !C->isAllOnes())
1627       if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1628         return true;
1629 
1630     // Attempt to avoid multi-use ops if we don't need anything from them.
1631     if (!DemandedBits.isAllOnes() || !DemandedElts.isAllOnes()) {
1632       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1633           Op0, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1634       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
1635           Op1, DemandedBits, DemandedElts, TLO.DAG, Depth + 1);
1636       if (DemandedOp0 || DemandedOp1) {
1637         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
1638         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
1639         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1);
1640         return TLO.CombineTo(Op, NewOp);
1641       }
1642     }
1643 
1644     Known ^= Known2;
1645     break;
1646   }
1647   case ISD::SELECT:
1648     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1649                              Known, TLO, Depth + 1))
1650       return true;
1651     if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
1652                              Known2, TLO, Depth + 1))
1653       return true;
1654     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1655     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1656 
1657     // If the operands are constants, see if we can simplify them.
1658     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1659       return true;
1660 
1661     // Only known if known in both the LHS and RHS.
1662     Known = Known.intersectWith(Known2);
1663     break;
1664   case ISD::VSELECT:
1665     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1666                              Known, TLO, Depth + 1))
1667       return true;
1668     if (SimplifyDemandedBits(Op.getOperand(1), DemandedBits, DemandedElts,
1669                              Known2, TLO, Depth + 1))
1670       return true;
1671     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1672     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1673 
1674     // Only known if known in both the LHS and RHS.
1675     Known = Known.intersectWith(Known2);
1676     break;
1677   case ISD::SELECT_CC:
1678     if (SimplifyDemandedBits(Op.getOperand(3), DemandedBits, DemandedElts,
1679                              Known, TLO, Depth + 1))
1680       return true;
1681     if (SimplifyDemandedBits(Op.getOperand(2), DemandedBits, DemandedElts,
1682                              Known2, TLO, Depth + 1))
1683       return true;
1684     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1685     assert(!Known2.hasConflict() && "Bits known to be one AND zero?");
1686 
1687     // If the operands are constants, see if we can simplify them.
1688     if (ShrinkDemandedConstant(Op, DemandedBits, DemandedElts, TLO))
1689       return true;
1690 
1691     // Only known if known in both the LHS and RHS.
1692     Known = Known.intersectWith(Known2);
1693     break;
1694   case ISD::SETCC: {
1695     SDValue Op0 = Op.getOperand(0);
1696     SDValue Op1 = Op.getOperand(1);
1697     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
1698     // If (1) we only need the sign-bit, (2) the setcc operands are the same
1699     // width as the setcc result, and (3) the result of a setcc conforms to 0 or
1700     // -1, we may be able to bypass the setcc.
1701     if (DemandedBits.isSignMask() &&
1702         Op0.getScalarValueSizeInBits() == BitWidth &&
1703         getBooleanContents(Op0.getValueType()) ==
1704             BooleanContent::ZeroOrNegativeOneBooleanContent) {
1705       // If we're testing X < 0, then this compare isn't needed - just use X!
1706       // FIXME: We're limiting to integer types here, but this should also work
1707       // if we don't care about FP signed-zero. The use of SETLT with FP means
1708       // that we don't care about NaNs.
1709       if (CC == ISD::SETLT && Op1.getValueType().isInteger() &&
1710           (isNullConstant(Op1) || ISD::isBuildVectorAllZeros(Op1.getNode())))
1711         return TLO.CombineTo(Op, Op0);
1712 
1713       // TODO: Should we check for other forms of sign-bit comparisons?
1714       // Examples: X <= -1, X >= 0
1715     }
1716     if (getBooleanContents(Op0.getValueType()) ==
1717             TargetLowering::ZeroOrOneBooleanContent &&
1718         BitWidth > 1)
1719       Known.Zero.setBitsFrom(1);
1720     break;
1721   }
1722   case ISD::SHL: {
1723     SDValue Op0 = Op.getOperand(0);
1724     SDValue Op1 = Op.getOperand(1);
1725     EVT ShiftVT = Op1.getValueType();
1726 
1727     if (const APInt *SA =
1728             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1729       unsigned ShAmt = SA->getZExtValue();
1730       if (ShAmt == 0)
1731         return TLO.CombineTo(Op, Op0);
1732 
1733       // If this is ((X >>u C1) << ShAmt), see if we can simplify this into a
1734       // single shift.  We can do this if the bottom bits (which are shifted
1735       // out) are never demanded.
1736       // TODO - support non-uniform vector amounts.
1737       if (Op0.getOpcode() == ISD::SRL) {
1738         if (!DemandedBits.intersects(APInt::getLowBitsSet(BitWidth, ShAmt))) {
1739           if (const APInt *SA2 =
1740                   TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) {
1741             unsigned C1 = SA2->getZExtValue();
1742             unsigned Opc = ISD::SHL;
1743             int Diff = ShAmt - C1;
1744             if (Diff < 0) {
1745               Diff = -Diff;
1746               Opc = ISD::SRL;
1747             }
1748             SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1749             return TLO.CombineTo(
1750                 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1751           }
1752         }
1753       }
1754 
1755       // Convert (shl (anyext x, c)) to (anyext (shl x, c)) if the high bits
1756       // are not demanded. This will likely allow the anyext to be folded away.
1757       // TODO - support non-uniform vector amounts.
1758       if (Op0.getOpcode() == ISD::ANY_EXTEND) {
1759         SDValue InnerOp = Op0.getOperand(0);
1760         EVT InnerVT = InnerOp.getValueType();
1761         unsigned InnerBits = InnerVT.getScalarSizeInBits();
1762         if (ShAmt < InnerBits && DemandedBits.getActiveBits() <= InnerBits &&
1763             isTypeDesirableForOp(ISD::SHL, InnerVT)) {
1764           SDValue NarrowShl = TLO.DAG.getNode(
1765               ISD::SHL, dl, InnerVT, InnerOp,
1766               TLO.DAG.getShiftAmountConstant(ShAmt, InnerVT, dl));
1767           return TLO.CombineTo(
1768               Op, TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT, NarrowShl));
1769         }
1770 
1771         // Repeat the SHL optimization above in cases where an extension
1772         // intervenes: (shl (anyext (shr x, c1)), c2) to
1773         // (shl (anyext x), c2-c1).  This requires that the bottom c1 bits
1774         // aren't demanded (as above) and that the shifted upper c1 bits of
1775         // x aren't demanded.
1776         // TODO - support non-uniform vector amounts.
1777         if (InnerOp.getOpcode() == ISD::SRL && Op0.hasOneUse() &&
1778             InnerOp.hasOneUse()) {
1779           if (const APInt *SA2 =
1780                   TLO.DAG.getValidShiftAmountConstant(InnerOp, DemandedElts)) {
1781             unsigned InnerShAmt = SA2->getZExtValue();
1782             if (InnerShAmt < ShAmt && InnerShAmt < InnerBits &&
1783                 DemandedBits.getActiveBits() <=
1784                     (InnerBits - InnerShAmt + ShAmt) &&
1785                 DemandedBits.countr_zero() >= ShAmt) {
1786               SDValue NewSA =
1787                   TLO.DAG.getConstant(ShAmt - InnerShAmt, dl, ShiftVT);
1788               SDValue NewExt = TLO.DAG.getNode(ISD::ANY_EXTEND, dl, VT,
1789                                                InnerOp.getOperand(0));
1790               return TLO.CombineTo(
1791                   Op, TLO.DAG.getNode(ISD::SHL, dl, VT, NewExt, NewSA));
1792             }
1793           }
1794         }
1795       }
1796 
1797       APInt InDemandedMask = DemandedBits.lshr(ShAmt);
1798       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1799                                Depth + 1)) {
1800         SDNodeFlags Flags = Op.getNode()->getFlags();
1801         if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
1802           // Disable the nsw and nuw flags. We can no longer guarantee that we
1803           // won't wrap after simplification.
1804           Flags.setNoSignedWrap(false);
1805           Flags.setNoUnsignedWrap(false);
1806           Op->setFlags(Flags);
1807         }
1808         return true;
1809       }
1810       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1811       Known.Zero <<= ShAmt;
1812       Known.One <<= ShAmt;
1813       // low bits known zero.
1814       Known.Zero.setLowBits(ShAmt);
1815 
1816       // Attempt to avoid multi-use ops if we don't need anything from them.
1817       if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
1818         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1819             Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
1820         if (DemandedOp0) {
1821           SDValue NewOp = TLO.DAG.getNode(ISD::SHL, dl, VT, DemandedOp0, Op1);
1822           return TLO.CombineTo(Op, NewOp);
1823         }
1824       }
1825 
1826       // Try shrinking the operation as long as the shift amount will still be
1827       // in range.
1828       if ((ShAmt < DemandedBits.getActiveBits()) &&
1829           ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO))
1830         return true;
1831 
1832       // Narrow shift to lower half - similar to ShrinkDemandedOp.
1833       // (shl i64:x, K) -> (i64 zero_extend (shl (i32 (trunc i64:x)), K))
1834       // Only do this if we demand the upper half so the knownbits are correct.
1835       unsigned HalfWidth = BitWidth / 2;
1836       if ((BitWidth % 2) == 0 && !VT.isVector() && ShAmt < HalfWidth &&
1837           DemandedBits.countLeadingOnes() >= HalfWidth) {
1838         EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), HalfWidth);
1839         if (isNarrowingProfitable(VT, HalfVT) &&
1840             isTypeDesirableForOp(ISD::SHL, HalfVT) &&
1841             isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
1842             (!TLO.LegalOperations() || isOperationLegal(ISD::SHL, HalfVT))) {
1843           // If we're demanding the upper bits at all, we must ensure
1844           // that the upper bits of the shift result are known to be zero,
1845           // which is equivalent to the narrow shift being NUW.
1846           if (bool IsNUW = (Known.countMinLeadingZeros() >= HalfWidth)) {
1847             bool IsNSW = Known.countMinSignBits() > HalfWidth;
1848             SDNodeFlags Flags;
1849             Flags.setNoSignedWrap(IsNSW);
1850             Flags.setNoUnsignedWrap(IsNUW);
1851             SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
1852             SDValue NewShiftAmt = TLO.DAG.getShiftAmountConstant(
1853                 ShAmt, HalfVT, dl, TLO.LegalTypes());
1854             SDValue NewShift = TLO.DAG.getNode(ISD::SHL, dl, HalfVT, NewOp,
1855                                                NewShiftAmt, Flags);
1856             SDValue NewExt =
1857                 TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift);
1858             return TLO.CombineTo(Op, NewExt);
1859           }
1860         }
1861       }
1862     } else {
1863       // This is a variable shift, so we can't shift the demand mask by a known
1864       // amount. But if we are not demanding high bits, then we are not
1865       // demanding those bits from the pre-shifted operand either.
1866       if (unsigned CTLZ = DemandedBits.countl_zero()) {
1867         APInt DemandedFromOp(APInt::getLowBitsSet(BitWidth, BitWidth - CTLZ));
1868         if (SimplifyDemandedBits(Op0, DemandedFromOp, DemandedElts, Known, TLO,
1869                                  Depth + 1)) {
1870           SDNodeFlags Flags = Op.getNode()->getFlags();
1871           if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
1872             // Disable the nsw and nuw flags. We can no longer guarantee that we
1873             // won't wrap after simplification.
1874             Flags.setNoSignedWrap(false);
1875             Flags.setNoUnsignedWrap(false);
1876             Op->setFlags(Flags);
1877           }
1878           return true;
1879         }
1880         Known.resetAll();
1881       }
1882     }
1883 
1884     // If we are only demanding sign bits then we can use the shift source
1885     // directly.
1886     if (const APInt *MaxSA =
1887             TLO.DAG.getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
1888       unsigned ShAmt = MaxSA->getZExtValue();
1889       unsigned NumSignBits =
1890           TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1);
1891       unsigned UpperDemandedBits = BitWidth - DemandedBits.countr_zero();
1892       if (NumSignBits > ShAmt && (NumSignBits - ShAmt) >= (UpperDemandedBits))
1893         return TLO.CombineTo(Op, Op0);
1894     }
1895     break;
1896   }
1897   case ISD::SRL: {
1898     SDValue Op0 = Op.getOperand(0);
1899     SDValue Op1 = Op.getOperand(1);
1900     EVT ShiftVT = Op1.getValueType();
1901 
1902     // Try to match AVG patterns.
1903     if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits,
1904                                         DemandedElts, Depth + 1))
1905       return TLO.CombineTo(Op, AVG);
1906 
1907     if (const APInt *SA =
1908             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
1909       unsigned ShAmt = SA->getZExtValue();
1910       if (ShAmt == 0)
1911         return TLO.CombineTo(Op, Op0);
1912 
1913       // If this is ((X << C1) >>u ShAmt), see if we can simplify this into a
1914       // single shift.  We can do this if the top bits (which are shifted out)
1915       // are never demanded.
1916       // TODO - support non-uniform vector amounts.
1917       if (Op0.getOpcode() == ISD::SHL) {
1918         if (!DemandedBits.intersects(APInt::getHighBitsSet(BitWidth, ShAmt))) {
1919           if (const APInt *SA2 =
1920                   TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) {
1921             unsigned C1 = SA2->getZExtValue();
1922             unsigned Opc = ISD::SRL;
1923             int Diff = ShAmt - C1;
1924             if (Diff < 0) {
1925               Diff = -Diff;
1926               Opc = ISD::SHL;
1927             }
1928             SDValue NewSA = TLO.DAG.getConstant(Diff, dl, ShiftVT);
1929             return TLO.CombineTo(
1930                 Op, TLO.DAG.getNode(Opc, dl, VT, Op0.getOperand(0), NewSA));
1931           }
1932         }
1933       }
1934 
1935       APInt InDemandedMask = (DemandedBits << ShAmt);
1936 
1937       // If the shift is exact, then it does demand the low bits (and knows that
1938       // they are zero).
1939       if (Op->getFlags().hasExact())
1940         InDemandedMask.setLowBits(ShAmt);
1941 
1942       // Narrow shift to lower half - similar to ShrinkDemandedOp.
1943       // (srl i64:x, K) -> (i64 zero_extend (srl (i32 (trunc i64:x)), K))
1944       if ((BitWidth % 2) == 0 && !VT.isVector()) {
1945         APInt HiBits = APInt::getHighBitsSet(BitWidth, BitWidth / 2);
1946         EVT HalfVT = EVT::getIntegerVT(*TLO.DAG.getContext(), BitWidth / 2);
1947         if (isNarrowingProfitable(VT, HalfVT) &&
1948             isTypeDesirableForOp(ISD::SRL, HalfVT) &&
1949             isTruncateFree(VT, HalfVT) && isZExtFree(HalfVT, VT) &&
1950             (!TLO.LegalOperations() || isOperationLegal(ISD::SRL, HalfVT)) &&
1951             ((InDemandedMask.countLeadingZeros() >= (BitWidth / 2)) ||
1952              TLO.DAG.MaskedValueIsZero(Op0, HiBits))) {
1953           SDValue NewOp = TLO.DAG.getNode(ISD::TRUNCATE, dl, HalfVT, Op0);
1954           SDValue NewShiftAmt = TLO.DAG.getShiftAmountConstant(
1955               ShAmt, HalfVT, dl, TLO.LegalTypes());
1956           SDValue NewShift =
1957               TLO.DAG.getNode(ISD::SRL, dl, HalfVT, NewOp, NewShiftAmt);
1958           return TLO.CombineTo(
1959               Op, TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, NewShift));
1960         }
1961       }
1962 
1963       // Compute the new bits that are at the top now.
1964       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
1965                                Depth + 1))
1966         return true;
1967       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
1968       Known.Zero.lshrInPlace(ShAmt);
1969       Known.One.lshrInPlace(ShAmt);
1970       // High bits known zero.
1971       Known.Zero.setHighBits(ShAmt);
1972 
1973       // Attempt to avoid multi-use ops if we don't need anything from them.
1974       if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
1975         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
1976             Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
1977         if (DemandedOp0) {
1978           SDValue NewOp = TLO.DAG.getNode(ISD::SRL, dl, VT, DemandedOp0, Op1);
1979           return TLO.CombineTo(Op, NewOp);
1980         }
1981       }
1982     } else {
1983       // Use generic knownbits computation as it has support for non-uniform
1984       // shift amounts.
1985       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
1986     }
1987     break;
1988   }
1989   case ISD::SRA: {
1990     SDValue Op0 = Op.getOperand(0);
1991     SDValue Op1 = Op.getOperand(1);
1992     EVT ShiftVT = Op1.getValueType();
1993 
1994     // If we only want bits that already match the signbit then we don't need
1995     // to shift.
1996     unsigned NumHiDemandedBits = BitWidth - DemandedBits.countr_zero();
1997     if (TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1) >=
1998         NumHiDemandedBits)
1999       return TLO.CombineTo(Op, Op0);
2000 
2001     // If this is an arithmetic shift right and only the low-bit is set, we can
2002     // always convert this into a logical shr, even if the shift amount is
2003     // variable.  The low bit of the shift cannot be an input sign bit unless
2004     // the shift amount is >= the size of the datatype, which is undefined.
2005     if (DemandedBits.isOne())
2006       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2007 
2008     // Try to match AVG patterns.
2009     if (SDValue AVG = combineShiftToAVG(Op, TLO.DAG, *this, DemandedBits,
2010                                         DemandedElts, Depth + 1))
2011       return TLO.CombineTo(Op, AVG);
2012 
2013     if (const APInt *SA =
2014             TLO.DAG.getValidShiftAmountConstant(Op, DemandedElts)) {
2015       unsigned ShAmt = SA->getZExtValue();
2016       if (ShAmt == 0)
2017         return TLO.CombineTo(Op, Op0);
2018 
2019       // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target
2020       // supports sext_inreg.
2021       if (Op0.getOpcode() == ISD::SHL) {
2022         if (const APInt *InnerSA =
2023                 TLO.DAG.getValidShiftAmountConstant(Op0, DemandedElts)) {
2024           unsigned LowBits = BitWidth - ShAmt;
2025           EVT ExtVT = EVT::getIntegerVT(*TLO.DAG.getContext(), LowBits);
2026           if (VT.isVector())
2027             ExtVT = EVT::getVectorVT(*TLO.DAG.getContext(), ExtVT,
2028                                      VT.getVectorElementCount());
2029 
2030           if (*InnerSA == ShAmt) {
2031             if (!TLO.LegalOperations() ||
2032                 getOperationAction(ISD::SIGN_EXTEND_INREG, ExtVT) == Legal)
2033               return TLO.CombineTo(
2034                   Op, TLO.DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, VT,
2035                                       Op0.getOperand(0),
2036                                       TLO.DAG.getValueType(ExtVT)));
2037 
2038             // Even if we can't convert to sext_inreg, we might be able to
2039             // remove this shift pair if the input is already sign extended.
2040             unsigned NumSignBits =
2041                 TLO.DAG.ComputeNumSignBits(Op0.getOperand(0), DemandedElts);
2042             if (NumSignBits > ShAmt)
2043               return TLO.CombineTo(Op, Op0.getOperand(0));
2044           }
2045         }
2046       }
2047 
2048       APInt InDemandedMask = (DemandedBits << ShAmt);
2049 
2050       // If the shift is exact, then it does demand the low bits (and knows that
2051       // they are zero).
2052       if (Op->getFlags().hasExact())
2053         InDemandedMask.setLowBits(ShAmt);
2054 
2055       // If any of the demanded bits are produced by the sign extension, we also
2056       // demand the input sign bit.
2057       if (DemandedBits.countl_zero() < ShAmt)
2058         InDemandedMask.setSignBit();
2059 
2060       if (SimplifyDemandedBits(Op0, InDemandedMask, DemandedElts, Known, TLO,
2061                                Depth + 1))
2062         return true;
2063       assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2064       Known.Zero.lshrInPlace(ShAmt);
2065       Known.One.lshrInPlace(ShAmt);
2066 
2067       // If the input sign bit is known to be zero, or if none of the top bits
2068       // are demanded, turn this into an unsigned shift right.
2069       if (Known.Zero[BitWidth - ShAmt - 1] ||
2070           DemandedBits.countl_zero() >= ShAmt) {
2071         SDNodeFlags Flags;
2072         Flags.setExact(Op->getFlags().hasExact());
2073         return TLO.CombineTo(
2074             Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1, Flags));
2075       }
2076 
2077       int Log2 = DemandedBits.exactLogBase2();
2078       if (Log2 >= 0) {
2079         // The bit must come from the sign.
2080         SDValue NewSA = TLO.DAG.getConstant(BitWidth - 1 - Log2, dl, ShiftVT);
2081         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, NewSA));
2082       }
2083 
2084       if (Known.One[BitWidth - ShAmt - 1])
2085         // New bits are known one.
2086         Known.One.setHighBits(ShAmt);
2087 
2088       // Attempt to avoid multi-use ops if we don't need anything from them.
2089       if (!InDemandedMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2090         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
2091             Op0, InDemandedMask, DemandedElts, TLO.DAG, Depth + 1);
2092         if (DemandedOp0) {
2093           SDValue NewOp = TLO.DAG.getNode(ISD::SRA, dl, VT, DemandedOp0, Op1);
2094           return TLO.CombineTo(Op, NewOp);
2095         }
2096       }
2097     }
2098     break;
2099   }
2100   case ISD::FSHL:
2101   case ISD::FSHR: {
2102     SDValue Op0 = Op.getOperand(0);
2103     SDValue Op1 = Op.getOperand(1);
2104     SDValue Op2 = Op.getOperand(2);
2105     bool IsFSHL = (Op.getOpcode() == ISD::FSHL);
2106 
2107     if (ConstantSDNode *SA = isConstOrConstSplat(Op2, DemandedElts)) {
2108       unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2109 
2110       // For fshl, 0-shift returns the 1st arg.
2111       // For fshr, 0-shift returns the 2nd arg.
2112       if (Amt == 0) {
2113         if (SimplifyDemandedBits(IsFSHL ? Op0 : Op1, DemandedBits, DemandedElts,
2114                                  Known, TLO, Depth + 1))
2115           return true;
2116         break;
2117       }
2118 
2119       // fshl: (Op0 << Amt) | (Op1 >> (BW - Amt))
2120       // fshr: (Op0 << (BW - Amt)) | (Op1 >> Amt)
2121       APInt Demanded0 = DemandedBits.lshr(IsFSHL ? Amt : (BitWidth - Amt));
2122       APInt Demanded1 = DemandedBits << (IsFSHL ? (BitWidth - Amt) : Amt);
2123       if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2124                                Depth + 1))
2125         return true;
2126       if (SimplifyDemandedBits(Op1, Demanded1, DemandedElts, Known, TLO,
2127                                Depth + 1))
2128         return true;
2129 
2130       Known2.One <<= (IsFSHL ? Amt : (BitWidth - Amt));
2131       Known2.Zero <<= (IsFSHL ? Amt : (BitWidth - Amt));
2132       Known.One.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
2133       Known.Zero.lshrInPlace(IsFSHL ? (BitWidth - Amt) : Amt);
2134       Known = Known.unionWith(Known2);
2135 
2136       // Attempt to avoid multi-use ops if we don't need anything from them.
2137       if (!Demanded0.isAllOnes() || !Demanded1.isAllOnes() ||
2138           !DemandedElts.isAllOnes()) {
2139         SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
2140             Op0, Demanded0, DemandedElts, TLO.DAG, Depth + 1);
2141         SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
2142             Op1, Demanded1, DemandedElts, TLO.DAG, Depth + 1);
2143         if (DemandedOp0 || DemandedOp1) {
2144           DemandedOp0 = DemandedOp0 ? DemandedOp0 : Op0;
2145           DemandedOp1 = DemandedOp1 ? DemandedOp1 : Op1;
2146           SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedOp0,
2147                                           DemandedOp1, Op2);
2148           return TLO.CombineTo(Op, NewOp);
2149         }
2150       }
2151     }
2152 
2153     // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2154     if (isPowerOf2_32(BitWidth)) {
2155       APInt DemandedAmtBits(Op2.getScalarValueSizeInBits(), BitWidth - 1);
2156       if (SimplifyDemandedBits(Op2, DemandedAmtBits, DemandedElts,
2157                                Known2, TLO, Depth + 1))
2158         return true;
2159     }
2160     break;
2161   }
2162   case ISD::ROTL:
2163   case ISD::ROTR: {
2164     SDValue Op0 = Op.getOperand(0);
2165     SDValue Op1 = Op.getOperand(1);
2166     bool IsROTL = (Op.getOpcode() == ISD::ROTL);
2167 
2168     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
2169     if (BitWidth == TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1))
2170       return TLO.CombineTo(Op, Op0);
2171 
2172     if (ConstantSDNode *SA = isConstOrConstSplat(Op1, DemandedElts)) {
2173       unsigned Amt = SA->getAPIntValue().urem(BitWidth);
2174       unsigned RevAmt = BitWidth - Amt;
2175 
2176       // rotl: (Op0 << Amt) | (Op0 >> (BW - Amt))
2177       // rotr: (Op0 << (BW - Amt)) | (Op0 >> Amt)
2178       APInt Demanded0 = DemandedBits.rotr(IsROTL ? Amt : RevAmt);
2179       if (SimplifyDemandedBits(Op0, Demanded0, DemandedElts, Known2, TLO,
2180                                Depth + 1))
2181         return true;
2182 
2183       // rot*(x, 0) --> x
2184       if (Amt == 0)
2185         return TLO.CombineTo(Op, Op0);
2186 
2187       // See if we don't demand either half of the rotated bits.
2188       if ((!TLO.LegalOperations() || isOperationLegal(ISD::SHL, VT)) &&
2189           DemandedBits.countr_zero() >= (IsROTL ? Amt : RevAmt)) {
2190         Op1 = TLO.DAG.getConstant(IsROTL ? Amt : RevAmt, dl, Op1.getValueType());
2191         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, Op1));
2192       }
2193       if ((!TLO.LegalOperations() || isOperationLegal(ISD::SRL, VT)) &&
2194           DemandedBits.countl_zero() >= (IsROTL ? RevAmt : Amt)) {
2195         Op1 = TLO.DAG.getConstant(IsROTL ? RevAmt : Amt, dl, Op1.getValueType());
2196         return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::SRL, dl, VT, Op0, Op1));
2197       }
2198     }
2199 
2200     // For pow-2 bitwidths we only demand the bottom modulo amt bits.
2201     if (isPowerOf2_32(BitWidth)) {
2202       APInt DemandedAmtBits(Op1.getScalarValueSizeInBits(), BitWidth - 1);
2203       if (SimplifyDemandedBits(Op1, DemandedAmtBits, DemandedElts, Known2, TLO,
2204                                Depth + 1))
2205         return true;
2206     }
2207     break;
2208   }
2209   case ISD::SMIN:
2210   case ISD::SMAX:
2211   case ISD::UMIN:
2212   case ISD::UMAX: {
2213     unsigned Opc = Op.getOpcode();
2214     SDValue Op0 = Op.getOperand(0);
2215     SDValue Op1 = Op.getOperand(1);
2216 
2217     // If we're only demanding signbits, then we can simplify to OR/AND node.
2218     unsigned BitOp =
2219         (Opc == ISD::SMIN || Opc == ISD::UMAX) ? ISD::OR : ISD::AND;
2220     unsigned NumSignBits =
2221         std::min(TLO.DAG.ComputeNumSignBits(Op0, DemandedElts, Depth + 1),
2222                  TLO.DAG.ComputeNumSignBits(Op1, DemandedElts, Depth + 1));
2223     unsigned NumDemandedUpperBits = BitWidth - DemandedBits.countr_zero();
2224     if (NumSignBits >= NumDemandedUpperBits)
2225       return TLO.CombineTo(Op, TLO.DAG.getNode(BitOp, SDLoc(Op), VT, Op0, Op1));
2226 
2227     // Check if one arg is always less/greater than (or equal) to the other arg.
2228     KnownBits Known0 = TLO.DAG.computeKnownBits(Op0, DemandedElts, Depth + 1);
2229     KnownBits Known1 = TLO.DAG.computeKnownBits(Op1, DemandedElts, Depth + 1);
2230     switch (Opc) {
2231     case ISD::SMIN:
2232       if (std::optional<bool> IsSLE = KnownBits::sle(Known0, Known1))
2233         return TLO.CombineTo(Op, *IsSLE ? Op0 : Op1);
2234       if (std::optional<bool> IsSLT = KnownBits::slt(Known0, Known1))
2235         return TLO.CombineTo(Op, *IsSLT ? Op0 : Op1);
2236       Known = KnownBits::smin(Known0, Known1);
2237       break;
2238     case ISD::SMAX:
2239       if (std::optional<bool> IsSGE = KnownBits::sge(Known0, Known1))
2240         return TLO.CombineTo(Op, *IsSGE ? Op0 : Op1);
2241       if (std::optional<bool> IsSGT = KnownBits::sgt(Known0, Known1))
2242         return TLO.CombineTo(Op, *IsSGT ? Op0 : Op1);
2243       Known = KnownBits::smax(Known0, Known1);
2244       break;
2245     case ISD::UMIN:
2246       if (std::optional<bool> IsULE = KnownBits::ule(Known0, Known1))
2247         return TLO.CombineTo(Op, *IsULE ? Op0 : Op1);
2248       if (std::optional<bool> IsULT = KnownBits::ult(Known0, Known1))
2249         return TLO.CombineTo(Op, *IsULT ? Op0 : Op1);
2250       Known = KnownBits::umin(Known0, Known1);
2251       break;
2252     case ISD::UMAX:
2253       if (std::optional<bool> IsUGE = KnownBits::uge(Known0, Known1))
2254         return TLO.CombineTo(Op, *IsUGE ? Op0 : Op1);
2255       if (std::optional<bool> IsUGT = KnownBits::ugt(Known0, Known1))
2256         return TLO.CombineTo(Op, *IsUGT ? Op0 : Op1);
2257       Known = KnownBits::umax(Known0, Known1);
2258       break;
2259     }
2260     break;
2261   }
2262   case ISD::BITREVERSE: {
2263     SDValue Src = Op.getOperand(0);
2264     APInt DemandedSrcBits = DemandedBits.reverseBits();
2265     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2266                              Depth + 1))
2267       return true;
2268     Known.One = Known2.One.reverseBits();
2269     Known.Zero = Known2.Zero.reverseBits();
2270     break;
2271   }
2272   case ISD::BSWAP: {
2273     SDValue Src = Op.getOperand(0);
2274 
2275     // If the only bits demanded come from one byte of the bswap result,
2276     // just shift the input byte into position to eliminate the bswap.
2277     unsigned NLZ = DemandedBits.countl_zero();
2278     unsigned NTZ = DemandedBits.countr_zero();
2279 
2280     // Round NTZ down to the next byte.  If we have 11 trailing zeros, then
2281     // we need all the bits down to bit 8.  Likewise, round NLZ.  If we
2282     // have 14 leading zeros, round to 8.
2283     NLZ = alignDown(NLZ, 8);
2284     NTZ = alignDown(NTZ, 8);
2285     // If we need exactly one byte, we can do this transformation.
2286     if (BitWidth - NLZ - NTZ == 8) {
2287       // Replace this with either a left or right shift to get the byte into
2288       // the right place.
2289       unsigned ShiftOpcode = NLZ > NTZ ? ISD::SRL : ISD::SHL;
2290       if (!TLO.LegalOperations() || isOperationLegal(ShiftOpcode, VT)) {
2291         EVT ShiftAmtTy = getShiftAmountTy(VT, DL);
2292         unsigned ShiftAmount = NLZ > NTZ ? NLZ - NTZ : NTZ - NLZ;
2293         SDValue ShAmt = TLO.DAG.getConstant(ShiftAmount, dl, ShiftAmtTy);
2294         SDValue NewOp = TLO.DAG.getNode(ShiftOpcode, dl, VT, Src, ShAmt);
2295         return TLO.CombineTo(Op, NewOp);
2296       }
2297     }
2298 
2299     APInt DemandedSrcBits = DemandedBits.byteSwap();
2300     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedElts, Known2, TLO,
2301                              Depth + 1))
2302       return true;
2303     Known.One = Known2.One.byteSwap();
2304     Known.Zero = Known2.Zero.byteSwap();
2305     break;
2306   }
2307   case ISD::CTPOP: {
2308     // If only 1 bit is demanded, replace with PARITY as long as we're before
2309     // op legalization.
2310     // FIXME: Limit to scalars for now.
2311     if (DemandedBits.isOne() && !TLO.LegalOps && !VT.isVector())
2312       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::PARITY, dl, VT,
2313                                                Op.getOperand(0)));
2314 
2315     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2316     break;
2317   }
2318   case ISD::SIGN_EXTEND_INREG: {
2319     SDValue Op0 = Op.getOperand(0);
2320     EVT ExVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2321     unsigned ExVTBits = ExVT.getScalarSizeInBits();
2322 
2323     // If we only care about the highest bit, don't bother shifting right.
2324     if (DemandedBits.isSignMask()) {
2325       unsigned MinSignedBits =
2326           TLO.DAG.ComputeMaxSignificantBits(Op0, DemandedElts, Depth + 1);
2327       bool AlreadySignExtended = ExVTBits >= MinSignedBits;
2328       // However if the input is already sign extended we expect the sign
2329       // extension to be dropped altogether later and do not simplify.
2330       if (!AlreadySignExtended) {
2331         // Compute the correct shift amount type, which must be getShiftAmountTy
2332         // for scalar types after legalization.
2333         SDValue ShiftAmt = TLO.DAG.getConstant(BitWidth - ExVTBits, dl,
2334                                                getShiftAmountTy(VT, DL));
2335         return TLO.CombineTo(Op,
2336                              TLO.DAG.getNode(ISD::SHL, dl, VT, Op0, ShiftAmt));
2337       }
2338     }
2339 
2340     // If none of the extended bits are demanded, eliminate the sextinreg.
2341     if (DemandedBits.getActiveBits() <= ExVTBits)
2342       return TLO.CombineTo(Op, Op0);
2343 
2344     APInt InputDemandedBits = DemandedBits.getLoBits(ExVTBits);
2345 
2346     // Since the sign extended bits are demanded, we know that the sign
2347     // bit is demanded.
2348     InputDemandedBits.setBit(ExVTBits - 1);
2349 
2350     if (SimplifyDemandedBits(Op0, InputDemandedBits, DemandedElts, Known, TLO,
2351                              Depth + 1))
2352       return true;
2353     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2354 
2355     // If the sign bit of the input is known set or clear, then we know the
2356     // top bits of the result.
2357 
2358     // If the input sign bit is known zero, convert this into a zero extension.
2359     if (Known.Zero[ExVTBits - 1])
2360       return TLO.CombineTo(Op, TLO.DAG.getZeroExtendInReg(Op0, dl, ExVT));
2361 
2362     APInt Mask = APInt::getLowBitsSet(BitWidth, ExVTBits);
2363     if (Known.One[ExVTBits - 1]) { // Input sign bit known set
2364       Known.One.setBitsFrom(ExVTBits);
2365       Known.Zero &= Mask;
2366     } else { // Input sign bit unknown
2367       Known.Zero &= Mask;
2368       Known.One &= Mask;
2369     }
2370     break;
2371   }
2372   case ISD::BUILD_PAIR: {
2373     EVT HalfVT = Op.getOperand(0).getValueType();
2374     unsigned HalfBitWidth = HalfVT.getScalarSizeInBits();
2375 
2376     APInt MaskLo = DemandedBits.getLoBits(HalfBitWidth).trunc(HalfBitWidth);
2377     APInt MaskHi = DemandedBits.getHiBits(HalfBitWidth).trunc(HalfBitWidth);
2378 
2379     KnownBits KnownLo, KnownHi;
2380 
2381     if (SimplifyDemandedBits(Op.getOperand(0), MaskLo, KnownLo, TLO, Depth + 1))
2382       return true;
2383 
2384     if (SimplifyDemandedBits(Op.getOperand(1), MaskHi, KnownHi, TLO, Depth + 1))
2385       return true;
2386 
2387     Known = KnownHi.concat(KnownLo);
2388     break;
2389   }
2390   case ISD::ZERO_EXTEND_VECTOR_INREG:
2391     if (VT.isScalableVector())
2392       return false;
2393     [[fallthrough]];
2394   case ISD::ZERO_EXTEND: {
2395     SDValue Src = Op.getOperand(0);
2396     EVT SrcVT = Src.getValueType();
2397     unsigned InBits = SrcVT.getScalarSizeInBits();
2398     unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2399     bool IsVecInReg = Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
2400 
2401     // If none of the top bits are demanded, convert this into an any_extend.
2402     if (DemandedBits.getActiveBits() <= InBits) {
2403       // If we only need the non-extended bits of the bottom element
2404       // then we can just bitcast to the result.
2405       if (IsLE && IsVecInReg && DemandedElts == 1 &&
2406           VT.getSizeInBits() == SrcVT.getSizeInBits())
2407         return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2408 
2409       unsigned Opc =
2410           IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND;
2411       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2412         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2413     }
2414 
2415     SDNodeFlags Flags = Op->getFlags();
2416     APInt InDemandedBits = DemandedBits.trunc(InBits);
2417     APInt InDemandedElts = DemandedElts.zext(InElts);
2418     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2419                              Depth + 1)) {
2420       if (Flags.hasNonNeg()) {
2421         Flags.setNonNeg(false);
2422         Op->setFlags(Flags);
2423       }
2424       return true;
2425     }
2426     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2427     assert(Known.getBitWidth() == InBits && "Src width has changed?");
2428     Known = Known.zext(BitWidth);
2429 
2430     // Attempt to avoid multi-use ops if we don't need anything from them.
2431     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2432             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2433       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2434     break;
2435   }
2436   case ISD::SIGN_EXTEND_VECTOR_INREG:
2437     if (VT.isScalableVector())
2438       return false;
2439     [[fallthrough]];
2440   case ISD::SIGN_EXTEND: {
2441     SDValue Src = Op.getOperand(0);
2442     EVT SrcVT = Src.getValueType();
2443     unsigned InBits = SrcVT.getScalarSizeInBits();
2444     unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2445     bool IsVecInReg = Op.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG;
2446 
2447     APInt InDemandedElts = DemandedElts.zext(InElts);
2448     APInt InDemandedBits = DemandedBits.trunc(InBits);
2449 
2450     // Since some of the sign extended bits are demanded, we know that the sign
2451     // bit is demanded.
2452     InDemandedBits.setBit(InBits - 1);
2453 
2454     // If none of the top bits are demanded, convert this into an any_extend.
2455     if (DemandedBits.getActiveBits() <= InBits) {
2456       // If we only need the non-extended bits of the bottom element
2457       // then we can just bitcast to the result.
2458       if (IsLE && IsVecInReg && DemandedElts == 1 &&
2459           VT.getSizeInBits() == SrcVT.getSizeInBits())
2460         return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2461 
2462       // Don't lose an all signbits 0/-1 splat on targets with 0/-1 booleans.
2463       if (getBooleanContents(VT) != ZeroOrNegativeOneBooleanContent ||
2464           TLO.DAG.ComputeNumSignBits(Src, InDemandedElts, Depth + 1) !=
2465               InBits) {
2466         unsigned Opc =
2467             IsVecInReg ? ISD::ANY_EXTEND_VECTOR_INREG : ISD::ANY_EXTEND;
2468         if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2469           return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2470       }
2471     }
2472 
2473     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2474                              Depth + 1))
2475       return true;
2476     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2477     assert(Known.getBitWidth() == InBits && "Src width has changed?");
2478 
2479     // If the sign bit is known one, the top bits match.
2480     Known = Known.sext(BitWidth);
2481 
2482     // If the sign bit is known zero, convert this to a zero extend.
2483     if (Known.isNonNegative()) {
2484       unsigned Opc =
2485           IsVecInReg ? ISD::ZERO_EXTEND_VECTOR_INREG : ISD::ZERO_EXTEND;
2486       if (!TLO.LegalOperations() || isOperationLegal(Opc, VT))
2487         return TLO.CombineTo(Op, TLO.DAG.getNode(Opc, dl, VT, Src));
2488     }
2489 
2490     // Attempt to avoid multi-use ops if we don't need anything from them.
2491     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2492             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2493       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2494     break;
2495   }
2496   case ISD::ANY_EXTEND_VECTOR_INREG:
2497     if (VT.isScalableVector())
2498       return false;
2499     [[fallthrough]];
2500   case ISD::ANY_EXTEND: {
2501     SDValue Src = Op.getOperand(0);
2502     EVT SrcVT = Src.getValueType();
2503     unsigned InBits = SrcVT.getScalarSizeInBits();
2504     unsigned InElts = SrcVT.isFixedLengthVector() ? SrcVT.getVectorNumElements() : 1;
2505     bool IsVecInReg = Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG;
2506 
2507     // If we only need the bottom element then we can just bitcast.
2508     // TODO: Handle ANY_EXTEND?
2509     if (IsLE && IsVecInReg && DemandedElts == 1 &&
2510         VT.getSizeInBits() == SrcVT.getSizeInBits())
2511       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
2512 
2513     APInt InDemandedBits = DemandedBits.trunc(InBits);
2514     APInt InDemandedElts = DemandedElts.zext(InElts);
2515     if (SimplifyDemandedBits(Src, InDemandedBits, InDemandedElts, Known, TLO,
2516                              Depth + 1))
2517       return true;
2518     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2519     assert(Known.getBitWidth() == InBits && "Src width has changed?");
2520     Known = Known.anyext(BitWidth);
2521 
2522     // Attempt to avoid multi-use ops if we don't need anything from them.
2523     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2524             Src, InDemandedBits, InDemandedElts, TLO.DAG, Depth + 1))
2525       return TLO.CombineTo(Op, TLO.DAG.getNode(Op.getOpcode(), dl, VT, NewSrc));
2526     break;
2527   }
2528   case ISD::TRUNCATE: {
2529     SDValue Src = Op.getOperand(0);
2530 
2531     // Simplify the input, using demanded bit information, and compute the known
2532     // zero/one bits live out.
2533     unsigned OperandBitWidth = Src.getScalarValueSizeInBits();
2534     APInt TruncMask = DemandedBits.zext(OperandBitWidth);
2535     if (SimplifyDemandedBits(Src, TruncMask, DemandedElts, Known, TLO,
2536                              Depth + 1))
2537       return true;
2538     Known = Known.trunc(BitWidth);
2539 
2540     // Attempt to avoid multi-use ops if we don't need anything from them.
2541     if (SDValue NewSrc = SimplifyMultipleUseDemandedBits(
2542             Src, TruncMask, DemandedElts, TLO.DAG, Depth + 1))
2543       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, NewSrc));
2544 
2545     // If the input is only used by this truncate, see if we can shrink it based
2546     // on the known demanded bits.
2547     switch (Src.getOpcode()) {
2548     default:
2549       break;
2550     case ISD::SRL:
2551       // Shrink SRL by a constant if none of the high bits shifted in are
2552       // demanded.
2553       if (TLO.LegalTypes() && !isTypeDesirableForOp(ISD::SRL, VT))
2554         // Do not turn (vt1 truncate (vt2 srl)) into (vt1 srl) if vt1 is
2555         // undesirable.
2556         break;
2557 
2558       if (Src.getNode()->hasOneUse()) {
2559         const APInt *ShAmtC =
2560             TLO.DAG.getValidShiftAmountConstant(Src, DemandedElts);
2561         if (!ShAmtC || ShAmtC->uge(BitWidth))
2562           break;
2563         uint64_t ShVal = ShAmtC->getZExtValue();
2564 
2565         APInt HighBits =
2566             APInt::getHighBitsSet(OperandBitWidth, OperandBitWidth - BitWidth);
2567         HighBits.lshrInPlace(ShVal);
2568         HighBits = HighBits.trunc(BitWidth);
2569 
2570         if (!(HighBits & DemandedBits)) {
2571           // None of the shifted in bits are needed.  Add a truncate of the
2572           // shift input, then shift it.
2573           SDValue NewShAmt = TLO.DAG.getConstant(
2574               ShVal, dl, getShiftAmountTy(VT, DL, TLO.LegalTypes()));
2575           SDValue NewTrunc =
2576               TLO.DAG.getNode(ISD::TRUNCATE, dl, VT, Src.getOperand(0));
2577           return TLO.CombineTo(
2578               Op, TLO.DAG.getNode(ISD::SRL, dl, VT, NewTrunc, NewShAmt));
2579         }
2580       }
2581       break;
2582     }
2583 
2584     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2585     break;
2586   }
2587   case ISD::AssertZext: {
2588     // AssertZext demands all of the high bits, plus any of the low bits
2589     // demanded by its users.
2590     EVT ZVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2591     APInt InMask = APInt::getLowBitsSet(BitWidth, ZVT.getSizeInBits());
2592     if (SimplifyDemandedBits(Op.getOperand(0), ~InMask | DemandedBits, Known,
2593                              TLO, Depth + 1))
2594       return true;
2595     assert(!Known.hasConflict() && "Bits known to be one AND zero?");
2596 
2597     Known.Zero |= ~InMask;
2598     Known.One &= (~Known.Zero);
2599     break;
2600   }
2601   case ISD::EXTRACT_VECTOR_ELT: {
2602     SDValue Src = Op.getOperand(0);
2603     SDValue Idx = Op.getOperand(1);
2604     ElementCount SrcEltCnt = Src.getValueType().getVectorElementCount();
2605     unsigned EltBitWidth = Src.getScalarValueSizeInBits();
2606 
2607     if (SrcEltCnt.isScalable())
2608       return false;
2609 
2610     // Demand the bits from every vector element without a constant index.
2611     unsigned NumSrcElts = SrcEltCnt.getFixedValue();
2612     APInt DemandedSrcElts = APInt::getAllOnes(NumSrcElts);
2613     if (auto *CIdx = dyn_cast<ConstantSDNode>(Idx))
2614       if (CIdx->getAPIntValue().ult(NumSrcElts))
2615         DemandedSrcElts = APInt::getOneBitSet(NumSrcElts, CIdx->getZExtValue());
2616 
2617     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
2618     // anything about the extended bits.
2619     APInt DemandedSrcBits = DemandedBits;
2620     if (BitWidth > EltBitWidth)
2621       DemandedSrcBits = DemandedSrcBits.trunc(EltBitWidth);
2622 
2623     if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts, Known2, TLO,
2624                              Depth + 1))
2625       return true;
2626 
2627     // Attempt to avoid multi-use ops if we don't need anything from them.
2628     if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
2629       if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
2630               Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
2631         SDValue NewOp =
2632             TLO.DAG.getNode(Op.getOpcode(), dl, VT, DemandedSrc, Idx);
2633         return TLO.CombineTo(Op, NewOp);
2634       }
2635     }
2636 
2637     Known = Known2;
2638     if (BitWidth > EltBitWidth)
2639       Known = Known.anyext(BitWidth);
2640     break;
2641   }
2642   case ISD::BITCAST: {
2643     if (VT.isScalableVector())
2644       return false;
2645     SDValue Src = Op.getOperand(0);
2646     EVT SrcVT = Src.getValueType();
2647     unsigned NumSrcEltBits = SrcVT.getScalarSizeInBits();
2648 
2649     // If this is an FP->Int bitcast and if the sign bit is the only
2650     // thing demanded, turn this into a FGETSIGN.
2651     if (!TLO.LegalOperations() && !VT.isVector() && !SrcVT.isVector() &&
2652         DemandedBits == APInt::getSignMask(Op.getValueSizeInBits()) &&
2653         SrcVT.isFloatingPoint()) {
2654       bool OpVTLegal = isOperationLegalOrCustom(ISD::FGETSIGN, VT);
2655       bool i32Legal = isOperationLegalOrCustom(ISD::FGETSIGN, MVT::i32);
2656       if ((OpVTLegal || i32Legal) && VT.isSimple() && SrcVT != MVT::f16 &&
2657           SrcVT != MVT::f128) {
2658         // Cannot eliminate/lower SHL for f128 yet.
2659         EVT Ty = OpVTLegal ? VT : MVT::i32;
2660         // Make a FGETSIGN + SHL to move the sign bit into the appropriate
2661         // place.  We expect the SHL to be eliminated by other optimizations.
2662         SDValue Sign = TLO.DAG.getNode(ISD::FGETSIGN, dl, Ty, Src);
2663         unsigned OpVTSizeInBits = Op.getValueSizeInBits();
2664         if (!OpVTLegal && OpVTSizeInBits > 32)
2665           Sign = TLO.DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Sign);
2666         unsigned ShVal = Op.getValueSizeInBits() - 1;
2667         SDValue ShAmt = TLO.DAG.getConstant(ShVal, dl, VT);
2668         return TLO.CombineTo(Op,
2669                              TLO.DAG.getNode(ISD::SHL, dl, VT, Sign, ShAmt));
2670       }
2671     }
2672 
2673     // Bitcast from a vector using SimplifyDemanded Bits/VectorElts.
2674     // Demand the elt/bit if any of the original elts/bits are demanded.
2675     if (SrcVT.isVector() && (BitWidth % NumSrcEltBits) == 0) {
2676       unsigned Scale = BitWidth / NumSrcEltBits;
2677       unsigned NumSrcElts = SrcVT.getVectorNumElements();
2678       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2679       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
2680       for (unsigned i = 0; i != Scale; ++i) {
2681         unsigned EltOffset = IsLE ? i : (Scale - 1 - i);
2682         unsigned BitOffset = EltOffset * NumSrcEltBits;
2683         APInt Sub = DemandedBits.extractBits(NumSrcEltBits, BitOffset);
2684         if (!Sub.isZero()) {
2685           DemandedSrcBits |= Sub;
2686           for (unsigned j = 0; j != NumElts; ++j)
2687             if (DemandedElts[j])
2688               DemandedSrcElts.setBit((j * Scale) + i);
2689         }
2690       }
2691 
2692       APInt KnownSrcUndef, KnownSrcZero;
2693       if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2694                                      KnownSrcZero, TLO, Depth + 1))
2695         return true;
2696 
2697       KnownBits KnownSrcBits;
2698       if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2699                                KnownSrcBits, TLO, Depth + 1))
2700         return true;
2701     } else if (IsLE && (NumSrcEltBits % BitWidth) == 0) {
2702       // TODO - bigendian once we have test coverage.
2703       unsigned Scale = NumSrcEltBits / BitWidth;
2704       unsigned NumSrcElts = SrcVT.isVector() ? SrcVT.getVectorNumElements() : 1;
2705       APInt DemandedSrcBits = APInt::getZero(NumSrcEltBits);
2706       APInt DemandedSrcElts = APInt::getZero(NumSrcElts);
2707       for (unsigned i = 0; i != NumElts; ++i)
2708         if (DemandedElts[i]) {
2709           unsigned Offset = (i % Scale) * BitWidth;
2710           DemandedSrcBits.insertBits(DemandedBits, Offset);
2711           DemandedSrcElts.setBit(i / Scale);
2712         }
2713 
2714       if (SrcVT.isVector()) {
2715         APInt KnownSrcUndef, KnownSrcZero;
2716         if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownSrcUndef,
2717                                        KnownSrcZero, TLO, Depth + 1))
2718           return true;
2719       }
2720 
2721       KnownBits KnownSrcBits;
2722       if (SimplifyDemandedBits(Src, DemandedSrcBits, DemandedSrcElts,
2723                                KnownSrcBits, TLO, Depth + 1))
2724         return true;
2725 
2726       // Attempt to avoid multi-use ops if we don't need anything from them.
2727       if (!DemandedSrcBits.isAllOnes() || !DemandedSrcElts.isAllOnes()) {
2728         if (SDValue DemandedSrc = SimplifyMultipleUseDemandedBits(
2729                 Src, DemandedSrcBits, DemandedSrcElts, TLO.DAG, Depth + 1)) {
2730           SDValue NewOp = TLO.DAG.getBitcast(VT, DemandedSrc);
2731           return TLO.CombineTo(Op, NewOp);
2732         }
2733       }
2734     }
2735 
2736     // If this is a bitcast, let computeKnownBits handle it.  Only do this on a
2737     // recursive call where Known may be useful to the caller.
2738     if (Depth > 0) {
2739       Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2740       return false;
2741     }
2742     break;
2743   }
2744   case ISD::MUL:
2745     if (DemandedBits.isPowerOf2()) {
2746       // The LSB of X*Y is set only if (X & 1) == 1 and (Y & 1) == 1.
2747       // If we demand exactly one bit N and we have "X * (C' << N)" where C' is
2748       // odd (has LSB set), then the left-shifted low bit of X is the answer.
2749       unsigned CTZ = DemandedBits.countr_zero();
2750       ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(1), DemandedElts);
2751       if (C && C->getAPIntValue().countr_zero() == CTZ) {
2752         EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout());
2753         SDValue AmtC = TLO.DAG.getConstant(CTZ, dl, ShiftAmtTy);
2754         SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, Op.getOperand(0), AmtC);
2755         return TLO.CombineTo(Op, Shl);
2756       }
2757     }
2758     // For a squared value "X * X", the bottom 2 bits are 0 and X[0] because:
2759     // X * X is odd iff X is odd.
2760     // 'Quadratic Reciprocity': X * X -> 0 for bit[1]
2761     if (Op.getOperand(0) == Op.getOperand(1) && DemandedBits.ult(4)) {
2762       SDValue One = TLO.DAG.getConstant(1, dl, VT);
2763       SDValue And1 = TLO.DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), One);
2764       return TLO.CombineTo(Op, And1);
2765     }
2766     [[fallthrough]];
2767   case ISD::ADD:
2768   case ISD::SUB: {
2769     // Add, Sub, and Mul don't demand any bits in positions beyond that
2770     // of the highest bit demanded of them.
2771     SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
2772     SDNodeFlags Flags = Op.getNode()->getFlags();
2773     unsigned DemandedBitsLZ = DemandedBits.countl_zero();
2774     APInt LoMask = APInt::getLowBitsSet(BitWidth, BitWidth - DemandedBitsLZ);
2775     KnownBits KnownOp0, KnownOp1;
2776     if (SimplifyDemandedBits(Op0, LoMask, DemandedElts, KnownOp0, TLO,
2777                              Depth + 1) ||
2778         SimplifyDemandedBits(Op1, LoMask, DemandedElts, KnownOp1, TLO,
2779                              Depth + 1) ||
2780         // See if the operation should be performed at a smaller bit width.
2781         ShrinkDemandedOp(Op, BitWidth, DemandedBits, TLO)) {
2782       if (Flags.hasNoSignedWrap() || Flags.hasNoUnsignedWrap()) {
2783         // Disable the nsw and nuw flags. We can no longer guarantee that we
2784         // won't wrap after simplification.
2785         Flags.setNoSignedWrap(false);
2786         Flags.setNoUnsignedWrap(false);
2787         Op->setFlags(Flags);
2788       }
2789       return true;
2790     }
2791 
2792     // neg x with only low bit demanded is simply x.
2793     if (Op.getOpcode() == ISD::SUB && DemandedBits.isOne() &&
2794         isNullConstant(Op0))
2795       return TLO.CombineTo(Op, Op1);
2796 
2797     // Attempt to avoid multi-use ops if we don't need anything from them.
2798     if (!LoMask.isAllOnes() || !DemandedElts.isAllOnes()) {
2799       SDValue DemandedOp0 = SimplifyMultipleUseDemandedBits(
2800           Op0, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2801       SDValue DemandedOp1 = SimplifyMultipleUseDemandedBits(
2802           Op1, LoMask, DemandedElts, TLO.DAG, Depth + 1);
2803       if (DemandedOp0 || DemandedOp1) {
2804         Flags.setNoSignedWrap(false);
2805         Flags.setNoUnsignedWrap(false);
2806         Op0 = DemandedOp0 ? DemandedOp0 : Op0;
2807         Op1 = DemandedOp1 ? DemandedOp1 : Op1;
2808         SDValue NewOp =
2809             TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Op1, Flags);
2810         return TLO.CombineTo(Op, NewOp);
2811       }
2812     }
2813 
2814     // If we have a constant operand, we may be able to turn it into -1 if we
2815     // do not demand the high bits. This can make the constant smaller to
2816     // encode, allow more general folding, or match specialized instruction
2817     // patterns (eg, 'blsr' on x86). Don't bother changing 1 to -1 because that
2818     // is probably not useful (and could be detrimental).
2819     ConstantSDNode *C = isConstOrConstSplat(Op1);
2820     APInt HighMask = APInt::getHighBitsSet(BitWidth, DemandedBitsLZ);
2821     if (C && !C->isAllOnes() && !C->isOne() &&
2822         (C->getAPIntValue() | HighMask).isAllOnes()) {
2823       SDValue Neg1 = TLO.DAG.getAllOnesConstant(dl, VT);
2824       // Disable the nsw and nuw flags. We can no longer guarantee that we
2825       // won't wrap after simplification.
2826       Flags.setNoSignedWrap(false);
2827       Flags.setNoUnsignedWrap(false);
2828       SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), dl, VT, Op0, Neg1, Flags);
2829       return TLO.CombineTo(Op, NewOp);
2830     }
2831 
2832     // Match a multiply with a disguised negated-power-of-2 and convert to a
2833     // an equivalent shift-left amount.
2834     // Example: (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
2835     auto getShiftLeftAmt = [&HighMask](SDValue Mul) -> unsigned {
2836       if (Mul.getOpcode() != ISD::MUL || !Mul.hasOneUse())
2837         return 0;
2838 
2839       // Don't touch opaque constants. Also, ignore zero and power-of-2
2840       // multiplies. Those will get folded later.
2841       ConstantSDNode *MulC = isConstOrConstSplat(Mul.getOperand(1));
2842       if (MulC && !MulC->isOpaque() && !MulC->isZero() &&
2843           !MulC->getAPIntValue().isPowerOf2()) {
2844         APInt UnmaskedC = MulC->getAPIntValue() | HighMask;
2845         if (UnmaskedC.isNegatedPowerOf2())
2846           return (-UnmaskedC).logBase2();
2847       }
2848       return 0;
2849     };
2850 
2851     auto foldMul = [&](ISD::NodeType NT, SDValue X, SDValue Y, unsigned ShlAmt) {
2852       EVT ShiftAmtTy = getShiftAmountTy(VT, TLO.DAG.getDataLayout());
2853       SDValue ShlAmtC = TLO.DAG.getConstant(ShlAmt, dl, ShiftAmtTy);
2854       SDValue Shl = TLO.DAG.getNode(ISD::SHL, dl, VT, X, ShlAmtC);
2855       SDValue Res = TLO.DAG.getNode(NT, dl, VT, Y, Shl);
2856       return TLO.CombineTo(Op, Res);
2857     };
2858 
2859     if (isOperationLegalOrCustom(ISD::SHL, VT)) {
2860       if (Op.getOpcode() == ISD::ADD) {
2861         // (X * MulC) + Op1 --> Op1 - (X << log2(-MulC))
2862         if (unsigned ShAmt = getShiftLeftAmt(Op0))
2863           return foldMul(ISD::SUB, Op0.getOperand(0), Op1, ShAmt);
2864         // Op0 + (X * MulC) --> Op0 - (X << log2(-MulC))
2865         if (unsigned ShAmt = getShiftLeftAmt(Op1))
2866           return foldMul(ISD::SUB, Op1.getOperand(0), Op0, ShAmt);
2867       }
2868       if (Op.getOpcode() == ISD::SUB) {
2869         // Op0 - (X * MulC) --> Op0 + (X << log2(-MulC))
2870         if (unsigned ShAmt = getShiftLeftAmt(Op1))
2871           return foldMul(ISD::ADD, Op1.getOperand(0), Op0, ShAmt);
2872       }
2873     }
2874 
2875     if (Op.getOpcode() == ISD::MUL) {
2876       Known = KnownBits::mul(KnownOp0, KnownOp1);
2877     } else { // Op.getOpcode() is either ISD::ADD or ISD::SUB.
2878       Known = KnownBits::computeForAddSub(Op.getOpcode() == ISD::ADD,
2879                                           Flags.hasNoSignedWrap(), KnownOp0,
2880                                           KnownOp1);
2881     }
2882     break;
2883   }
2884   default:
2885     // We also ask the target about intrinsics (which could be specific to it).
2886     if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2887         Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
2888       // TODO: Probably okay to remove after audit; here to reduce change size
2889       // in initial enablement patch for scalable vectors
2890       if (Op.getValueType().isScalableVector())
2891         break;
2892       if (SimplifyDemandedBitsForTargetNode(Op, DemandedBits, DemandedElts,
2893                                             Known, TLO, Depth))
2894         return true;
2895       break;
2896     }
2897 
2898     // Just use computeKnownBits to compute output bits.
2899     Known = TLO.DAG.computeKnownBits(Op, DemandedElts, Depth);
2900     break;
2901   }
2902 
2903   // If we know the value of all of the demanded bits, return this as a
2904   // constant.
2905   if (!isTargetCanonicalConstantNode(Op) &&
2906       DemandedBits.isSubsetOf(Known.Zero | Known.One)) {
2907     // Avoid folding to a constant if any OpaqueConstant is involved.
2908     const SDNode *N = Op.getNode();
2909     for (SDNode *Op :
2910          llvm::make_range(SDNodeIterator::begin(N), SDNodeIterator::end(N))) {
2911       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op))
2912         if (C->isOpaque())
2913           return false;
2914     }
2915     if (VT.isInteger())
2916       return TLO.CombineTo(Op, TLO.DAG.getConstant(Known.One, dl, VT));
2917     if (VT.isFloatingPoint())
2918       return TLO.CombineTo(
2919           Op,
2920           TLO.DAG.getConstantFP(
2921               APFloat(TLO.DAG.EVTToAPFloatSemantics(VT), Known.One), dl, VT));
2922   }
2923 
2924   // A multi use 'all demanded elts' simplify failed to find any knownbits.
2925   // Try again just for the original demanded elts.
2926   // Ensure we do this AFTER constant folding above.
2927   if (HasMultiUse && Known.isUnknown() && !OriginalDemandedElts.isAllOnes())
2928     Known = TLO.DAG.computeKnownBits(Op, OriginalDemandedElts, Depth);
2929 
2930   return false;
2931 }
2932 
2933 bool TargetLowering::SimplifyDemandedVectorElts(SDValue Op,
2934                                                 const APInt &DemandedElts,
2935                                                 DAGCombinerInfo &DCI) const {
2936   SelectionDAG &DAG = DCI.DAG;
2937   TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
2938                         !DCI.isBeforeLegalizeOps());
2939 
2940   APInt KnownUndef, KnownZero;
2941   bool Simplified =
2942       SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero, TLO);
2943   if (Simplified) {
2944     DCI.AddToWorklist(Op.getNode());
2945     DCI.CommitTargetLoweringOpt(TLO);
2946   }
2947 
2948   return Simplified;
2949 }
2950 
2951 /// Given a vector binary operation and known undefined elements for each input
2952 /// operand, compute whether each element of the output is undefined.
2953 static APInt getKnownUndefForVectorBinop(SDValue BO, SelectionDAG &DAG,
2954                                          const APInt &UndefOp0,
2955                                          const APInt &UndefOp1) {
2956   EVT VT = BO.getValueType();
2957   assert(DAG.getTargetLoweringInfo().isBinOp(BO.getOpcode()) && VT.isVector() &&
2958          "Vector binop only");
2959 
2960   EVT EltVT = VT.getVectorElementType();
2961   unsigned NumElts = VT.isFixedLengthVector() ? VT.getVectorNumElements() : 1;
2962   assert(UndefOp0.getBitWidth() == NumElts &&
2963          UndefOp1.getBitWidth() == NumElts && "Bad type for undef analysis");
2964 
2965   auto getUndefOrConstantElt = [&](SDValue V, unsigned Index,
2966                                    const APInt &UndefVals) {
2967     if (UndefVals[Index])
2968       return DAG.getUNDEF(EltVT);
2969 
2970     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
2971       // Try hard to make sure that the getNode() call is not creating temporary
2972       // nodes. Ignore opaque integers because they do not constant fold.
2973       SDValue Elt = BV->getOperand(Index);
2974       auto *C = dyn_cast<ConstantSDNode>(Elt);
2975       if (isa<ConstantFPSDNode>(Elt) || Elt.isUndef() || (C && !C->isOpaque()))
2976         return Elt;
2977     }
2978 
2979     return SDValue();
2980   };
2981 
2982   APInt KnownUndef = APInt::getZero(NumElts);
2983   for (unsigned i = 0; i != NumElts; ++i) {
2984     // If both inputs for this element are either constant or undef and match
2985     // the element type, compute the constant/undef result for this element of
2986     // the vector.
2987     // TODO: Ideally we would use FoldConstantArithmetic() here, but that does
2988     // not handle FP constants. The code within getNode() should be refactored
2989     // to avoid the danger of creating a bogus temporary node here.
2990     SDValue C0 = getUndefOrConstantElt(BO.getOperand(0), i, UndefOp0);
2991     SDValue C1 = getUndefOrConstantElt(BO.getOperand(1), i, UndefOp1);
2992     if (C0 && C1 && C0.getValueType() == EltVT && C1.getValueType() == EltVT)
2993       if (DAG.getNode(BO.getOpcode(), SDLoc(BO), EltVT, C0, C1).isUndef())
2994         KnownUndef.setBit(i);
2995   }
2996   return KnownUndef;
2997 }
2998 
2999 bool TargetLowering::SimplifyDemandedVectorElts(
3000     SDValue Op, const APInt &OriginalDemandedElts, APInt &KnownUndef,
3001     APInt &KnownZero, TargetLoweringOpt &TLO, unsigned Depth,
3002     bool AssumeSingleUse) const {
3003   EVT VT = Op.getValueType();
3004   unsigned Opcode = Op.getOpcode();
3005   APInt DemandedElts = OriginalDemandedElts;
3006   unsigned NumElts = DemandedElts.getBitWidth();
3007   assert(VT.isVector() && "Expected vector op");
3008 
3009   KnownUndef = KnownZero = APInt::getZero(NumElts);
3010 
3011   const TargetLowering &TLI = TLO.DAG.getTargetLoweringInfo();
3012   if (!TLI.shouldSimplifyDemandedVectorElts(Op, TLO))
3013     return false;
3014 
3015   // TODO: For now we assume we know nothing about scalable vectors.
3016   if (VT.isScalableVector())
3017     return false;
3018 
3019   assert(VT.getVectorNumElements() == NumElts &&
3020          "Mask size mismatches value type element count!");
3021 
3022   // Undef operand.
3023   if (Op.isUndef()) {
3024     KnownUndef.setAllBits();
3025     return false;
3026   }
3027 
3028   // If Op has other users, assume that all elements are needed.
3029   if (!AssumeSingleUse && !Op.getNode()->hasOneUse())
3030     DemandedElts.setAllBits();
3031 
3032   // Not demanding any elements from Op.
3033   if (DemandedElts == 0) {
3034     KnownUndef.setAllBits();
3035     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3036   }
3037 
3038   // Limit search depth.
3039   if (Depth >= SelectionDAG::MaxRecursionDepth)
3040     return false;
3041 
3042   SDLoc DL(Op);
3043   unsigned EltSizeInBits = VT.getScalarSizeInBits();
3044   bool IsLE = TLO.DAG.getDataLayout().isLittleEndian();
3045 
3046   // Helper for demanding the specified elements and all the bits of both binary
3047   // operands.
3048   auto SimplifyDemandedVectorEltsBinOp = [&](SDValue Op0, SDValue Op1) {
3049     SDValue NewOp0 = SimplifyMultipleUseDemandedVectorElts(Op0, DemandedElts,
3050                                                            TLO.DAG, Depth + 1);
3051     SDValue NewOp1 = SimplifyMultipleUseDemandedVectorElts(Op1, DemandedElts,
3052                                                            TLO.DAG, Depth + 1);
3053     if (NewOp0 || NewOp1) {
3054       SDValue NewOp =
3055           TLO.DAG.getNode(Opcode, SDLoc(Op), VT, NewOp0 ? NewOp0 : Op0,
3056                           NewOp1 ? NewOp1 : Op1, Op->getFlags());
3057       return TLO.CombineTo(Op, NewOp);
3058     }
3059     return false;
3060   };
3061 
3062   switch (Opcode) {
3063   case ISD::SCALAR_TO_VECTOR: {
3064     if (!DemandedElts[0]) {
3065       KnownUndef.setAllBits();
3066       return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3067     }
3068     SDValue ScalarSrc = Op.getOperand(0);
3069     if (ScalarSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
3070       SDValue Src = ScalarSrc.getOperand(0);
3071       SDValue Idx = ScalarSrc.getOperand(1);
3072       EVT SrcVT = Src.getValueType();
3073 
3074       ElementCount SrcEltCnt = SrcVT.getVectorElementCount();
3075 
3076       if (SrcEltCnt.isScalable())
3077         return false;
3078 
3079       unsigned NumSrcElts = SrcEltCnt.getFixedValue();
3080       if (isNullConstant(Idx)) {
3081         APInt SrcDemandedElts = APInt::getOneBitSet(NumSrcElts, 0);
3082         APInt SrcUndef = KnownUndef.zextOrTrunc(NumSrcElts);
3083         APInt SrcZero = KnownZero.zextOrTrunc(NumSrcElts);
3084         if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3085                                        TLO, Depth + 1))
3086           return true;
3087       }
3088     }
3089     KnownUndef.setHighBits(NumElts - 1);
3090     break;
3091   }
3092   case ISD::BITCAST: {
3093     SDValue Src = Op.getOperand(0);
3094     EVT SrcVT = Src.getValueType();
3095 
3096     // We only handle vectors here.
3097     // TODO - investigate calling SimplifyDemandedBits/ComputeKnownBits?
3098     if (!SrcVT.isVector())
3099       break;
3100 
3101     // Fast handling of 'identity' bitcasts.
3102     unsigned NumSrcElts = SrcVT.getVectorNumElements();
3103     if (NumSrcElts == NumElts)
3104       return SimplifyDemandedVectorElts(Src, DemandedElts, KnownUndef,
3105                                         KnownZero, TLO, Depth + 1);
3106 
3107     APInt SrcDemandedElts, SrcZero, SrcUndef;
3108 
3109     // Bitcast from 'large element' src vector to 'small element' vector, we
3110     // must demand a source element if any DemandedElt maps to it.
3111     if ((NumElts % NumSrcElts) == 0) {
3112       unsigned Scale = NumElts / NumSrcElts;
3113       SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3114       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3115                                      TLO, Depth + 1))
3116         return true;
3117 
3118       // Try calling SimplifyDemandedBits, converting demanded elts to the bits
3119       // of the large element.
3120       // TODO - bigendian once we have test coverage.
3121       if (IsLE) {
3122         unsigned SrcEltSizeInBits = SrcVT.getScalarSizeInBits();
3123         APInt SrcDemandedBits = APInt::getZero(SrcEltSizeInBits);
3124         for (unsigned i = 0; i != NumElts; ++i)
3125           if (DemandedElts[i]) {
3126             unsigned Ofs = (i % Scale) * EltSizeInBits;
3127             SrcDemandedBits.setBits(Ofs, Ofs + EltSizeInBits);
3128           }
3129 
3130         KnownBits Known;
3131         if (SimplifyDemandedBits(Src, SrcDemandedBits, SrcDemandedElts, Known,
3132                                  TLO, Depth + 1))
3133           return true;
3134 
3135         // The bitcast has split each wide element into a number of
3136         // narrow subelements. We have just computed the Known bits
3137         // for wide elements. See if element splitting results in
3138         // some subelements being zero. Only for demanded elements!
3139         for (unsigned SubElt = 0; SubElt != Scale; ++SubElt) {
3140           if (!Known.Zero.extractBits(EltSizeInBits, SubElt * EltSizeInBits)
3141                    .isAllOnes())
3142             continue;
3143           for (unsigned SrcElt = 0; SrcElt != NumSrcElts; ++SrcElt) {
3144             unsigned Elt = Scale * SrcElt + SubElt;
3145             if (DemandedElts[Elt])
3146               KnownZero.setBit(Elt);
3147           }
3148         }
3149       }
3150 
3151       // If the src element is zero/undef then all the output elements will be -
3152       // only demanded elements are guaranteed to be correct.
3153       for (unsigned i = 0; i != NumSrcElts; ++i) {
3154         if (SrcDemandedElts[i]) {
3155           if (SrcZero[i])
3156             KnownZero.setBits(i * Scale, (i + 1) * Scale);
3157           if (SrcUndef[i])
3158             KnownUndef.setBits(i * Scale, (i + 1) * Scale);
3159         }
3160       }
3161     }
3162 
3163     // Bitcast from 'small element' src vector to 'large element' vector, we
3164     // demand all smaller source elements covered by the larger demanded element
3165     // of this vector.
3166     if ((NumSrcElts % NumElts) == 0) {
3167       unsigned Scale = NumSrcElts / NumElts;
3168       SrcDemandedElts = APIntOps::ScaleBitMask(DemandedElts, NumSrcElts);
3169       if (SimplifyDemandedVectorElts(Src, SrcDemandedElts, SrcUndef, SrcZero,
3170                                      TLO, Depth + 1))
3171         return true;
3172 
3173       // If all the src elements covering an output element are zero/undef, then
3174       // the output element will be as well, assuming it was demanded.
3175       for (unsigned i = 0; i != NumElts; ++i) {
3176         if (DemandedElts[i]) {
3177           if (SrcZero.extractBits(Scale, i * Scale).isAllOnes())
3178             KnownZero.setBit(i);
3179           if (SrcUndef.extractBits(Scale, i * Scale).isAllOnes())
3180             KnownUndef.setBit(i);
3181         }
3182       }
3183     }
3184     break;
3185   }
3186   case ISD::BUILD_VECTOR: {
3187     // Check all elements and simplify any unused elements with UNDEF.
3188     if (!DemandedElts.isAllOnes()) {
3189       // Don't simplify BROADCASTS.
3190       if (llvm::any_of(Op->op_values(),
3191                        [&](SDValue Elt) { return Op.getOperand(0) != Elt; })) {
3192         SmallVector<SDValue, 32> Ops(Op->op_begin(), Op->op_end());
3193         bool Updated = false;
3194         for (unsigned i = 0; i != NumElts; ++i) {
3195           if (!DemandedElts[i] && !Ops[i].isUndef()) {
3196             Ops[i] = TLO.DAG.getUNDEF(Ops[0].getValueType());
3197             KnownUndef.setBit(i);
3198             Updated = true;
3199           }
3200         }
3201         if (Updated)
3202           return TLO.CombineTo(Op, TLO.DAG.getBuildVector(VT, DL, Ops));
3203       }
3204     }
3205     for (unsigned i = 0; i != NumElts; ++i) {
3206       SDValue SrcOp = Op.getOperand(i);
3207       if (SrcOp.isUndef()) {
3208         KnownUndef.setBit(i);
3209       } else if (EltSizeInBits == SrcOp.getScalarValueSizeInBits() &&
3210                  (isNullConstant(SrcOp) || isNullFPConstant(SrcOp))) {
3211         KnownZero.setBit(i);
3212       }
3213     }
3214     break;
3215   }
3216   case ISD::CONCAT_VECTORS: {
3217     EVT SubVT = Op.getOperand(0).getValueType();
3218     unsigned NumSubVecs = Op.getNumOperands();
3219     unsigned NumSubElts = SubVT.getVectorNumElements();
3220     for (unsigned i = 0; i != NumSubVecs; ++i) {
3221       SDValue SubOp = Op.getOperand(i);
3222       APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3223       APInt SubUndef, SubZero;
3224       if (SimplifyDemandedVectorElts(SubOp, SubElts, SubUndef, SubZero, TLO,
3225                                      Depth + 1))
3226         return true;
3227       KnownUndef.insertBits(SubUndef, i * NumSubElts);
3228       KnownZero.insertBits(SubZero, i * NumSubElts);
3229     }
3230 
3231     // Attempt to avoid multi-use ops if we don't need anything from them.
3232     if (!DemandedElts.isAllOnes()) {
3233       bool FoundNewSub = false;
3234       SmallVector<SDValue, 2> DemandedSubOps;
3235       for (unsigned i = 0; i != NumSubVecs; ++i) {
3236         SDValue SubOp = Op.getOperand(i);
3237         APInt SubElts = DemandedElts.extractBits(NumSubElts, i * NumSubElts);
3238         SDValue NewSubOp = SimplifyMultipleUseDemandedVectorElts(
3239             SubOp, SubElts, TLO.DAG, Depth + 1);
3240         DemandedSubOps.push_back(NewSubOp ? NewSubOp : SubOp);
3241         FoundNewSub = NewSubOp ? true : FoundNewSub;
3242       }
3243       if (FoundNewSub) {
3244         SDValue NewOp =
3245             TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, DemandedSubOps);
3246         return TLO.CombineTo(Op, NewOp);
3247       }
3248     }
3249     break;
3250   }
3251   case ISD::INSERT_SUBVECTOR: {
3252     // Demand any elements from the subvector and the remainder from the src its
3253     // inserted into.
3254     SDValue Src = Op.getOperand(0);
3255     SDValue Sub = Op.getOperand(1);
3256     uint64_t Idx = Op.getConstantOperandVal(2);
3257     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
3258     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
3259     APInt DemandedSrcElts = DemandedElts;
3260     DemandedSrcElts.insertBits(APInt::getZero(NumSubElts), Idx);
3261 
3262     APInt SubUndef, SubZero;
3263     if (SimplifyDemandedVectorElts(Sub, DemandedSubElts, SubUndef, SubZero, TLO,
3264                                    Depth + 1))
3265       return true;
3266 
3267     // If none of the src operand elements are demanded, replace it with undef.
3268     if (!DemandedSrcElts && !Src.isUndef())
3269       return TLO.CombineTo(Op, TLO.DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
3270                                                TLO.DAG.getUNDEF(VT), Sub,
3271                                                Op.getOperand(2)));
3272 
3273     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, KnownUndef, KnownZero,
3274                                    TLO, Depth + 1))
3275       return true;
3276     KnownUndef.insertBits(SubUndef, Idx);
3277     KnownZero.insertBits(SubZero, Idx);
3278 
3279     // Attempt to avoid multi-use ops if we don't need anything from them.
3280     if (!DemandedSrcElts.isAllOnes() || !DemandedSubElts.isAllOnes()) {
3281       SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
3282           Src, DemandedSrcElts, TLO.DAG, Depth + 1);
3283       SDValue NewSub = SimplifyMultipleUseDemandedVectorElts(
3284           Sub, DemandedSubElts, TLO.DAG, Depth + 1);
3285       if (NewSrc || NewSub) {
3286         NewSrc = NewSrc ? NewSrc : Src;
3287         NewSub = NewSub ? NewSub : Sub;
3288         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3289                                         NewSub, Op.getOperand(2));
3290         return TLO.CombineTo(Op, NewOp);
3291       }
3292     }
3293     break;
3294   }
3295   case ISD::EXTRACT_SUBVECTOR: {
3296     // Offset the demanded elts by the subvector index.
3297     SDValue Src = Op.getOperand(0);
3298     if (Src.getValueType().isScalableVector())
3299       break;
3300     uint64_t Idx = Op.getConstantOperandVal(1);
3301     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3302     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts).shl(Idx);
3303 
3304     APInt SrcUndef, SrcZero;
3305     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3306                                    Depth + 1))
3307       return true;
3308     KnownUndef = SrcUndef.extractBits(NumElts, Idx);
3309     KnownZero = SrcZero.extractBits(NumElts, Idx);
3310 
3311     // Attempt to avoid multi-use ops if we don't need anything from them.
3312     if (!DemandedElts.isAllOnes()) {
3313       SDValue NewSrc = SimplifyMultipleUseDemandedVectorElts(
3314           Src, DemandedSrcElts, TLO.DAG, Depth + 1);
3315       if (NewSrc) {
3316         SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, NewSrc,
3317                                         Op.getOperand(1));
3318         return TLO.CombineTo(Op, NewOp);
3319       }
3320     }
3321     break;
3322   }
3323   case ISD::INSERT_VECTOR_ELT: {
3324     SDValue Vec = Op.getOperand(0);
3325     SDValue Scl = Op.getOperand(1);
3326     auto *CIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
3327 
3328     // For a legal, constant insertion index, if we don't need this insertion
3329     // then strip it, else remove it from the demanded elts.
3330     if (CIdx && CIdx->getAPIntValue().ult(NumElts)) {
3331       unsigned Idx = CIdx->getZExtValue();
3332       if (!DemandedElts[Idx])
3333         return TLO.CombineTo(Op, Vec);
3334 
3335       APInt DemandedVecElts(DemandedElts);
3336       DemandedVecElts.clearBit(Idx);
3337       if (SimplifyDemandedVectorElts(Vec, DemandedVecElts, KnownUndef,
3338                                      KnownZero, TLO, Depth + 1))
3339         return true;
3340 
3341       KnownUndef.setBitVal(Idx, Scl.isUndef());
3342 
3343       KnownZero.setBitVal(Idx, isNullConstant(Scl) || isNullFPConstant(Scl));
3344       break;
3345     }
3346 
3347     APInt VecUndef, VecZero;
3348     if (SimplifyDemandedVectorElts(Vec, DemandedElts, VecUndef, VecZero, TLO,
3349                                    Depth + 1))
3350       return true;
3351     // Without knowing the insertion index we can't set KnownUndef/KnownZero.
3352     break;
3353   }
3354   case ISD::VSELECT: {
3355     SDValue Sel = Op.getOperand(0);
3356     SDValue LHS = Op.getOperand(1);
3357     SDValue RHS = Op.getOperand(2);
3358 
3359     // Try to transform the select condition based on the current demanded
3360     // elements.
3361     APInt UndefSel, ZeroSel;
3362     if (SimplifyDemandedVectorElts(Sel, DemandedElts, UndefSel, ZeroSel, TLO,
3363                                    Depth + 1))
3364       return true;
3365 
3366     // See if we can simplify either vselect operand.
3367     APInt DemandedLHS(DemandedElts);
3368     APInt DemandedRHS(DemandedElts);
3369     APInt UndefLHS, ZeroLHS;
3370     APInt UndefRHS, ZeroRHS;
3371     if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3372                                    Depth + 1))
3373       return true;
3374     if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3375                                    Depth + 1))
3376       return true;
3377 
3378     KnownUndef = UndefLHS & UndefRHS;
3379     KnownZero = ZeroLHS & ZeroRHS;
3380 
3381     // If we know that the selected element is always zero, we don't need the
3382     // select value element.
3383     APInt DemandedSel = DemandedElts & ~KnownZero;
3384     if (DemandedSel != DemandedElts)
3385       if (SimplifyDemandedVectorElts(Sel, DemandedSel, UndefSel, ZeroSel, TLO,
3386                                      Depth + 1))
3387         return true;
3388 
3389     break;
3390   }
3391   case ISD::VECTOR_SHUFFLE: {
3392     SDValue LHS = Op.getOperand(0);
3393     SDValue RHS = Op.getOperand(1);
3394     ArrayRef<int> ShuffleMask = cast<ShuffleVectorSDNode>(Op)->getMask();
3395 
3396     // Collect demanded elements from shuffle operands..
3397     APInt DemandedLHS(NumElts, 0);
3398     APInt DemandedRHS(NumElts, 0);
3399     for (unsigned i = 0; i != NumElts; ++i) {
3400       int M = ShuffleMask[i];
3401       if (M < 0 || !DemandedElts[i])
3402         continue;
3403       assert(0 <= M && M < (int)(2 * NumElts) && "Shuffle index out of range");
3404       if (M < (int)NumElts)
3405         DemandedLHS.setBit(M);
3406       else
3407         DemandedRHS.setBit(M - NumElts);
3408     }
3409 
3410     // See if we can simplify either shuffle operand.
3411     APInt UndefLHS, ZeroLHS;
3412     APInt UndefRHS, ZeroRHS;
3413     if (SimplifyDemandedVectorElts(LHS, DemandedLHS, UndefLHS, ZeroLHS, TLO,
3414                                    Depth + 1))
3415       return true;
3416     if (SimplifyDemandedVectorElts(RHS, DemandedRHS, UndefRHS, ZeroRHS, TLO,
3417                                    Depth + 1))
3418       return true;
3419 
3420     // Simplify mask using undef elements from LHS/RHS.
3421     bool Updated = false;
3422     bool IdentityLHS = true, IdentityRHS = true;
3423     SmallVector<int, 32> NewMask(ShuffleMask);
3424     for (unsigned i = 0; i != NumElts; ++i) {
3425       int &M = NewMask[i];
3426       if (M < 0)
3427         continue;
3428       if (!DemandedElts[i] || (M < (int)NumElts && UndefLHS[M]) ||
3429           (M >= (int)NumElts && UndefRHS[M - NumElts])) {
3430         Updated = true;
3431         M = -1;
3432       }
3433       IdentityLHS &= (M < 0) || (M == (int)i);
3434       IdentityRHS &= (M < 0) || ((M - NumElts) == i);
3435     }
3436 
3437     // Update legal shuffle masks based on demanded elements if it won't reduce
3438     // to Identity which can cause premature removal of the shuffle mask.
3439     if (Updated && !IdentityLHS && !IdentityRHS && !TLO.LegalOps) {
3440       SDValue LegalShuffle =
3441           buildLegalVectorShuffle(VT, DL, LHS, RHS, NewMask, TLO.DAG);
3442       if (LegalShuffle)
3443         return TLO.CombineTo(Op, LegalShuffle);
3444     }
3445 
3446     // Propagate undef/zero elements from LHS/RHS.
3447     for (unsigned i = 0; i != NumElts; ++i) {
3448       int M = ShuffleMask[i];
3449       if (M < 0) {
3450         KnownUndef.setBit(i);
3451       } else if (M < (int)NumElts) {
3452         if (UndefLHS[M])
3453           KnownUndef.setBit(i);
3454         if (ZeroLHS[M])
3455           KnownZero.setBit(i);
3456       } else {
3457         if (UndefRHS[M - NumElts])
3458           KnownUndef.setBit(i);
3459         if (ZeroRHS[M - NumElts])
3460           KnownZero.setBit(i);
3461       }
3462     }
3463     break;
3464   }
3465   case ISD::ANY_EXTEND_VECTOR_INREG:
3466   case ISD::SIGN_EXTEND_VECTOR_INREG:
3467   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3468     APInt SrcUndef, SrcZero;
3469     SDValue Src = Op.getOperand(0);
3470     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3471     APInt DemandedSrcElts = DemandedElts.zext(NumSrcElts);
3472     if (SimplifyDemandedVectorElts(Src, DemandedSrcElts, SrcUndef, SrcZero, TLO,
3473                                    Depth + 1))
3474       return true;
3475     KnownZero = SrcZero.zextOrTrunc(NumElts);
3476     KnownUndef = SrcUndef.zextOrTrunc(NumElts);
3477 
3478     if (IsLE && Op.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG &&
3479         Op.getValueSizeInBits() == Src.getValueSizeInBits() &&
3480         DemandedSrcElts == 1) {
3481       // aext - if we just need the bottom element then we can bitcast.
3482       return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Src));
3483     }
3484 
3485     if (Op.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
3486       // zext(undef) upper bits are guaranteed to be zero.
3487       if (DemandedElts.isSubsetOf(KnownUndef))
3488         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3489       KnownUndef.clearAllBits();
3490 
3491       // zext - if we just need the bottom element then we can mask:
3492       // zext(and(x,c)) -> and(x,c') iff the zext is the only user of the and.
3493       if (IsLE && DemandedSrcElts == 1 && Src.getOpcode() == ISD::AND &&
3494           Op->isOnlyUserOf(Src.getNode()) &&
3495           Op.getValueSizeInBits() == Src.getValueSizeInBits()) {
3496         SDLoc DL(Op);
3497         EVT SrcVT = Src.getValueType();
3498         EVT SrcSVT = SrcVT.getScalarType();
3499         SmallVector<SDValue> MaskElts;
3500         MaskElts.push_back(TLO.DAG.getAllOnesConstant(DL, SrcSVT));
3501         MaskElts.append(NumSrcElts - 1, TLO.DAG.getConstant(0, DL, SrcSVT));
3502         SDValue Mask = TLO.DAG.getBuildVector(SrcVT, DL, MaskElts);
3503         if (SDValue Fold = TLO.DAG.FoldConstantArithmetic(
3504                 ISD::AND, DL, SrcVT, {Src.getOperand(1), Mask})) {
3505           Fold = TLO.DAG.getNode(ISD::AND, DL, SrcVT, Src.getOperand(0), Fold);
3506           return TLO.CombineTo(Op, TLO.DAG.getBitcast(VT, Fold));
3507         }
3508       }
3509     }
3510     break;
3511   }
3512 
3513   // TODO: There are more binop opcodes that could be handled here - MIN,
3514   // MAX, saturated math, etc.
3515   case ISD::ADD: {
3516     SDValue Op0 = Op.getOperand(0);
3517     SDValue Op1 = Op.getOperand(1);
3518     if (Op0 == Op1 && Op->isOnlyUserOf(Op0.getNode())) {
3519       APInt UndefLHS, ZeroLHS;
3520       if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3521                                      Depth + 1, /*AssumeSingleUse*/ true))
3522         return true;
3523     }
3524     [[fallthrough]];
3525   }
3526   case ISD::OR:
3527   case ISD::XOR:
3528   case ISD::SUB:
3529   case ISD::FADD:
3530   case ISD::FSUB:
3531   case ISD::FMUL:
3532   case ISD::FDIV:
3533   case ISD::FREM: {
3534     SDValue Op0 = Op.getOperand(0);
3535     SDValue Op1 = Op.getOperand(1);
3536 
3537     APInt UndefRHS, ZeroRHS;
3538     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3539                                    Depth + 1))
3540       return true;
3541     APInt UndefLHS, ZeroLHS;
3542     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3543                                    Depth + 1))
3544       return true;
3545 
3546     KnownZero = ZeroLHS & ZeroRHS;
3547     KnownUndef = getKnownUndefForVectorBinop(Op, TLO.DAG, UndefLHS, UndefRHS);
3548 
3549     // Attempt to avoid multi-use ops if we don't need anything from them.
3550     // TODO - use KnownUndef to relax the demandedelts?
3551     if (!DemandedElts.isAllOnes())
3552       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3553         return true;
3554     break;
3555   }
3556   case ISD::SHL:
3557   case ISD::SRL:
3558   case ISD::SRA:
3559   case ISD::ROTL:
3560   case ISD::ROTR: {
3561     SDValue Op0 = Op.getOperand(0);
3562     SDValue Op1 = Op.getOperand(1);
3563 
3564     APInt UndefRHS, ZeroRHS;
3565     if (SimplifyDemandedVectorElts(Op1, DemandedElts, UndefRHS, ZeroRHS, TLO,
3566                                    Depth + 1))
3567       return true;
3568     APInt UndefLHS, ZeroLHS;
3569     if (SimplifyDemandedVectorElts(Op0, DemandedElts, UndefLHS, ZeroLHS, TLO,
3570                                    Depth + 1))
3571       return true;
3572 
3573     KnownZero = ZeroLHS;
3574     KnownUndef = UndefLHS & UndefRHS; // TODO: use getKnownUndefForVectorBinop?
3575 
3576     // Attempt to avoid multi-use ops if we don't need anything from them.
3577     // TODO - use KnownUndef to relax the demandedelts?
3578     if (!DemandedElts.isAllOnes())
3579       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3580         return true;
3581     break;
3582   }
3583   case ISD::MUL:
3584   case ISD::MULHU:
3585   case ISD::MULHS:
3586   case ISD::AND: {
3587     SDValue Op0 = Op.getOperand(0);
3588     SDValue Op1 = Op.getOperand(1);
3589 
3590     APInt SrcUndef, SrcZero;
3591     if (SimplifyDemandedVectorElts(Op1, DemandedElts, SrcUndef, SrcZero, TLO,
3592                                    Depth + 1))
3593       return true;
3594     // If we know that a demanded element was zero in Op1 we don't need to
3595     // demand it in Op0 - its guaranteed to be zero.
3596     APInt DemandedElts0 = DemandedElts & ~SrcZero;
3597     if (SimplifyDemandedVectorElts(Op0, DemandedElts0, KnownUndef, KnownZero,
3598                                    TLO, Depth + 1))
3599       return true;
3600 
3601     KnownUndef &= DemandedElts0;
3602     KnownZero &= DemandedElts0;
3603 
3604     // If every element pair has a zero/undef then just fold to zero.
3605     // fold (and x, undef) -> 0  /  (and x, 0) -> 0
3606     // fold (mul x, undef) -> 0  /  (mul x, 0) -> 0
3607     if (DemandedElts.isSubsetOf(SrcZero | KnownZero | SrcUndef | KnownUndef))
3608       return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3609 
3610     // If either side has a zero element, then the result element is zero, even
3611     // if the other is an UNDEF.
3612     // TODO: Extend getKnownUndefForVectorBinop to also deal with known zeros
3613     // and then handle 'and' nodes with the rest of the binop opcodes.
3614     KnownZero |= SrcZero;
3615     KnownUndef &= SrcUndef;
3616     KnownUndef &= ~KnownZero;
3617 
3618     // Attempt to avoid multi-use ops if we don't need anything from them.
3619     if (!DemandedElts.isAllOnes())
3620       if (SimplifyDemandedVectorEltsBinOp(Op0, Op1))
3621         return true;
3622     break;
3623   }
3624   case ISD::TRUNCATE:
3625   case ISD::SIGN_EXTEND:
3626   case ISD::ZERO_EXTEND:
3627     if (SimplifyDemandedVectorElts(Op.getOperand(0), DemandedElts, KnownUndef,
3628                                    KnownZero, TLO, Depth + 1))
3629       return true;
3630 
3631     if (Op.getOpcode() == ISD::ZERO_EXTEND) {
3632       // zext(undef) upper bits are guaranteed to be zero.
3633       if (DemandedElts.isSubsetOf(KnownUndef))
3634         return TLO.CombineTo(Op, TLO.DAG.getConstant(0, SDLoc(Op), VT));
3635       KnownUndef.clearAllBits();
3636     }
3637     break;
3638   default: {
3639     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
3640       if (SimplifyDemandedVectorEltsForTargetNode(Op, DemandedElts, KnownUndef,
3641                                                   KnownZero, TLO, Depth))
3642         return true;
3643     } else {
3644       KnownBits Known;
3645       APInt DemandedBits = APInt::getAllOnes(EltSizeInBits);
3646       if (SimplifyDemandedBits(Op, DemandedBits, OriginalDemandedElts, Known,
3647                                TLO, Depth, AssumeSingleUse))
3648         return true;
3649     }
3650     break;
3651   }
3652   }
3653   assert((KnownUndef & KnownZero) == 0 && "Elements flagged as undef AND zero");
3654 
3655   // Constant fold all undef cases.
3656   // TODO: Handle zero cases as well.
3657   if (DemandedElts.isSubsetOf(KnownUndef))
3658     return TLO.CombineTo(Op, TLO.DAG.getUNDEF(VT));
3659 
3660   return false;
3661 }
3662 
3663 /// Determine which of the bits specified in Mask are known to be either zero or
3664 /// one and return them in the Known.
3665 void TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
3666                                                    KnownBits &Known,
3667                                                    const APInt &DemandedElts,
3668                                                    const SelectionDAG &DAG,
3669                                                    unsigned Depth) const {
3670   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3671           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3672           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3673           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3674          "Should use MaskedValueIsZero if you don't know whether Op"
3675          " is a target node!");
3676   Known.resetAll();
3677 }
3678 
3679 void TargetLowering::computeKnownBitsForTargetInstr(
3680     GISelKnownBits &Analysis, Register R, KnownBits &Known,
3681     const APInt &DemandedElts, const MachineRegisterInfo &MRI,
3682     unsigned Depth) const {
3683   Known.resetAll();
3684 }
3685 
3686 void TargetLowering::computeKnownBitsForFrameIndex(
3687   const int FrameIdx, KnownBits &Known, const MachineFunction &MF) const {
3688   // The low bits are known zero if the pointer is aligned.
3689   Known.Zero.setLowBits(Log2(MF.getFrameInfo().getObjectAlign(FrameIdx)));
3690 }
3691 
3692 Align TargetLowering::computeKnownAlignForTargetInstr(
3693   GISelKnownBits &Analysis, Register R, const MachineRegisterInfo &MRI,
3694   unsigned Depth) const {
3695   return Align(1);
3696 }
3697 
3698 /// This method can be implemented by targets that want to expose additional
3699 /// information about sign bits to the DAG Combiner.
3700 unsigned TargetLowering::ComputeNumSignBitsForTargetNode(SDValue Op,
3701                                                          const APInt &,
3702                                                          const SelectionDAG &,
3703                                                          unsigned Depth) const {
3704   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3705           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3706           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3707           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3708          "Should use ComputeNumSignBits if you don't know whether Op"
3709          " is a target node!");
3710   return 1;
3711 }
3712 
3713 unsigned TargetLowering::computeNumSignBitsForTargetInstr(
3714   GISelKnownBits &Analysis, Register R, const APInt &DemandedElts,
3715   const MachineRegisterInfo &MRI, unsigned Depth) const {
3716   return 1;
3717 }
3718 
3719 bool TargetLowering::SimplifyDemandedVectorEltsForTargetNode(
3720     SDValue Op, const APInt &DemandedElts, APInt &KnownUndef, APInt &KnownZero,
3721     TargetLoweringOpt &TLO, unsigned Depth) const {
3722   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3723           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3724           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3725           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3726          "Should use SimplifyDemandedVectorElts if you don't know whether Op"
3727          " is a target node!");
3728   return false;
3729 }
3730 
3731 bool TargetLowering::SimplifyDemandedBitsForTargetNode(
3732     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3733     KnownBits &Known, TargetLoweringOpt &TLO, unsigned Depth) const {
3734   assert((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 SimplifyDemandedBits if you don't know whether Op"
3739          " is a target node!");
3740   computeKnownBitsForTargetNode(Op, Known, DemandedElts, TLO.DAG, Depth);
3741   return false;
3742 }
3743 
3744 SDValue TargetLowering::SimplifyMultipleUseDemandedBitsForTargetNode(
3745     SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
3746     SelectionDAG &DAG, unsigned Depth) const {
3747   assert(
3748       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3749        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3750        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3751        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3752       "Should use SimplifyMultipleUseDemandedBits if you don't know whether Op"
3753       " is a target node!");
3754   return SDValue();
3755 }
3756 
3757 SDValue
3758 TargetLowering::buildLegalVectorShuffle(EVT VT, const SDLoc &DL, SDValue N0,
3759                                         SDValue N1, MutableArrayRef<int> Mask,
3760                                         SelectionDAG &DAG) const {
3761   bool LegalMask = isShuffleMaskLegal(Mask, VT);
3762   if (!LegalMask) {
3763     std::swap(N0, N1);
3764     ShuffleVectorSDNode::commuteMask(Mask);
3765     LegalMask = isShuffleMaskLegal(Mask, VT);
3766   }
3767 
3768   if (!LegalMask)
3769     return SDValue();
3770 
3771   return DAG.getVectorShuffle(VT, DL, N0, N1, Mask);
3772 }
3773 
3774 const Constant *TargetLowering::getTargetConstantFromLoad(LoadSDNode*) const {
3775   return nullptr;
3776 }
3777 
3778 bool TargetLowering::isGuaranteedNotToBeUndefOrPoisonForTargetNode(
3779     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
3780     bool PoisonOnly, unsigned Depth) const {
3781   assert(
3782       (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3783        Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3784        Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3785        Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3786       "Should use isGuaranteedNotToBeUndefOrPoison if you don't know whether Op"
3787       " is a target node!");
3788   return false;
3789 }
3790 
3791 bool TargetLowering::canCreateUndefOrPoisonForTargetNode(
3792     SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
3793     bool PoisonOnly, bool ConsiderFlags, 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 canCreateUndefOrPoison if you don't know whether Op"
3799          " is a target node!");
3800   // Be conservative and return true.
3801   return true;
3802 }
3803 
3804 bool TargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
3805                                                   const SelectionDAG &DAG,
3806                                                   bool SNaN,
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 isKnownNeverNaN if you don't know whether Op"
3813          " is a target node!");
3814   return false;
3815 }
3816 
3817 bool TargetLowering::isSplatValueForTargetNode(SDValue Op,
3818                                                const APInt &DemandedElts,
3819                                                APInt &UndefElts,
3820                                                const SelectionDAG &DAG,
3821                                                unsigned Depth) const {
3822   assert((Op.getOpcode() >= ISD::BUILTIN_OP_END ||
3823           Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
3824           Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
3825           Op.getOpcode() == ISD::INTRINSIC_VOID) &&
3826          "Should use isSplatValue if you don't know whether Op"
3827          " is a target node!");
3828   return false;
3829 }
3830 
3831 // FIXME: Ideally, this would use ISD::isConstantSplatVector(), but that must
3832 // work with truncating build vectors and vectors with elements of less than
3833 // 8 bits.
3834 bool TargetLowering::isConstTrueVal(SDValue N) const {
3835   if (!N)
3836     return false;
3837 
3838   unsigned EltWidth;
3839   APInt CVal;
3840   if (ConstantSDNode *CN = isConstOrConstSplat(N, /*AllowUndefs=*/false,
3841                                                /*AllowTruncation=*/true)) {
3842     CVal = CN->getAPIntValue();
3843     EltWidth = N.getValueType().getScalarSizeInBits();
3844   } else
3845     return false;
3846 
3847   // If this is a truncating splat, truncate the splat value.
3848   // Otherwise, we may fail to match the expected values below.
3849   if (EltWidth < CVal.getBitWidth())
3850     CVal = CVal.trunc(EltWidth);
3851 
3852   switch (getBooleanContents(N.getValueType())) {
3853   case UndefinedBooleanContent:
3854     return CVal[0];
3855   case ZeroOrOneBooleanContent:
3856     return CVal.isOne();
3857   case ZeroOrNegativeOneBooleanContent:
3858     return CVal.isAllOnes();
3859   }
3860 
3861   llvm_unreachable("Invalid boolean contents");
3862 }
3863 
3864 bool TargetLowering::isConstFalseVal(SDValue N) const {
3865   if (!N)
3866     return false;
3867 
3868   const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N);
3869   if (!CN) {
3870     const BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
3871     if (!BV)
3872       return false;
3873 
3874     // Only interested in constant splats, we don't care about undef
3875     // elements in identifying boolean constants and getConstantSplatNode
3876     // returns NULL if all ops are undef;
3877     CN = BV->getConstantSplatNode();
3878     if (!CN)
3879       return false;
3880   }
3881 
3882   if (getBooleanContents(N->getValueType(0)) == UndefinedBooleanContent)
3883     return !CN->getAPIntValue()[0];
3884 
3885   return CN->isZero();
3886 }
3887 
3888 bool TargetLowering::isExtendedTrueVal(const ConstantSDNode *N, EVT VT,
3889                                        bool SExt) const {
3890   if (VT == MVT::i1)
3891     return N->isOne();
3892 
3893   TargetLowering::BooleanContent Cnt = getBooleanContents(VT);
3894   switch (Cnt) {
3895   case TargetLowering::ZeroOrOneBooleanContent:
3896     // An extended value of 1 is always true, unless its original type is i1,
3897     // in which case it will be sign extended to -1.
3898     return (N->isOne() && !SExt) || (SExt && (N->getValueType(0) != MVT::i1));
3899   case TargetLowering::UndefinedBooleanContent:
3900   case TargetLowering::ZeroOrNegativeOneBooleanContent:
3901     return N->isAllOnes() && SExt;
3902   }
3903   llvm_unreachable("Unexpected enumeration.");
3904 }
3905 
3906 /// This helper function of SimplifySetCC tries to optimize the comparison when
3907 /// either operand of the SetCC node is a bitwise-and instruction.
3908 SDValue TargetLowering::foldSetCCWithAnd(EVT VT, SDValue N0, SDValue N1,
3909                                          ISD::CondCode Cond, const SDLoc &DL,
3910                                          DAGCombinerInfo &DCI) const {
3911   if (N1.getOpcode() == ISD::AND && N0.getOpcode() != ISD::AND)
3912     std::swap(N0, N1);
3913 
3914   SelectionDAG &DAG = DCI.DAG;
3915   EVT OpVT = N0.getValueType();
3916   if (N0.getOpcode() != ISD::AND || !OpVT.isInteger() ||
3917       (Cond != ISD::SETEQ && Cond != ISD::SETNE))
3918     return SDValue();
3919 
3920   // (X & Y) != 0 --> zextOrTrunc(X & Y)
3921   // iff everything but LSB is known zero:
3922   if (Cond == ISD::SETNE && isNullConstant(N1) &&
3923       (getBooleanContents(OpVT) == TargetLowering::UndefinedBooleanContent ||
3924        getBooleanContents(OpVT) == TargetLowering::ZeroOrOneBooleanContent)) {
3925     unsigned NumEltBits = OpVT.getScalarSizeInBits();
3926     APInt UpperBits = APInt::getHighBitsSet(NumEltBits, NumEltBits - 1);
3927     if (DAG.MaskedValueIsZero(N0, UpperBits))
3928       return DAG.getBoolExtOrTrunc(N0, DL, VT, OpVT);
3929   }
3930 
3931   // Try to eliminate a power-of-2 mask constant by converting to a signbit
3932   // test in a narrow type that we can truncate to with no cost. Examples:
3933   // (i32 X & 32768) == 0 --> (trunc X to i16) >= 0
3934   // (i32 X & 32768) != 0 --> (trunc X to i16) < 0
3935   // TODO: This conservatively checks for type legality on the source and
3936   //       destination types. That may inhibit optimizations, but it also
3937   //       allows setcc->shift transforms that may be more beneficial.
3938   auto *AndC = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3939   if (AndC && isNullConstant(N1) && AndC->getAPIntValue().isPowerOf2() &&
3940       isTypeLegal(OpVT) && N0.hasOneUse()) {
3941     EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(),
3942                                      AndC->getAPIntValue().getActiveBits());
3943     if (isTruncateFree(OpVT, NarrowVT) && isTypeLegal(NarrowVT)) {
3944       SDValue Trunc = DAG.getZExtOrTrunc(N0.getOperand(0), DL, NarrowVT);
3945       SDValue Zero = DAG.getConstant(0, DL, NarrowVT);
3946       return DAG.getSetCC(DL, VT, Trunc, Zero,
3947                           Cond == ISD::SETEQ ? ISD::SETGE : ISD::SETLT);
3948     }
3949   }
3950 
3951   // Match these patterns in any of their permutations:
3952   // (X & Y) == Y
3953   // (X & Y) != Y
3954   SDValue X, Y;
3955   if (N0.getOperand(0) == N1) {
3956     X = N0.getOperand(1);
3957     Y = N0.getOperand(0);
3958   } else if (N0.getOperand(1) == N1) {
3959     X = N0.getOperand(0);
3960     Y = N0.getOperand(1);
3961   } else {
3962     return SDValue();
3963   }
3964 
3965   // TODO: We should invert (X & Y) eq/ne 0 -> (X & Y) ne/eq Y if
3966   // `isXAndYEqZeroPreferableToXAndYEqY` is false. This is a bit difficult as
3967   // its liable to create and infinite loop.
3968   SDValue Zero = DAG.getConstant(0, DL, OpVT);
3969   if (isXAndYEqZeroPreferableToXAndYEqY(Cond, OpVT) &&
3970       DAG.isKnownToBeAPowerOfTwo(Y)) {
3971     // Simplify X & Y == Y to X & Y != 0 if Y has exactly one bit set.
3972     // Note that where Y is variable and is known to have at most one bit set
3973     // (for example, if it is Z & 1) we cannot do this; the expressions are not
3974     // equivalent when Y == 0.
3975     assert(OpVT.isInteger());
3976     Cond = ISD::getSetCCInverse(Cond, OpVT);
3977     if (DCI.isBeforeLegalizeOps() ||
3978         isCondCodeLegal(Cond, N0.getSimpleValueType()))
3979       return DAG.getSetCC(DL, VT, N0, Zero, Cond);
3980   } else if (N0.hasOneUse() && hasAndNotCompare(Y)) {
3981     // If the target supports an 'and-not' or 'and-complement' logic operation,
3982     // try to use that to make a comparison operation more efficient.
3983     // But don't do this transform if the mask is a single bit because there are
3984     // more efficient ways to deal with that case (for example, 'bt' on x86 or
3985     // 'rlwinm' on PPC).
3986 
3987     // Bail out if the compare operand that we want to turn into a zero is
3988     // already a zero (otherwise, infinite loop).
3989     if (isNullConstant(Y))
3990       return SDValue();
3991 
3992     // Transform this into: ~X & Y == 0.
3993     SDValue NotX = DAG.getNOT(SDLoc(X), X, OpVT);
3994     SDValue NewAnd = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, NotX, Y);
3995     return DAG.getSetCC(DL, VT, NewAnd, Zero, Cond);
3996   }
3997 
3998   return SDValue();
3999 }
4000 
4001 /// There are multiple IR patterns that could be checking whether certain
4002 /// truncation of a signed number would be lossy or not. The pattern which is
4003 /// best at IR level, may not lower optimally. Thus, we want to unfold it.
4004 /// We are looking for the following pattern: (KeptBits is a constant)
4005 ///   (add %x, (1 << (KeptBits-1))) srccond (1 << KeptBits)
4006 /// KeptBits won't be bitwidth(x), that will be constant-folded to true/false.
4007 /// KeptBits also can't be 1, that would have been folded to  %x dstcond 0
4008 /// We will unfold it into the natural trunc+sext pattern:
4009 ///   ((%x << C) a>> C) dstcond %x
4010 /// Where  C = bitwidth(x) - KeptBits  and  C u< bitwidth(x)
4011 SDValue TargetLowering::optimizeSetCCOfSignedTruncationCheck(
4012     EVT SCCVT, SDValue N0, SDValue N1, ISD::CondCode Cond, DAGCombinerInfo &DCI,
4013     const SDLoc &DL) const {
4014   // We must be comparing with a constant.
4015   ConstantSDNode *C1;
4016   if (!(C1 = dyn_cast<ConstantSDNode>(N1)))
4017     return SDValue();
4018 
4019   // N0 should be:  add %x, (1 << (KeptBits-1))
4020   if (N0->getOpcode() != ISD::ADD)
4021     return SDValue();
4022 
4023   // And we must be 'add'ing a constant.
4024   ConstantSDNode *C01;
4025   if (!(C01 = dyn_cast<ConstantSDNode>(N0->getOperand(1))))
4026     return SDValue();
4027 
4028   SDValue X = N0->getOperand(0);
4029   EVT XVT = X.getValueType();
4030 
4031   // Validate constants ...
4032 
4033   APInt I1 = C1->getAPIntValue();
4034 
4035   ISD::CondCode NewCond;
4036   if (Cond == ISD::CondCode::SETULT) {
4037     NewCond = ISD::CondCode::SETEQ;
4038   } else if (Cond == ISD::CondCode::SETULE) {
4039     NewCond = ISD::CondCode::SETEQ;
4040     // But need to 'canonicalize' the constant.
4041     I1 += 1;
4042   } else if (Cond == ISD::CondCode::SETUGT) {
4043     NewCond = ISD::CondCode::SETNE;
4044     // But need to 'canonicalize' the constant.
4045     I1 += 1;
4046   } else if (Cond == ISD::CondCode::SETUGE) {
4047     NewCond = ISD::CondCode::SETNE;
4048   } else
4049     return SDValue();
4050 
4051   APInt I01 = C01->getAPIntValue();
4052 
4053   auto checkConstants = [&I1, &I01]() -> bool {
4054     // Both of them must be power-of-two, and the constant from setcc is bigger.
4055     return I1.ugt(I01) && I1.isPowerOf2() && I01.isPowerOf2();
4056   };
4057 
4058   if (checkConstants()) {
4059     // Great, e.g. got  icmp ult i16 (add i16 %x, 128), 256
4060   } else {
4061     // What if we invert constants? (and the target predicate)
4062     I1.negate();
4063     I01.negate();
4064     assert(XVT.isInteger());
4065     NewCond = getSetCCInverse(NewCond, XVT);
4066     if (!checkConstants())
4067       return SDValue();
4068     // Great, e.g. got  icmp uge i16 (add i16 %x, -128), -256
4069   }
4070 
4071   // They are power-of-two, so which bit is set?
4072   const unsigned KeptBits = I1.logBase2();
4073   const unsigned KeptBitsMinusOne = I01.logBase2();
4074 
4075   // Magic!
4076   if (KeptBits != (KeptBitsMinusOne + 1))
4077     return SDValue();
4078   assert(KeptBits > 0 && KeptBits < XVT.getSizeInBits() && "unreachable");
4079 
4080   // We don't want to do this in every single case.
4081   SelectionDAG &DAG = DCI.DAG;
4082   if (!DAG.getTargetLoweringInfo().shouldTransformSignedTruncationCheck(
4083           XVT, KeptBits))
4084     return SDValue();
4085 
4086   const unsigned MaskedBits = XVT.getSizeInBits() - KeptBits;
4087   assert(MaskedBits > 0 && MaskedBits < XVT.getSizeInBits() && "unreachable");
4088 
4089   // Unfold into:  ((%x << C) a>> C) cond %x
4090   // Where 'cond' will be either 'eq' or 'ne'.
4091   SDValue ShiftAmt = DAG.getConstant(MaskedBits, DL, XVT);
4092   SDValue T0 = DAG.getNode(ISD::SHL, DL, XVT, X, ShiftAmt);
4093   SDValue T1 = DAG.getNode(ISD::SRA, DL, XVT, T0, ShiftAmt);
4094   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, X, NewCond);
4095 
4096   return T2;
4097 }
4098 
4099 // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
4100 SDValue TargetLowering::optimizeSetCCByHoistingAndByConstFromLogicalShift(
4101     EVT SCCVT, SDValue N0, SDValue N1C, ISD::CondCode Cond,
4102     DAGCombinerInfo &DCI, const SDLoc &DL) const {
4103   assert(isConstOrConstSplat(N1C) && isConstOrConstSplat(N1C)->isZero() &&
4104          "Should be a comparison with 0.");
4105   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4106          "Valid only for [in]equality comparisons.");
4107 
4108   unsigned NewShiftOpcode;
4109   SDValue X, C, Y;
4110 
4111   SelectionDAG &DAG = DCI.DAG;
4112   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4113 
4114   // Look for '(C l>>/<< Y)'.
4115   auto Match = [&NewShiftOpcode, &X, &C, &Y, &TLI, &DAG](SDValue V) {
4116     // The shift should be one-use.
4117     if (!V.hasOneUse())
4118       return false;
4119     unsigned OldShiftOpcode = V.getOpcode();
4120     switch (OldShiftOpcode) {
4121     case ISD::SHL:
4122       NewShiftOpcode = ISD::SRL;
4123       break;
4124     case ISD::SRL:
4125       NewShiftOpcode = ISD::SHL;
4126       break;
4127     default:
4128       return false; // must be a logical shift.
4129     }
4130     // We should be shifting a constant.
4131     // FIXME: best to use isConstantOrConstantVector().
4132     C = V.getOperand(0);
4133     ConstantSDNode *CC =
4134         isConstOrConstSplat(C, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4135     if (!CC)
4136       return false;
4137     Y = V.getOperand(1);
4138 
4139     ConstantSDNode *XC =
4140         isConstOrConstSplat(X, /*AllowUndefs=*/true, /*AllowTruncation=*/true);
4141     return TLI.shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
4142         X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG);
4143   };
4144 
4145   // LHS of comparison should be an one-use 'and'.
4146   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
4147     return SDValue();
4148 
4149   X = N0.getOperand(0);
4150   SDValue Mask = N0.getOperand(1);
4151 
4152   // 'and' is commutative!
4153   if (!Match(Mask)) {
4154     std::swap(X, Mask);
4155     if (!Match(Mask))
4156       return SDValue();
4157   }
4158 
4159   EVT VT = X.getValueType();
4160 
4161   // Produce:
4162   // ((X 'OppositeShiftOpcode' Y) & C) Cond 0
4163   SDValue T0 = DAG.getNode(NewShiftOpcode, DL, VT, X, Y);
4164   SDValue T1 = DAG.getNode(ISD::AND, DL, VT, T0, C);
4165   SDValue T2 = DAG.getSetCC(DL, SCCVT, T1, N1C, Cond);
4166   return T2;
4167 }
4168 
4169 /// Try to fold an equality comparison with a {add/sub/xor} binary operation as
4170 /// the 1st operand (N0). Callers are expected to swap the N0/N1 parameters to
4171 /// handle the commuted versions of these patterns.
4172 SDValue TargetLowering::foldSetCCWithBinOp(EVT VT, SDValue N0, SDValue N1,
4173                                            ISD::CondCode Cond, const SDLoc &DL,
4174                                            DAGCombinerInfo &DCI) const {
4175   unsigned BOpcode = N0.getOpcode();
4176   assert((BOpcode == ISD::ADD || BOpcode == ISD::SUB || BOpcode == ISD::XOR) &&
4177          "Unexpected binop");
4178   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) && "Unexpected condcode");
4179 
4180   // (X + Y) == X --> Y == 0
4181   // (X - Y) == X --> Y == 0
4182   // (X ^ Y) == X --> Y == 0
4183   SelectionDAG &DAG = DCI.DAG;
4184   EVT OpVT = N0.getValueType();
4185   SDValue X = N0.getOperand(0);
4186   SDValue Y = N0.getOperand(1);
4187   if (X == N1)
4188     return DAG.getSetCC(DL, VT, Y, DAG.getConstant(0, DL, OpVT), Cond);
4189 
4190   if (Y != N1)
4191     return SDValue();
4192 
4193   // (X + Y) == Y --> X == 0
4194   // (X ^ Y) == Y --> X == 0
4195   if (BOpcode == ISD::ADD || BOpcode == ISD::XOR)
4196     return DAG.getSetCC(DL, VT, X, DAG.getConstant(0, DL, OpVT), Cond);
4197 
4198   // The shift would not be valid if the operands are boolean (i1).
4199   if (!N0.hasOneUse() || OpVT.getScalarSizeInBits() == 1)
4200     return SDValue();
4201 
4202   // (X - Y) == Y --> X == Y << 1
4203   EVT ShiftVT = getShiftAmountTy(OpVT, DAG.getDataLayout(),
4204                                  !DCI.isBeforeLegalize());
4205   SDValue One = DAG.getConstant(1, DL, ShiftVT);
4206   SDValue YShl1 = DAG.getNode(ISD::SHL, DL, N1.getValueType(), Y, One);
4207   if (!DCI.isCalledByLegalizer())
4208     DCI.AddToWorklist(YShl1.getNode());
4209   return DAG.getSetCC(DL, VT, X, YShl1, Cond);
4210 }
4211 
4212 static SDValue simplifySetCCWithCTPOP(const TargetLowering &TLI, EVT VT,
4213                                       SDValue N0, const APInt &C1,
4214                                       ISD::CondCode Cond, const SDLoc &dl,
4215                                       SelectionDAG &DAG) {
4216   // Look through truncs that don't change the value of a ctpop.
4217   // FIXME: Add vector support? Need to be careful with setcc result type below.
4218   SDValue CTPOP = N0;
4219   if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() && !VT.isVector() &&
4220       N0.getScalarValueSizeInBits() > Log2_32(N0.getOperand(0).getScalarValueSizeInBits()))
4221     CTPOP = N0.getOperand(0);
4222 
4223   if (CTPOP.getOpcode() != ISD::CTPOP || !CTPOP.hasOneUse())
4224     return SDValue();
4225 
4226   EVT CTVT = CTPOP.getValueType();
4227   SDValue CTOp = CTPOP.getOperand(0);
4228 
4229   // Expand a power-of-2-or-zero comparison based on ctpop:
4230   // (ctpop x) u< 2 -> (x & x-1) == 0
4231   // (ctpop x) u> 1 -> (x & x-1) != 0
4232   if (Cond == ISD::SETULT || Cond == ISD::SETUGT) {
4233     // Keep the CTPOP if it is a cheap vector op.
4234     if (CTVT.isVector() && TLI.isCtpopFast(CTVT))
4235       return SDValue();
4236 
4237     unsigned CostLimit = TLI.getCustomCtpopCost(CTVT, Cond);
4238     if (C1.ugt(CostLimit + (Cond == ISD::SETULT)))
4239       return SDValue();
4240     if (C1 == 0 && (Cond == ISD::SETULT))
4241       return SDValue(); // This is handled elsewhere.
4242 
4243     unsigned Passes = C1.getLimitedValue() - (Cond == ISD::SETULT);
4244 
4245     SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4246     SDValue Result = CTOp;
4247     for (unsigned i = 0; i < Passes; i++) {
4248       SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, Result, NegOne);
4249       Result = DAG.getNode(ISD::AND, dl, CTVT, Result, Add);
4250     }
4251     ISD::CondCode CC = Cond == ISD::SETULT ? ISD::SETEQ : ISD::SETNE;
4252     return DAG.getSetCC(dl, VT, Result, DAG.getConstant(0, dl, CTVT), CC);
4253   }
4254 
4255   // Expand a power-of-2 comparison based on ctpop
4256   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) && C1 == 1) {
4257     // Keep the CTPOP if it is cheap.
4258     if (TLI.isCtpopFast(CTVT))
4259       return SDValue();
4260 
4261     SDValue Zero = DAG.getConstant(0, dl, CTVT);
4262     SDValue NegOne = DAG.getAllOnesConstant(dl, CTVT);
4263     assert(CTVT.isInteger());
4264     SDValue Add = DAG.getNode(ISD::ADD, dl, CTVT, CTOp, NegOne);
4265 
4266     // Its not uncommon for known-never-zero X to exist in (ctpop X) eq/ne 1, so
4267     // check before emitting a potentially unnecessary op.
4268     if (DAG.isKnownNeverZero(CTOp)) {
4269       // (ctpop x) == 1 --> (x & x-1) == 0
4270       // (ctpop x) != 1 --> (x & x-1) != 0
4271       SDValue And = DAG.getNode(ISD::AND, dl, CTVT, CTOp, Add);
4272       SDValue RHS = DAG.getSetCC(dl, VT, And, Zero, Cond);
4273       return RHS;
4274     }
4275 
4276     // (ctpop x) == 1 --> (x ^ x-1) >  x-1
4277     // (ctpop x) != 1 --> (x ^ x-1) <= x-1
4278     SDValue Xor = DAG.getNode(ISD::XOR, dl, CTVT, CTOp, Add);
4279     ISD::CondCode CmpCond = Cond == ISD::SETEQ ? ISD::SETUGT : ISD::SETULE;
4280     return DAG.getSetCC(dl, VT, Xor, Add, CmpCond);
4281   }
4282 
4283   return SDValue();
4284 }
4285 
4286 static SDValue foldSetCCWithRotate(EVT VT, SDValue N0, SDValue N1,
4287                                    ISD::CondCode Cond, const SDLoc &dl,
4288                                    SelectionDAG &DAG) {
4289   if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4290     return SDValue();
4291 
4292   auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
4293   if (!C1 || !(C1->isZero() || C1->isAllOnes()))
4294     return SDValue();
4295 
4296   auto getRotateSource = [](SDValue X) {
4297     if (X.getOpcode() == ISD::ROTL || X.getOpcode() == ISD::ROTR)
4298       return X.getOperand(0);
4299     return SDValue();
4300   };
4301 
4302   // Peek through a rotated value compared against 0 or -1:
4303   // (rot X, Y) == 0/-1 --> X == 0/-1
4304   // (rot X, Y) != 0/-1 --> X != 0/-1
4305   if (SDValue R = getRotateSource(N0))
4306     return DAG.getSetCC(dl, VT, R, N1, Cond);
4307 
4308   // Peek through an 'or' of a rotated value compared against 0:
4309   // or (rot X, Y), Z ==/!= 0 --> (or X, Z) ==/!= 0
4310   // or Z, (rot X, Y) ==/!= 0 --> (or X, Z) ==/!= 0
4311   //
4312   // TODO: Add the 'and' with -1 sibling.
4313   // TODO: Recurse through a series of 'or' ops to find the rotate.
4314   EVT OpVT = N0.getValueType();
4315   if (N0.hasOneUse() && N0.getOpcode() == ISD::OR && C1->isZero()) {
4316     if (SDValue R = getRotateSource(N0.getOperand(0))) {
4317       SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(1));
4318       return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4319     }
4320     if (SDValue R = getRotateSource(N0.getOperand(1))) {
4321       SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, R, N0.getOperand(0));
4322       return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4323     }
4324   }
4325 
4326   return SDValue();
4327 }
4328 
4329 static SDValue foldSetCCWithFunnelShift(EVT VT, SDValue N0, SDValue N1,
4330                                         ISD::CondCode Cond, const SDLoc &dl,
4331                                         SelectionDAG &DAG) {
4332   // If we are testing for all-bits-clear, we might be able to do that with
4333   // less shifting since bit-order does not matter.
4334   if (Cond != ISD::SETEQ && Cond != ISD::SETNE)
4335     return SDValue();
4336 
4337   auto *C1 = isConstOrConstSplat(N1, /* AllowUndefs */ true);
4338   if (!C1 || !C1->isZero())
4339     return SDValue();
4340 
4341   if (!N0.hasOneUse() ||
4342       (N0.getOpcode() != ISD::FSHL && N0.getOpcode() != ISD::FSHR))
4343     return SDValue();
4344 
4345   unsigned BitWidth = N0.getScalarValueSizeInBits();
4346   auto *ShAmtC = isConstOrConstSplat(N0.getOperand(2));
4347   if (!ShAmtC || ShAmtC->getAPIntValue().uge(BitWidth))
4348     return SDValue();
4349 
4350   // Canonicalize fshr as fshl to reduce pattern-matching.
4351   unsigned ShAmt = ShAmtC->getZExtValue();
4352   if (N0.getOpcode() == ISD::FSHR)
4353     ShAmt = BitWidth - ShAmt;
4354 
4355   // Match an 'or' with a specific operand 'Other' in either commuted variant.
4356   SDValue X, Y;
4357   auto matchOr = [&X, &Y](SDValue Or, SDValue Other) {
4358     if (Or.getOpcode() != ISD::OR || !Or.hasOneUse())
4359       return false;
4360     if (Or.getOperand(0) == Other) {
4361       X = Or.getOperand(0);
4362       Y = Or.getOperand(1);
4363       return true;
4364     }
4365     if (Or.getOperand(1) == Other) {
4366       X = Or.getOperand(1);
4367       Y = Or.getOperand(0);
4368       return true;
4369     }
4370     return false;
4371   };
4372 
4373   EVT OpVT = N0.getValueType();
4374   EVT ShAmtVT = N0.getOperand(2).getValueType();
4375   SDValue F0 = N0.getOperand(0);
4376   SDValue F1 = N0.getOperand(1);
4377   if (matchOr(F0, F1)) {
4378     // fshl (or X, Y), X, C ==/!= 0 --> or (shl Y, C), X ==/!= 0
4379     SDValue NewShAmt = DAG.getConstant(ShAmt, dl, ShAmtVT);
4380     SDValue Shift = DAG.getNode(ISD::SHL, dl, OpVT, Y, NewShAmt);
4381     SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4382     return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4383   }
4384   if (matchOr(F1, F0)) {
4385     // fshl X, (or X, Y), C ==/!= 0 --> or (srl Y, BW-C), X ==/!= 0
4386     SDValue NewShAmt = DAG.getConstant(BitWidth - ShAmt, dl, ShAmtVT);
4387     SDValue Shift = DAG.getNode(ISD::SRL, dl, OpVT, Y, NewShAmt);
4388     SDValue NewOr = DAG.getNode(ISD::OR, dl, OpVT, Shift, X);
4389     return DAG.getSetCC(dl, VT, NewOr, N1, Cond);
4390   }
4391 
4392   return SDValue();
4393 }
4394 
4395 /// Try to simplify a setcc built with the specified operands and cc. If it is
4396 /// unable to simplify it, return a null SDValue.
4397 SDValue TargetLowering::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
4398                                       ISD::CondCode Cond, bool foldBooleans,
4399                                       DAGCombinerInfo &DCI,
4400                                       const SDLoc &dl) const {
4401   SelectionDAG &DAG = DCI.DAG;
4402   const DataLayout &Layout = DAG.getDataLayout();
4403   EVT OpVT = N0.getValueType();
4404   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
4405 
4406   // Constant fold or commute setcc.
4407   if (SDValue Fold = DAG.FoldSetCC(VT, N0, N1, Cond, dl))
4408     return Fold;
4409 
4410   bool N0ConstOrSplat =
4411       isConstOrConstSplat(N0, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
4412   bool N1ConstOrSplat =
4413       isConstOrConstSplat(N1, /*AllowUndefs*/ false, /*AllowTruncate*/ true);
4414 
4415   // Canonicalize toward having the constant on the RHS.
4416   // TODO: Handle non-splat vector constants. All undef causes trouble.
4417   // FIXME: We can't yet fold constant scalable vector splats, so avoid an
4418   // infinite loop here when we encounter one.
4419   ISD::CondCode SwappedCC = ISD::getSetCCSwappedOperands(Cond);
4420   if (N0ConstOrSplat && !N1ConstOrSplat &&
4421       (DCI.isBeforeLegalizeOps() ||
4422        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())))
4423     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
4424 
4425   // If we have a subtract with the same 2 non-constant operands as this setcc
4426   // -- but in reverse order -- then try to commute the operands of this setcc
4427   // to match. A matching pair of setcc (cmp) and sub may be combined into 1
4428   // instruction on some targets.
4429   if (!N0ConstOrSplat && !N1ConstOrSplat &&
4430       (DCI.isBeforeLegalizeOps() ||
4431        isCondCodeLegal(SwappedCC, N0.getSimpleValueType())) &&
4432       DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N1, N0}) &&
4433       !DAG.doesNodeExist(ISD::SUB, DAG.getVTList(OpVT), {N0, N1}))
4434     return DAG.getSetCC(dl, VT, N1, N0, SwappedCC);
4435 
4436   if (SDValue V = foldSetCCWithRotate(VT, N0, N1, Cond, dl, DAG))
4437     return V;
4438 
4439   if (SDValue V = foldSetCCWithFunnelShift(VT, N0, N1, Cond, dl, DAG))
4440     return V;
4441 
4442   if (auto *N1C = isConstOrConstSplat(N1)) {
4443     const APInt &C1 = N1C->getAPIntValue();
4444 
4445     // Optimize some CTPOP cases.
4446     if (SDValue V = simplifySetCCWithCTPOP(*this, VT, N0, C1, Cond, dl, DAG))
4447       return V;
4448 
4449     // For equality to 0 of a no-wrap multiply, decompose and test each op:
4450     // X * Y == 0 --> (X == 0) || (Y == 0)
4451     // X * Y != 0 --> (X != 0) && (Y != 0)
4452     // TODO: This bails out if minsize is set, but if the target doesn't have a
4453     //       single instruction multiply for this type, it would likely be
4454     //       smaller to decompose.
4455     if (C1.isZero() && (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4456         N0.getOpcode() == ISD::MUL && N0.hasOneUse() &&
4457         (N0->getFlags().hasNoUnsignedWrap() ||
4458          N0->getFlags().hasNoSignedWrap()) &&
4459         !Attr.hasFnAttr(Attribute::MinSize)) {
4460       SDValue IsXZero = DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
4461       SDValue IsYZero = DAG.getSetCC(dl, VT, N0.getOperand(1), N1, Cond);
4462       unsigned LogicOp = Cond == ISD::SETEQ ? ISD::OR : ISD::AND;
4463       return DAG.getNode(LogicOp, dl, VT, IsXZero, IsYZero);
4464     }
4465 
4466     // If the LHS is '(srl (ctlz x), 5)', the RHS is 0/1, and this is an
4467     // equality comparison, then we're just comparing whether X itself is
4468     // zero.
4469     if (N0.getOpcode() == ISD::SRL && (C1.isZero() || C1.isOne()) &&
4470         N0.getOperand(0).getOpcode() == ISD::CTLZ &&
4471         llvm::has_single_bit<uint32_t>(N0.getScalarValueSizeInBits())) {
4472       if (ConstantSDNode *ShAmt = isConstOrConstSplat(N0.getOperand(1))) {
4473         if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4474             ShAmt->getAPIntValue() == Log2_32(N0.getScalarValueSizeInBits())) {
4475           if ((C1 == 0) == (Cond == ISD::SETEQ)) {
4476             // (srl (ctlz x), 5) == 0  -> X != 0
4477             // (srl (ctlz x), 5) != 1  -> X != 0
4478             Cond = ISD::SETNE;
4479           } else {
4480             // (srl (ctlz x), 5) != 0  -> X == 0
4481             // (srl (ctlz x), 5) == 1  -> X == 0
4482             Cond = ISD::SETEQ;
4483           }
4484           SDValue Zero = DAG.getConstant(0, dl, N0.getValueType());
4485           return DAG.getSetCC(dl, VT, N0.getOperand(0).getOperand(0), Zero,
4486                               Cond);
4487         }
4488       }
4489     }
4490   }
4491 
4492   // FIXME: Support vectors.
4493   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
4494     const APInt &C1 = N1C->getAPIntValue();
4495 
4496     // (zext x) == C --> x == (trunc C)
4497     // (sext x) == C --> x == (trunc C)
4498     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4499         DCI.isBeforeLegalize() && N0->hasOneUse()) {
4500       unsigned MinBits = N0.getValueSizeInBits();
4501       SDValue PreExt;
4502       bool Signed = false;
4503       if (N0->getOpcode() == ISD::ZERO_EXTEND) {
4504         // ZExt
4505         MinBits = N0->getOperand(0).getValueSizeInBits();
4506         PreExt = N0->getOperand(0);
4507       } else if (N0->getOpcode() == ISD::AND) {
4508         // DAGCombine turns costly ZExts into ANDs
4509         if (auto *C = dyn_cast<ConstantSDNode>(N0->getOperand(1)))
4510           if ((C->getAPIntValue()+1).isPowerOf2()) {
4511             MinBits = C->getAPIntValue().countr_one();
4512             PreExt = N0->getOperand(0);
4513           }
4514       } else if (N0->getOpcode() == ISD::SIGN_EXTEND) {
4515         // SExt
4516         MinBits = N0->getOperand(0).getValueSizeInBits();
4517         PreExt = N0->getOperand(0);
4518         Signed = true;
4519       } else if (auto *LN0 = dyn_cast<LoadSDNode>(N0)) {
4520         // ZEXTLOAD / SEXTLOAD
4521         if (LN0->getExtensionType() == ISD::ZEXTLOAD) {
4522           MinBits = LN0->getMemoryVT().getSizeInBits();
4523           PreExt = N0;
4524         } else if (LN0->getExtensionType() == ISD::SEXTLOAD) {
4525           Signed = true;
4526           MinBits = LN0->getMemoryVT().getSizeInBits();
4527           PreExt = N0;
4528         }
4529       }
4530 
4531       // Figure out how many bits we need to preserve this constant.
4532       unsigned ReqdBits = Signed ? C1.getSignificantBits() : C1.getActiveBits();
4533 
4534       // Make sure we're not losing bits from the constant.
4535       if (MinBits > 0 &&
4536           MinBits < C1.getBitWidth() &&
4537           MinBits >= ReqdBits) {
4538         EVT MinVT = EVT::getIntegerVT(*DAG.getContext(), MinBits);
4539         if (isTypeDesirableForOp(ISD::SETCC, MinVT)) {
4540           // Will get folded away.
4541           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MinVT, PreExt);
4542           if (MinBits == 1 && C1 == 1)
4543             // Invert the condition.
4544             return DAG.getSetCC(dl, VT, Trunc, DAG.getConstant(0, dl, MVT::i1),
4545                                 Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4546           SDValue C = DAG.getConstant(C1.trunc(MinBits), dl, MinVT);
4547           return DAG.getSetCC(dl, VT, Trunc, C, Cond);
4548         }
4549 
4550         // If truncating the setcc operands is not desirable, we can still
4551         // simplify the expression in some cases:
4552         // setcc ([sz]ext (setcc x, y, cc)), 0, setne) -> setcc (x, y, cc)
4553         // setcc ([sz]ext (setcc x, y, cc)), 0, seteq) -> setcc (x, y, inv(cc))
4554         // setcc (zext (setcc x, y, cc)), 1, setne) -> setcc (x, y, inv(cc))
4555         // setcc (zext (setcc x, y, cc)), 1, seteq) -> setcc (x, y, cc)
4556         // setcc (sext (setcc x, y, cc)), -1, setne) -> setcc (x, y, inv(cc))
4557         // setcc (sext (setcc x, y, cc)), -1, seteq) -> setcc (x, y, cc)
4558         SDValue TopSetCC = N0->getOperand(0);
4559         unsigned N0Opc = N0->getOpcode();
4560         bool SExt = (N0Opc == ISD::SIGN_EXTEND);
4561         if (TopSetCC.getValueType() == MVT::i1 && VT == MVT::i1 &&
4562             TopSetCC.getOpcode() == ISD::SETCC &&
4563             (N0Opc == ISD::ZERO_EXTEND || N0Opc == ISD::SIGN_EXTEND) &&
4564             (isConstFalseVal(N1) ||
4565              isExtendedTrueVal(N1C, N0->getValueType(0), SExt))) {
4566 
4567           bool Inverse = (N1C->isZero() && Cond == ISD::SETEQ) ||
4568                          (!N1C->isZero() && Cond == ISD::SETNE);
4569 
4570           if (!Inverse)
4571             return TopSetCC;
4572 
4573           ISD::CondCode InvCond = ISD::getSetCCInverse(
4574               cast<CondCodeSDNode>(TopSetCC.getOperand(2))->get(),
4575               TopSetCC.getOperand(0).getValueType());
4576           return DAG.getSetCC(dl, VT, TopSetCC.getOperand(0),
4577                                       TopSetCC.getOperand(1),
4578                                       InvCond);
4579         }
4580       }
4581     }
4582 
4583     // If the LHS is '(and load, const)', the RHS is 0, the test is for
4584     // equality or unsigned, and all 1 bits of the const are in the same
4585     // partial word, see if we can shorten the load.
4586     if (DCI.isBeforeLegalize() &&
4587         !ISD::isSignedIntSetCC(Cond) &&
4588         N0.getOpcode() == ISD::AND && C1 == 0 &&
4589         N0.getNode()->hasOneUse() &&
4590         isa<LoadSDNode>(N0.getOperand(0)) &&
4591         N0.getOperand(0).getNode()->hasOneUse() &&
4592         isa<ConstantSDNode>(N0.getOperand(1))) {
4593       LoadSDNode *Lod = cast<LoadSDNode>(N0.getOperand(0));
4594       APInt bestMask;
4595       unsigned bestWidth = 0, bestOffset = 0;
4596       if (Lod->isSimple() && Lod->isUnindexed()) {
4597         unsigned origWidth = N0.getValueSizeInBits();
4598         unsigned maskWidth = origWidth;
4599         // We can narrow (e.g.) 16-bit extending loads on 32-bit target to
4600         // 8 bits, but have to be careful...
4601         if (Lod->getExtensionType() != ISD::NON_EXTLOAD)
4602           origWidth = Lod->getMemoryVT().getSizeInBits();
4603         const APInt &Mask = N0.getConstantOperandAPInt(1);
4604         for (unsigned width = origWidth / 2; width>=8; width /= 2) {
4605           APInt newMask = APInt::getLowBitsSet(maskWidth, width);
4606           for (unsigned offset=0; offset<origWidth/width; offset++) {
4607             if (Mask.isSubsetOf(newMask)) {
4608               if (Layout.isLittleEndian())
4609                 bestOffset = (uint64_t)offset * (width/8);
4610               else
4611                 bestOffset = (origWidth/width - offset - 1) * (width/8);
4612               bestMask = Mask.lshr(offset * (width/8) * 8);
4613               bestWidth = width;
4614               break;
4615             }
4616             newMask <<= width;
4617           }
4618         }
4619       }
4620       if (bestWidth) {
4621         EVT newVT = EVT::getIntegerVT(*DAG.getContext(), bestWidth);
4622         if (newVT.isRound() &&
4623             shouldReduceLoadWidth(Lod, ISD::NON_EXTLOAD, newVT)) {
4624           SDValue Ptr = Lod->getBasePtr();
4625           if (bestOffset != 0)
4626             Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::getFixed(bestOffset),
4627                                            dl);
4628           SDValue NewLoad =
4629               DAG.getLoad(newVT, dl, Lod->getChain(), Ptr,
4630                           Lod->getPointerInfo().getWithOffset(bestOffset),
4631                           Lod->getOriginalAlign());
4632           return DAG.getSetCC(dl, VT,
4633                               DAG.getNode(ISD::AND, dl, newVT, NewLoad,
4634                                       DAG.getConstant(bestMask.trunc(bestWidth),
4635                                                       dl, newVT)),
4636                               DAG.getConstant(0LL, dl, newVT), Cond);
4637         }
4638       }
4639     }
4640 
4641     // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
4642     if (N0.getOpcode() == ISD::ZERO_EXTEND) {
4643       unsigned InSize = N0.getOperand(0).getValueSizeInBits();
4644 
4645       // If the comparison constant has bits in the upper part, the
4646       // zero-extended value could never match.
4647       if (C1.intersects(APInt::getHighBitsSet(C1.getBitWidth(),
4648                                               C1.getBitWidth() - InSize))) {
4649         switch (Cond) {
4650         case ISD::SETUGT:
4651         case ISD::SETUGE:
4652         case ISD::SETEQ:
4653           return DAG.getConstant(0, dl, VT);
4654         case ISD::SETULT:
4655         case ISD::SETULE:
4656         case ISD::SETNE:
4657           return DAG.getConstant(1, dl, VT);
4658         case ISD::SETGT:
4659         case ISD::SETGE:
4660           // True if the sign bit of C1 is set.
4661           return DAG.getConstant(C1.isNegative(), dl, VT);
4662         case ISD::SETLT:
4663         case ISD::SETLE:
4664           // True if the sign bit of C1 isn't set.
4665           return DAG.getConstant(C1.isNonNegative(), dl, VT);
4666         default:
4667           break;
4668         }
4669       }
4670 
4671       // Otherwise, we can perform the comparison with the low bits.
4672       switch (Cond) {
4673       case ISD::SETEQ:
4674       case ISD::SETNE:
4675       case ISD::SETUGT:
4676       case ISD::SETUGE:
4677       case ISD::SETULT:
4678       case ISD::SETULE: {
4679         EVT newVT = N0.getOperand(0).getValueType();
4680         if (DCI.isBeforeLegalizeOps() ||
4681             (isOperationLegal(ISD::SETCC, newVT) &&
4682              isCondCodeLegal(Cond, newVT.getSimpleVT()))) {
4683           EVT NewSetCCVT = getSetCCResultType(Layout, *DAG.getContext(), newVT);
4684           SDValue NewConst = DAG.getConstant(C1.trunc(InSize), dl, newVT);
4685 
4686           SDValue NewSetCC = DAG.getSetCC(dl, NewSetCCVT, N0.getOperand(0),
4687                                           NewConst, Cond);
4688           return DAG.getBoolExtOrTrunc(NewSetCC, dl, VT, N0.getValueType());
4689         }
4690         break;
4691       }
4692       default:
4693         break; // todo, be more careful with signed comparisons
4694       }
4695     } else if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4696                (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4697                !isSExtCheaperThanZExt(cast<VTSDNode>(N0.getOperand(1))->getVT(),
4698                                       OpVT)) {
4699       EVT ExtSrcTy = cast<VTSDNode>(N0.getOperand(1))->getVT();
4700       unsigned ExtSrcTyBits = ExtSrcTy.getSizeInBits();
4701       EVT ExtDstTy = N0.getValueType();
4702       unsigned ExtDstTyBits = ExtDstTy.getSizeInBits();
4703 
4704       // If the constant doesn't fit into the number of bits for the source of
4705       // the sign extension, it is impossible for both sides to be equal.
4706       if (C1.getSignificantBits() > ExtSrcTyBits)
4707         return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
4708 
4709       assert(ExtDstTy == N0.getOperand(0).getValueType() &&
4710              ExtDstTy != ExtSrcTy && "Unexpected types!");
4711       APInt Imm = APInt::getLowBitsSet(ExtDstTyBits, ExtSrcTyBits);
4712       SDValue ZextOp = DAG.getNode(ISD::AND, dl, ExtDstTy, N0.getOperand(0),
4713                                    DAG.getConstant(Imm, dl, ExtDstTy));
4714       if (!DCI.isCalledByLegalizer())
4715         DCI.AddToWorklist(ZextOp.getNode());
4716       // Otherwise, make this a use of a zext.
4717       return DAG.getSetCC(dl, VT, ZextOp,
4718                           DAG.getConstant(C1 & Imm, dl, ExtDstTy), Cond);
4719     } else if ((N1C->isZero() || N1C->isOne()) &&
4720                (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4721       // SETCC (SETCC), [0|1], [EQ|NE]  -> SETCC
4722       if (N0.getOpcode() == ISD::SETCC &&
4723           isTypeLegal(VT) && VT.bitsLE(N0.getValueType()) &&
4724           (N0.getValueType() == MVT::i1 ||
4725            getBooleanContents(N0.getOperand(0).getValueType()) ==
4726                        ZeroOrOneBooleanContent)) {
4727         bool TrueWhenTrue = (Cond == ISD::SETEQ) ^ (!N1C->isOne());
4728         if (TrueWhenTrue)
4729           return DAG.getNode(ISD::TRUNCATE, dl, VT, N0);
4730         // Invert the condition.
4731         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4732         CC = ISD::getSetCCInverse(CC, N0.getOperand(0).getValueType());
4733         if (DCI.isBeforeLegalizeOps() ||
4734             isCondCodeLegal(CC, N0.getOperand(0).getSimpleValueType()))
4735           return DAG.getSetCC(dl, VT, N0.getOperand(0), N0.getOperand(1), CC);
4736       }
4737 
4738       if ((N0.getOpcode() == ISD::XOR ||
4739            (N0.getOpcode() == ISD::AND &&
4740             N0.getOperand(0).getOpcode() == ISD::XOR &&
4741             N0.getOperand(1) == N0.getOperand(0).getOperand(1))) &&
4742           isOneConstant(N0.getOperand(1))) {
4743         // If this is (X^1) == 0/1, swap the RHS and eliminate the xor.  We
4744         // can only do this if the top bits are known zero.
4745         unsigned BitWidth = N0.getValueSizeInBits();
4746         if (DAG.MaskedValueIsZero(N0,
4747                                   APInt::getHighBitsSet(BitWidth,
4748                                                         BitWidth-1))) {
4749           // Okay, get the un-inverted input value.
4750           SDValue Val;
4751           if (N0.getOpcode() == ISD::XOR) {
4752             Val = N0.getOperand(0);
4753           } else {
4754             assert(N0.getOpcode() == ISD::AND &&
4755                     N0.getOperand(0).getOpcode() == ISD::XOR);
4756             // ((X^1)&1)^1 -> X & 1
4757             Val = DAG.getNode(ISD::AND, dl, N0.getValueType(),
4758                               N0.getOperand(0).getOperand(0),
4759                               N0.getOperand(1));
4760           }
4761 
4762           return DAG.getSetCC(dl, VT, Val, N1,
4763                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4764         }
4765       } else if (N1C->isOne()) {
4766         SDValue Op0 = N0;
4767         if (Op0.getOpcode() == ISD::TRUNCATE)
4768           Op0 = Op0.getOperand(0);
4769 
4770         if ((Op0.getOpcode() == ISD::XOR) &&
4771             Op0.getOperand(0).getOpcode() == ISD::SETCC &&
4772             Op0.getOperand(1).getOpcode() == ISD::SETCC) {
4773           SDValue XorLHS = Op0.getOperand(0);
4774           SDValue XorRHS = Op0.getOperand(1);
4775           // Ensure that the input setccs return an i1 type or 0/1 value.
4776           if (Op0.getValueType() == MVT::i1 ||
4777               (getBooleanContents(XorLHS.getOperand(0).getValueType()) ==
4778                       ZeroOrOneBooleanContent &&
4779                getBooleanContents(XorRHS.getOperand(0).getValueType()) ==
4780                         ZeroOrOneBooleanContent)) {
4781             // (xor (setcc), (setcc)) == / != 1 -> (setcc) != / == (setcc)
4782             Cond = (Cond == ISD::SETEQ) ? ISD::SETNE : ISD::SETEQ;
4783             return DAG.getSetCC(dl, VT, XorLHS, XorRHS, Cond);
4784           }
4785         }
4786         if (Op0.getOpcode() == ISD::AND && isOneConstant(Op0.getOperand(1))) {
4787           // If this is (X&1) == / != 1, normalize it to (X&1) != / == 0.
4788           if (Op0.getValueType().bitsGT(VT))
4789             Op0 = DAG.getNode(ISD::AND, dl, VT,
4790                           DAG.getNode(ISD::TRUNCATE, dl, VT, Op0.getOperand(0)),
4791                           DAG.getConstant(1, dl, VT));
4792           else if (Op0.getValueType().bitsLT(VT))
4793             Op0 = DAG.getNode(ISD::AND, dl, VT,
4794                         DAG.getNode(ISD::ANY_EXTEND, dl, VT, Op0.getOperand(0)),
4795                         DAG.getConstant(1, dl, VT));
4796 
4797           return DAG.getSetCC(dl, VT, Op0,
4798                               DAG.getConstant(0, dl, Op0.getValueType()),
4799                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4800         }
4801         if (Op0.getOpcode() == ISD::AssertZext &&
4802             cast<VTSDNode>(Op0.getOperand(1))->getVT() == MVT::i1)
4803           return DAG.getSetCC(dl, VT, Op0,
4804                               DAG.getConstant(0, dl, Op0.getValueType()),
4805                               Cond == ISD::SETEQ ? ISD::SETNE : ISD::SETEQ);
4806       }
4807     }
4808 
4809     // Given:
4810     //   icmp eq/ne (urem %x, %y), 0
4811     // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
4812     //   icmp eq/ne %x, 0
4813     if (N0.getOpcode() == ISD::UREM && N1C->isZero() &&
4814         (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
4815       KnownBits XKnown = DAG.computeKnownBits(N0.getOperand(0));
4816       KnownBits YKnown = DAG.computeKnownBits(N0.getOperand(1));
4817       if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
4818         return DAG.getSetCC(dl, VT, N0.getOperand(0), N1, Cond);
4819     }
4820 
4821     // Fold set_cc seteq (ashr X, BW-1), -1 -> set_cc setlt X, 0
4822     //  and set_cc setne (ashr X, BW-1), -1 -> set_cc setge X, 0
4823     if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
4824         N0.getOpcode() == ISD::SRA && isa<ConstantSDNode>(N0.getOperand(1)) &&
4825         N0.getConstantOperandAPInt(1) == OpVT.getScalarSizeInBits() - 1 &&
4826         N1C && N1C->isAllOnes()) {
4827       return DAG.getSetCC(dl, VT, N0.getOperand(0),
4828                           DAG.getConstant(0, dl, OpVT),
4829                           Cond == ISD::SETEQ ? ISD::SETLT : ISD::SETGE);
4830     }
4831 
4832     if (SDValue V =
4833             optimizeSetCCOfSignedTruncationCheck(VT, N0, N1, Cond, DCI, dl))
4834       return V;
4835   }
4836 
4837   // These simplifications apply to splat vectors as well.
4838   // TODO: Handle more splat vector cases.
4839   if (auto *N1C = isConstOrConstSplat(N1)) {
4840     const APInt &C1 = N1C->getAPIntValue();
4841 
4842     APInt MinVal, MaxVal;
4843     unsigned OperandBitSize = N1C->getValueType(0).getScalarSizeInBits();
4844     if (ISD::isSignedIntSetCC(Cond)) {
4845       MinVal = APInt::getSignedMinValue(OperandBitSize);
4846       MaxVal = APInt::getSignedMaxValue(OperandBitSize);
4847     } else {
4848       MinVal = APInt::getMinValue(OperandBitSize);
4849       MaxVal = APInt::getMaxValue(OperandBitSize);
4850     }
4851 
4852     // Canonicalize GE/LE comparisons to use GT/LT comparisons.
4853     if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
4854       // X >= MIN --> true
4855       if (C1 == MinVal)
4856         return DAG.getBoolConstant(true, dl, VT, OpVT);
4857 
4858       if (!VT.isVector()) { // TODO: Support this for vectors.
4859         // X >= C0 --> X > (C0 - 1)
4860         APInt C = C1 - 1;
4861         ISD::CondCode NewCC = (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT;
4862         if ((DCI.isBeforeLegalizeOps() ||
4863              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
4864             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
4865                                   isLegalICmpImmediate(C.getSExtValue())))) {
4866           return DAG.getSetCC(dl, VT, N0,
4867                               DAG.getConstant(C, dl, N1.getValueType()),
4868                               NewCC);
4869         }
4870       }
4871     }
4872 
4873     if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
4874       // X <= MAX --> true
4875       if (C1 == MaxVal)
4876         return DAG.getBoolConstant(true, dl, VT, OpVT);
4877 
4878       // X <= C0 --> X < (C0 + 1)
4879       if (!VT.isVector()) { // TODO: Support this for vectors.
4880         APInt C = C1 + 1;
4881         ISD::CondCode NewCC = (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT;
4882         if ((DCI.isBeforeLegalizeOps() ||
4883              isCondCodeLegal(NewCC, VT.getSimpleVT())) &&
4884             (!N1C->isOpaque() || (C.getBitWidth() <= 64 &&
4885                                   isLegalICmpImmediate(C.getSExtValue())))) {
4886           return DAG.getSetCC(dl, VT, N0,
4887                               DAG.getConstant(C, dl, N1.getValueType()),
4888                               NewCC);
4889         }
4890       }
4891     }
4892 
4893     if (Cond == ISD::SETLT || Cond == ISD::SETULT) {
4894       if (C1 == MinVal)
4895         return DAG.getBoolConstant(false, dl, VT, OpVT); // X < MIN --> false
4896 
4897       // TODO: Support this for vectors after legalize ops.
4898       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4899         // Canonicalize setlt X, Max --> setne X, Max
4900         if (C1 == MaxVal)
4901           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
4902 
4903         // If we have setult X, 1, turn it into seteq X, 0
4904         if (C1 == MinVal+1)
4905           return DAG.getSetCC(dl, VT, N0,
4906                               DAG.getConstant(MinVal, dl, N0.getValueType()),
4907                               ISD::SETEQ);
4908       }
4909     }
4910 
4911     if (Cond == ISD::SETGT || Cond == ISD::SETUGT) {
4912       if (C1 == MaxVal)
4913         return DAG.getBoolConstant(false, dl, VT, OpVT); // X > MAX --> false
4914 
4915       // TODO: Support this for vectors after legalize ops.
4916       if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
4917         // Canonicalize setgt X, Min --> setne X, Min
4918         if (C1 == MinVal)
4919           return DAG.getSetCC(dl, VT, N0, N1, ISD::SETNE);
4920 
4921         // If we have setugt X, Max-1, turn it into seteq X, Max
4922         if (C1 == MaxVal-1)
4923           return DAG.getSetCC(dl, VT, N0,
4924                               DAG.getConstant(MaxVal, dl, N0.getValueType()),
4925                               ISD::SETEQ);
4926       }
4927     }
4928 
4929     if (Cond == ISD::SETEQ || Cond == ISD::SETNE) {
4930       // (X & (C l>>/<< Y)) ==/!= 0  -->  ((X <</l>> Y) & C) ==/!= 0
4931       if (C1.isZero())
4932         if (SDValue CC = optimizeSetCCByHoistingAndByConstFromLogicalShift(
4933                 VT, N0, N1, Cond, DCI, dl))
4934           return CC;
4935 
4936       // For all/any comparisons, replace or(x,shl(y,bw/2)) with and/or(x,y).
4937       // For example, when high 32-bits of i64 X are known clear:
4938       // all bits clear: (X | (Y<<32)) ==  0 --> (X | Y) ==  0
4939       // all bits set:   (X | (Y<<32)) == -1 --> (X & Y) == -1
4940       bool CmpZero = N1C->isZero();
4941       bool CmpNegOne = N1C->isAllOnes();
4942       if ((CmpZero || CmpNegOne) && N0.hasOneUse()) {
4943         // Match or(lo,shl(hi,bw/2)) pattern.
4944         auto IsConcat = [&](SDValue V, SDValue &Lo, SDValue &Hi) {
4945           unsigned EltBits = V.getScalarValueSizeInBits();
4946           if (V.getOpcode() != ISD::OR || (EltBits % 2) != 0)
4947             return false;
4948           SDValue LHS = V.getOperand(0);
4949           SDValue RHS = V.getOperand(1);
4950           APInt HiBits = APInt::getHighBitsSet(EltBits, EltBits / 2);
4951           // Unshifted element must have zero upperbits.
4952           if (RHS.getOpcode() == ISD::SHL &&
4953               isa<ConstantSDNode>(RHS.getOperand(1)) &&
4954               RHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
4955               DAG.MaskedValueIsZero(LHS, HiBits)) {
4956             Lo = LHS;
4957             Hi = RHS.getOperand(0);
4958             return true;
4959           }
4960           if (LHS.getOpcode() == ISD::SHL &&
4961               isa<ConstantSDNode>(LHS.getOperand(1)) &&
4962               LHS.getConstantOperandAPInt(1) == (EltBits / 2) &&
4963               DAG.MaskedValueIsZero(RHS, HiBits)) {
4964             Lo = RHS;
4965             Hi = LHS.getOperand(0);
4966             return true;
4967           }
4968           return false;
4969         };
4970 
4971         auto MergeConcat = [&](SDValue Lo, SDValue Hi) {
4972           unsigned EltBits = N0.getScalarValueSizeInBits();
4973           unsigned HalfBits = EltBits / 2;
4974           APInt HiBits = APInt::getHighBitsSet(EltBits, HalfBits);
4975           SDValue LoBits = DAG.getConstant(~HiBits, dl, OpVT);
4976           SDValue HiMask = DAG.getNode(ISD::AND, dl, OpVT, Hi, LoBits);
4977           SDValue NewN0 =
4978               DAG.getNode(CmpZero ? ISD::OR : ISD::AND, dl, OpVT, Lo, HiMask);
4979           SDValue NewN1 = CmpZero ? DAG.getConstant(0, dl, OpVT) : LoBits;
4980           return DAG.getSetCC(dl, VT, NewN0, NewN1, Cond);
4981         };
4982 
4983         SDValue Lo, Hi;
4984         if (IsConcat(N0, Lo, Hi))
4985           return MergeConcat(Lo, Hi);
4986 
4987         if (N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR) {
4988           SDValue Lo0, Lo1, Hi0, Hi1;
4989           if (IsConcat(N0.getOperand(0), Lo0, Hi0) &&
4990               IsConcat(N0.getOperand(1), Lo1, Hi1)) {
4991             return MergeConcat(DAG.getNode(N0.getOpcode(), dl, OpVT, Lo0, Lo1),
4992                                DAG.getNode(N0.getOpcode(), dl, OpVT, Hi0, Hi1));
4993           }
4994         }
4995       }
4996     }
4997 
4998     // If we have "setcc X, C0", check to see if we can shrink the immediate
4999     // by changing cc.
5000     // TODO: Support this for vectors after legalize ops.
5001     if (!VT.isVector() || DCI.isBeforeLegalizeOps()) {
5002       // SETUGT X, SINTMAX  -> SETLT X, 0
5003       // SETUGE X, SINTMIN -> SETLT X, 0
5004       if ((Cond == ISD::SETUGT && C1.isMaxSignedValue()) ||
5005           (Cond == ISD::SETUGE && C1.isMinSignedValue()))
5006         return DAG.getSetCC(dl, VT, N0,
5007                             DAG.getConstant(0, dl, N1.getValueType()),
5008                             ISD::SETLT);
5009 
5010       // SETULT X, SINTMIN  -> SETGT X, -1
5011       // SETULE X, SINTMAX  -> SETGT X, -1
5012       if ((Cond == ISD::SETULT && C1.isMinSignedValue()) ||
5013           (Cond == ISD::SETULE && C1.isMaxSignedValue()))
5014         return DAG.getSetCC(dl, VT, N0,
5015                             DAG.getAllOnesConstant(dl, N1.getValueType()),
5016                             ISD::SETGT);
5017     }
5018   }
5019 
5020   // Back to non-vector simplifications.
5021   // TODO: Can we do these for vector splats?
5022   if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
5023     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5024     const APInt &C1 = N1C->getAPIntValue();
5025     EVT ShValTy = N0.getValueType();
5026 
5027     // Fold bit comparisons when we can. This will result in an
5028     // incorrect value when boolean false is negative one, unless
5029     // the bitsize is 1 in which case the false value is the same
5030     // in practice regardless of the representation.
5031     if ((VT.getSizeInBits() == 1 ||
5032          getBooleanContents(N0.getValueType()) == ZeroOrOneBooleanContent) &&
5033         (Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5034         (VT == ShValTy || (isTypeLegal(VT) && VT.bitsLE(ShValTy))) &&
5035         N0.getOpcode() == ISD::AND) {
5036       if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5037         EVT ShiftTy =
5038             getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
5039         if (Cond == ISD::SETNE && C1 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
5040           // Perform the xform if the AND RHS is a single bit.
5041           unsigned ShCt = AndRHS->getAPIntValue().logBase2();
5042           if (AndRHS->getAPIntValue().isPowerOf2() &&
5043               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
5044             return DAG.getNode(ISD::TRUNCATE, dl, VT,
5045                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5046                                            DAG.getConstant(ShCt, dl, ShiftTy)));
5047           }
5048         } else if (Cond == ISD::SETEQ && C1 == AndRHS->getAPIntValue()) {
5049           // (X & 8) == 8  -->  (X & 8) >> 3
5050           // Perform the xform if C1 is a single bit.
5051           unsigned ShCt = C1.logBase2();
5052           if (C1.isPowerOf2() &&
5053               !TLI.shouldAvoidTransformToShift(ShValTy, ShCt)) {
5054             return DAG.getNode(ISD::TRUNCATE, dl, VT,
5055                                DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5056                                            DAG.getConstant(ShCt, dl, ShiftTy)));
5057           }
5058         }
5059       }
5060     }
5061 
5062     if (C1.getSignificantBits() <= 64 &&
5063         !isLegalICmpImmediate(C1.getSExtValue())) {
5064       EVT ShiftTy = getShiftAmountTy(ShValTy, Layout, !DCI.isBeforeLegalize());
5065       // (X & -256) == 256 -> (X >> 8) == 1
5066       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5067           N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
5068         if (auto *AndRHS = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5069           const APInt &AndRHSC = AndRHS->getAPIntValue();
5070           if (AndRHSC.isNegatedPowerOf2() && (AndRHSC & C1) == C1) {
5071             unsigned ShiftBits = AndRHSC.countr_zero();
5072             if (!TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5073               SDValue Shift =
5074                 DAG.getNode(ISD::SRL, dl, ShValTy, N0.getOperand(0),
5075                             DAG.getConstant(ShiftBits, dl, ShiftTy));
5076               SDValue CmpRHS = DAG.getConstant(C1.lshr(ShiftBits), dl, ShValTy);
5077               return DAG.getSetCC(dl, VT, Shift, CmpRHS, Cond);
5078             }
5079           }
5080         }
5081       } else if (Cond == ISD::SETULT || Cond == ISD::SETUGE ||
5082                  Cond == ISD::SETULE || Cond == ISD::SETUGT) {
5083         bool AdjOne = (Cond == ISD::SETULE || Cond == ISD::SETUGT);
5084         // X <  0x100000000 -> (X >> 32) <  1
5085         // X >= 0x100000000 -> (X >> 32) >= 1
5086         // X <= 0x0ffffffff -> (X >> 32) <  1
5087         // X >  0x0ffffffff -> (X >> 32) >= 1
5088         unsigned ShiftBits;
5089         APInt NewC = C1;
5090         ISD::CondCode NewCond = Cond;
5091         if (AdjOne) {
5092           ShiftBits = C1.countr_one();
5093           NewC = NewC + 1;
5094           NewCond = (Cond == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
5095         } else {
5096           ShiftBits = C1.countr_zero();
5097         }
5098         NewC.lshrInPlace(ShiftBits);
5099         if (ShiftBits && NewC.getSignificantBits() <= 64 &&
5100             isLegalICmpImmediate(NewC.getSExtValue()) &&
5101             !TLI.shouldAvoidTransformToShift(ShValTy, ShiftBits)) {
5102           SDValue Shift = DAG.getNode(ISD::SRL, dl, ShValTy, N0,
5103                                       DAG.getConstant(ShiftBits, dl, ShiftTy));
5104           SDValue CmpRHS = DAG.getConstant(NewC, dl, ShValTy);
5105           return DAG.getSetCC(dl, VT, Shift, CmpRHS, NewCond);
5106         }
5107       }
5108     }
5109   }
5110 
5111   if (!isa<ConstantFPSDNode>(N0) && isa<ConstantFPSDNode>(N1)) {
5112     auto *CFP = cast<ConstantFPSDNode>(N1);
5113     assert(!CFP->getValueAPF().isNaN() && "Unexpected NaN value");
5114 
5115     // Otherwise, we know the RHS is not a NaN.  Simplify the node to drop the
5116     // constant if knowing that the operand is non-nan is enough.  We prefer to
5117     // have SETO(x,x) instead of SETO(x, 0.0) because this avoids having to
5118     // materialize 0.0.
5119     if (Cond == ISD::SETO || Cond == ISD::SETUO)
5120       return DAG.getSetCC(dl, VT, N0, N0, Cond);
5121 
5122     // setcc (fneg x), C -> setcc swap(pred) x, -C
5123     if (N0.getOpcode() == ISD::FNEG) {
5124       ISD::CondCode SwapCond = ISD::getSetCCSwappedOperands(Cond);
5125       if (DCI.isBeforeLegalizeOps() ||
5126           isCondCodeLegal(SwapCond, N0.getSimpleValueType())) {
5127         SDValue NegN1 = DAG.getNode(ISD::FNEG, dl, N0.getValueType(), N1);
5128         return DAG.getSetCC(dl, VT, N0.getOperand(0), NegN1, SwapCond);
5129       }
5130     }
5131 
5132     // setueq/setoeq X, (fabs Inf) -> is_fpclass X, fcInf
5133     if (isOperationLegalOrCustom(ISD::IS_FPCLASS, N0.getValueType()) &&
5134         !isFPImmLegal(CFP->getValueAPF(), CFP->getValueType(0))) {
5135       bool IsFabs = N0.getOpcode() == ISD::FABS;
5136       SDValue Op = IsFabs ? N0.getOperand(0) : N0;
5137       if ((Cond == ISD::SETOEQ || Cond == ISD::SETUEQ) && CFP->isInfinity()) {
5138         FPClassTest Flag = CFP->isNegative() ? (IsFabs ? fcNone : fcNegInf)
5139                                              : (IsFabs ? fcInf : fcPosInf);
5140         if (Cond == ISD::SETUEQ)
5141           Flag |= fcNan;
5142         return DAG.getNode(ISD::IS_FPCLASS, dl, VT, Op,
5143                            DAG.getTargetConstant(Flag, dl, MVT::i32));
5144       }
5145     }
5146 
5147     // If the condition is not legal, see if we can find an equivalent one
5148     // which is legal.
5149     if (!isCondCodeLegal(Cond, N0.getSimpleValueType())) {
5150       // If the comparison was an awkward floating-point == or != and one of
5151       // the comparison operands is infinity or negative infinity, convert the
5152       // condition to a less-awkward <= or >=.
5153       if (CFP->getValueAPF().isInfinity()) {
5154         bool IsNegInf = CFP->getValueAPF().isNegative();
5155         ISD::CondCode NewCond = ISD::SETCC_INVALID;
5156         switch (Cond) {
5157         case ISD::SETOEQ: NewCond = IsNegInf ? ISD::SETOLE : ISD::SETOGE; break;
5158         case ISD::SETUEQ: NewCond = IsNegInf ? ISD::SETULE : ISD::SETUGE; break;
5159         case ISD::SETUNE: NewCond = IsNegInf ? ISD::SETUGT : ISD::SETULT; break;
5160         case ISD::SETONE: NewCond = IsNegInf ? ISD::SETOGT : ISD::SETOLT; break;
5161         default: break;
5162         }
5163         if (NewCond != ISD::SETCC_INVALID &&
5164             isCondCodeLegal(NewCond, N0.getSimpleValueType()))
5165           return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5166       }
5167     }
5168   }
5169 
5170   if (N0 == N1) {
5171     // The sext(setcc()) => setcc() optimization relies on the appropriate
5172     // constant being emitted.
5173     assert(!N0.getValueType().isInteger() &&
5174            "Integer types should be handled by FoldSetCC");
5175 
5176     bool EqTrue = ISD::isTrueWhenEqual(Cond);
5177     unsigned UOF = ISD::getUnorderedFlavor(Cond);
5178     if (UOF == 2) // FP operators that are undefined on NaNs.
5179       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5180     if (UOF == unsigned(EqTrue))
5181       return DAG.getBoolConstant(EqTrue, dl, VT, OpVT);
5182     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
5183     // if it is not already.
5184     ISD::CondCode NewCond = UOF == 0 ? ISD::SETO : ISD::SETUO;
5185     if (NewCond != Cond &&
5186         (DCI.isBeforeLegalizeOps() ||
5187                             isCondCodeLegal(NewCond, N0.getSimpleValueType())))
5188       return DAG.getSetCC(dl, VT, N0, N1, NewCond);
5189   }
5190 
5191   // ~X > ~Y --> Y > X
5192   // ~X < ~Y --> Y < X
5193   // ~X < C --> X > ~C
5194   // ~X > C --> X < ~C
5195   if ((isSignedIntSetCC(Cond) || isUnsignedIntSetCC(Cond)) &&
5196       N0.getValueType().isInteger()) {
5197     if (isBitwiseNot(N0)) {
5198       if (isBitwiseNot(N1))
5199         return DAG.getSetCC(dl, VT, N1.getOperand(0), N0.getOperand(0), Cond);
5200 
5201       if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
5202           !DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(0))) {
5203         SDValue Not = DAG.getNOT(dl, N1, OpVT);
5204         return DAG.getSetCC(dl, VT, Not, N0.getOperand(0), Cond);
5205       }
5206     }
5207   }
5208 
5209   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
5210       N0.getValueType().isInteger()) {
5211     if (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::SUB ||
5212         N0.getOpcode() == ISD::XOR) {
5213       // Simplify (X+Y) == (X+Z) -->  Y == Z
5214       if (N0.getOpcode() == N1.getOpcode()) {
5215         if (N0.getOperand(0) == N1.getOperand(0))
5216           return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(1), Cond);
5217         if (N0.getOperand(1) == N1.getOperand(1))
5218           return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(0), Cond);
5219         if (isCommutativeBinOp(N0.getOpcode())) {
5220           // If X op Y == Y op X, try other combinations.
5221           if (N0.getOperand(0) == N1.getOperand(1))
5222             return DAG.getSetCC(dl, VT, N0.getOperand(1), N1.getOperand(0),
5223                                 Cond);
5224           if (N0.getOperand(1) == N1.getOperand(0))
5225             return DAG.getSetCC(dl, VT, N0.getOperand(0), N1.getOperand(1),
5226                                 Cond);
5227         }
5228       }
5229 
5230       // If RHS is a legal immediate value for a compare instruction, we need
5231       // to be careful about increasing register pressure needlessly.
5232       bool LegalRHSImm = false;
5233 
5234       if (auto *RHSC = dyn_cast<ConstantSDNode>(N1)) {
5235         if (auto *LHSR = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5236           // Turn (X+C1) == C2 --> X == C2-C1
5237           if (N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse())
5238             return DAG.getSetCC(
5239                 dl, VT, N0.getOperand(0),
5240                 DAG.getConstant(RHSC->getAPIntValue() - LHSR->getAPIntValue(),
5241                                 dl, N0.getValueType()),
5242                 Cond);
5243 
5244           // Turn (X^C1) == C2 --> X == C1^C2
5245           if (N0.getOpcode() == ISD::XOR && N0.getNode()->hasOneUse())
5246             return DAG.getSetCC(
5247                 dl, VT, N0.getOperand(0),
5248                 DAG.getConstant(LHSR->getAPIntValue() ^ RHSC->getAPIntValue(),
5249                                 dl, N0.getValueType()),
5250                 Cond);
5251         }
5252 
5253         // Turn (C1-X) == C2 --> X == C1-C2
5254         if (auto *SUBC = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
5255           if (N0.getOpcode() == ISD::SUB && N0.getNode()->hasOneUse())
5256             return DAG.getSetCC(
5257                 dl, VT, N0.getOperand(1),
5258                 DAG.getConstant(SUBC->getAPIntValue() - RHSC->getAPIntValue(),
5259                                 dl, N0.getValueType()),
5260                 Cond);
5261 
5262         // Could RHSC fold directly into a compare?
5263         if (RHSC->getValueType(0).getSizeInBits() <= 64)
5264           LegalRHSImm = isLegalICmpImmediate(RHSC->getSExtValue());
5265       }
5266 
5267       // (X+Y) == X --> Y == 0 and similar folds.
5268       // Don't do this if X is an immediate that can fold into a cmp
5269       // instruction and X+Y has other uses. It could be an induction variable
5270       // chain, and the transform would increase register pressure.
5271       if (!LegalRHSImm || N0.hasOneUse())
5272         if (SDValue V = foldSetCCWithBinOp(VT, N0, N1, Cond, dl, DCI))
5273           return V;
5274     }
5275 
5276     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
5277         N1.getOpcode() == ISD::XOR)
5278       if (SDValue V = foldSetCCWithBinOp(VT, N1, N0, Cond, dl, DCI))
5279         return V;
5280 
5281     if (SDValue V = foldSetCCWithAnd(VT, N0, N1, Cond, dl, DCI))
5282       return V;
5283   }
5284 
5285   // Fold remainder of division by a constant.
5286   if ((N0.getOpcode() == ISD::UREM || N0.getOpcode() == ISD::SREM) &&
5287       N0.hasOneUse() && (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
5288     // When division is cheap or optimizing for minimum size,
5289     // fall through to DIVREM creation by skipping this fold.
5290     if (!isIntDivCheap(VT, Attr) && !Attr.hasFnAttr(Attribute::MinSize)) {
5291       if (N0.getOpcode() == ISD::UREM) {
5292         if (SDValue Folded = buildUREMEqFold(VT, N0, N1, Cond, DCI, dl))
5293           return Folded;
5294       } else if (N0.getOpcode() == ISD::SREM) {
5295         if (SDValue Folded = buildSREMEqFold(VT, N0, N1, Cond, DCI, dl))
5296           return Folded;
5297       }
5298     }
5299   }
5300 
5301   // Fold away ALL boolean setcc's.
5302   if (N0.getValueType().getScalarType() == MVT::i1 && foldBooleans) {
5303     SDValue Temp;
5304     switch (Cond) {
5305     default: llvm_unreachable("Unknown integer setcc!");
5306     case ISD::SETEQ:  // X == Y  -> ~(X^Y)
5307       Temp = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
5308       N0 = DAG.getNOT(dl, Temp, OpVT);
5309       if (!DCI.isCalledByLegalizer())
5310         DCI.AddToWorklist(Temp.getNode());
5311       break;
5312     case ISD::SETNE:  // X != Y   -->  (X^Y)
5313       N0 = DAG.getNode(ISD::XOR, dl, OpVT, N0, N1);
5314       break;
5315     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  ~X & Y
5316     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  ~X & Y
5317       Temp = DAG.getNOT(dl, N0, OpVT);
5318       N0 = DAG.getNode(ISD::AND, dl, OpVT, N1, Temp);
5319       if (!DCI.isCalledByLegalizer())
5320         DCI.AddToWorklist(Temp.getNode());
5321       break;
5322     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  ~Y & X
5323     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  ~Y & X
5324       Temp = DAG.getNOT(dl, N1, OpVT);
5325       N0 = DAG.getNode(ISD::AND, dl, OpVT, N0, Temp);
5326       if (!DCI.isCalledByLegalizer())
5327         DCI.AddToWorklist(Temp.getNode());
5328       break;
5329     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  ~X | Y
5330     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  ~X | Y
5331       Temp = DAG.getNOT(dl, N0, OpVT);
5332       N0 = DAG.getNode(ISD::OR, dl, OpVT, N1, Temp);
5333       if (!DCI.isCalledByLegalizer())
5334         DCI.AddToWorklist(Temp.getNode());
5335       break;
5336     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  ~Y | X
5337     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  ~Y | X
5338       Temp = DAG.getNOT(dl, N1, OpVT);
5339       N0 = DAG.getNode(ISD::OR, dl, OpVT, N0, Temp);
5340       break;
5341     }
5342     if (VT.getScalarType() != MVT::i1) {
5343       if (!DCI.isCalledByLegalizer())
5344         DCI.AddToWorklist(N0.getNode());
5345       // FIXME: If running after legalize, we probably can't do this.
5346       ISD::NodeType ExtendCode = getExtendForContent(getBooleanContents(OpVT));
5347       N0 = DAG.getNode(ExtendCode, dl, VT, N0);
5348     }
5349     return N0;
5350   }
5351 
5352   // Could not fold it.
5353   return SDValue();
5354 }
5355 
5356 /// Returns true (and the GlobalValue and the offset) if the node is a
5357 /// GlobalAddress + offset.
5358 bool TargetLowering::isGAPlusOffset(SDNode *WN, const GlobalValue *&GA,
5359                                     int64_t &Offset) const {
5360 
5361   SDNode *N = unwrapAddress(SDValue(WN, 0)).getNode();
5362 
5363   if (auto *GASD = dyn_cast<GlobalAddressSDNode>(N)) {
5364     GA = GASD->getGlobal();
5365     Offset += GASD->getOffset();
5366     return true;
5367   }
5368 
5369   if (N->getOpcode() == ISD::ADD) {
5370     SDValue N1 = N->getOperand(0);
5371     SDValue N2 = N->getOperand(1);
5372     if (isGAPlusOffset(N1.getNode(), GA, Offset)) {
5373       if (auto *V = dyn_cast<ConstantSDNode>(N2)) {
5374         Offset += V->getSExtValue();
5375         return true;
5376       }
5377     } else if (isGAPlusOffset(N2.getNode(), GA, Offset)) {
5378       if (auto *V = dyn_cast<ConstantSDNode>(N1)) {
5379         Offset += V->getSExtValue();
5380         return true;
5381       }
5382     }
5383   }
5384 
5385   return false;
5386 }
5387 
5388 SDValue TargetLowering::PerformDAGCombine(SDNode *N,
5389                                           DAGCombinerInfo &DCI) const {
5390   // Default implementation: no optimization.
5391   return SDValue();
5392 }
5393 
5394 //===----------------------------------------------------------------------===//
5395 //  Inline Assembler Implementation Methods
5396 //===----------------------------------------------------------------------===//
5397 
5398 TargetLowering::ConstraintType
5399 TargetLowering::getConstraintType(StringRef Constraint) const {
5400   unsigned S = Constraint.size();
5401 
5402   if (S == 1) {
5403     switch (Constraint[0]) {
5404     default: break;
5405     case 'r':
5406       return C_RegisterClass;
5407     case 'm': // memory
5408     case 'o': // offsetable
5409     case 'V': // not offsetable
5410       return C_Memory;
5411     case 'p': // Address.
5412       return C_Address;
5413     case 'n': // Simple Integer
5414     case 'E': // Floating Point Constant
5415     case 'F': // Floating Point Constant
5416       return C_Immediate;
5417     case 'i': // Simple Integer or Relocatable Constant
5418     case 's': // Relocatable Constant
5419     case 'X': // Allow ANY value.
5420     case 'I': // Target registers.
5421     case 'J':
5422     case 'K':
5423     case 'L':
5424     case 'M':
5425     case 'N':
5426     case 'O':
5427     case 'P':
5428     case '<':
5429     case '>':
5430       return C_Other;
5431     }
5432   }
5433 
5434   if (S > 1 && Constraint[0] == '{' && Constraint[S - 1] == '}') {
5435     if (S == 8 && Constraint.substr(1, 6) == "memory") // "{memory}"
5436       return C_Memory;
5437     return C_Register;
5438   }
5439   return C_Unknown;
5440 }
5441 
5442 /// Try to replace an X constraint, which matches anything, with another that
5443 /// has more specific requirements based on the type of the corresponding
5444 /// operand.
5445 const char *TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5446   if (ConstraintVT.isInteger())
5447     return "r";
5448   if (ConstraintVT.isFloatingPoint())
5449     return "f"; // works for many targets
5450   return nullptr;
5451 }
5452 
5453 SDValue TargetLowering::LowerAsmOutputForConstraint(
5454     SDValue &Chain, SDValue &Glue, const SDLoc &DL,
5455     const AsmOperandInfo &OpInfo, SelectionDAG &DAG) const {
5456   return SDValue();
5457 }
5458 
5459 /// Lower the specified operand into the Ops vector.
5460 /// If it is invalid, don't add anything to Ops.
5461 void TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
5462                                                   StringRef Constraint,
5463                                                   std::vector<SDValue> &Ops,
5464                                                   SelectionDAG &DAG) const {
5465 
5466   if (Constraint.size() > 1)
5467     return;
5468 
5469   char ConstraintLetter = Constraint[0];
5470   switch (ConstraintLetter) {
5471   default: break;
5472   case 'X':    // Allows any operand
5473   case 'i':    // Simple Integer or Relocatable Constant
5474   case 'n':    // Simple Integer
5475   case 's': {  // Relocatable Constant
5476 
5477     ConstantSDNode *C;
5478     uint64_t Offset = 0;
5479 
5480     // Match (GA) or (C) or (GA+C) or (GA-C) or ((GA+C)+C) or (((GA+C)+C)+C),
5481     // etc., since getelementpointer is variadic. We can't use
5482     // SelectionDAG::FoldSymbolOffset because it expects the GA to be accessible
5483     // while in this case the GA may be furthest from the root node which is
5484     // likely an ISD::ADD.
5485     while (true) {
5486       if ((C = dyn_cast<ConstantSDNode>(Op)) && ConstraintLetter != 's') {
5487         // gcc prints these as sign extended.  Sign extend value to 64 bits
5488         // now; without this it would get ZExt'd later in
5489         // ScheduleDAGSDNodes::EmitNode, which is very generic.
5490         bool IsBool = C->getConstantIntValue()->getBitWidth() == 1;
5491         BooleanContent BCont = getBooleanContents(MVT::i64);
5492         ISD::NodeType ExtOpc =
5493             IsBool ? getExtendForContent(BCont) : ISD::SIGN_EXTEND;
5494         int64_t ExtVal =
5495             ExtOpc == ISD::ZERO_EXTEND ? C->getZExtValue() : C->getSExtValue();
5496         Ops.push_back(
5497             DAG.getTargetConstant(Offset + ExtVal, SDLoc(C), MVT::i64));
5498         return;
5499       }
5500       if (ConstraintLetter != 'n') {
5501         if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5502           Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5503                                                    GA->getValueType(0),
5504                                                    Offset + GA->getOffset()));
5505           return;
5506         }
5507         if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
5508           Ops.push_back(DAG.getTargetBlockAddress(
5509               BA->getBlockAddress(), BA->getValueType(0),
5510               Offset + BA->getOffset(), BA->getTargetFlags()));
5511           return;
5512         }
5513         if (isa<BasicBlockSDNode>(Op)) {
5514           Ops.push_back(Op);
5515           return;
5516         }
5517       }
5518       const unsigned OpCode = Op.getOpcode();
5519       if (OpCode == ISD::ADD || OpCode == ISD::SUB) {
5520         if ((C = dyn_cast<ConstantSDNode>(Op.getOperand(0))))
5521           Op = Op.getOperand(1);
5522         // Subtraction is not commutative.
5523         else if (OpCode == ISD::ADD &&
5524                  (C = dyn_cast<ConstantSDNode>(Op.getOperand(1))))
5525           Op = Op.getOperand(0);
5526         else
5527           return;
5528         Offset += (OpCode == ISD::ADD ? 1 : -1) * C->getSExtValue();
5529         continue;
5530       }
5531       return;
5532     }
5533     break;
5534   }
5535   }
5536 }
5537 
5538 void TargetLowering::CollectTargetIntrinsicOperands(
5539     const CallInst &I, SmallVectorImpl<SDValue> &Ops, SelectionDAG &DAG) const {
5540 }
5541 
5542 std::pair<unsigned, const TargetRegisterClass *>
5543 TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *RI,
5544                                              StringRef Constraint,
5545                                              MVT VT) const {
5546   if (Constraint.empty() || Constraint[0] != '{')
5547     return std::make_pair(0u, static_cast<TargetRegisterClass *>(nullptr));
5548   assert(*(Constraint.end() - 1) == '}' && "Not a brace enclosed constraint?");
5549 
5550   // Remove the braces from around the name.
5551   StringRef RegName(Constraint.data() + 1, Constraint.size() - 2);
5552 
5553   std::pair<unsigned, const TargetRegisterClass *> R =
5554       std::make_pair(0u, static_cast<const TargetRegisterClass *>(nullptr));
5555 
5556   // Figure out which register class contains this reg.
5557   for (const TargetRegisterClass *RC : RI->regclasses()) {
5558     // If none of the value types for this register class are valid, we
5559     // can't use it.  For example, 64-bit reg classes on 32-bit targets.
5560     if (!isLegalRC(*RI, *RC))
5561       continue;
5562 
5563     for (const MCPhysReg &PR : *RC) {
5564       if (RegName.equals_insensitive(RI->getRegAsmName(PR))) {
5565         std::pair<unsigned, const TargetRegisterClass *> S =
5566             std::make_pair(PR, RC);
5567 
5568         // If this register class has the requested value type, return it,
5569         // otherwise keep searching and return the first class found
5570         // if no other is found which explicitly has the requested type.
5571         if (RI->isTypeLegalForClass(*RC, VT))
5572           return S;
5573         if (!R.second)
5574           R = S;
5575       }
5576     }
5577   }
5578 
5579   return R;
5580 }
5581 
5582 //===----------------------------------------------------------------------===//
5583 // Constraint Selection.
5584 
5585 /// Return true of this is an input operand that is a matching constraint like
5586 /// "4".
5587 bool TargetLowering::AsmOperandInfo::isMatchingInputConstraint() const {
5588   assert(!ConstraintCode.empty() && "No known constraint!");
5589   return isdigit(static_cast<unsigned char>(ConstraintCode[0]));
5590 }
5591 
5592 /// If this is an input matching constraint, this method returns the output
5593 /// operand it matches.
5594 unsigned TargetLowering::AsmOperandInfo::getMatchedOperand() const {
5595   assert(!ConstraintCode.empty() && "No known constraint!");
5596   return atoi(ConstraintCode.c_str());
5597 }
5598 
5599 /// Split up the constraint string from the inline assembly value into the
5600 /// specific constraints and their prefixes, and also tie in the associated
5601 /// operand values.
5602 /// If this returns an empty vector, and if the constraint string itself
5603 /// isn't empty, there was an error parsing.
5604 TargetLowering::AsmOperandInfoVector
5605 TargetLowering::ParseConstraints(const DataLayout &DL,
5606                                  const TargetRegisterInfo *TRI,
5607                                  const CallBase &Call) const {
5608   /// Information about all of the constraints.
5609   AsmOperandInfoVector ConstraintOperands;
5610   const InlineAsm *IA = cast<InlineAsm>(Call.getCalledOperand());
5611   unsigned maCount = 0; // Largest number of multiple alternative constraints.
5612 
5613   // Do a prepass over the constraints, canonicalizing them, and building up the
5614   // ConstraintOperands list.
5615   unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5616   unsigned ResNo = 0; // ResNo - The result number of the next output.
5617   unsigned LabelNo = 0; // LabelNo - CallBr indirect dest number.
5618 
5619   for (InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
5620     ConstraintOperands.emplace_back(std::move(CI));
5621     AsmOperandInfo &OpInfo = ConstraintOperands.back();
5622 
5623     // Update multiple alternative constraint count.
5624     if (OpInfo.multipleAlternatives.size() > maCount)
5625       maCount = OpInfo.multipleAlternatives.size();
5626 
5627     OpInfo.ConstraintVT = MVT::Other;
5628 
5629     // Compute the value type for each operand.
5630     switch (OpInfo.Type) {
5631     case InlineAsm::isOutput:
5632       // Indirect outputs just consume an argument.
5633       if (OpInfo.isIndirect) {
5634         OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
5635         break;
5636       }
5637 
5638       // The return value of the call is this value.  As such, there is no
5639       // corresponding argument.
5640       assert(!Call.getType()->isVoidTy() && "Bad inline asm!");
5641       if (StructType *STy = dyn_cast<StructType>(Call.getType())) {
5642         OpInfo.ConstraintVT =
5643             getSimpleValueType(DL, STy->getElementType(ResNo));
5644       } else {
5645         assert(ResNo == 0 && "Asm only has one result!");
5646         OpInfo.ConstraintVT =
5647             getAsmOperandValueType(DL, Call.getType()).getSimpleVT();
5648       }
5649       ++ResNo;
5650       break;
5651     case InlineAsm::isInput:
5652       OpInfo.CallOperandVal = Call.getArgOperand(ArgNo);
5653       break;
5654     case InlineAsm::isLabel:
5655       OpInfo.CallOperandVal = cast<CallBrInst>(&Call)->getIndirectDest(LabelNo);
5656       ++LabelNo;
5657       continue;
5658     case InlineAsm::isClobber:
5659       // Nothing to do.
5660       break;
5661     }
5662 
5663     if (OpInfo.CallOperandVal) {
5664       llvm::Type *OpTy = OpInfo.CallOperandVal->getType();
5665       if (OpInfo.isIndirect) {
5666         OpTy = Call.getParamElementType(ArgNo);
5667         assert(OpTy && "Indirect operand must have elementtype attribute");
5668       }
5669 
5670       // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
5671       if (StructType *STy = dyn_cast<StructType>(OpTy))
5672         if (STy->getNumElements() == 1)
5673           OpTy = STy->getElementType(0);
5674 
5675       // If OpTy is not a single value, it may be a struct/union that we
5676       // can tile with integers.
5677       if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5678         unsigned BitSize = DL.getTypeSizeInBits(OpTy);
5679         switch (BitSize) {
5680         default: break;
5681         case 1:
5682         case 8:
5683         case 16:
5684         case 32:
5685         case 64:
5686         case 128:
5687           OpTy = IntegerType::get(OpTy->getContext(), BitSize);
5688           break;
5689         }
5690       }
5691 
5692       EVT VT = getAsmOperandValueType(DL, OpTy, true);
5693       OpInfo.ConstraintVT = VT.isSimple() ? VT.getSimpleVT() : MVT::Other;
5694       ArgNo++;
5695     }
5696   }
5697 
5698   // If we have multiple alternative constraints, select the best alternative.
5699   if (!ConstraintOperands.empty()) {
5700     if (maCount) {
5701       unsigned bestMAIndex = 0;
5702       int bestWeight = -1;
5703       // weight:  -1 = invalid match, and 0 = so-so match to 5 = good match.
5704       int weight = -1;
5705       unsigned maIndex;
5706       // Compute the sums of the weights for each alternative, keeping track
5707       // of the best (highest weight) one so far.
5708       for (maIndex = 0; maIndex < maCount; ++maIndex) {
5709         int weightSum = 0;
5710         for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
5711              cIndex != eIndex; ++cIndex) {
5712           AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
5713           if (OpInfo.Type == InlineAsm::isClobber)
5714             continue;
5715 
5716           // If this is an output operand with a matching input operand,
5717           // look up the matching input. If their types mismatch, e.g. one
5718           // is an integer, the other is floating point, or their sizes are
5719           // different, flag it as an maCantMatch.
5720           if (OpInfo.hasMatchingInput()) {
5721             AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5722             if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5723               if ((OpInfo.ConstraintVT.isInteger() !=
5724                    Input.ConstraintVT.isInteger()) ||
5725                   (OpInfo.ConstraintVT.getSizeInBits() !=
5726                    Input.ConstraintVT.getSizeInBits())) {
5727                 weightSum = -1; // Can't match.
5728                 break;
5729               }
5730             }
5731           }
5732           weight = getMultipleConstraintMatchWeight(OpInfo, maIndex);
5733           if (weight == -1) {
5734             weightSum = -1;
5735             break;
5736           }
5737           weightSum += weight;
5738         }
5739         // Update best.
5740         if (weightSum > bestWeight) {
5741           bestWeight = weightSum;
5742           bestMAIndex = maIndex;
5743         }
5744       }
5745 
5746       // Now select chosen alternative in each constraint.
5747       for (AsmOperandInfo &cInfo : ConstraintOperands)
5748         if (cInfo.Type != InlineAsm::isClobber)
5749           cInfo.selectAlternative(bestMAIndex);
5750     }
5751   }
5752 
5753   // Check and hook up tied operands, choose constraint code to use.
5754   for (unsigned cIndex = 0, eIndex = ConstraintOperands.size();
5755        cIndex != eIndex; ++cIndex) {
5756     AsmOperandInfo &OpInfo = ConstraintOperands[cIndex];
5757 
5758     // If this is an output operand with a matching input operand, look up the
5759     // matching input. If their types mismatch, e.g. one is an integer, the
5760     // other is floating point, or their sizes are different, flag it as an
5761     // error.
5762     if (OpInfo.hasMatchingInput()) {
5763       AsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5764 
5765       if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5766         std::pair<unsigned, const TargetRegisterClass *> MatchRC =
5767             getRegForInlineAsmConstraint(TRI, OpInfo.ConstraintCode,
5768                                          OpInfo.ConstraintVT);
5769         std::pair<unsigned, const TargetRegisterClass *> InputRC =
5770             getRegForInlineAsmConstraint(TRI, Input.ConstraintCode,
5771                                          Input.ConstraintVT);
5772         if ((OpInfo.ConstraintVT.isInteger() !=
5773              Input.ConstraintVT.isInteger()) ||
5774             (MatchRC.second != InputRC.second)) {
5775           report_fatal_error("Unsupported asm: input constraint"
5776                              " with a matching output constraint of"
5777                              " incompatible type!");
5778         }
5779       }
5780     }
5781   }
5782 
5783   return ConstraintOperands;
5784 }
5785 
5786 /// Return a number indicating our preference for chosing a type of constraint
5787 /// over another, for the purpose of sorting them. Immediates are almost always
5788 /// preferrable (when they can be emitted). A higher return value means a
5789 /// stronger preference for one constraint type relative to another.
5790 /// FIXME: We should prefer registers over memory but doing so may lead to
5791 /// unrecoverable register exhaustion later.
5792 /// https://github.com/llvm/llvm-project/issues/20571
5793 static unsigned getConstraintPiority(TargetLowering::ConstraintType CT) {
5794   switch (CT) {
5795   case TargetLowering::C_Immediate:
5796   case TargetLowering::C_Other:
5797     return 4;
5798   case TargetLowering::C_Memory:
5799   case TargetLowering::C_Address:
5800     return 3;
5801   case TargetLowering::C_RegisterClass:
5802     return 2;
5803   case TargetLowering::C_Register:
5804     return 1;
5805   case TargetLowering::C_Unknown:
5806     return 0;
5807   }
5808   llvm_unreachable("Invalid constraint type");
5809 }
5810 
5811 /// Examine constraint type and operand type and determine a weight value.
5812 /// This object must already have been set up with the operand type
5813 /// and the current alternative constraint selected.
5814 TargetLowering::ConstraintWeight
5815   TargetLowering::getMultipleConstraintMatchWeight(
5816     AsmOperandInfo &info, int maIndex) const {
5817   InlineAsm::ConstraintCodeVector *rCodes;
5818   if (maIndex >= (int)info.multipleAlternatives.size())
5819     rCodes = &info.Codes;
5820   else
5821     rCodes = &info.multipleAlternatives[maIndex].Codes;
5822   ConstraintWeight BestWeight = CW_Invalid;
5823 
5824   // Loop over the options, keeping track of the most general one.
5825   for (const std::string &rCode : *rCodes) {
5826     ConstraintWeight weight =
5827         getSingleConstraintMatchWeight(info, rCode.c_str());
5828     if (weight > BestWeight)
5829       BestWeight = weight;
5830   }
5831 
5832   return BestWeight;
5833 }
5834 
5835 /// Examine constraint type and operand type and determine a weight value.
5836 /// This object must already have been set up with the operand type
5837 /// and the current alternative constraint selected.
5838 TargetLowering::ConstraintWeight
5839   TargetLowering::getSingleConstraintMatchWeight(
5840     AsmOperandInfo &info, const char *constraint) const {
5841   ConstraintWeight weight = CW_Invalid;
5842   Value *CallOperandVal = info.CallOperandVal;
5843     // If we don't have a value, we can't do a match,
5844     // but allow it at the lowest weight.
5845   if (!CallOperandVal)
5846     return CW_Default;
5847   // Look at the constraint type.
5848   switch (*constraint) {
5849     case 'i': // immediate integer.
5850     case 'n': // immediate integer with a known value.
5851       if (isa<ConstantInt>(CallOperandVal))
5852         weight = CW_Constant;
5853       break;
5854     case 's': // non-explicit intregal immediate.
5855       if (isa<GlobalValue>(CallOperandVal))
5856         weight = CW_Constant;
5857       break;
5858     case 'E': // immediate float if host format.
5859     case 'F': // immediate float.
5860       if (isa<ConstantFP>(CallOperandVal))
5861         weight = CW_Constant;
5862       break;
5863     case '<': // memory operand with autodecrement.
5864     case '>': // memory operand with autoincrement.
5865     case 'm': // memory operand.
5866     case 'o': // offsettable memory operand
5867     case 'V': // non-offsettable memory operand
5868       weight = CW_Memory;
5869       break;
5870     case 'r': // general register.
5871     case 'g': // general register, memory operand or immediate integer.
5872               // note: Clang converts "g" to "imr".
5873       if (CallOperandVal->getType()->isIntegerTy())
5874         weight = CW_Register;
5875       break;
5876     case 'X': // any operand.
5877   default:
5878     weight = CW_Default;
5879     break;
5880   }
5881   return weight;
5882 }
5883 
5884 /// If there are multiple different constraints that we could pick for this
5885 /// operand (e.g. "imr") try to pick the 'best' one.
5886 /// This is somewhat tricky: constraints (TargetLowering::ConstraintType) fall
5887 /// into seven classes:
5888 ///    Register      -> one specific register
5889 ///    RegisterClass -> a group of regs
5890 ///    Memory        -> memory
5891 ///    Address       -> a symbolic memory reference
5892 ///    Immediate     -> immediate values
5893 ///    Other         -> magic values (such as "Flag Output Operands")
5894 ///    Unknown       -> something we don't recognize yet and can't handle
5895 /// Ideally, we would pick the most specific constraint possible: if we have
5896 /// something that fits into a register, we would pick it.  The problem here
5897 /// is that if we have something that could either be in a register or in
5898 /// memory that use of the register could cause selection of *other*
5899 /// operands to fail: they might only succeed if we pick memory.  Because of
5900 /// this the heuristic we use is:
5901 ///
5902 ///  1) If there is an 'other' constraint, and if the operand is valid for
5903 ///     that constraint, use it.  This makes us take advantage of 'i'
5904 ///     constraints when available.
5905 ///  2) Otherwise, pick the most general constraint present.  This prefers
5906 ///     'm' over 'r', for example.
5907 ///
5908 TargetLowering::ConstraintGroup TargetLowering::getConstraintPreferences(
5909     TargetLowering::AsmOperandInfo &OpInfo) const {
5910   ConstraintGroup Ret;
5911 
5912   Ret.reserve(OpInfo.Codes.size());
5913   for (StringRef Code : OpInfo.Codes) {
5914     TargetLowering::ConstraintType CType = getConstraintType(Code);
5915 
5916     // Indirect 'other' or 'immediate' constraints are not allowed.
5917     if (OpInfo.isIndirect && !(CType == TargetLowering::C_Memory ||
5918                                CType == TargetLowering::C_Register ||
5919                                CType == TargetLowering::C_RegisterClass))
5920       continue;
5921 
5922     // Things with matching constraints can only be registers, per gcc
5923     // documentation.  This mainly affects "g" constraints.
5924     if (CType == TargetLowering::C_Memory && OpInfo.hasMatchingInput())
5925       continue;
5926 
5927     Ret.emplace_back(Code, CType);
5928   }
5929 
5930   std::stable_sort(
5931       Ret.begin(), Ret.end(), [](ConstraintPair a, ConstraintPair b) {
5932         return getConstraintPiority(a.second) > getConstraintPiority(b.second);
5933       });
5934 
5935   return Ret;
5936 }
5937 
5938 /// If we have an immediate, see if we can lower it. Return true if we can,
5939 /// false otherwise.
5940 static bool lowerImmediateIfPossible(TargetLowering::ConstraintPair &P,
5941                                      SDValue Op, SelectionDAG *DAG,
5942                                      const TargetLowering &TLI) {
5943 
5944   assert((P.second == TargetLowering::C_Other ||
5945           P.second == TargetLowering::C_Immediate) &&
5946          "need immediate or other");
5947 
5948   if (!Op.getNode())
5949     return false;
5950 
5951   std::vector<SDValue> ResultOps;
5952   TLI.LowerAsmOperandForConstraint(Op, P.first, ResultOps, *DAG);
5953   return !ResultOps.empty();
5954 }
5955 
5956 /// Determines the constraint code and constraint type to use for the specific
5957 /// AsmOperandInfo, setting OpInfo.ConstraintCode and OpInfo.ConstraintType.
5958 void TargetLowering::ComputeConstraintToUse(AsmOperandInfo &OpInfo,
5959                                             SDValue Op,
5960                                             SelectionDAG *DAG) const {
5961   assert(!OpInfo.Codes.empty() && "Must have at least one constraint");
5962 
5963   // Single-letter constraints ('r') are very common.
5964   if (OpInfo.Codes.size() == 1) {
5965     OpInfo.ConstraintCode = OpInfo.Codes[0];
5966     OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
5967   } else {
5968     ConstraintGroup G = getConstraintPreferences(OpInfo);
5969     if (G.empty())
5970       return;
5971 
5972     unsigned BestIdx = 0;
5973     for (const unsigned E = G.size();
5974          BestIdx < E && (G[BestIdx].second == TargetLowering::C_Other ||
5975                          G[BestIdx].second == TargetLowering::C_Immediate);
5976          ++BestIdx) {
5977       if (lowerImmediateIfPossible(G[BestIdx], Op, DAG, *this))
5978         break;
5979       // If we're out of constraints, just pick the first one.
5980       if (BestIdx + 1 == E) {
5981         BestIdx = 0;
5982         break;
5983       }
5984     }
5985 
5986     OpInfo.ConstraintCode = G[BestIdx].first;
5987     OpInfo.ConstraintType = G[BestIdx].second;
5988   }
5989 
5990   // 'X' matches anything.
5991   if (OpInfo.ConstraintCode == "X" && OpInfo.CallOperandVal) {
5992     // Constants are handled elsewhere.  For Functions, the type here is the
5993     // type of the result, which is not what we want to look at; leave them
5994     // alone.
5995     Value *v = OpInfo.CallOperandVal;
5996     if (isa<ConstantInt>(v) || isa<Function>(v)) {
5997       return;
5998     }
5999 
6000     if (isa<BasicBlock>(v) || isa<BlockAddress>(v)) {
6001       OpInfo.ConstraintCode = "i";
6002       return;
6003     }
6004 
6005     // Otherwise, try to resolve it to something we know about by looking at
6006     // the actual operand type.
6007     if (const char *Repl = LowerXConstraint(OpInfo.ConstraintVT)) {
6008       OpInfo.ConstraintCode = Repl;
6009       OpInfo.ConstraintType = getConstraintType(OpInfo.ConstraintCode);
6010     }
6011   }
6012 }
6013 
6014 /// Given an exact SDIV by a constant, create a multiplication
6015 /// with the multiplicative inverse of the constant.
6016 static SDValue BuildExactSDIV(const TargetLowering &TLI, SDNode *N,
6017                               const SDLoc &dl, SelectionDAG &DAG,
6018                               SmallVectorImpl<SDNode *> &Created) {
6019   SDValue Op0 = N->getOperand(0);
6020   SDValue Op1 = N->getOperand(1);
6021   EVT VT = N->getValueType(0);
6022   EVT SVT = VT.getScalarType();
6023   EVT ShVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
6024   EVT ShSVT = ShVT.getScalarType();
6025 
6026   bool UseSRA = false;
6027   SmallVector<SDValue, 16> Shifts, Factors;
6028 
6029   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6030     if (C->isZero())
6031       return false;
6032     APInt Divisor = C->getAPIntValue();
6033     unsigned Shift = Divisor.countr_zero();
6034     if (Shift) {
6035       Divisor.ashrInPlace(Shift);
6036       UseSRA = true;
6037     }
6038     // Calculate the multiplicative inverse, using Newton's method.
6039     APInt t;
6040     APInt Factor = Divisor;
6041     while ((t = Divisor * Factor) != 1)
6042       Factor *= APInt(Divisor.getBitWidth(), 2) - t;
6043     Shifts.push_back(DAG.getConstant(Shift, dl, ShSVT));
6044     Factors.push_back(DAG.getConstant(Factor, dl, SVT));
6045     return true;
6046   };
6047 
6048   // Collect all magic values from the build vector.
6049   if (!ISD::matchUnaryPredicate(Op1, BuildSDIVPattern))
6050     return SDValue();
6051 
6052   SDValue Shift, Factor;
6053   if (Op1.getOpcode() == ISD::BUILD_VECTOR) {
6054     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6055     Factor = DAG.getBuildVector(VT, dl, Factors);
6056   } else if (Op1.getOpcode() == ISD::SPLAT_VECTOR) {
6057     assert(Shifts.size() == 1 && Factors.size() == 1 &&
6058            "Expected matchUnaryPredicate to return one element for scalable "
6059            "vectors");
6060     Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6061     Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6062   } else {
6063     assert(isa<ConstantSDNode>(Op1) && "Expected a constant");
6064     Shift = Shifts[0];
6065     Factor = Factors[0];
6066   }
6067 
6068   SDValue Res = Op0;
6069 
6070   // Shift the value upfront if it is even, so the LSB is one.
6071   if (UseSRA) {
6072     // TODO: For UDIV use SRL instead of SRA.
6073     SDNodeFlags Flags;
6074     Flags.setExact(true);
6075     Res = DAG.getNode(ISD::SRA, dl, VT, Res, Shift, Flags);
6076     Created.push_back(Res.getNode());
6077   }
6078 
6079   return DAG.getNode(ISD::MUL, dl, VT, Res, Factor);
6080 }
6081 
6082 SDValue TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
6083                               SelectionDAG &DAG,
6084                               SmallVectorImpl<SDNode *> &Created) const {
6085   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
6086   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6087   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
6088     return SDValue(N, 0); // Lower SDIV as SDIV
6089   return SDValue();
6090 }
6091 
6092 SDValue
6093 TargetLowering::BuildSREMPow2(SDNode *N, const APInt &Divisor,
6094                               SelectionDAG &DAG,
6095                               SmallVectorImpl<SDNode *> &Created) const {
6096   AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
6097   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6098   if (TLI.isIntDivCheap(N->getValueType(0), Attr))
6099     return SDValue(N, 0); // Lower SREM as SREM
6100   return SDValue();
6101 }
6102 
6103 /// Build sdiv by power-of-2 with conditional move instructions
6104 /// Ref: "Hacker's Delight" by Henry Warren 10-1
6105 /// If conditional move/branch is preferred, we lower sdiv x, +/-2**k into:
6106 ///   bgez x, label
6107 ///   add x, x, 2**k-1
6108 /// label:
6109 ///   sra res, x, k
6110 ///   neg res, res (when the divisor is negative)
6111 SDValue TargetLowering::buildSDIVPow2WithCMov(
6112     SDNode *N, const APInt &Divisor, SelectionDAG &DAG,
6113     SmallVectorImpl<SDNode *> &Created) const {
6114   unsigned Lg2 = Divisor.countr_zero();
6115   EVT VT = N->getValueType(0);
6116 
6117   SDLoc DL(N);
6118   SDValue N0 = N->getOperand(0);
6119   SDValue Zero = DAG.getConstant(0, DL, VT);
6120   APInt Lg2Mask = APInt::getLowBitsSet(VT.getSizeInBits(), Lg2);
6121   SDValue Pow2MinusOne = DAG.getConstant(Lg2Mask, DL, VT);
6122 
6123   // If N0 is negative, we need to add (Pow2 - 1) to it before shifting right.
6124   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6125   SDValue Cmp = DAG.getSetCC(DL, CCVT, N0, Zero, ISD::SETLT);
6126   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
6127   SDValue CMov = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0);
6128 
6129   Created.push_back(Cmp.getNode());
6130   Created.push_back(Add.getNode());
6131   Created.push_back(CMov.getNode());
6132 
6133   // Divide by pow2.
6134   SDValue SRA =
6135       DAG.getNode(ISD::SRA, DL, VT, CMov, DAG.getConstant(Lg2, DL, VT));
6136 
6137   // If we're dividing by a positive value, we're done.  Otherwise, we must
6138   // negate the result.
6139   if (Divisor.isNonNegative())
6140     return SRA;
6141 
6142   Created.push_back(SRA.getNode());
6143   return DAG.getNode(ISD::SUB, DL, VT, Zero, SRA);
6144 }
6145 
6146 /// Given an ISD::SDIV node expressing a divide by constant,
6147 /// return a DAG expression to select that will generate the same value by
6148 /// multiplying by a magic number.
6149 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
6150 SDValue TargetLowering::BuildSDIV(SDNode *N, SelectionDAG &DAG,
6151                                   bool IsAfterLegalization,
6152                                   SmallVectorImpl<SDNode *> &Created) const {
6153   SDLoc dl(N);
6154   EVT VT = N->getValueType(0);
6155   EVT SVT = VT.getScalarType();
6156   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
6157   EVT ShSVT = ShVT.getScalarType();
6158   unsigned EltBits = VT.getScalarSizeInBits();
6159   EVT MulVT;
6160 
6161   // Check to see if we can do this.
6162   // FIXME: We should be more aggressive here.
6163   if (!isTypeLegal(VT)) {
6164     // Limit this to simple scalars for now.
6165     if (VT.isVector() || !VT.isSimple())
6166       return SDValue();
6167 
6168     // If this type will be promoted to a large enough type with a legal
6169     // multiply operation, we can go ahead and do this transform.
6170     if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger)
6171       return SDValue();
6172 
6173     MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
6174     if (MulVT.getSizeInBits() < (2 * EltBits) ||
6175         !isOperationLegal(ISD::MUL, MulVT))
6176       return SDValue();
6177   }
6178 
6179   // If the sdiv has an 'exact' bit we can use a simpler lowering.
6180   if (N->getFlags().hasExact())
6181     return BuildExactSDIV(*this, N, dl, DAG, Created);
6182 
6183   SmallVector<SDValue, 16> MagicFactors, Factors, Shifts, ShiftMasks;
6184 
6185   auto BuildSDIVPattern = [&](ConstantSDNode *C) {
6186     if (C->isZero())
6187       return false;
6188 
6189     const APInt &Divisor = C->getAPIntValue();
6190     SignedDivisionByConstantInfo magics = SignedDivisionByConstantInfo::get(Divisor);
6191     int NumeratorFactor = 0;
6192     int ShiftMask = -1;
6193 
6194     if (Divisor.isOne() || Divisor.isAllOnes()) {
6195       // If d is +1/-1, we just multiply the numerator by +1/-1.
6196       NumeratorFactor = Divisor.getSExtValue();
6197       magics.Magic = 0;
6198       magics.ShiftAmount = 0;
6199       ShiftMask = 0;
6200     } else if (Divisor.isStrictlyPositive() && magics.Magic.isNegative()) {
6201       // If d > 0 and m < 0, add the numerator.
6202       NumeratorFactor = 1;
6203     } else if (Divisor.isNegative() && magics.Magic.isStrictlyPositive()) {
6204       // If d < 0 and m > 0, subtract the numerator.
6205       NumeratorFactor = -1;
6206     }
6207 
6208     MagicFactors.push_back(DAG.getConstant(magics.Magic, dl, SVT));
6209     Factors.push_back(DAG.getConstant(NumeratorFactor, dl, SVT));
6210     Shifts.push_back(DAG.getConstant(magics.ShiftAmount, dl, ShSVT));
6211     ShiftMasks.push_back(DAG.getConstant(ShiftMask, dl, SVT));
6212     return true;
6213   };
6214 
6215   SDValue N0 = N->getOperand(0);
6216   SDValue N1 = N->getOperand(1);
6217 
6218   // Collect the shifts / magic values from each element.
6219   if (!ISD::matchUnaryPredicate(N1, BuildSDIVPattern))
6220     return SDValue();
6221 
6222   SDValue MagicFactor, Factor, Shift, ShiftMask;
6223   if (N1.getOpcode() == ISD::BUILD_VECTOR) {
6224     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
6225     Factor = DAG.getBuildVector(VT, dl, Factors);
6226     Shift = DAG.getBuildVector(ShVT, dl, Shifts);
6227     ShiftMask = DAG.getBuildVector(VT, dl, ShiftMasks);
6228   } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
6229     assert(MagicFactors.size() == 1 && Factors.size() == 1 &&
6230            Shifts.size() == 1 && ShiftMasks.size() == 1 &&
6231            "Expected matchUnaryPredicate to return one element for scalable "
6232            "vectors");
6233     MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
6234     Factor = DAG.getSplatVector(VT, dl, Factors[0]);
6235     Shift = DAG.getSplatVector(ShVT, dl, Shifts[0]);
6236     ShiftMask = DAG.getSplatVector(VT, dl, ShiftMasks[0]);
6237   } else {
6238     assert(isa<ConstantSDNode>(N1) && "Expected a constant");
6239     MagicFactor = MagicFactors[0];
6240     Factor = Factors[0];
6241     Shift = Shifts[0];
6242     ShiftMask = ShiftMasks[0];
6243   }
6244 
6245   // Multiply the numerator (operand 0) by the magic value.
6246   // FIXME: We should support doing a MUL in a wider type.
6247   auto GetMULHS = [&](SDValue X, SDValue Y) {
6248     // If the type isn't legal, use a wider mul of the type calculated
6249     // earlier.
6250     if (!isTypeLegal(VT)) {
6251       X = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, X);
6252       Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MulVT, Y);
6253       Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
6254       Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
6255                       DAG.getShiftAmountConstant(EltBits, MulVT, dl));
6256       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
6257     }
6258 
6259     if (isOperationLegalOrCustom(ISD::MULHS, VT, IsAfterLegalization))
6260       return DAG.getNode(ISD::MULHS, dl, VT, X, Y);
6261     if (isOperationLegalOrCustom(ISD::SMUL_LOHI, VT, IsAfterLegalization)) {
6262       SDValue LoHi =
6263           DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
6264       return SDValue(LoHi.getNode(), 1);
6265     }
6266     // If type twice as wide legal, widen and use a mul plus a shift.
6267     unsigned Size = VT.getScalarSizeInBits();
6268     EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), Size * 2);
6269     if (VT.isVector())
6270       WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT,
6271                                 VT.getVectorElementCount());
6272     if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
6273       X = DAG.getNode(ISD::SIGN_EXTEND, dl, WideVT, X);
6274       Y = DAG.getNode(ISD::SIGN_EXTEND, dl, WideVT, Y);
6275       Y = DAG.getNode(ISD::MUL, dl, WideVT, X, Y);
6276       Y = DAG.getNode(ISD::SRL, dl, WideVT, Y,
6277                       DAG.getShiftAmountConstant(EltBits, WideVT, dl));
6278       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
6279     }
6280     return SDValue();
6281   };
6282 
6283   SDValue Q = GetMULHS(N0, MagicFactor);
6284   if (!Q)
6285     return SDValue();
6286 
6287   Created.push_back(Q.getNode());
6288 
6289   // (Optionally) Add/subtract the numerator using Factor.
6290   Factor = DAG.getNode(ISD::MUL, dl, VT, N0, Factor);
6291   Created.push_back(Factor.getNode());
6292   Q = DAG.getNode(ISD::ADD, dl, VT, Q, Factor);
6293   Created.push_back(Q.getNode());
6294 
6295   // Shift right algebraic by shift value.
6296   Q = DAG.getNode(ISD::SRA, dl, VT, Q, Shift);
6297   Created.push_back(Q.getNode());
6298 
6299   // Extract the sign bit, mask it and add it to the quotient.
6300   SDValue SignShift = DAG.getConstant(EltBits - 1, dl, ShVT);
6301   SDValue T = DAG.getNode(ISD::SRL, dl, VT, Q, SignShift);
6302   Created.push_back(T.getNode());
6303   T = DAG.getNode(ISD::AND, dl, VT, T, ShiftMask);
6304   Created.push_back(T.getNode());
6305   return DAG.getNode(ISD::ADD, dl, VT, Q, T);
6306 }
6307 
6308 /// Given an ISD::UDIV node expressing a divide by constant,
6309 /// return a DAG expression to select that will generate the same value by
6310 /// multiplying by a magic number.
6311 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
6312 SDValue TargetLowering::BuildUDIV(SDNode *N, SelectionDAG &DAG,
6313                                   bool IsAfterLegalization,
6314                                   SmallVectorImpl<SDNode *> &Created) const {
6315   SDLoc dl(N);
6316   EVT VT = N->getValueType(0);
6317   EVT SVT = VT.getScalarType();
6318   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
6319   EVT ShSVT = ShVT.getScalarType();
6320   unsigned EltBits = VT.getScalarSizeInBits();
6321   EVT MulVT;
6322 
6323   // Check to see if we can do this.
6324   // FIXME: We should be more aggressive here.
6325   if (!isTypeLegal(VT)) {
6326     // Limit this to simple scalars for now.
6327     if (VT.isVector() || !VT.isSimple())
6328       return SDValue();
6329 
6330     // If this type will be promoted to a large enough type with a legal
6331     // multiply operation, we can go ahead and do this transform.
6332     if (getTypeAction(VT.getSimpleVT()) != TypePromoteInteger)
6333       return SDValue();
6334 
6335     MulVT = getTypeToTransformTo(*DAG.getContext(), VT);
6336     if (MulVT.getSizeInBits() < (2 * EltBits) ||
6337         !isOperationLegal(ISD::MUL, MulVT))
6338       return SDValue();
6339   }
6340 
6341   SDValue N0 = N->getOperand(0);
6342   SDValue N1 = N->getOperand(1);
6343 
6344   // Try to use leading zeros of the dividend to reduce the multiplier and
6345   // avoid expensive fixups.
6346   // TODO: Support vectors.
6347   unsigned LeadingZeros = 0;
6348   if (!VT.isVector() && isa<ConstantSDNode>(N1)) {
6349     assert(!isOneConstant(N1) && "Unexpected divisor");
6350     LeadingZeros = DAG.computeKnownBits(N0).countMinLeadingZeros();
6351     // UnsignedDivisionByConstantInfo doesn't work correctly if leading zeros in
6352     // the dividend exceeds the leading zeros for the divisor.
6353     LeadingZeros = std::min(LeadingZeros, N1->getAsAPIntVal().countl_zero());
6354   }
6355 
6356   bool UseNPQ = false, UsePreShift = false, UsePostShift = false;
6357   SmallVector<SDValue, 16> PreShifts, PostShifts, MagicFactors, NPQFactors;
6358 
6359   auto BuildUDIVPattern = [&](ConstantSDNode *C) {
6360     if (C->isZero())
6361       return false;
6362     const APInt& Divisor = C->getAPIntValue();
6363 
6364     SDValue PreShift, MagicFactor, NPQFactor, PostShift;
6365 
6366     // Magic algorithm doesn't work for division by 1. We need to emit a select
6367     // at the end.
6368     if (Divisor.isOne()) {
6369       PreShift = PostShift = DAG.getUNDEF(ShSVT);
6370       MagicFactor = NPQFactor = DAG.getUNDEF(SVT);
6371     } else {
6372       UnsignedDivisionByConstantInfo magics =
6373           UnsignedDivisionByConstantInfo::get(Divisor, LeadingZeros);
6374 
6375       MagicFactor = DAG.getConstant(magics.Magic, dl, SVT);
6376 
6377       assert(magics.PreShift < Divisor.getBitWidth() &&
6378              "We shouldn't generate an undefined shift!");
6379       assert(magics.PostShift < Divisor.getBitWidth() &&
6380              "We shouldn't generate an undefined shift!");
6381       assert((!magics.IsAdd || magics.PreShift == 0) &&
6382              "Unexpected pre-shift");
6383       PreShift = DAG.getConstant(magics.PreShift, dl, ShSVT);
6384       PostShift = DAG.getConstant(magics.PostShift, dl, ShSVT);
6385       NPQFactor = DAG.getConstant(
6386           magics.IsAdd ? APInt::getOneBitSet(EltBits, EltBits - 1)
6387                        : APInt::getZero(EltBits),
6388           dl, SVT);
6389       UseNPQ |= magics.IsAdd;
6390       UsePreShift |= magics.PreShift != 0;
6391       UsePostShift |= magics.PostShift != 0;
6392     }
6393 
6394     PreShifts.push_back(PreShift);
6395     MagicFactors.push_back(MagicFactor);
6396     NPQFactors.push_back(NPQFactor);
6397     PostShifts.push_back(PostShift);
6398     return true;
6399   };
6400 
6401   // Collect the shifts/magic values from each element.
6402   if (!ISD::matchUnaryPredicate(N1, BuildUDIVPattern))
6403     return SDValue();
6404 
6405   SDValue PreShift, PostShift, MagicFactor, NPQFactor;
6406   if (N1.getOpcode() == ISD::BUILD_VECTOR) {
6407     PreShift = DAG.getBuildVector(ShVT, dl, PreShifts);
6408     MagicFactor = DAG.getBuildVector(VT, dl, MagicFactors);
6409     NPQFactor = DAG.getBuildVector(VT, dl, NPQFactors);
6410     PostShift = DAG.getBuildVector(ShVT, dl, PostShifts);
6411   } else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
6412     assert(PreShifts.size() == 1 && MagicFactors.size() == 1 &&
6413            NPQFactors.size() == 1 && PostShifts.size() == 1 &&
6414            "Expected matchUnaryPredicate to return one for scalable vectors");
6415     PreShift = DAG.getSplatVector(ShVT, dl, PreShifts[0]);
6416     MagicFactor = DAG.getSplatVector(VT, dl, MagicFactors[0]);
6417     NPQFactor = DAG.getSplatVector(VT, dl, NPQFactors[0]);
6418     PostShift = DAG.getSplatVector(ShVT, dl, PostShifts[0]);
6419   } else {
6420     assert(isa<ConstantSDNode>(N1) && "Expected a constant");
6421     PreShift = PreShifts[0];
6422     MagicFactor = MagicFactors[0];
6423     PostShift = PostShifts[0];
6424   }
6425 
6426   SDValue Q = N0;
6427   if (UsePreShift) {
6428     Q = DAG.getNode(ISD::SRL, dl, VT, Q, PreShift);
6429     Created.push_back(Q.getNode());
6430   }
6431 
6432   // FIXME: We should support doing a MUL in a wider type.
6433   auto GetMULHU = [&](SDValue X, SDValue Y) {
6434     // If the type isn't legal, use a wider mul of the type calculated
6435     // earlier.
6436     if (!isTypeLegal(VT)) {
6437       X = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, X);
6438       Y = DAG.getNode(ISD::ZERO_EXTEND, dl, MulVT, Y);
6439       Y = DAG.getNode(ISD::MUL, dl, MulVT, X, Y);
6440       Y = DAG.getNode(ISD::SRL, dl, MulVT, Y,
6441                       DAG.getShiftAmountConstant(EltBits, MulVT, dl));
6442       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
6443     }
6444 
6445     if (isOperationLegalOrCustom(ISD::MULHU, VT, IsAfterLegalization))
6446       return DAG.getNode(ISD::MULHU, dl, VT, X, Y);
6447     if (isOperationLegalOrCustom(ISD::UMUL_LOHI, VT, IsAfterLegalization)) {
6448       SDValue LoHi =
6449           DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(VT, VT), X, Y);
6450       return SDValue(LoHi.getNode(), 1);
6451     }
6452     // If type twice as wide legal, widen and use a mul plus a shift.
6453     unsigned Size = VT.getScalarSizeInBits();
6454     EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), Size * 2);
6455     if (VT.isVector())
6456       WideVT = EVT::getVectorVT(*DAG.getContext(), WideVT,
6457                                 VT.getVectorElementCount());
6458     if (isOperationLegalOrCustom(ISD::MUL, WideVT)) {
6459       X = DAG.getNode(ISD::ZERO_EXTEND, dl, WideVT, X);
6460       Y = DAG.getNode(ISD::ZERO_EXTEND, dl, WideVT, Y);
6461       Y = DAG.getNode(ISD::MUL, dl, WideVT, X, Y);
6462       Y = DAG.getNode(ISD::SRL, dl, WideVT, Y,
6463                       DAG.getShiftAmountConstant(EltBits, WideVT, dl));
6464       return DAG.getNode(ISD::TRUNCATE, dl, VT, Y);
6465     }
6466     return SDValue(); // No mulhu or equivalent
6467   };
6468 
6469   // Multiply the numerator (operand 0) by the magic value.
6470   Q = GetMULHU(Q, MagicFactor);
6471   if (!Q)
6472     return SDValue();
6473 
6474   Created.push_back(Q.getNode());
6475 
6476   if (UseNPQ) {
6477     SDValue NPQ = DAG.getNode(ISD::SUB, dl, VT, N0, Q);
6478     Created.push_back(NPQ.getNode());
6479 
6480     // For vectors we might have a mix of non-NPQ/NPQ paths, so use
6481     // MULHU to act as a SRL-by-1 for NPQ, else multiply by zero.
6482     if (VT.isVector())
6483       NPQ = GetMULHU(NPQ, NPQFactor);
6484     else
6485       NPQ = DAG.getNode(ISD::SRL, dl, VT, NPQ, DAG.getConstant(1, dl, ShVT));
6486 
6487     Created.push_back(NPQ.getNode());
6488 
6489     Q = DAG.getNode(ISD::ADD, dl, VT, NPQ, Q);
6490     Created.push_back(Q.getNode());
6491   }
6492 
6493   if (UsePostShift) {
6494     Q = DAG.getNode(ISD::SRL, dl, VT, Q, PostShift);
6495     Created.push_back(Q.getNode());
6496   }
6497 
6498   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
6499 
6500   SDValue One = DAG.getConstant(1, dl, VT);
6501   SDValue IsOne = DAG.getSetCC(dl, SetCCVT, N1, One, ISD::SETEQ);
6502   return DAG.getSelect(dl, VT, IsOne, N0, Q);
6503 }
6504 
6505 /// If all values in Values that *don't* match the predicate are same 'splat'
6506 /// value, then replace all values with that splat value.
6507 /// Else, if AlternativeReplacement was provided, then replace all values that
6508 /// do match predicate with AlternativeReplacement value.
6509 static void
6510 turnVectorIntoSplatVector(MutableArrayRef<SDValue> Values,
6511                           std::function<bool(SDValue)> Predicate,
6512                           SDValue AlternativeReplacement = SDValue()) {
6513   SDValue Replacement;
6514   // Is there a value for which the Predicate does *NOT* match? What is it?
6515   auto SplatValue = llvm::find_if_not(Values, Predicate);
6516   if (SplatValue != Values.end()) {
6517     // Does Values consist only of SplatValue's and values matching Predicate?
6518     if (llvm::all_of(Values, [Predicate, SplatValue](SDValue Value) {
6519           return Value == *SplatValue || Predicate(Value);
6520         })) // Then we shall replace values matching predicate with SplatValue.
6521       Replacement = *SplatValue;
6522   }
6523   if (!Replacement) {
6524     // Oops, we did not find the "baseline" splat value.
6525     if (!AlternativeReplacement)
6526       return; // Nothing to do.
6527     // Let's replace with provided value then.
6528     Replacement = AlternativeReplacement;
6529   }
6530   std::replace_if(Values.begin(), Values.end(), Predicate, Replacement);
6531 }
6532 
6533 /// Given an ISD::UREM used only by an ISD::SETEQ or ISD::SETNE
6534 /// where the divisor is constant and the comparison target is zero,
6535 /// return a DAG expression that will generate the same comparison result
6536 /// using only multiplications, additions and shifts/rotations.
6537 /// Ref: "Hacker's Delight" 10-17.
6538 SDValue TargetLowering::buildUREMEqFold(EVT SETCCVT, SDValue REMNode,
6539                                         SDValue CompTargetNode,
6540                                         ISD::CondCode Cond,
6541                                         DAGCombinerInfo &DCI,
6542                                         const SDLoc &DL) const {
6543   SmallVector<SDNode *, 5> Built;
6544   if (SDValue Folded = prepareUREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
6545                                          DCI, DL, Built)) {
6546     for (SDNode *N : Built)
6547       DCI.AddToWorklist(N);
6548     return Folded;
6549   }
6550 
6551   return SDValue();
6552 }
6553 
6554 SDValue
6555 TargetLowering::prepareUREMEqFold(EVT SETCCVT, SDValue REMNode,
6556                                   SDValue CompTargetNode, ISD::CondCode Cond,
6557                                   DAGCombinerInfo &DCI, const SDLoc &DL,
6558                                   SmallVectorImpl<SDNode *> &Created) const {
6559   // fold (seteq/ne (urem N, D), 0) -> (setule/ugt (rotr (mul N, P), K), Q)
6560   // - D must be constant, with D = D0 * 2^K where D0 is odd
6561   // - P is the multiplicative inverse of D0 modulo 2^W
6562   // - Q = floor(((2^W) - 1) / D)
6563   // where W is the width of the common type of N and D.
6564   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
6565          "Only applicable for (in)equality comparisons.");
6566 
6567   SelectionDAG &DAG = DCI.DAG;
6568 
6569   EVT VT = REMNode.getValueType();
6570   EVT SVT = VT.getScalarType();
6571   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize());
6572   EVT ShSVT = ShVT.getScalarType();
6573 
6574   // If MUL is unavailable, we cannot proceed in any case.
6575   if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
6576     return SDValue();
6577 
6578   bool ComparingWithAllZeros = true;
6579   bool AllComparisonsWithNonZerosAreTautological = true;
6580   bool HadTautologicalLanes = false;
6581   bool AllLanesAreTautological = true;
6582   bool HadEvenDivisor = false;
6583   bool AllDivisorsArePowerOfTwo = true;
6584   bool HadTautologicalInvertedLanes = false;
6585   SmallVector<SDValue, 16> PAmts, KAmts, QAmts, IAmts;
6586 
6587   auto BuildUREMPattern = [&](ConstantSDNode *CDiv, ConstantSDNode *CCmp) {
6588     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
6589     if (CDiv->isZero())
6590       return false;
6591 
6592     const APInt &D = CDiv->getAPIntValue();
6593     const APInt &Cmp = CCmp->getAPIntValue();
6594 
6595     ComparingWithAllZeros &= Cmp.isZero();
6596 
6597     // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
6598     // if C2 is not less than C1, the comparison is always false.
6599     // But we will only be able to produce the comparison that will give the
6600     // opposive tautological answer. So this lane would need to be fixed up.
6601     bool TautologicalInvertedLane = D.ule(Cmp);
6602     HadTautologicalInvertedLanes |= TautologicalInvertedLane;
6603 
6604     // If all lanes are tautological (either all divisors are ones, or divisor
6605     // is not greater than the constant we are comparing with),
6606     // we will prefer to avoid the fold.
6607     bool TautologicalLane = D.isOne() || TautologicalInvertedLane;
6608     HadTautologicalLanes |= TautologicalLane;
6609     AllLanesAreTautological &= TautologicalLane;
6610 
6611     // If we are comparing with non-zero, we need'll need  to subtract said
6612     // comparison value from the LHS. But there is no point in doing that if
6613     // every lane where we are comparing with non-zero is tautological..
6614     if (!Cmp.isZero())
6615       AllComparisonsWithNonZerosAreTautological &= TautologicalLane;
6616 
6617     // Decompose D into D0 * 2^K
6618     unsigned K = D.countr_zero();
6619     assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
6620     APInt D0 = D.lshr(K);
6621 
6622     // D is even if it has trailing zeros.
6623     HadEvenDivisor |= (K != 0);
6624     // D is a power-of-two if D0 is one.
6625     // If all divisors are power-of-two, we will prefer to avoid the fold.
6626     AllDivisorsArePowerOfTwo &= D0.isOne();
6627 
6628     // P = inv(D0, 2^W)
6629     // 2^W requires W + 1 bits, so we have to extend and then truncate.
6630     unsigned W = D.getBitWidth();
6631     APInt P = D0.zext(W + 1)
6632                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
6633                   .trunc(W);
6634     assert(!P.isZero() && "No multiplicative inverse!"); // unreachable
6635     assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
6636 
6637     // Q = floor((2^W - 1) u/ D)
6638     // R = ((2^W - 1) u% D)
6639     APInt Q, R;
6640     APInt::udivrem(APInt::getAllOnes(W), D, Q, R);
6641 
6642     // If we are comparing with zero, then that comparison constant is okay,
6643     // else it may need to be one less than that.
6644     if (Cmp.ugt(R))
6645       Q -= 1;
6646 
6647     assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) &&
6648            "We are expecting that K is always less than all-ones for ShSVT");
6649 
6650     // If the lane is tautological the result can be constant-folded.
6651     if (TautologicalLane) {
6652       // Set P and K amount to a bogus values so we can try to splat them.
6653       P = 0;
6654       K = -1;
6655       // And ensure that comparison constant is tautological,
6656       // it will always compare true/false.
6657       Q = -1;
6658     }
6659 
6660     PAmts.push_back(DAG.getConstant(P, DL, SVT));
6661     KAmts.push_back(
6662         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
6663     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
6664     return true;
6665   };
6666 
6667   SDValue N = REMNode.getOperand(0);
6668   SDValue D = REMNode.getOperand(1);
6669 
6670   // Collect the values from each element.
6671   if (!ISD::matchBinaryPredicate(D, CompTargetNode, BuildUREMPattern))
6672     return SDValue();
6673 
6674   // If all lanes are tautological, the result can be constant-folded.
6675   if (AllLanesAreTautological)
6676     return SDValue();
6677 
6678   // If this is a urem by a powers-of-two, avoid the fold since it can be
6679   // best implemented as a bit test.
6680   if (AllDivisorsArePowerOfTwo)
6681     return SDValue();
6682 
6683   SDValue PVal, KVal, QVal;
6684   if (D.getOpcode() == ISD::BUILD_VECTOR) {
6685     if (HadTautologicalLanes) {
6686       // Try to turn PAmts into a splat, since we don't care about the values
6687       // that are currently '0'. If we can't, just keep '0'`s.
6688       turnVectorIntoSplatVector(PAmts, isNullConstant);
6689       // Try to turn KAmts into a splat, since we don't care about the values
6690       // that are currently '-1'. If we can't, change them to '0'`s.
6691       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
6692                                 DAG.getConstant(0, DL, ShSVT));
6693     }
6694 
6695     PVal = DAG.getBuildVector(VT, DL, PAmts);
6696     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
6697     QVal = DAG.getBuildVector(VT, DL, QAmts);
6698   } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
6699     assert(PAmts.size() == 1 && KAmts.size() == 1 && QAmts.size() == 1 &&
6700            "Expected matchBinaryPredicate to return one element for "
6701            "SPLAT_VECTORs");
6702     PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
6703     KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
6704     QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
6705   } else {
6706     PVal = PAmts[0];
6707     KVal = KAmts[0];
6708     QVal = QAmts[0];
6709   }
6710 
6711   if (!ComparingWithAllZeros && !AllComparisonsWithNonZerosAreTautological) {
6712     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::SUB, VT))
6713       return SDValue(); // FIXME: Could/should use `ISD::ADD`?
6714     assert(CompTargetNode.getValueType() == N.getValueType() &&
6715            "Expecting that the types on LHS and RHS of comparisons match.");
6716     N = DAG.getNode(ISD::SUB, DL, VT, N, CompTargetNode);
6717   }
6718 
6719   // (mul N, P)
6720   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
6721   Created.push_back(Op0.getNode());
6722 
6723   // Rotate right only if any divisor was even. We avoid rotates for all-odd
6724   // divisors as a performance improvement, since rotating by 0 is a no-op.
6725   if (HadEvenDivisor) {
6726     // We need ROTR to do this.
6727     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
6728       return SDValue();
6729     // UREM: (rotr (mul N, P), K)
6730     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
6731     Created.push_back(Op0.getNode());
6732   }
6733 
6734   // UREM: (setule/setugt (rotr (mul N, P), K), Q)
6735   SDValue NewCC =
6736       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
6737                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
6738   if (!HadTautologicalInvertedLanes)
6739     return NewCC;
6740 
6741   // If any lanes previously compared always-false, the NewCC will give
6742   // always-true result for them, so we need to fixup those lanes.
6743   // Or the other way around for inequality predicate.
6744   assert(VT.isVector() && "Can/should only get here for vectors.");
6745   Created.push_back(NewCC.getNode());
6746 
6747   // x u% C1` is *always* less than C1. So given `x u% C1 == C2`,
6748   // if C2 is not less than C1, the comparison is always false.
6749   // But we have produced the comparison that will give the
6750   // opposive tautological answer. So these lanes would need to be fixed up.
6751   SDValue TautologicalInvertedChannels =
6752       DAG.getSetCC(DL, SETCCVT, D, CompTargetNode, ISD::SETULE);
6753   Created.push_back(TautologicalInvertedChannels.getNode());
6754 
6755   // NOTE: we avoid letting illegal types through even if we're before legalize
6756   // ops – legalization has a hard time producing good code for this.
6757   if (isOperationLegalOrCustom(ISD::VSELECT, SETCCVT)) {
6758     // If we have a vector select, let's replace the comparison results in the
6759     // affected lanes with the correct tautological result.
6760     SDValue Replacement = DAG.getBoolConstant(Cond == ISD::SETEQ ? false : true,
6761                                               DL, SETCCVT, SETCCVT);
6762     return DAG.getNode(ISD::VSELECT, DL, SETCCVT, TautologicalInvertedChannels,
6763                        Replacement, NewCC);
6764   }
6765 
6766   // Else, we can just invert the comparison result in the appropriate lanes.
6767   //
6768   // NOTE: see the note above VSELECT above.
6769   if (isOperationLegalOrCustom(ISD::XOR, SETCCVT))
6770     return DAG.getNode(ISD::XOR, DL, SETCCVT, NewCC,
6771                        TautologicalInvertedChannels);
6772 
6773   return SDValue(); // Don't know how to lower.
6774 }
6775 
6776 /// Given an ISD::SREM used only by an ISD::SETEQ or ISD::SETNE
6777 /// where the divisor is constant and the comparison target is zero,
6778 /// return a DAG expression that will generate the same comparison result
6779 /// using only multiplications, additions and shifts/rotations.
6780 /// Ref: "Hacker's Delight" 10-17.
6781 SDValue TargetLowering::buildSREMEqFold(EVT SETCCVT, SDValue REMNode,
6782                                         SDValue CompTargetNode,
6783                                         ISD::CondCode Cond,
6784                                         DAGCombinerInfo &DCI,
6785                                         const SDLoc &DL) const {
6786   SmallVector<SDNode *, 7> Built;
6787   if (SDValue Folded = prepareSREMEqFold(SETCCVT, REMNode, CompTargetNode, Cond,
6788                                          DCI, DL, Built)) {
6789     assert(Built.size() <= 7 && "Max size prediction failed.");
6790     for (SDNode *N : Built)
6791       DCI.AddToWorklist(N);
6792     return Folded;
6793   }
6794 
6795   return SDValue();
6796 }
6797 
6798 SDValue
6799 TargetLowering::prepareSREMEqFold(EVT SETCCVT, SDValue REMNode,
6800                                   SDValue CompTargetNode, ISD::CondCode Cond,
6801                                   DAGCombinerInfo &DCI, const SDLoc &DL,
6802                                   SmallVectorImpl<SDNode *> &Created) const {
6803   // Fold:
6804   //   (seteq/ne (srem N, D), 0)
6805   // To:
6806   //   (setule/ugt (rotr (add (mul N, P), A), K), Q)
6807   //
6808   // - D must be constant, with D = D0 * 2^K where D0 is odd
6809   // - P is the multiplicative inverse of D0 modulo 2^W
6810   // - A = bitwiseand(floor((2^(W - 1) - 1) / D0), (-(2^k)))
6811   // - Q = floor((2 * A) / (2^K))
6812   // where W is the width of the common type of N and D.
6813   assert((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
6814          "Only applicable for (in)equality comparisons.");
6815 
6816   SelectionDAG &DAG = DCI.DAG;
6817 
6818   EVT VT = REMNode.getValueType();
6819   EVT SVT = VT.getScalarType();
6820   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout(), !DCI.isBeforeLegalize());
6821   EVT ShSVT = ShVT.getScalarType();
6822 
6823   // If we are after ops legalization, and MUL is unavailable, we can not
6824   // proceed.
6825   if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::MUL, VT))
6826     return SDValue();
6827 
6828   // TODO: Could support comparing with non-zero too.
6829   ConstantSDNode *CompTarget = isConstOrConstSplat(CompTargetNode);
6830   if (!CompTarget || !CompTarget->isZero())
6831     return SDValue();
6832 
6833   bool HadIntMinDivisor = false;
6834   bool HadOneDivisor = false;
6835   bool AllDivisorsAreOnes = true;
6836   bool HadEvenDivisor = false;
6837   bool NeedToApplyOffset = false;
6838   bool AllDivisorsArePowerOfTwo = true;
6839   SmallVector<SDValue, 16> PAmts, AAmts, KAmts, QAmts;
6840 
6841   auto BuildSREMPattern = [&](ConstantSDNode *C) {
6842     // Division by 0 is UB. Leave it to be constant-folded elsewhere.
6843     if (C->isZero())
6844       return false;
6845 
6846     // FIXME: we don't fold `rem %X, -C` to `rem %X, C` in DAGCombine.
6847 
6848     // WARNING: this fold is only valid for positive divisors!
6849     APInt D = C->getAPIntValue();
6850     if (D.isNegative())
6851       D.negate(); //  `rem %X, -C` is equivalent to `rem %X, C`
6852 
6853     HadIntMinDivisor |= D.isMinSignedValue();
6854 
6855     // If all divisors are ones, we will prefer to avoid the fold.
6856     HadOneDivisor |= D.isOne();
6857     AllDivisorsAreOnes &= D.isOne();
6858 
6859     // Decompose D into D0 * 2^K
6860     unsigned K = D.countr_zero();
6861     assert((!D.isOne() || (K == 0)) && "For divisor '1' we won't rotate.");
6862     APInt D0 = D.lshr(K);
6863 
6864     if (!D.isMinSignedValue()) {
6865       // D is even if it has trailing zeros; unless it's INT_MIN, in which case
6866       // we don't care about this lane in this fold, we'll special-handle it.
6867       HadEvenDivisor |= (K != 0);
6868     }
6869 
6870     // D is a power-of-two if D0 is one. This includes INT_MIN.
6871     // If all divisors are power-of-two, we will prefer to avoid the fold.
6872     AllDivisorsArePowerOfTwo &= D0.isOne();
6873 
6874     // P = inv(D0, 2^W)
6875     // 2^W requires W + 1 bits, so we have to extend and then truncate.
6876     unsigned W = D.getBitWidth();
6877     APInt P = D0.zext(W + 1)
6878                   .multiplicativeInverse(APInt::getSignedMinValue(W + 1))
6879                   .trunc(W);
6880     assert(!P.isZero() && "No multiplicative inverse!"); // unreachable
6881     assert((D0 * P).isOne() && "Multiplicative inverse basic check failed.");
6882 
6883     // A = floor((2^(W - 1) - 1) / D0) & -2^K
6884     APInt A = APInt::getSignedMaxValue(W).udiv(D0);
6885     A.clearLowBits(K);
6886 
6887     if (!D.isMinSignedValue()) {
6888       // If divisor INT_MIN, then we don't care about this lane in this fold,
6889       // we'll special-handle it.
6890       NeedToApplyOffset |= A != 0;
6891     }
6892 
6893     // Q = floor((2 * A) / (2^K))
6894     APInt Q = (2 * A).udiv(APInt::getOneBitSet(W, K));
6895 
6896     assert(APInt::getAllOnes(SVT.getSizeInBits()).ugt(A) &&
6897            "We are expecting that A is always less than all-ones for SVT");
6898     assert(APInt::getAllOnes(ShSVT.getSizeInBits()).ugt(K) &&
6899            "We are expecting that K is always less than all-ones for ShSVT");
6900 
6901     // If the divisor is 1 the result can be constant-folded. Likewise, we
6902     // don't care about INT_MIN lanes, those can be set to undef if appropriate.
6903     if (D.isOne()) {
6904       // Set P, A and K to a bogus values so we can try to splat them.
6905       P = 0;
6906       A = -1;
6907       K = -1;
6908 
6909       // x ?% 1 == 0  <-->  true  <-->  x u<= -1
6910       Q = -1;
6911     }
6912 
6913     PAmts.push_back(DAG.getConstant(P, DL, SVT));
6914     AAmts.push_back(DAG.getConstant(A, DL, SVT));
6915     KAmts.push_back(
6916         DAG.getConstant(APInt(ShSVT.getSizeInBits(), K), DL, ShSVT));
6917     QAmts.push_back(DAG.getConstant(Q, DL, SVT));
6918     return true;
6919   };
6920 
6921   SDValue N = REMNode.getOperand(0);
6922   SDValue D = REMNode.getOperand(1);
6923 
6924   // Collect the values from each element.
6925   if (!ISD::matchUnaryPredicate(D, BuildSREMPattern))
6926     return SDValue();
6927 
6928   // If this is a srem by a one, avoid the fold since it can be constant-folded.
6929   if (AllDivisorsAreOnes)
6930     return SDValue();
6931 
6932   // If this is a srem by a powers-of-two (including INT_MIN), avoid the fold
6933   // since it can be best implemented as a bit test.
6934   if (AllDivisorsArePowerOfTwo)
6935     return SDValue();
6936 
6937   SDValue PVal, AVal, KVal, QVal;
6938   if (D.getOpcode() == ISD::BUILD_VECTOR) {
6939     if (HadOneDivisor) {
6940       // Try to turn PAmts into a splat, since we don't care about the values
6941       // that are currently '0'. If we can't, just keep '0'`s.
6942       turnVectorIntoSplatVector(PAmts, isNullConstant);
6943       // Try to turn AAmts into a splat, since we don't care about the
6944       // values that are currently '-1'. If we can't, change them to '0'`s.
6945       turnVectorIntoSplatVector(AAmts, isAllOnesConstant,
6946                                 DAG.getConstant(0, DL, SVT));
6947       // Try to turn KAmts into a splat, since we don't care about the values
6948       // that are currently '-1'. If we can't, change them to '0'`s.
6949       turnVectorIntoSplatVector(KAmts, isAllOnesConstant,
6950                                 DAG.getConstant(0, DL, ShSVT));
6951     }
6952 
6953     PVal = DAG.getBuildVector(VT, DL, PAmts);
6954     AVal = DAG.getBuildVector(VT, DL, AAmts);
6955     KVal = DAG.getBuildVector(ShVT, DL, KAmts);
6956     QVal = DAG.getBuildVector(VT, DL, QAmts);
6957   } else if (D.getOpcode() == ISD::SPLAT_VECTOR) {
6958     assert(PAmts.size() == 1 && AAmts.size() == 1 && KAmts.size() == 1 &&
6959            QAmts.size() == 1 &&
6960            "Expected matchUnaryPredicate to return one element for scalable "
6961            "vectors");
6962     PVal = DAG.getSplatVector(VT, DL, PAmts[0]);
6963     AVal = DAG.getSplatVector(VT, DL, AAmts[0]);
6964     KVal = DAG.getSplatVector(ShVT, DL, KAmts[0]);
6965     QVal = DAG.getSplatVector(VT, DL, QAmts[0]);
6966   } else {
6967     assert(isa<ConstantSDNode>(D) && "Expected a constant");
6968     PVal = PAmts[0];
6969     AVal = AAmts[0];
6970     KVal = KAmts[0];
6971     QVal = QAmts[0];
6972   }
6973 
6974   // (mul N, P)
6975   SDValue Op0 = DAG.getNode(ISD::MUL, DL, VT, N, PVal);
6976   Created.push_back(Op0.getNode());
6977 
6978   if (NeedToApplyOffset) {
6979     // We need ADD to do this.
6980     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ADD, VT))
6981       return SDValue();
6982 
6983     // (add (mul N, P), A)
6984     Op0 = DAG.getNode(ISD::ADD, DL, VT, Op0, AVal);
6985     Created.push_back(Op0.getNode());
6986   }
6987 
6988   // Rotate right only if any divisor was even. We avoid rotates for all-odd
6989   // divisors as a performance improvement, since rotating by 0 is a no-op.
6990   if (HadEvenDivisor) {
6991     // We need ROTR to do this.
6992     if (!DCI.isBeforeLegalizeOps() && !isOperationLegalOrCustom(ISD::ROTR, VT))
6993       return SDValue();
6994     // SREM: (rotr (add (mul N, P), A), K)
6995     Op0 = DAG.getNode(ISD::ROTR, DL, VT, Op0, KVal);
6996     Created.push_back(Op0.getNode());
6997   }
6998 
6999   // SREM: (setule/setugt (rotr (add (mul N, P), A), K), Q)
7000   SDValue Fold =
7001       DAG.getSetCC(DL, SETCCVT, Op0, QVal,
7002                    ((Cond == ISD::SETEQ) ? ISD::SETULE : ISD::SETUGT));
7003 
7004   // If we didn't have lanes with INT_MIN divisor, then we're done.
7005   if (!HadIntMinDivisor)
7006     return Fold;
7007 
7008   // That fold is only valid for positive divisors. Which effectively means,
7009   // it is invalid for INT_MIN divisors. So if we have such a lane,
7010   // we must fix-up results for said lanes.
7011   assert(VT.isVector() && "Can/should only get here for vectors.");
7012 
7013   // NOTE: we avoid letting illegal types through even if we're before legalize
7014   // ops – legalization has a hard time producing good code for the code that
7015   // follows.
7016   if (!isOperationLegalOrCustom(ISD::SETCC, SETCCVT) ||
7017       !isOperationLegalOrCustom(ISD::AND, VT) ||
7018       !isCondCodeLegalOrCustom(Cond, VT.getSimpleVT()) ||
7019       !isOperationLegalOrCustom(ISD::VSELECT, SETCCVT))
7020     return SDValue();
7021 
7022   Created.push_back(Fold.getNode());
7023 
7024   SDValue IntMin = DAG.getConstant(
7025       APInt::getSignedMinValue(SVT.getScalarSizeInBits()), DL, VT);
7026   SDValue IntMax = DAG.getConstant(
7027       APInt::getSignedMaxValue(SVT.getScalarSizeInBits()), DL, VT);
7028   SDValue Zero =
7029       DAG.getConstant(APInt::getZero(SVT.getScalarSizeInBits()), DL, VT);
7030 
7031   // Which lanes had INT_MIN divisors? Divisor is constant, so const-folded.
7032   SDValue DivisorIsIntMin = DAG.getSetCC(DL, SETCCVT, D, IntMin, ISD::SETEQ);
7033   Created.push_back(DivisorIsIntMin.getNode());
7034 
7035   // (N s% INT_MIN) ==/!= 0  <-->  (N & INT_MAX) ==/!= 0
7036   SDValue Masked = DAG.getNode(ISD::AND, DL, VT, N, IntMax);
7037   Created.push_back(Masked.getNode());
7038   SDValue MaskedIsZero = DAG.getSetCC(DL, SETCCVT, Masked, Zero, Cond);
7039   Created.push_back(MaskedIsZero.getNode());
7040 
7041   // To produce final result we need to blend 2 vectors: 'SetCC' and
7042   // 'MaskedIsZero'. If the divisor for channel was *NOT* INT_MIN, we pick
7043   // from 'Fold', else pick from 'MaskedIsZero'. Since 'DivisorIsIntMin' is
7044   // constant-folded, select can get lowered to a shuffle with constant mask.
7045   SDValue Blended = DAG.getNode(ISD::VSELECT, DL, SETCCVT, DivisorIsIntMin,
7046                                 MaskedIsZero, Fold);
7047 
7048   return Blended;
7049 }
7050 
7051 bool TargetLowering::
7052 verifyReturnAddressArgumentIsConstant(SDValue Op, SelectionDAG &DAG) const {
7053   if (!isa<ConstantSDNode>(Op.getOperand(0))) {
7054     DAG.getContext()->emitError("argument to '__builtin_return_address' must "
7055                                 "be a constant integer");
7056     return true;
7057   }
7058 
7059   return false;
7060 }
7061 
7062 SDValue TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
7063                                          const DenormalMode &Mode) const {
7064   SDLoc DL(Op);
7065   EVT VT = Op.getValueType();
7066   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7067   SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
7068 
7069   // This is specifically a check for the handling of denormal inputs, not the
7070   // result.
7071   if (Mode.Input == DenormalMode::PreserveSign ||
7072       Mode.Input == DenormalMode::PositiveZero) {
7073     // Test = X == 0.0
7074     return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
7075   }
7076 
7077   // Testing it with denormal inputs to avoid wrong estimate.
7078   //
7079   // Test = fabs(X) < SmallestNormal
7080   const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
7081   APFloat SmallestNorm = APFloat::getSmallestNormalized(FltSem);
7082   SDValue NormC = DAG.getConstantFP(SmallestNorm, DL, VT);
7083   SDValue Fabs = DAG.getNode(ISD::FABS, DL, VT, Op);
7084   return DAG.getSetCC(DL, CCVT, Fabs, NormC, ISD::SETLT);
7085 }
7086 
7087 SDValue TargetLowering::getNegatedExpression(SDValue Op, SelectionDAG &DAG,
7088                                              bool LegalOps, bool OptForSize,
7089                                              NegatibleCost &Cost,
7090                                              unsigned Depth) const {
7091   // fneg is removable even if it has multiple uses.
7092   if (Op.getOpcode() == ISD::FNEG || Op.getOpcode() == ISD::VP_FNEG) {
7093     Cost = NegatibleCost::Cheaper;
7094     return Op.getOperand(0);
7095   }
7096 
7097   // Don't recurse exponentially.
7098   if (Depth > SelectionDAG::MaxRecursionDepth)
7099     return SDValue();
7100 
7101   // Pre-increment recursion depth for use in recursive calls.
7102   ++Depth;
7103   const SDNodeFlags Flags = Op->getFlags();
7104   const TargetOptions &Options = DAG.getTarget().Options;
7105   EVT VT = Op.getValueType();
7106   unsigned Opcode = Op.getOpcode();
7107 
7108   // Don't allow anything with multiple uses unless we know it is free.
7109   if (!Op.hasOneUse() && Opcode != ISD::ConstantFP) {
7110     bool IsFreeExtend = Opcode == ISD::FP_EXTEND &&
7111                         isFPExtFree(VT, Op.getOperand(0).getValueType());
7112     if (!IsFreeExtend)
7113       return SDValue();
7114   }
7115 
7116   auto RemoveDeadNode = [&](SDValue N) {
7117     if (N && N.getNode()->use_empty())
7118       DAG.RemoveDeadNode(N.getNode());
7119   };
7120 
7121   SDLoc DL(Op);
7122 
7123   // Because getNegatedExpression can delete nodes we need a handle to keep
7124   // temporary nodes alive in case the recursion manages to create an identical
7125   // node.
7126   std::list<HandleSDNode> Handles;
7127 
7128   switch (Opcode) {
7129   case ISD::ConstantFP: {
7130     // Don't invert constant FP values after legalization unless the target says
7131     // the negated constant is legal.
7132     bool IsOpLegal =
7133         isOperationLegal(ISD::ConstantFP, VT) ||
7134         isFPImmLegal(neg(cast<ConstantFPSDNode>(Op)->getValueAPF()), VT,
7135                      OptForSize);
7136 
7137     if (LegalOps && !IsOpLegal)
7138       break;
7139 
7140     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
7141     V.changeSign();
7142     SDValue CFP = DAG.getConstantFP(V, DL, VT);
7143 
7144     // If we already have the use of the negated floating constant, it is free
7145     // to negate it even it has multiple uses.
7146     if (!Op.hasOneUse() && CFP.use_empty())
7147       break;
7148     Cost = NegatibleCost::Neutral;
7149     return CFP;
7150   }
7151   case ISD::BUILD_VECTOR: {
7152     // Only permit BUILD_VECTOR of constants.
7153     if (llvm::any_of(Op->op_values(), [&](SDValue N) {
7154           return !N.isUndef() && !isa<ConstantFPSDNode>(N);
7155         }))
7156       break;
7157 
7158     bool IsOpLegal =
7159         (isOperationLegal(ISD::ConstantFP, VT) &&
7160          isOperationLegal(ISD::BUILD_VECTOR, VT)) ||
7161         llvm::all_of(Op->op_values(), [&](SDValue N) {
7162           return N.isUndef() ||
7163                  isFPImmLegal(neg(cast<ConstantFPSDNode>(N)->getValueAPF()), VT,
7164                               OptForSize);
7165         });
7166 
7167     if (LegalOps && !IsOpLegal)
7168       break;
7169 
7170     SmallVector<SDValue, 4> Ops;
7171     for (SDValue C : Op->op_values()) {
7172       if (C.isUndef()) {
7173         Ops.push_back(C);
7174         continue;
7175       }
7176       APFloat V = cast<ConstantFPSDNode>(C)->getValueAPF();
7177       V.changeSign();
7178       Ops.push_back(DAG.getConstantFP(V, DL, C.getValueType()));
7179     }
7180     Cost = NegatibleCost::Neutral;
7181     return DAG.getBuildVector(VT, DL, Ops);
7182   }
7183   case ISD::FADD: {
7184     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
7185       break;
7186 
7187     // After operation legalization, it might not be legal to create new FSUBs.
7188     if (LegalOps && !isOperationLegalOrCustom(ISD::FSUB, VT))
7189       break;
7190     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
7191 
7192     // fold (fneg (fadd X, Y)) -> (fsub (fneg X), Y)
7193     NegatibleCost CostX = NegatibleCost::Expensive;
7194     SDValue NegX =
7195         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
7196     // Prevent this node from being deleted by the next call.
7197     if (NegX)
7198       Handles.emplace_back(NegX);
7199 
7200     // fold (fneg (fadd X, Y)) -> (fsub (fneg Y), X)
7201     NegatibleCost CostY = NegatibleCost::Expensive;
7202     SDValue NegY =
7203         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
7204 
7205     // We're done with the handles.
7206     Handles.clear();
7207 
7208     // Negate the X if its cost is less or equal than Y.
7209     if (NegX && (CostX <= CostY)) {
7210       Cost = CostX;
7211       SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegX, Y, Flags);
7212       if (NegY != N)
7213         RemoveDeadNode(NegY);
7214       return N;
7215     }
7216 
7217     // Negate the Y if it is not expensive.
7218     if (NegY) {
7219       Cost = CostY;
7220       SDValue N = DAG.getNode(ISD::FSUB, DL, VT, NegY, X, Flags);
7221       if (NegX != N)
7222         RemoveDeadNode(NegX);
7223       return N;
7224     }
7225     break;
7226   }
7227   case ISD::FSUB: {
7228     // We can't turn -(A-B) into B-A when we honor signed zeros.
7229     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
7230       break;
7231 
7232     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
7233     // fold (fneg (fsub 0, Y)) -> Y
7234     if (ConstantFPSDNode *C = isConstOrConstSplatFP(X, /*AllowUndefs*/ true))
7235       if (C->isZero()) {
7236         Cost = NegatibleCost::Cheaper;
7237         return Y;
7238       }
7239 
7240     // fold (fneg (fsub X, Y)) -> (fsub Y, X)
7241     Cost = NegatibleCost::Neutral;
7242     return DAG.getNode(ISD::FSUB, DL, VT, Y, X, Flags);
7243   }
7244   case ISD::FMUL:
7245   case ISD::FDIV: {
7246     SDValue X = Op.getOperand(0), Y = Op.getOperand(1);
7247 
7248     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
7249     NegatibleCost CostX = NegatibleCost::Expensive;
7250     SDValue NegX =
7251         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
7252     // Prevent this node from being deleted by the next call.
7253     if (NegX)
7254       Handles.emplace_back(NegX);
7255 
7256     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
7257     NegatibleCost CostY = NegatibleCost::Expensive;
7258     SDValue NegY =
7259         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
7260 
7261     // We're done with the handles.
7262     Handles.clear();
7263 
7264     // Negate the X if its cost is less or equal than Y.
7265     if (NegX && (CostX <= CostY)) {
7266       Cost = CostX;
7267       SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, Flags);
7268       if (NegY != N)
7269         RemoveDeadNode(NegY);
7270       return N;
7271     }
7272 
7273     // Ignore X * 2.0 because that is expected to be canonicalized to X + X.
7274     if (auto *C = isConstOrConstSplatFP(Op.getOperand(1)))
7275       if (C->isExactlyValue(2.0) && Op.getOpcode() == ISD::FMUL)
7276         break;
7277 
7278     // Negate the Y if it is not expensive.
7279     if (NegY) {
7280       Cost = CostY;
7281       SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, Flags);
7282       if (NegX != N)
7283         RemoveDeadNode(NegX);
7284       return N;
7285     }
7286     break;
7287   }
7288   case ISD::FMA:
7289   case ISD::FMAD: {
7290     if (!Options.NoSignedZerosFPMath && !Flags.hasNoSignedZeros())
7291       break;
7292 
7293     SDValue X = Op.getOperand(0), Y = Op.getOperand(1), Z = Op.getOperand(2);
7294     NegatibleCost CostZ = NegatibleCost::Expensive;
7295     SDValue NegZ =
7296         getNegatedExpression(Z, DAG, LegalOps, OptForSize, CostZ, Depth);
7297     // Give up if fail to negate the Z.
7298     if (!NegZ)
7299       break;
7300 
7301     // Prevent this node from being deleted by the next two calls.
7302     Handles.emplace_back(NegZ);
7303 
7304     // fold (fneg (fma X, Y, Z)) -> (fma (fneg X), Y, (fneg Z))
7305     NegatibleCost CostX = NegatibleCost::Expensive;
7306     SDValue NegX =
7307         getNegatedExpression(X, DAG, LegalOps, OptForSize, CostX, Depth);
7308     // Prevent this node from being deleted by the next call.
7309     if (NegX)
7310       Handles.emplace_back(NegX);
7311 
7312     // fold (fneg (fma X, Y, Z)) -> (fma X, (fneg Y), (fneg Z))
7313     NegatibleCost CostY = NegatibleCost::Expensive;
7314     SDValue NegY =
7315         getNegatedExpression(Y, DAG, LegalOps, OptForSize, CostY, Depth);
7316 
7317     // We're done with the handles.
7318     Handles.clear();
7319 
7320     // Negate the X if its cost is less or equal than Y.
7321     if (NegX && (CostX <= CostY)) {
7322       Cost = std::min(CostX, CostZ);
7323       SDValue N = DAG.getNode(Opcode, DL, VT, NegX, Y, NegZ, Flags);
7324       if (NegY != N)
7325         RemoveDeadNode(NegY);
7326       return N;
7327     }
7328 
7329     // Negate the Y if it is not expensive.
7330     if (NegY) {
7331       Cost = std::min(CostY, CostZ);
7332       SDValue N = DAG.getNode(Opcode, DL, VT, X, NegY, NegZ, Flags);
7333       if (NegX != N)
7334         RemoveDeadNode(NegX);
7335       return N;
7336     }
7337     break;
7338   }
7339 
7340   case ISD::FP_EXTEND:
7341   case ISD::FSIN:
7342     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
7343                                             OptForSize, Cost, Depth))
7344       return DAG.getNode(Opcode, DL, VT, NegV);
7345     break;
7346   case ISD::FP_ROUND:
7347     if (SDValue NegV = getNegatedExpression(Op.getOperand(0), DAG, LegalOps,
7348                                             OptForSize, Cost, Depth))
7349       return DAG.getNode(ISD::FP_ROUND, DL, VT, NegV, Op.getOperand(1));
7350     break;
7351   case ISD::SELECT:
7352   case ISD::VSELECT: {
7353     // fold (fneg (select C, LHS, RHS)) -> (select C, (fneg LHS), (fneg RHS))
7354     // iff at least one cost is cheaper and the other is neutral/cheaper
7355     SDValue LHS = Op.getOperand(1);
7356     NegatibleCost CostLHS = NegatibleCost::Expensive;
7357     SDValue NegLHS =
7358         getNegatedExpression(LHS, DAG, LegalOps, OptForSize, CostLHS, Depth);
7359     if (!NegLHS || CostLHS > NegatibleCost::Neutral) {
7360       RemoveDeadNode(NegLHS);
7361       break;
7362     }
7363 
7364     // Prevent this node from being deleted by the next call.
7365     Handles.emplace_back(NegLHS);
7366 
7367     SDValue RHS = Op.getOperand(2);
7368     NegatibleCost CostRHS = NegatibleCost::Expensive;
7369     SDValue NegRHS =
7370         getNegatedExpression(RHS, DAG, LegalOps, OptForSize, CostRHS, Depth);
7371 
7372     // We're done with the handles.
7373     Handles.clear();
7374 
7375     if (!NegRHS || CostRHS > NegatibleCost::Neutral ||
7376         (CostLHS != NegatibleCost::Cheaper &&
7377          CostRHS != NegatibleCost::Cheaper)) {
7378       RemoveDeadNode(NegLHS);
7379       RemoveDeadNode(NegRHS);
7380       break;
7381     }
7382 
7383     Cost = std::min(CostLHS, CostRHS);
7384     return DAG.getSelect(DL, VT, Op.getOperand(0), NegLHS, NegRHS);
7385   }
7386   }
7387 
7388   return SDValue();
7389 }
7390 
7391 //===----------------------------------------------------------------------===//
7392 // Legalization Utilities
7393 //===----------------------------------------------------------------------===//
7394 
7395 bool TargetLowering::expandMUL_LOHI(unsigned Opcode, EVT VT, const SDLoc &dl,
7396                                     SDValue LHS, SDValue RHS,
7397                                     SmallVectorImpl<SDValue> &Result,
7398                                     EVT HiLoVT, SelectionDAG &DAG,
7399                                     MulExpansionKind Kind, SDValue LL,
7400                                     SDValue LH, SDValue RL, SDValue RH) const {
7401   assert(Opcode == ISD::MUL || Opcode == ISD::UMUL_LOHI ||
7402          Opcode == ISD::SMUL_LOHI);
7403 
7404   bool HasMULHS = (Kind == MulExpansionKind::Always) ||
7405                   isOperationLegalOrCustom(ISD::MULHS, HiLoVT);
7406   bool HasMULHU = (Kind == MulExpansionKind::Always) ||
7407                   isOperationLegalOrCustom(ISD::MULHU, HiLoVT);
7408   bool HasSMUL_LOHI = (Kind == MulExpansionKind::Always) ||
7409                       isOperationLegalOrCustom(ISD::SMUL_LOHI, HiLoVT);
7410   bool HasUMUL_LOHI = (Kind == MulExpansionKind::Always) ||
7411                       isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT);
7412 
7413   if (!HasMULHU && !HasMULHS && !HasUMUL_LOHI && !HasSMUL_LOHI)
7414     return false;
7415 
7416   unsigned OuterBitSize = VT.getScalarSizeInBits();
7417   unsigned InnerBitSize = HiLoVT.getScalarSizeInBits();
7418 
7419   // LL, LH, RL, and RH must be either all NULL or all set to a value.
7420   assert((LL.getNode() && LH.getNode() && RL.getNode() && RH.getNode()) ||
7421          (!LL.getNode() && !LH.getNode() && !RL.getNode() && !RH.getNode()));
7422 
7423   SDVTList VTs = DAG.getVTList(HiLoVT, HiLoVT);
7424   auto MakeMUL_LOHI = [&](SDValue L, SDValue R, SDValue &Lo, SDValue &Hi,
7425                           bool Signed) -> bool {
7426     if ((Signed && HasSMUL_LOHI) || (!Signed && HasUMUL_LOHI)) {
7427       Lo = DAG.getNode(Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI, dl, VTs, L, R);
7428       Hi = SDValue(Lo.getNode(), 1);
7429       return true;
7430     }
7431     if ((Signed && HasMULHS) || (!Signed && HasMULHU)) {
7432       Lo = DAG.getNode(ISD::MUL, dl, HiLoVT, L, R);
7433       Hi = DAG.getNode(Signed ? ISD::MULHS : ISD::MULHU, dl, HiLoVT, L, R);
7434       return true;
7435     }
7436     return false;
7437   };
7438 
7439   SDValue Lo, Hi;
7440 
7441   if (!LL.getNode() && !RL.getNode() &&
7442       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
7443     LL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LHS);
7444     RL = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RHS);
7445   }
7446 
7447   if (!LL.getNode())
7448     return false;
7449 
7450   APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
7451   if (DAG.MaskedValueIsZero(LHS, HighMask) &&
7452       DAG.MaskedValueIsZero(RHS, HighMask)) {
7453     // The inputs are both zero-extended.
7454     if (MakeMUL_LOHI(LL, RL, Lo, Hi, false)) {
7455       Result.push_back(Lo);
7456       Result.push_back(Hi);
7457       if (Opcode != ISD::MUL) {
7458         SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
7459         Result.push_back(Zero);
7460         Result.push_back(Zero);
7461       }
7462       return true;
7463     }
7464   }
7465 
7466   if (!VT.isVector() && Opcode == ISD::MUL &&
7467       DAG.ComputeMaxSignificantBits(LHS) <= InnerBitSize &&
7468       DAG.ComputeMaxSignificantBits(RHS) <= InnerBitSize) {
7469     // The input values are both sign-extended.
7470     // TODO non-MUL case?
7471     if (MakeMUL_LOHI(LL, RL, Lo, Hi, true)) {
7472       Result.push_back(Lo);
7473       Result.push_back(Hi);
7474       return true;
7475     }
7476   }
7477 
7478   unsigned ShiftAmount = OuterBitSize - InnerBitSize;
7479   SDValue Shift = DAG.getShiftAmountConstant(ShiftAmount, VT, dl);
7480 
7481   if (!LH.getNode() && !RH.getNode() &&
7482       isOperationLegalOrCustom(ISD::SRL, VT) &&
7483       isOperationLegalOrCustom(ISD::TRUNCATE, HiLoVT)) {
7484     LH = DAG.getNode(ISD::SRL, dl, VT, LHS, Shift);
7485     LH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, LH);
7486     RH = DAG.getNode(ISD::SRL, dl, VT, RHS, Shift);
7487     RH = DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, RH);
7488   }
7489 
7490   if (!LH.getNode())
7491     return false;
7492 
7493   if (!MakeMUL_LOHI(LL, RL, Lo, Hi, false))
7494     return false;
7495 
7496   Result.push_back(Lo);
7497 
7498   if (Opcode == ISD::MUL) {
7499     RH = DAG.getNode(ISD::MUL, dl, HiLoVT, LL, RH);
7500     LH = DAG.getNode(ISD::MUL, dl, HiLoVT, LH, RL);
7501     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, RH);
7502     Hi = DAG.getNode(ISD::ADD, dl, HiLoVT, Hi, LH);
7503     Result.push_back(Hi);
7504     return true;
7505   }
7506 
7507   // Compute the full width result.
7508   auto Merge = [&](SDValue Lo, SDValue Hi) -> SDValue {
7509     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Lo);
7510     Hi = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
7511     Hi = DAG.getNode(ISD::SHL, dl, VT, Hi, Shift);
7512     return DAG.getNode(ISD::OR, dl, VT, Lo, Hi);
7513   };
7514 
7515   SDValue Next = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Hi);
7516   if (!MakeMUL_LOHI(LL, RH, Lo, Hi, false))
7517     return false;
7518 
7519   // This is effectively the add part of a multiply-add of half-sized operands,
7520   // so it cannot overflow.
7521   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
7522 
7523   if (!MakeMUL_LOHI(LH, RL, Lo, Hi, false))
7524     return false;
7525 
7526   SDValue Zero = DAG.getConstant(0, dl, HiLoVT);
7527   EVT BoolType = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
7528 
7529   bool UseGlue = (isOperationLegalOrCustom(ISD::ADDC, VT) &&
7530                   isOperationLegalOrCustom(ISD::ADDE, VT));
7531   if (UseGlue)
7532     Next = DAG.getNode(ISD::ADDC, dl, DAG.getVTList(VT, MVT::Glue), Next,
7533                        Merge(Lo, Hi));
7534   else
7535     Next = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(VT, BoolType), Next,
7536                        Merge(Lo, Hi), DAG.getConstant(0, dl, BoolType));
7537 
7538   SDValue Carry = Next.getValue(1);
7539   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
7540   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
7541 
7542   if (!MakeMUL_LOHI(LH, RH, Lo, Hi, Opcode == ISD::SMUL_LOHI))
7543     return false;
7544 
7545   if (UseGlue)
7546     Hi = DAG.getNode(ISD::ADDE, dl, DAG.getVTList(HiLoVT, MVT::Glue), Hi, Zero,
7547                      Carry);
7548   else
7549     Hi = DAG.getNode(ISD::UADDO_CARRY, dl, DAG.getVTList(HiLoVT, BoolType), Hi,
7550                      Zero, Carry);
7551 
7552   Next = DAG.getNode(ISD::ADD, dl, VT, Next, Merge(Lo, Hi));
7553 
7554   if (Opcode == ISD::SMUL_LOHI) {
7555     SDValue NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
7556                                   DAG.getNode(ISD::ZERO_EXTEND, dl, VT, RL));
7557     Next = DAG.getSelectCC(dl, LH, Zero, NextSub, Next, ISD::SETLT);
7558 
7559     NextSub = DAG.getNode(ISD::SUB, dl, VT, Next,
7560                           DAG.getNode(ISD::ZERO_EXTEND, dl, VT, LL));
7561     Next = DAG.getSelectCC(dl, RH, Zero, NextSub, Next, ISD::SETLT);
7562   }
7563 
7564   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
7565   Next = DAG.getNode(ISD::SRL, dl, VT, Next, Shift);
7566   Result.push_back(DAG.getNode(ISD::TRUNCATE, dl, HiLoVT, Next));
7567   return true;
7568 }
7569 
7570 bool TargetLowering::expandMUL(SDNode *N, SDValue &Lo, SDValue &Hi, EVT HiLoVT,
7571                                SelectionDAG &DAG, MulExpansionKind Kind,
7572                                SDValue LL, SDValue LH, SDValue RL,
7573                                SDValue RH) const {
7574   SmallVector<SDValue, 2> Result;
7575   bool Ok = expandMUL_LOHI(N->getOpcode(), N->getValueType(0), SDLoc(N),
7576                            N->getOperand(0), N->getOperand(1), Result, HiLoVT,
7577                            DAG, Kind, LL, LH, RL, RH);
7578   if (Ok) {
7579     assert(Result.size() == 2);
7580     Lo = Result[0];
7581     Hi = Result[1];
7582   }
7583   return Ok;
7584 }
7585 
7586 // Optimize unsigned division or remainder by constants for types twice as large
7587 // as a legal VT.
7588 //
7589 // If (1 << (BitWidth / 2)) % Constant == 1, then the remainder
7590 // can be computed
7591 // as:
7592 //   Sum += __builtin_uadd_overflow(Lo, High, &Sum);
7593 //   Remainder = Sum % Constant
7594 // This is based on "Remainder by Summing Digits" from Hacker's Delight.
7595 //
7596 // For division, we can compute the remainder using the algorithm described
7597 // above, subtract it from the dividend to get an exact multiple of Constant.
7598 // Then multiply that extact multiply by the multiplicative inverse modulo
7599 // (1 << (BitWidth / 2)) to get the quotient.
7600 
7601 // If Constant is even, we can shift right the dividend and the divisor by the
7602 // number of trailing zeros in Constant before applying the remainder algorithm.
7603 // If we're after the quotient, we can subtract this value from the shifted
7604 // dividend and multiply by the multiplicative inverse of the shifted divisor.
7605 // If we want the remainder, we shift the value left by the number of trailing
7606 // zeros and add the bits that were shifted out of the dividend.
7607 bool TargetLowering::expandDIVREMByConstant(SDNode *N,
7608                                             SmallVectorImpl<SDValue> &Result,
7609                                             EVT HiLoVT, SelectionDAG &DAG,
7610                                             SDValue LL, SDValue LH) const {
7611   unsigned Opcode = N->getOpcode();
7612   EVT VT = N->getValueType(0);
7613 
7614   // TODO: Support signed division/remainder.
7615   if (Opcode == ISD::SREM || Opcode == ISD::SDIV || Opcode == ISD::SDIVREM)
7616     return false;
7617   assert(
7618       (Opcode == ISD::UREM || Opcode == ISD::UDIV || Opcode == ISD::UDIVREM) &&
7619       "Unexpected opcode");
7620 
7621   auto *CN = dyn_cast<ConstantSDNode>(N->getOperand(1));
7622   if (!CN)
7623     return false;
7624 
7625   APInt Divisor = CN->getAPIntValue();
7626   unsigned BitWidth = Divisor.getBitWidth();
7627   unsigned HBitWidth = BitWidth / 2;
7628   assert(VT.getScalarSizeInBits() == BitWidth &&
7629          HiLoVT.getScalarSizeInBits() == HBitWidth && "Unexpected VTs");
7630 
7631   // Divisor needs to less than (1 << HBitWidth).
7632   APInt HalfMaxPlus1 = APInt::getOneBitSet(BitWidth, HBitWidth);
7633   if (Divisor.uge(HalfMaxPlus1))
7634     return false;
7635 
7636   // We depend on the UREM by constant optimization in DAGCombiner that requires
7637   // high multiply.
7638   if (!isOperationLegalOrCustom(ISD::MULHU, HiLoVT) &&
7639       !isOperationLegalOrCustom(ISD::UMUL_LOHI, HiLoVT))
7640     return false;
7641 
7642   // Don't expand if optimizing for size.
7643   if (DAG.shouldOptForSize())
7644     return false;
7645 
7646   // Early out for 0 or 1 divisors.
7647   if (Divisor.ule(1))
7648     return false;
7649 
7650   // If the divisor is even, shift it until it becomes odd.
7651   unsigned TrailingZeros = 0;
7652   if (!Divisor[0]) {
7653     TrailingZeros = Divisor.countr_zero();
7654     Divisor.lshrInPlace(TrailingZeros);
7655   }
7656 
7657   SDLoc dl(N);
7658   SDValue Sum;
7659   SDValue PartialRem;
7660 
7661   // If (1 << HBitWidth) % divisor == 1, we can add the two halves together and
7662   // then add in the carry.
7663   // TODO: If we can't split it in half, we might be able to split into 3 or
7664   // more pieces using a smaller bit width.
7665   if (HalfMaxPlus1.urem(Divisor).isOne()) {
7666     assert(!LL == !LH && "Expected both input halves or no input halves!");
7667     if (!LL)
7668       std::tie(LL, LH) = DAG.SplitScalar(N->getOperand(0), dl, HiLoVT, HiLoVT);
7669 
7670     // Shift the input by the number of TrailingZeros in the divisor. The
7671     // shifted out bits will be added to the remainder later.
7672     if (TrailingZeros) {
7673       // Save the shifted off bits if we need the remainder.
7674       if (Opcode != ISD::UDIV) {
7675         APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
7676         PartialRem = DAG.getNode(ISD::AND, dl, HiLoVT, LL,
7677                                  DAG.getConstant(Mask, dl, HiLoVT));
7678       }
7679 
7680       LL = DAG.getNode(
7681           ISD::OR, dl, HiLoVT,
7682           DAG.getNode(ISD::SRL, dl, HiLoVT, LL,
7683                       DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl)),
7684           DAG.getNode(ISD::SHL, dl, HiLoVT, LH,
7685                       DAG.getShiftAmountConstant(HBitWidth - TrailingZeros,
7686                                                  HiLoVT, dl)));
7687       LH = DAG.getNode(ISD::SRL, dl, HiLoVT, LH,
7688                        DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
7689     }
7690 
7691     // Use uaddo_carry if we can, otherwise use a compare to detect overflow.
7692     EVT SetCCType =
7693         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), HiLoVT);
7694     if (isOperationLegalOrCustom(ISD::UADDO_CARRY, HiLoVT)) {
7695       SDVTList VTList = DAG.getVTList(HiLoVT, SetCCType);
7696       Sum = DAG.getNode(ISD::UADDO, dl, VTList, LL, LH);
7697       Sum = DAG.getNode(ISD::UADDO_CARRY, dl, VTList, Sum,
7698                         DAG.getConstant(0, dl, HiLoVT), Sum.getValue(1));
7699     } else {
7700       Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, LL, LH);
7701       SDValue Carry = DAG.getSetCC(dl, SetCCType, Sum, LL, ISD::SETULT);
7702       // If the boolean for the target is 0 or 1, we can add the setcc result
7703       // directly.
7704       if (getBooleanContents(HiLoVT) ==
7705           TargetLoweringBase::ZeroOrOneBooleanContent)
7706         Carry = DAG.getZExtOrTrunc(Carry, dl, HiLoVT);
7707       else
7708         Carry = DAG.getSelect(dl, HiLoVT, Carry, DAG.getConstant(1, dl, HiLoVT),
7709                               DAG.getConstant(0, dl, HiLoVT));
7710       Sum = DAG.getNode(ISD::ADD, dl, HiLoVT, Sum, Carry);
7711     }
7712   }
7713 
7714   // If we didn't find a sum, we can't do the expansion.
7715   if (!Sum)
7716     return false;
7717 
7718   // Perform a HiLoVT urem on the Sum using truncated divisor.
7719   SDValue RemL =
7720       DAG.getNode(ISD::UREM, dl, HiLoVT, Sum,
7721                   DAG.getConstant(Divisor.trunc(HBitWidth), dl, HiLoVT));
7722   SDValue RemH = DAG.getConstant(0, dl, HiLoVT);
7723 
7724   if (Opcode != ISD::UREM) {
7725     // Subtract the remainder from the shifted dividend.
7726     SDValue Dividend = DAG.getNode(ISD::BUILD_PAIR, dl, VT, LL, LH);
7727     SDValue Rem = DAG.getNode(ISD::BUILD_PAIR, dl, VT, RemL, RemH);
7728 
7729     Dividend = DAG.getNode(ISD::SUB, dl, VT, Dividend, Rem);
7730 
7731     // Multiply by the multiplicative inverse of the divisor modulo
7732     // (1 << BitWidth).
7733     APInt Mod = APInt::getSignedMinValue(BitWidth + 1);
7734     APInt MulFactor = Divisor.zext(BitWidth + 1);
7735     MulFactor = MulFactor.multiplicativeInverse(Mod);
7736     MulFactor = MulFactor.trunc(BitWidth);
7737 
7738     SDValue Quotient = DAG.getNode(ISD::MUL, dl, VT, Dividend,
7739                                    DAG.getConstant(MulFactor, dl, VT));
7740 
7741     // Split the quotient into low and high parts.
7742     SDValue QuotL, QuotH;
7743     std::tie(QuotL, QuotH) = DAG.SplitScalar(Quotient, dl, HiLoVT, HiLoVT);
7744     Result.push_back(QuotL);
7745     Result.push_back(QuotH);
7746   }
7747 
7748   if (Opcode != ISD::UDIV) {
7749     // If we shifted the input, shift the remainder left and add the bits we
7750     // shifted off the input.
7751     if (TrailingZeros) {
7752       APInt Mask = APInt::getLowBitsSet(HBitWidth, TrailingZeros);
7753       RemL = DAG.getNode(ISD::SHL, dl, HiLoVT, RemL,
7754                          DAG.getShiftAmountConstant(TrailingZeros, HiLoVT, dl));
7755       RemL = DAG.getNode(ISD::ADD, dl, HiLoVT, RemL, PartialRem);
7756     }
7757     Result.push_back(RemL);
7758     Result.push_back(DAG.getConstant(0, dl, HiLoVT));
7759   }
7760 
7761   return true;
7762 }
7763 
7764 // Check that (every element of) Z is undef or not an exact multiple of BW.
7765 static bool isNonZeroModBitWidthOrUndef(SDValue Z, unsigned BW) {
7766   return ISD::matchUnaryPredicate(
7767       Z,
7768       [=](ConstantSDNode *C) { return !C || C->getAPIntValue().urem(BW) != 0; },
7769       true);
7770 }
7771 
7772 static SDValue expandVPFunnelShift(SDNode *Node, SelectionDAG &DAG) {
7773   EVT VT = Node->getValueType(0);
7774   SDValue ShX, ShY;
7775   SDValue ShAmt, InvShAmt;
7776   SDValue X = Node->getOperand(0);
7777   SDValue Y = Node->getOperand(1);
7778   SDValue Z = Node->getOperand(2);
7779   SDValue Mask = Node->getOperand(3);
7780   SDValue VL = Node->getOperand(4);
7781 
7782   unsigned BW = VT.getScalarSizeInBits();
7783   bool IsFSHL = Node->getOpcode() == ISD::VP_FSHL;
7784   SDLoc DL(SDValue(Node, 0));
7785 
7786   EVT ShVT = Z.getValueType();
7787   if (isNonZeroModBitWidthOrUndef(Z, BW)) {
7788     // fshl: X << C | Y >> (BW - C)
7789     // fshr: X << (BW - C) | Y >> C
7790     // where C = Z % BW is not zero
7791     SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
7792     ShAmt = DAG.getNode(ISD::VP_UREM, DL, ShVT, Z, BitWidthC, Mask, VL);
7793     InvShAmt = DAG.getNode(ISD::VP_SUB, DL, ShVT, BitWidthC, ShAmt, Mask, VL);
7794     ShX = DAG.getNode(ISD::VP_SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt, Mask,
7795                       VL);
7796     ShY = DAG.getNode(ISD::VP_LSHR, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt, Mask,
7797                       VL);
7798   } else {
7799     // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
7800     // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
7801     SDValue BitMask = DAG.getConstant(BW - 1, DL, ShVT);
7802     if (isPowerOf2_32(BW)) {
7803       // Z % BW -> Z & (BW - 1)
7804       ShAmt = DAG.getNode(ISD::VP_AND, DL, ShVT, Z, BitMask, Mask, VL);
7805       // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
7806       SDValue NotZ = DAG.getNode(ISD::VP_XOR, DL, ShVT, Z,
7807                                  DAG.getAllOnesConstant(DL, ShVT), Mask, VL);
7808       InvShAmt = DAG.getNode(ISD::VP_AND, DL, ShVT, NotZ, BitMask, Mask, VL);
7809     } else {
7810       SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
7811       ShAmt = DAG.getNode(ISD::VP_UREM, DL, ShVT, Z, BitWidthC, Mask, VL);
7812       InvShAmt = DAG.getNode(ISD::VP_SUB, DL, ShVT, BitMask, ShAmt, Mask, VL);
7813     }
7814 
7815     SDValue One = DAG.getConstant(1, DL, ShVT);
7816     if (IsFSHL) {
7817       ShX = DAG.getNode(ISD::VP_SHL, DL, VT, X, ShAmt, Mask, VL);
7818       SDValue ShY1 = DAG.getNode(ISD::VP_LSHR, DL, VT, Y, One, Mask, VL);
7819       ShY = DAG.getNode(ISD::VP_LSHR, DL, VT, ShY1, InvShAmt, Mask, VL);
7820     } else {
7821       SDValue ShX1 = DAG.getNode(ISD::VP_SHL, DL, VT, X, One, Mask, VL);
7822       ShX = DAG.getNode(ISD::VP_SHL, DL, VT, ShX1, InvShAmt, Mask, VL);
7823       ShY = DAG.getNode(ISD::VP_LSHR, DL, VT, Y, ShAmt, Mask, VL);
7824     }
7825   }
7826   return DAG.getNode(ISD::VP_OR, DL, VT, ShX, ShY, Mask, VL);
7827 }
7828 
7829 SDValue TargetLowering::expandFunnelShift(SDNode *Node,
7830                                           SelectionDAG &DAG) const {
7831   if (Node->isVPOpcode())
7832     return expandVPFunnelShift(Node, DAG);
7833 
7834   EVT VT = Node->getValueType(0);
7835 
7836   if (VT.isVector() && (!isOperationLegalOrCustom(ISD::SHL, VT) ||
7837                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
7838                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
7839                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
7840     return SDValue();
7841 
7842   SDValue X = Node->getOperand(0);
7843   SDValue Y = Node->getOperand(1);
7844   SDValue Z = Node->getOperand(2);
7845 
7846   unsigned BW = VT.getScalarSizeInBits();
7847   bool IsFSHL = Node->getOpcode() == ISD::FSHL;
7848   SDLoc DL(SDValue(Node, 0));
7849 
7850   EVT ShVT = Z.getValueType();
7851 
7852   // If a funnel shift in the other direction is more supported, use it.
7853   unsigned RevOpcode = IsFSHL ? ISD::FSHR : ISD::FSHL;
7854   if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
7855       isOperationLegalOrCustom(RevOpcode, VT) && isPowerOf2_32(BW)) {
7856     if (isNonZeroModBitWidthOrUndef(Z, BW)) {
7857       // fshl X, Y, Z -> fshr X, Y, -Z
7858       // fshr X, Y, Z -> fshl X, Y, -Z
7859       SDValue Zero = DAG.getConstant(0, DL, ShVT);
7860       Z = DAG.getNode(ISD::SUB, DL, VT, Zero, Z);
7861     } else {
7862       // fshl X, Y, Z -> fshr (srl X, 1), (fshr X, Y, 1), ~Z
7863       // fshr X, Y, Z -> fshl (fshl X, Y, 1), (shl Y, 1), ~Z
7864       SDValue One = DAG.getConstant(1, DL, ShVT);
7865       if (IsFSHL) {
7866         Y = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
7867         X = DAG.getNode(ISD::SRL, DL, VT, X, One);
7868       } else {
7869         X = DAG.getNode(RevOpcode, DL, VT, X, Y, One);
7870         Y = DAG.getNode(ISD::SHL, DL, VT, Y, One);
7871       }
7872       Z = DAG.getNOT(DL, Z, ShVT);
7873     }
7874     return DAG.getNode(RevOpcode, DL, VT, X, Y, Z);
7875   }
7876 
7877   SDValue ShX, ShY;
7878   SDValue ShAmt, InvShAmt;
7879   if (isNonZeroModBitWidthOrUndef(Z, BW)) {
7880     // fshl: X << C | Y >> (BW - C)
7881     // fshr: X << (BW - C) | Y >> C
7882     // where C = Z % BW is not zero
7883     SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
7884     ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
7885     InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthC, ShAmt);
7886     ShX = DAG.getNode(ISD::SHL, DL, VT, X, IsFSHL ? ShAmt : InvShAmt);
7887     ShY = DAG.getNode(ISD::SRL, DL, VT, Y, IsFSHL ? InvShAmt : ShAmt);
7888   } else {
7889     // fshl: X << (Z % BW) | Y >> 1 >> (BW - 1 - (Z % BW))
7890     // fshr: X << 1 << (BW - 1 - (Z % BW)) | Y >> (Z % BW)
7891     SDValue Mask = DAG.getConstant(BW - 1, DL, ShVT);
7892     if (isPowerOf2_32(BW)) {
7893       // Z % BW -> Z & (BW - 1)
7894       ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Z, Mask);
7895       // (BW - 1) - (Z % BW) -> ~Z & (BW - 1)
7896       InvShAmt = DAG.getNode(ISD::AND, DL, ShVT, DAG.getNOT(DL, Z, ShVT), Mask);
7897     } else {
7898       SDValue BitWidthC = DAG.getConstant(BW, DL, ShVT);
7899       ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Z, BitWidthC);
7900       InvShAmt = DAG.getNode(ISD::SUB, DL, ShVT, Mask, ShAmt);
7901     }
7902 
7903     SDValue One = DAG.getConstant(1, DL, ShVT);
7904     if (IsFSHL) {
7905       ShX = DAG.getNode(ISD::SHL, DL, VT, X, ShAmt);
7906       SDValue ShY1 = DAG.getNode(ISD::SRL, DL, VT, Y, One);
7907       ShY = DAG.getNode(ISD::SRL, DL, VT, ShY1, InvShAmt);
7908     } else {
7909       SDValue ShX1 = DAG.getNode(ISD::SHL, DL, VT, X, One);
7910       ShX = DAG.getNode(ISD::SHL, DL, VT, ShX1, InvShAmt);
7911       ShY = DAG.getNode(ISD::SRL, DL, VT, Y, ShAmt);
7912     }
7913   }
7914   return DAG.getNode(ISD::OR, DL, VT, ShX, ShY);
7915 }
7916 
7917 // TODO: Merge with expandFunnelShift.
7918 SDValue TargetLowering::expandROT(SDNode *Node, bool AllowVectorOps,
7919                                   SelectionDAG &DAG) const {
7920   EVT VT = Node->getValueType(0);
7921   unsigned EltSizeInBits = VT.getScalarSizeInBits();
7922   bool IsLeft = Node->getOpcode() == ISD::ROTL;
7923   SDValue Op0 = Node->getOperand(0);
7924   SDValue Op1 = Node->getOperand(1);
7925   SDLoc DL(SDValue(Node, 0));
7926 
7927   EVT ShVT = Op1.getValueType();
7928   SDValue Zero = DAG.getConstant(0, DL, ShVT);
7929 
7930   // If a rotate in the other direction is more supported, use it.
7931   unsigned RevRot = IsLeft ? ISD::ROTR : ISD::ROTL;
7932   if (!isOperationLegalOrCustom(Node->getOpcode(), VT) &&
7933       isOperationLegalOrCustom(RevRot, VT) && isPowerOf2_32(EltSizeInBits)) {
7934     SDValue Sub = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
7935     return DAG.getNode(RevRot, DL, VT, Op0, Sub);
7936   }
7937 
7938   if (!AllowVectorOps && VT.isVector() &&
7939       (!isOperationLegalOrCustom(ISD::SHL, VT) ||
7940        !isOperationLegalOrCustom(ISD::SRL, VT) ||
7941        !isOperationLegalOrCustom(ISD::SUB, VT) ||
7942        !isOperationLegalOrCustomOrPromote(ISD::OR, VT) ||
7943        !isOperationLegalOrCustomOrPromote(ISD::AND, VT)))
7944     return SDValue();
7945 
7946   unsigned ShOpc = IsLeft ? ISD::SHL : ISD::SRL;
7947   unsigned HsOpc = IsLeft ? ISD::SRL : ISD::SHL;
7948   SDValue BitWidthMinusOneC = DAG.getConstant(EltSizeInBits - 1, DL, ShVT);
7949   SDValue ShVal;
7950   SDValue HsVal;
7951   if (isPowerOf2_32(EltSizeInBits)) {
7952     // (rotl x, c) -> x << (c & (w - 1)) | x >> (-c & (w - 1))
7953     // (rotr x, c) -> x >> (c & (w - 1)) | x << (-c & (w - 1))
7954     SDValue NegOp1 = DAG.getNode(ISD::SUB, DL, ShVT, Zero, Op1);
7955     SDValue ShAmt = DAG.getNode(ISD::AND, DL, ShVT, Op1, BitWidthMinusOneC);
7956     ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
7957     SDValue HsAmt = DAG.getNode(ISD::AND, DL, ShVT, NegOp1, BitWidthMinusOneC);
7958     HsVal = DAG.getNode(HsOpc, DL, VT, Op0, HsAmt);
7959   } else {
7960     // (rotl x, c) -> x << (c % w) | x >> 1 >> (w - 1 - (c % w))
7961     // (rotr x, c) -> x >> (c % w) | x << 1 << (w - 1 - (c % w))
7962     SDValue BitWidthC = DAG.getConstant(EltSizeInBits, DL, ShVT);
7963     SDValue ShAmt = DAG.getNode(ISD::UREM, DL, ShVT, Op1, BitWidthC);
7964     ShVal = DAG.getNode(ShOpc, DL, VT, Op0, ShAmt);
7965     SDValue HsAmt = DAG.getNode(ISD::SUB, DL, ShVT, BitWidthMinusOneC, ShAmt);
7966     SDValue One = DAG.getConstant(1, DL, ShVT);
7967     HsVal =
7968         DAG.getNode(HsOpc, DL, VT, DAG.getNode(HsOpc, DL, VT, Op0, One), HsAmt);
7969   }
7970   return DAG.getNode(ISD::OR, DL, VT, ShVal, HsVal);
7971 }
7972 
7973 void TargetLowering::expandShiftParts(SDNode *Node, SDValue &Lo, SDValue &Hi,
7974                                       SelectionDAG &DAG) const {
7975   assert(Node->getNumOperands() == 3 && "Not a double-shift!");
7976   EVT VT = Node->getValueType(0);
7977   unsigned VTBits = VT.getScalarSizeInBits();
7978   assert(isPowerOf2_32(VTBits) && "Power-of-two integer type expected");
7979 
7980   bool IsSHL = Node->getOpcode() == ISD::SHL_PARTS;
7981   bool IsSRA = Node->getOpcode() == ISD::SRA_PARTS;
7982   SDValue ShOpLo = Node->getOperand(0);
7983   SDValue ShOpHi = Node->getOperand(1);
7984   SDValue ShAmt = Node->getOperand(2);
7985   EVT ShAmtVT = ShAmt.getValueType();
7986   EVT ShAmtCCVT =
7987       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), ShAmtVT);
7988   SDLoc dl(Node);
7989 
7990   // ISD::FSHL and ISD::FSHR have defined overflow behavior but ISD::SHL and
7991   // ISD::SRA/L nodes haven't. Insert an AND to be safe, it's usually optimized
7992   // away during isel.
7993   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
7994                                   DAG.getConstant(VTBits - 1, dl, ShAmtVT));
7995   SDValue Tmp1 = IsSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
7996                                      DAG.getConstant(VTBits - 1, dl, ShAmtVT))
7997                        : DAG.getConstant(0, dl, VT);
7998 
7999   SDValue Tmp2, Tmp3;
8000   if (IsSHL) {
8001     Tmp2 = DAG.getNode(ISD::FSHL, dl, VT, ShOpHi, ShOpLo, ShAmt);
8002     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
8003   } else {
8004     Tmp2 = DAG.getNode(ISD::FSHR, dl, VT, ShOpHi, ShOpLo, ShAmt);
8005     Tmp3 = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
8006   }
8007 
8008   // If the shift amount is larger or equal than the width of a part we don't
8009   // use the result from the FSHL/FSHR. Insert a test and select the appropriate
8010   // values for large shift amounts.
8011   SDValue AndNode = DAG.getNode(ISD::AND, dl, ShAmtVT, ShAmt,
8012                                 DAG.getConstant(VTBits, dl, ShAmtVT));
8013   SDValue Cond = DAG.getSetCC(dl, ShAmtCCVT, AndNode,
8014                               DAG.getConstant(0, dl, ShAmtVT), ISD::SETNE);
8015 
8016   if (IsSHL) {
8017     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
8018     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
8019   } else {
8020     Lo = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp3, Tmp2);
8021     Hi = DAG.getNode(ISD::SELECT, dl, VT, Cond, Tmp1, Tmp3);
8022   }
8023 }
8024 
8025 bool TargetLowering::expandFP_TO_SINT(SDNode *Node, SDValue &Result,
8026                                       SelectionDAG &DAG) const {
8027   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
8028   SDValue Src = Node->getOperand(OpNo);
8029   EVT SrcVT = Src.getValueType();
8030   EVT DstVT = Node->getValueType(0);
8031   SDLoc dl(SDValue(Node, 0));
8032 
8033   // FIXME: Only f32 to i64 conversions are supported.
8034   if (SrcVT != MVT::f32 || DstVT != MVT::i64)
8035     return false;
8036 
8037   if (Node->isStrictFPOpcode())
8038     // When a NaN is converted to an integer a trap is allowed. We can't
8039     // use this expansion here because it would eliminate that trap. Other
8040     // traps are also allowed and cannot be eliminated. See
8041     // IEEE 754-2008 sec 5.8.
8042     return false;
8043 
8044   // Expand f32 -> i64 conversion
8045   // This algorithm comes from compiler-rt's implementation of fixsfdi:
8046   // https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/fixsfdi.c
8047   unsigned SrcEltBits = SrcVT.getScalarSizeInBits();
8048   EVT IntVT = SrcVT.changeTypeToInteger();
8049   EVT IntShVT = getShiftAmountTy(IntVT, DAG.getDataLayout());
8050 
8051   SDValue ExponentMask = DAG.getConstant(0x7F800000, dl, IntVT);
8052   SDValue ExponentLoBit = DAG.getConstant(23, dl, IntVT);
8053   SDValue Bias = DAG.getConstant(127, dl, IntVT);
8054   SDValue SignMask = DAG.getConstant(APInt::getSignMask(SrcEltBits), dl, IntVT);
8055   SDValue SignLowBit = DAG.getConstant(SrcEltBits - 1, dl, IntVT);
8056   SDValue MantissaMask = DAG.getConstant(0x007FFFFF, dl, IntVT);
8057 
8058   SDValue Bits = DAG.getNode(ISD::BITCAST, dl, IntVT, Src);
8059 
8060   SDValue ExponentBits = DAG.getNode(
8061       ISD::SRL, dl, IntVT, DAG.getNode(ISD::AND, dl, IntVT, Bits, ExponentMask),
8062       DAG.getZExtOrTrunc(ExponentLoBit, dl, IntShVT));
8063   SDValue Exponent = DAG.getNode(ISD::SUB, dl, IntVT, ExponentBits, Bias);
8064 
8065   SDValue Sign = DAG.getNode(ISD::SRA, dl, IntVT,
8066                              DAG.getNode(ISD::AND, dl, IntVT, Bits, SignMask),
8067                              DAG.getZExtOrTrunc(SignLowBit, dl, IntShVT));
8068   Sign = DAG.getSExtOrTrunc(Sign, dl, DstVT);
8069 
8070   SDValue R = DAG.getNode(ISD::OR, dl, IntVT,
8071                           DAG.getNode(ISD::AND, dl, IntVT, Bits, MantissaMask),
8072                           DAG.getConstant(0x00800000, dl, IntVT));
8073 
8074   R = DAG.getZExtOrTrunc(R, dl, DstVT);
8075 
8076   R = DAG.getSelectCC(
8077       dl, Exponent, ExponentLoBit,
8078       DAG.getNode(ISD::SHL, dl, DstVT, R,
8079                   DAG.getZExtOrTrunc(
8080                       DAG.getNode(ISD::SUB, dl, IntVT, Exponent, ExponentLoBit),
8081                       dl, IntShVT)),
8082       DAG.getNode(ISD::SRL, dl, DstVT, R,
8083                   DAG.getZExtOrTrunc(
8084                       DAG.getNode(ISD::SUB, dl, IntVT, ExponentLoBit, Exponent),
8085                       dl, IntShVT)),
8086       ISD::SETGT);
8087 
8088   SDValue Ret = DAG.getNode(ISD::SUB, dl, DstVT,
8089                             DAG.getNode(ISD::XOR, dl, DstVT, R, Sign), Sign);
8090 
8091   Result = DAG.getSelectCC(dl, Exponent, DAG.getConstant(0, dl, IntVT),
8092                            DAG.getConstant(0, dl, DstVT), Ret, ISD::SETLT);
8093   return true;
8094 }
8095 
8096 bool TargetLowering::expandFP_TO_UINT(SDNode *Node, SDValue &Result,
8097                                       SDValue &Chain,
8098                                       SelectionDAG &DAG) const {
8099   SDLoc dl(SDValue(Node, 0));
8100   unsigned OpNo = Node->isStrictFPOpcode() ? 1 : 0;
8101   SDValue Src = Node->getOperand(OpNo);
8102 
8103   EVT SrcVT = Src.getValueType();
8104   EVT DstVT = Node->getValueType(0);
8105   EVT SetCCVT =
8106       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
8107   EVT DstSetCCVT =
8108       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), DstVT);
8109 
8110   // Only expand vector types if we have the appropriate vector bit operations.
8111   unsigned SIntOpcode = Node->isStrictFPOpcode() ? ISD::STRICT_FP_TO_SINT :
8112                                                    ISD::FP_TO_SINT;
8113   if (DstVT.isVector() && (!isOperationLegalOrCustom(SIntOpcode, DstVT) ||
8114                            !isOperationLegalOrCustomOrPromote(ISD::XOR, SrcVT)))
8115     return false;
8116 
8117   // If the maximum float value is smaller then the signed integer range,
8118   // the destination signmask can't be represented by the float, so we can
8119   // just use FP_TO_SINT directly.
8120   const fltSemantics &APFSem = DAG.EVTToAPFloatSemantics(SrcVT);
8121   APFloat APF(APFSem, APInt::getZero(SrcVT.getScalarSizeInBits()));
8122   APInt SignMask = APInt::getSignMask(DstVT.getScalarSizeInBits());
8123   if (APFloat::opOverflow &
8124       APF.convertFromAPInt(SignMask, false, APFloat::rmNearestTiesToEven)) {
8125     if (Node->isStrictFPOpcode()) {
8126       Result = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
8127                            { Node->getOperand(0), Src });
8128       Chain = Result.getValue(1);
8129     } else
8130       Result = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
8131     return true;
8132   }
8133 
8134   // Don't expand it if there isn't cheap fsub instruction.
8135   if (!isOperationLegalOrCustom(
8136           Node->isStrictFPOpcode() ? ISD::STRICT_FSUB : ISD::FSUB, SrcVT))
8137     return false;
8138 
8139   SDValue Cst = DAG.getConstantFP(APF, dl, SrcVT);
8140   SDValue Sel;
8141 
8142   if (Node->isStrictFPOpcode()) {
8143     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT,
8144                        Node->getOperand(0), /*IsSignaling*/ true);
8145     Chain = Sel.getValue(1);
8146   } else {
8147     Sel = DAG.getSetCC(dl, SetCCVT, Src, Cst, ISD::SETLT);
8148   }
8149 
8150   bool Strict = Node->isStrictFPOpcode() ||
8151                 shouldUseStrictFP_TO_INT(SrcVT, DstVT, /*IsSigned*/ false);
8152 
8153   if (Strict) {
8154     // Expand based on maximum range of FP_TO_SINT, if the value exceeds the
8155     // signmask then offset (the result of which should be fully representable).
8156     // Sel = Src < 0x8000000000000000
8157     // FltOfs = select Sel, 0, 0x8000000000000000
8158     // IntOfs = select Sel, 0, 0x8000000000000000
8159     // Result = fp_to_sint(Src - FltOfs) ^ IntOfs
8160 
8161     // TODO: Should any fast-math-flags be set for the FSUB?
8162     SDValue FltOfs = DAG.getSelect(dl, SrcVT, Sel,
8163                                    DAG.getConstantFP(0.0, dl, SrcVT), Cst);
8164     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8165     SDValue IntOfs = DAG.getSelect(dl, DstVT, Sel,
8166                                    DAG.getConstant(0, dl, DstVT),
8167                                    DAG.getConstant(SignMask, dl, DstVT));
8168     SDValue SInt;
8169     if (Node->isStrictFPOpcode()) {
8170       SDValue Val = DAG.getNode(ISD::STRICT_FSUB, dl, { SrcVT, MVT::Other },
8171                                 { Chain, Src, FltOfs });
8172       SInt = DAG.getNode(ISD::STRICT_FP_TO_SINT, dl, { DstVT, MVT::Other },
8173                          { Val.getValue(1), Val });
8174       Chain = SInt.getValue(1);
8175     } else {
8176       SDValue Val = DAG.getNode(ISD::FSUB, dl, SrcVT, Src, FltOfs);
8177       SInt = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Val);
8178     }
8179     Result = DAG.getNode(ISD::XOR, dl, DstVT, SInt, IntOfs);
8180   } else {
8181     // Expand based on maximum range of FP_TO_SINT:
8182     // True = fp_to_sint(Src)
8183     // False = 0x8000000000000000 + fp_to_sint(Src - 0x8000000000000000)
8184     // Result = select (Src < 0x8000000000000000), True, False
8185 
8186     SDValue True = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT, Src);
8187     // TODO: Should any fast-math-flags be set for the FSUB?
8188     SDValue False = DAG.getNode(ISD::FP_TO_SINT, dl, DstVT,
8189                                 DAG.getNode(ISD::FSUB, dl, SrcVT, Src, Cst));
8190     False = DAG.getNode(ISD::XOR, dl, DstVT, False,
8191                         DAG.getConstant(SignMask, dl, DstVT));
8192     Sel = DAG.getBoolExtOrTrunc(Sel, dl, DstSetCCVT, DstVT);
8193     Result = DAG.getSelect(dl, DstVT, Sel, True, False);
8194   }
8195   return true;
8196 }
8197 
8198 bool TargetLowering::expandUINT_TO_FP(SDNode *Node, SDValue &Result,
8199                                       SDValue &Chain,
8200                                       SelectionDAG &DAG) const {
8201   // This transform is not correct for converting 0 when rounding mode is set
8202   // to round toward negative infinity which will produce -0.0. So disable under
8203   // strictfp.
8204   if (Node->isStrictFPOpcode())
8205     return false;
8206 
8207   SDValue Src = Node->getOperand(0);
8208   EVT SrcVT = Src.getValueType();
8209   EVT DstVT = Node->getValueType(0);
8210 
8211   if (SrcVT.getScalarType() != MVT::i64 || DstVT.getScalarType() != MVT::f64)
8212     return false;
8213 
8214   // Only expand vector types if we have the appropriate vector bit operations.
8215   if (SrcVT.isVector() && (!isOperationLegalOrCustom(ISD::SRL, SrcVT) ||
8216                            !isOperationLegalOrCustom(ISD::FADD, DstVT) ||
8217                            !isOperationLegalOrCustom(ISD::FSUB, DstVT) ||
8218                            !isOperationLegalOrCustomOrPromote(ISD::OR, SrcVT) ||
8219                            !isOperationLegalOrCustomOrPromote(ISD::AND, SrcVT)))
8220     return false;
8221 
8222   SDLoc dl(SDValue(Node, 0));
8223   EVT ShiftVT = getShiftAmountTy(SrcVT, DAG.getDataLayout());
8224 
8225   // Implementation of unsigned i64 to f64 following the algorithm in
8226   // __floatundidf in compiler_rt.  This implementation performs rounding
8227   // correctly in all rounding modes with the exception of converting 0
8228   // when rounding toward negative infinity. In that case the fsub will produce
8229   // -0.0. This will be added to +0.0 and produce -0.0 which is incorrect.
8230   SDValue TwoP52 = DAG.getConstant(UINT64_C(0x4330000000000000), dl, SrcVT);
8231   SDValue TwoP84PlusTwoP52 = DAG.getConstantFP(
8232       llvm::bit_cast<double>(UINT64_C(0x4530000000100000)), dl, DstVT);
8233   SDValue TwoP84 = DAG.getConstant(UINT64_C(0x4530000000000000), dl, SrcVT);
8234   SDValue LoMask = DAG.getConstant(UINT64_C(0x00000000FFFFFFFF), dl, SrcVT);
8235   SDValue HiShift = DAG.getConstant(32, dl, ShiftVT);
8236 
8237   SDValue Lo = DAG.getNode(ISD::AND, dl, SrcVT, Src, LoMask);
8238   SDValue Hi = DAG.getNode(ISD::SRL, dl, SrcVT, Src, HiShift);
8239   SDValue LoOr = DAG.getNode(ISD::OR, dl, SrcVT, Lo, TwoP52);
8240   SDValue HiOr = DAG.getNode(ISD::OR, dl, SrcVT, Hi, TwoP84);
8241   SDValue LoFlt = DAG.getBitcast(DstVT, LoOr);
8242   SDValue HiFlt = DAG.getBitcast(DstVT, HiOr);
8243   SDValue HiSub =
8244       DAG.getNode(ISD::FSUB, dl, DstVT, HiFlt, TwoP84PlusTwoP52);
8245   Result = DAG.getNode(ISD::FADD, dl, DstVT, LoFlt, HiSub);
8246   return true;
8247 }
8248 
8249 SDValue
8250 TargetLowering::createSelectForFMINNUM_FMAXNUM(SDNode *Node,
8251                                                SelectionDAG &DAG) const {
8252   unsigned Opcode = Node->getOpcode();
8253   assert((Opcode == ISD::FMINNUM || Opcode == ISD::FMAXNUM ||
8254           Opcode == ISD::STRICT_FMINNUM || Opcode == ISD::STRICT_FMAXNUM) &&
8255          "Wrong opcode");
8256 
8257   if (Node->getFlags().hasNoNaNs()) {
8258     ISD::CondCode Pred = Opcode == ISD::FMINNUM ? ISD::SETLT : ISD::SETGT;
8259     SDValue Op1 = Node->getOperand(0);
8260     SDValue Op2 = Node->getOperand(1);
8261     SDValue SelCC = DAG.getSelectCC(SDLoc(Node), Op1, Op2, Op1, Op2, Pred);
8262     // Copy FMF flags, but always set the no-signed-zeros flag
8263     // as this is implied by the FMINNUM/FMAXNUM semantics.
8264     SDNodeFlags Flags = Node->getFlags();
8265     Flags.setNoSignedZeros(true);
8266     SelCC->setFlags(Flags);
8267     return SelCC;
8268   }
8269 
8270   return SDValue();
8271 }
8272 
8273 SDValue TargetLowering::expandFMINNUM_FMAXNUM(SDNode *Node,
8274                                               SelectionDAG &DAG) const {
8275   SDLoc dl(Node);
8276   unsigned NewOp = Node->getOpcode() == ISD::FMINNUM ?
8277     ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
8278   EVT VT = Node->getValueType(0);
8279 
8280   if (VT.isScalableVector())
8281     report_fatal_error(
8282         "Expanding fminnum/fmaxnum for scalable vectors is undefined.");
8283 
8284   if (isOperationLegalOrCustom(NewOp, VT)) {
8285     SDValue Quiet0 = Node->getOperand(0);
8286     SDValue Quiet1 = Node->getOperand(1);
8287 
8288     if (!Node->getFlags().hasNoNaNs()) {
8289       // Insert canonicalizes if it's possible we need to quiet to get correct
8290       // sNaN behavior.
8291       if (!DAG.isKnownNeverSNaN(Quiet0)) {
8292         Quiet0 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet0,
8293                              Node->getFlags());
8294       }
8295       if (!DAG.isKnownNeverSNaN(Quiet1)) {
8296         Quiet1 = DAG.getNode(ISD::FCANONICALIZE, dl, VT, Quiet1,
8297                              Node->getFlags());
8298       }
8299     }
8300 
8301     return DAG.getNode(NewOp, dl, VT, Quiet0, Quiet1, Node->getFlags());
8302   }
8303 
8304   // If the target has FMINIMUM/FMAXIMUM but not FMINNUM/FMAXNUM use that
8305   // instead if there are no NaNs and there can't be an incompatible zero
8306   // compare: at least one operand isn't +/-0, or there are no signed-zeros.
8307   if ((Node->getFlags().hasNoNaNs() ||
8308        (DAG.isKnownNeverNaN(Node->getOperand(0)) &&
8309         DAG.isKnownNeverNaN(Node->getOperand(1)))) &&
8310       (Node->getFlags().hasNoSignedZeros() ||
8311        DAG.isKnownNeverZeroFloat(Node->getOperand(0)) ||
8312        DAG.isKnownNeverZeroFloat(Node->getOperand(1)))) {
8313     unsigned IEEE2018Op =
8314         Node->getOpcode() == ISD::FMINNUM ? ISD::FMINIMUM : ISD::FMAXIMUM;
8315     if (isOperationLegalOrCustom(IEEE2018Op, VT))
8316       return DAG.getNode(IEEE2018Op, dl, VT, Node->getOperand(0),
8317                          Node->getOperand(1), Node->getFlags());
8318   }
8319 
8320   if (SDValue SelCC = createSelectForFMINNUM_FMAXNUM(Node, DAG))
8321     return SelCC;
8322 
8323   return SDValue();
8324 }
8325 
8326 /// Returns a true value if if this FPClassTest can be performed with an ordered
8327 /// fcmp to 0, and a false value if it's an unordered fcmp to 0. Returns
8328 /// std::nullopt if it cannot be performed as a compare with 0.
8329 static std::optional<bool> isFCmpEqualZero(FPClassTest Test,
8330                                            const fltSemantics &Semantics,
8331                                            const MachineFunction &MF) {
8332   FPClassTest OrderedMask = Test & ~fcNan;
8333   FPClassTest NanTest = Test & fcNan;
8334   bool IsOrdered = NanTest == fcNone;
8335   bool IsUnordered = NanTest == fcNan;
8336 
8337   // Skip cases that are testing for only a qnan or snan.
8338   if (!IsOrdered && !IsUnordered)
8339     return std::nullopt;
8340 
8341   if (OrderedMask == fcZero &&
8342       MF.getDenormalMode(Semantics).Input == DenormalMode::IEEE)
8343     return IsOrdered;
8344   if (OrderedMask == (fcZero | fcSubnormal) &&
8345       MF.getDenormalMode(Semantics).inputsAreZero())
8346     return IsOrdered;
8347   return std::nullopt;
8348 }
8349 
8350 SDValue TargetLowering::expandIS_FPCLASS(EVT ResultVT, SDValue Op,
8351                                          FPClassTest Test, SDNodeFlags Flags,
8352                                          const SDLoc &DL,
8353                                          SelectionDAG &DAG) const {
8354   EVT OperandVT = Op.getValueType();
8355   assert(OperandVT.isFloatingPoint());
8356 
8357   // Degenerated cases.
8358   if (Test == fcNone)
8359     return DAG.getBoolConstant(false, DL, ResultVT, OperandVT);
8360   if ((Test & fcAllFlags) == fcAllFlags)
8361     return DAG.getBoolConstant(true, DL, ResultVT, OperandVT);
8362 
8363   // PPC double double is a pair of doubles, of which the higher part determines
8364   // the value class.
8365   if (OperandVT == MVT::ppcf128) {
8366     Op = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::f64, Op,
8367                      DAG.getConstant(1, DL, MVT::i32));
8368     OperandVT = MVT::f64;
8369   }
8370 
8371   // Some checks may be represented as inversion of simpler check, for example
8372   // "inf|normal|subnormal|zero" => !"nan".
8373   bool IsInverted = false;
8374   if (FPClassTest InvertedCheck = invertFPClassTestIfSimpler(Test)) {
8375     IsInverted = true;
8376     Test = InvertedCheck;
8377   }
8378 
8379   // Floating-point type properties.
8380   EVT ScalarFloatVT = OperandVT.getScalarType();
8381   const Type *FloatTy = ScalarFloatVT.getTypeForEVT(*DAG.getContext());
8382   const llvm::fltSemantics &Semantics = FloatTy->getFltSemantics();
8383   bool IsF80 = (ScalarFloatVT == MVT::f80);
8384 
8385   // Some checks can be implemented using float comparisons, if floating point
8386   // exceptions are ignored.
8387   if (Flags.hasNoFPExcept() &&
8388       isOperationLegalOrCustom(ISD::SETCC, OperandVT.getScalarType())) {
8389     ISD::CondCode OrderedCmpOpcode = IsInverted ? ISD::SETUNE : ISD::SETOEQ;
8390     ISD::CondCode UnorderedCmpOpcode = IsInverted ? ISD::SETONE : ISD::SETUEQ;
8391 
8392     if (std::optional<bool> IsCmp0 =
8393             isFCmpEqualZero(Test, Semantics, DAG.getMachineFunction());
8394         IsCmp0 && (isCondCodeLegalOrCustom(
8395                       *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode,
8396                       OperandVT.getScalarType().getSimpleVT()))) {
8397 
8398       // If denormals could be implicitly treated as 0, this is not equivalent
8399       // to a compare with 0 since it will also be true for denormals.
8400       return DAG.getSetCC(DL, ResultVT, Op,
8401                           DAG.getConstantFP(0.0, DL, OperandVT),
8402                           *IsCmp0 ? OrderedCmpOpcode : UnorderedCmpOpcode);
8403     }
8404 
8405     if (Test == fcNan &&
8406         isCondCodeLegalOrCustom(IsInverted ? ISD::SETO : ISD::SETUO,
8407                                 OperandVT.getScalarType().getSimpleVT())) {
8408       return DAG.getSetCC(DL, ResultVT, Op, Op,
8409                           IsInverted ? ISD::SETO : ISD::SETUO);
8410     }
8411 
8412     if (Test == fcInf &&
8413         isCondCodeLegalOrCustom(IsInverted ? ISD::SETUNE : ISD::SETOEQ,
8414                                 OperandVT.getScalarType().getSimpleVT()) &&
8415         isOperationLegalOrCustom(ISD::FABS, OperandVT.getScalarType())) {
8416       // isinf(x) --> fabs(x) == inf
8417       SDValue Abs = DAG.getNode(ISD::FABS, DL, OperandVT, Op);
8418       SDValue Inf =
8419           DAG.getConstantFP(APFloat::getInf(Semantics), DL, OperandVT);
8420       return DAG.getSetCC(DL, ResultVT, Abs, Inf,
8421                           IsInverted ? ISD::SETUNE : ISD::SETOEQ);
8422     }
8423   }
8424 
8425   // In the general case use integer operations.
8426   unsigned BitSize = OperandVT.getScalarSizeInBits();
8427   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), BitSize);
8428   if (OperandVT.isVector())
8429     IntVT = EVT::getVectorVT(*DAG.getContext(), IntVT,
8430                              OperandVT.getVectorElementCount());
8431   SDValue OpAsInt = DAG.getBitcast(IntVT, Op);
8432 
8433   // Various masks.
8434   APInt SignBit = APInt::getSignMask(BitSize);
8435   APInt ValueMask = APInt::getSignedMaxValue(BitSize);     // All bits but sign.
8436   APInt Inf = APFloat::getInf(Semantics).bitcastToAPInt(); // Exp and int bit.
8437   const unsigned ExplicitIntBitInF80 = 63;
8438   APInt ExpMask = Inf;
8439   if (IsF80)
8440     ExpMask.clearBit(ExplicitIntBitInF80);
8441   APInt AllOneMantissa = APFloat::getLargest(Semantics).bitcastToAPInt() & ~Inf;
8442   APInt QNaNBitMask =
8443       APInt::getOneBitSet(BitSize, AllOneMantissa.getActiveBits() - 1);
8444   APInt InvertionMask = APInt::getAllOnes(ResultVT.getScalarSizeInBits());
8445 
8446   SDValue ValueMaskV = DAG.getConstant(ValueMask, DL, IntVT);
8447   SDValue SignBitV = DAG.getConstant(SignBit, DL, IntVT);
8448   SDValue ExpMaskV = DAG.getConstant(ExpMask, DL, IntVT);
8449   SDValue ZeroV = DAG.getConstant(0, DL, IntVT);
8450   SDValue InfV = DAG.getConstant(Inf, DL, IntVT);
8451   SDValue ResultInvertionMask = DAG.getConstant(InvertionMask, DL, ResultVT);
8452 
8453   SDValue Res;
8454   const auto appendResult = [&](SDValue PartialRes) {
8455     if (PartialRes) {
8456       if (Res)
8457         Res = DAG.getNode(ISD::OR, DL, ResultVT, Res, PartialRes);
8458       else
8459         Res = PartialRes;
8460     }
8461   };
8462 
8463   SDValue IntBitIsSetV; // Explicit integer bit in f80 mantissa is set.
8464   const auto getIntBitIsSet = [&]() -> SDValue {
8465     if (!IntBitIsSetV) {
8466       APInt IntBitMask(BitSize, 0);
8467       IntBitMask.setBit(ExplicitIntBitInF80);
8468       SDValue IntBitMaskV = DAG.getConstant(IntBitMask, DL, IntVT);
8469       SDValue IntBitV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, IntBitMaskV);
8470       IntBitIsSetV = DAG.getSetCC(DL, ResultVT, IntBitV, ZeroV, ISD::SETNE);
8471     }
8472     return IntBitIsSetV;
8473   };
8474 
8475   // Split the value into sign bit and absolute value.
8476   SDValue AbsV = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ValueMaskV);
8477   SDValue SignV = DAG.getSetCC(DL, ResultVT, OpAsInt,
8478                                DAG.getConstant(0.0, DL, IntVT), ISD::SETLT);
8479 
8480   // Tests that involve more than one class should be processed first.
8481   SDValue PartialRes;
8482 
8483   if (IsF80)
8484     ; // Detect finite numbers of f80 by checking individual classes because
8485       // they have different settings of the explicit integer bit.
8486   else if ((Test & fcFinite) == fcFinite) {
8487     // finite(V) ==> abs(V) < exp_mask
8488     PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
8489     Test &= ~fcFinite;
8490   } else if ((Test & fcFinite) == fcPosFinite) {
8491     // finite(V) && V > 0 ==> V < exp_mask
8492     PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ExpMaskV, ISD::SETULT);
8493     Test &= ~fcPosFinite;
8494   } else if ((Test & fcFinite) == fcNegFinite) {
8495     // finite(V) && V < 0 ==> abs(V) < exp_mask && signbit == 1
8496     PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ExpMaskV, ISD::SETLT);
8497     PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
8498     Test &= ~fcNegFinite;
8499   }
8500   appendResult(PartialRes);
8501 
8502   if (FPClassTest PartialCheck = Test & (fcZero | fcSubnormal)) {
8503     // fcZero | fcSubnormal => test all exponent bits are 0
8504     // TODO: Handle sign bit specific cases
8505     if (PartialCheck == (fcZero | fcSubnormal)) {
8506       SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, OpAsInt, ExpMaskV);
8507       SDValue ExpIsZero =
8508           DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
8509       appendResult(ExpIsZero);
8510       Test &= ~PartialCheck & fcAllFlags;
8511     }
8512   }
8513 
8514   // Check for individual classes.
8515 
8516   if (unsigned PartialCheck = Test & fcZero) {
8517     if (PartialCheck == fcPosZero)
8518       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, ZeroV, ISD::SETEQ);
8519     else if (PartialCheck == fcZero)
8520       PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, ZeroV, ISD::SETEQ);
8521     else // ISD::fcNegZero
8522       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, SignBitV, ISD::SETEQ);
8523     appendResult(PartialRes);
8524   }
8525 
8526   if (unsigned PartialCheck = Test & fcSubnormal) {
8527     // issubnormal(V) ==> unsigned(abs(V) - 1) < (all mantissa bits set)
8528     // issubnormal(V) && V>0 ==> unsigned(V - 1) < (all mantissa bits set)
8529     SDValue V = (PartialCheck == fcPosSubnormal) ? OpAsInt : AbsV;
8530     SDValue MantissaV = DAG.getConstant(AllOneMantissa, DL, IntVT);
8531     SDValue VMinusOneV =
8532         DAG.getNode(ISD::SUB, DL, IntVT, V, DAG.getConstant(1, DL, IntVT));
8533     PartialRes = DAG.getSetCC(DL, ResultVT, VMinusOneV, MantissaV, ISD::SETULT);
8534     if (PartialCheck == fcNegSubnormal)
8535       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
8536     appendResult(PartialRes);
8537   }
8538 
8539   if (unsigned PartialCheck = Test & fcInf) {
8540     if (PartialCheck == fcPosInf)
8541       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, InfV, ISD::SETEQ);
8542     else if (PartialCheck == fcInf)
8543       PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETEQ);
8544     else { // ISD::fcNegInf
8545       APInt NegInf = APFloat::getInf(Semantics, true).bitcastToAPInt();
8546       SDValue NegInfV = DAG.getConstant(NegInf, DL, IntVT);
8547       PartialRes = DAG.getSetCC(DL, ResultVT, OpAsInt, NegInfV, ISD::SETEQ);
8548     }
8549     appendResult(PartialRes);
8550   }
8551 
8552   if (unsigned PartialCheck = Test & fcNan) {
8553     APInt InfWithQnanBit = Inf | QNaNBitMask;
8554     SDValue InfWithQnanBitV = DAG.getConstant(InfWithQnanBit, DL, IntVT);
8555     if (PartialCheck == fcNan) {
8556       // isnan(V) ==> abs(V) > int(inf)
8557       PartialRes = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
8558       if (IsF80) {
8559         // Recognize unsupported values as NaNs for compatibility with glibc.
8560         // In them (exp(V)==0) == int_bit.
8561         SDValue ExpBits = DAG.getNode(ISD::AND, DL, IntVT, AbsV, ExpMaskV);
8562         SDValue ExpIsZero =
8563             DAG.getSetCC(DL, ResultVT, ExpBits, ZeroV, ISD::SETEQ);
8564         SDValue IsPseudo =
8565             DAG.getSetCC(DL, ResultVT, getIntBitIsSet(), ExpIsZero, ISD::SETEQ);
8566         PartialRes = DAG.getNode(ISD::OR, DL, ResultVT, PartialRes, IsPseudo);
8567       }
8568     } else if (PartialCheck == fcQNan) {
8569       // isquiet(V) ==> abs(V) >= (unsigned(Inf) | quiet_bit)
8570       PartialRes =
8571           DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETGE);
8572     } else { // ISD::fcSNan
8573       // issignaling(V) ==> abs(V) > unsigned(Inf) &&
8574       //                    abs(V) < (unsigned(Inf) | quiet_bit)
8575       SDValue IsNan = DAG.getSetCC(DL, ResultVT, AbsV, InfV, ISD::SETGT);
8576       SDValue IsNotQnan =
8577           DAG.getSetCC(DL, ResultVT, AbsV, InfWithQnanBitV, ISD::SETLT);
8578       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, IsNan, IsNotQnan);
8579     }
8580     appendResult(PartialRes);
8581   }
8582 
8583   if (unsigned PartialCheck = Test & fcNormal) {
8584     // isnormal(V) ==> (0 < exp < max_exp) ==> (unsigned(exp-1) < (max_exp-1))
8585     APInt ExpLSB = ExpMask & ~(ExpMask.shl(1));
8586     SDValue ExpLSBV = DAG.getConstant(ExpLSB, DL, IntVT);
8587     SDValue ExpMinus1 = DAG.getNode(ISD::SUB, DL, IntVT, AbsV, ExpLSBV);
8588     APInt ExpLimit = ExpMask - ExpLSB;
8589     SDValue ExpLimitV = DAG.getConstant(ExpLimit, DL, IntVT);
8590     PartialRes = DAG.getSetCC(DL, ResultVT, ExpMinus1, ExpLimitV, ISD::SETULT);
8591     if (PartialCheck == fcNegNormal)
8592       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, SignV);
8593     else if (PartialCheck == fcPosNormal) {
8594       SDValue PosSignV =
8595           DAG.getNode(ISD::XOR, DL, ResultVT, SignV, ResultInvertionMask);
8596       PartialRes = DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, PosSignV);
8597     }
8598     if (IsF80)
8599       PartialRes =
8600           DAG.getNode(ISD::AND, DL, ResultVT, PartialRes, getIntBitIsSet());
8601     appendResult(PartialRes);
8602   }
8603 
8604   if (!Res)
8605     return DAG.getConstant(IsInverted, DL, ResultVT);
8606   if (IsInverted)
8607     Res = DAG.getNode(ISD::XOR, DL, ResultVT, Res, ResultInvertionMask);
8608   return Res;
8609 }
8610 
8611 // Only expand vector types if we have the appropriate vector bit operations.
8612 static bool canExpandVectorCTPOP(const TargetLowering &TLI, EVT VT) {
8613   assert(VT.isVector() && "Expected vector type");
8614   unsigned Len = VT.getScalarSizeInBits();
8615   return TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
8616          TLI.isOperationLegalOrCustom(ISD::SUB, VT) &&
8617          TLI.isOperationLegalOrCustom(ISD::SRL, VT) &&
8618          (Len == 8 || TLI.isOperationLegalOrCustom(ISD::MUL, VT)) &&
8619          TLI.isOperationLegalOrCustomOrPromote(ISD::AND, VT);
8620 }
8621 
8622 SDValue TargetLowering::expandCTPOP(SDNode *Node, SelectionDAG &DAG) const {
8623   SDLoc dl(Node);
8624   EVT VT = Node->getValueType(0);
8625   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
8626   SDValue Op = Node->getOperand(0);
8627   unsigned Len = VT.getScalarSizeInBits();
8628   assert(VT.isInteger() && "CTPOP not implemented for this type.");
8629 
8630   // TODO: Add support for irregular type lengths.
8631   if (!(Len <= 128 && Len % 8 == 0))
8632     return SDValue();
8633 
8634   // Only expand vector types if we have the appropriate vector bit operations.
8635   if (VT.isVector() && !canExpandVectorCTPOP(*this, VT))
8636     return SDValue();
8637 
8638   // This is the "best" algorithm from
8639   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
8640   SDValue Mask55 =
8641       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
8642   SDValue Mask33 =
8643       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
8644   SDValue Mask0F =
8645       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
8646 
8647   // v = v - ((v >> 1) & 0x55555555...)
8648   Op = DAG.getNode(ISD::SUB, dl, VT, Op,
8649                    DAG.getNode(ISD::AND, dl, VT,
8650                                DAG.getNode(ISD::SRL, dl, VT, Op,
8651                                            DAG.getConstant(1, dl, ShVT)),
8652                                Mask55));
8653   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
8654   Op = DAG.getNode(ISD::ADD, dl, VT, DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
8655                    DAG.getNode(ISD::AND, dl, VT,
8656                                DAG.getNode(ISD::SRL, dl, VT, Op,
8657                                            DAG.getConstant(2, dl, ShVT)),
8658                                Mask33));
8659   // v = (v + (v >> 4)) & 0x0F0F0F0F...
8660   Op = DAG.getNode(ISD::AND, dl, VT,
8661                    DAG.getNode(ISD::ADD, dl, VT, Op,
8662                                DAG.getNode(ISD::SRL, dl, VT, Op,
8663                                            DAG.getConstant(4, dl, ShVT))),
8664                    Mask0F);
8665 
8666   if (Len <= 8)
8667     return Op;
8668 
8669   // Avoid the multiply if we only have 2 bytes to add.
8670   // TODO: Only doing this for scalars because vectors weren't as obviously
8671   // improved.
8672   if (Len == 16 && !VT.isVector()) {
8673     // v = (v + (v >> 8)) & 0x00FF;
8674     return DAG.getNode(ISD::AND, dl, VT,
8675                      DAG.getNode(ISD::ADD, dl, VT, Op,
8676                                  DAG.getNode(ISD::SRL, dl, VT, Op,
8677                                              DAG.getConstant(8, dl, ShVT))),
8678                      DAG.getConstant(0xFF, dl, VT));
8679   }
8680 
8681   // v = (v * 0x01010101...) >> (Len - 8)
8682   SDValue Mask01 =
8683       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
8684   return DAG.getNode(ISD::SRL, dl, VT,
8685                      DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
8686                      DAG.getConstant(Len - 8, dl, ShVT));
8687 }
8688 
8689 SDValue TargetLowering::expandVPCTPOP(SDNode *Node, SelectionDAG &DAG) const {
8690   SDLoc dl(Node);
8691   EVT VT = Node->getValueType(0);
8692   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
8693   SDValue Op = Node->getOperand(0);
8694   SDValue Mask = Node->getOperand(1);
8695   SDValue VL = Node->getOperand(2);
8696   unsigned Len = VT.getScalarSizeInBits();
8697   assert(VT.isInteger() && "VP_CTPOP not implemented for this type.");
8698 
8699   // TODO: Add support for irregular type lengths.
8700   if (!(Len <= 128 && Len % 8 == 0))
8701     return SDValue();
8702 
8703   // This is same algorithm of expandCTPOP from
8704   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
8705   SDValue Mask55 =
8706       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x55)), dl, VT);
8707   SDValue Mask33 =
8708       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x33)), dl, VT);
8709   SDValue Mask0F =
8710       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x0F)), dl, VT);
8711 
8712   SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5;
8713 
8714   // v = v - ((v >> 1) & 0x55555555...)
8715   Tmp1 = DAG.getNode(ISD::VP_AND, dl, VT,
8716                      DAG.getNode(ISD::VP_LSHR, dl, VT, Op,
8717                                  DAG.getConstant(1, dl, ShVT), Mask, VL),
8718                      Mask55, Mask, VL);
8719   Op = DAG.getNode(ISD::VP_SUB, dl, VT, Op, Tmp1, Mask, VL);
8720 
8721   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
8722   Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Op, Mask33, Mask, VL);
8723   Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT,
8724                      DAG.getNode(ISD::VP_LSHR, dl, VT, Op,
8725                                  DAG.getConstant(2, dl, ShVT), Mask, VL),
8726                      Mask33, Mask, VL);
8727   Op = DAG.getNode(ISD::VP_ADD, dl, VT, Tmp2, Tmp3, Mask, VL);
8728 
8729   // v = (v + (v >> 4)) & 0x0F0F0F0F...
8730   Tmp4 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(4, dl, ShVT),
8731                      Mask, VL),
8732   Tmp5 = DAG.getNode(ISD::VP_ADD, dl, VT, Op, Tmp4, Mask, VL);
8733   Op = DAG.getNode(ISD::VP_AND, dl, VT, Tmp5, Mask0F, Mask, VL);
8734 
8735   if (Len <= 8)
8736     return Op;
8737 
8738   // v = (v * 0x01010101...) >> (Len - 8)
8739   SDValue Mask01 =
8740       DAG.getConstant(APInt::getSplat(Len, APInt(8, 0x01)), dl, VT);
8741   return DAG.getNode(ISD::VP_LSHR, dl, VT,
8742                      DAG.getNode(ISD::VP_MUL, dl, VT, Op, Mask01, Mask, VL),
8743                      DAG.getConstant(Len - 8, dl, ShVT), Mask, VL);
8744 }
8745 
8746 SDValue TargetLowering::expandCTLZ(SDNode *Node, SelectionDAG &DAG) const {
8747   SDLoc dl(Node);
8748   EVT VT = Node->getValueType(0);
8749   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
8750   SDValue Op = Node->getOperand(0);
8751   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
8752 
8753   // If the non-ZERO_UNDEF version is supported we can use that instead.
8754   if (Node->getOpcode() == ISD::CTLZ_ZERO_UNDEF &&
8755       isOperationLegalOrCustom(ISD::CTLZ, VT))
8756     return DAG.getNode(ISD::CTLZ, dl, VT, Op);
8757 
8758   // If the ZERO_UNDEF version is supported use that and handle the zero case.
8759   if (isOperationLegalOrCustom(ISD::CTLZ_ZERO_UNDEF, VT)) {
8760     EVT SetCCVT =
8761         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8762     SDValue CTLZ = DAG.getNode(ISD::CTLZ_ZERO_UNDEF, dl, VT, Op);
8763     SDValue Zero = DAG.getConstant(0, dl, VT);
8764     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
8765     return DAG.getSelect(dl, VT, SrcIsZero,
8766                          DAG.getConstant(NumBitsPerElt, dl, VT), CTLZ);
8767   }
8768 
8769   // Only expand vector types if we have the appropriate vector bit operations.
8770   // This includes the operations needed to expand CTPOP if it isn't supported.
8771   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
8772                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
8773                          !canExpandVectorCTPOP(*this, VT)) ||
8774                         !isOperationLegalOrCustom(ISD::SRL, VT) ||
8775                         !isOperationLegalOrCustomOrPromote(ISD::OR, VT)))
8776     return SDValue();
8777 
8778   // for now, we do this:
8779   // x = x | (x >> 1);
8780   // x = x | (x >> 2);
8781   // ...
8782   // x = x | (x >>16);
8783   // x = x | (x >>32); // for 64-bit input
8784   // return popcount(~x);
8785   //
8786   // Ref: "Hacker's Delight" by Henry Warren
8787   for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) {
8788     SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
8789     Op = DAG.getNode(ISD::OR, dl, VT, Op,
8790                      DAG.getNode(ISD::SRL, dl, VT, Op, Tmp));
8791   }
8792   Op = DAG.getNOT(dl, Op, VT);
8793   return DAG.getNode(ISD::CTPOP, dl, VT, Op);
8794 }
8795 
8796 SDValue TargetLowering::expandVPCTLZ(SDNode *Node, SelectionDAG &DAG) const {
8797   SDLoc dl(Node);
8798   EVT VT = Node->getValueType(0);
8799   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
8800   SDValue Op = Node->getOperand(0);
8801   SDValue Mask = Node->getOperand(1);
8802   SDValue VL = Node->getOperand(2);
8803   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
8804 
8805   // do this:
8806   // x = x | (x >> 1);
8807   // x = x | (x >> 2);
8808   // ...
8809   // x = x | (x >>16);
8810   // x = x | (x >>32); // for 64-bit input
8811   // return popcount(~x);
8812   for (unsigned i = 0; (1U << i) < NumBitsPerElt; ++i) {
8813     SDValue Tmp = DAG.getConstant(1ULL << i, dl, ShVT);
8814     Op = DAG.getNode(ISD::VP_OR, dl, VT, Op,
8815                      DAG.getNode(ISD::VP_LSHR, dl, VT, Op, Tmp, Mask, VL), Mask,
8816                      VL);
8817   }
8818   Op = DAG.getNode(ISD::VP_XOR, dl, VT, Op, DAG.getConstant(-1, dl, VT), Mask,
8819                    VL);
8820   return DAG.getNode(ISD::VP_CTPOP, dl, VT, Op, Mask, VL);
8821 }
8822 
8823 SDValue TargetLowering::CTTZTableLookup(SDNode *Node, SelectionDAG &DAG,
8824                                         const SDLoc &DL, EVT VT, SDValue Op,
8825                                         unsigned BitWidth) const {
8826   if (BitWidth != 32 && BitWidth != 64)
8827     return SDValue();
8828   APInt DeBruijn = BitWidth == 32 ? APInt(32, 0x077CB531U)
8829                                   : APInt(64, 0x0218A392CD3D5DBFULL);
8830   const DataLayout &TD = DAG.getDataLayout();
8831   MachinePointerInfo PtrInfo =
8832       MachinePointerInfo::getConstantPool(DAG.getMachineFunction());
8833   unsigned ShiftAmt = BitWidth - Log2_32(BitWidth);
8834   SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Op);
8835   SDValue Lookup = DAG.getNode(
8836       ISD::SRL, DL, VT,
8837       DAG.getNode(ISD::MUL, DL, VT, DAG.getNode(ISD::AND, DL, VT, Op, Neg),
8838                   DAG.getConstant(DeBruijn, DL, VT)),
8839       DAG.getConstant(ShiftAmt, DL, VT));
8840   Lookup = DAG.getSExtOrTrunc(Lookup, DL, getPointerTy(TD));
8841 
8842   SmallVector<uint8_t> Table(BitWidth, 0);
8843   for (unsigned i = 0; i < BitWidth; i++) {
8844     APInt Shl = DeBruijn.shl(i);
8845     APInt Lshr = Shl.lshr(ShiftAmt);
8846     Table[Lshr.getZExtValue()] = i;
8847   }
8848 
8849   // Create a ConstantArray in Constant Pool
8850   auto *CA = ConstantDataArray::get(*DAG.getContext(), Table);
8851   SDValue CPIdx = DAG.getConstantPool(CA, getPointerTy(TD),
8852                                       TD.getPrefTypeAlign(CA->getType()));
8853   SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, DL, VT, DAG.getEntryNode(),
8854                                    DAG.getMemBasePlusOffset(CPIdx, Lookup, DL),
8855                                    PtrInfo, MVT::i8);
8856   if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF)
8857     return ExtLoad;
8858 
8859   EVT SetCCVT =
8860       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8861   SDValue Zero = DAG.getConstant(0, DL, VT);
8862   SDValue SrcIsZero = DAG.getSetCC(DL, SetCCVT, Op, Zero, ISD::SETEQ);
8863   return DAG.getSelect(DL, VT, SrcIsZero,
8864                        DAG.getConstant(BitWidth, DL, VT), ExtLoad);
8865 }
8866 
8867 SDValue TargetLowering::expandCTTZ(SDNode *Node, SelectionDAG &DAG) const {
8868   SDLoc dl(Node);
8869   EVT VT = Node->getValueType(0);
8870   SDValue Op = Node->getOperand(0);
8871   unsigned NumBitsPerElt = VT.getScalarSizeInBits();
8872 
8873   // If the non-ZERO_UNDEF version is supported we can use that instead.
8874   if (Node->getOpcode() == ISD::CTTZ_ZERO_UNDEF &&
8875       isOperationLegalOrCustom(ISD::CTTZ, VT))
8876     return DAG.getNode(ISD::CTTZ, dl, VT, Op);
8877 
8878   // If the ZERO_UNDEF version is supported use that and handle the zero case.
8879   if (isOperationLegalOrCustom(ISD::CTTZ_ZERO_UNDEF, VT)) {
8880     EVT SetCCVT =
8881         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
8882     SDValue CTTZ = DAG.getNode(ISD::CTTZ_ZERO_UNDEF, dl, VT, Op);
8883     SDValue Zero = DAG.getConstant(0, dl, VT);
8884     SDValue SrcIsZero = DAG.getSetCC(dl, SetCCVT, Op, Zero, ISD::SETEQ);
8885     return DAG.getSelect(dl, VT, SrcIsZero,
8886                          DAG.getConstant(NumBitsPerElt, dl, VT), CTTZ);
8887   }
8888 
8889   // Only expand vector types if we have the appropriate vector bit operations.
8890   // This includes the operations needed to expand CTPOP if it isn't supported.
8891   if (VT.isVector() && (!isPowerOf2_32(NumBitsPerElt) ||
8892                         (!isOperationLegalOrCustom(ISD::CTPOP, VT) &&
8893                          !isOperationLegalOrCustom(ISD::CTLZ, VT) &&
8894                          !canExpandVectorCTPOP(*this, VT)) ||
8895                         !isOperationLegalOrCustom(ISD::SUB, VT) ||
8896                         !isOperationLegalOrCustomOrPromote(ISD::AND, VT) ||
8897                         !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
8898     return SDValue();
8899 
8900   // Emit Table Lookup if ISD::CTLZ and ISD::CTPOP are not legal.
8901   if (!VT.isVector() && isOperationExpand(ISD::CTPOP, VT) &&
8902       !isOperationLegal(ISD::CTLZ, VT))
8903     if (SDValue V = CTTZTableLookup(Node, DAG, dl, VT, Op, NumBitsPerElt))
8904       return V;
8905 
8906   // for now, we use: { return popcount(~x & (x - 1)); }
8907   // unless the target has ctlz but not ctpop, in which case we use:
8908   // { return 32 - nlz(~x & (x-1)); }
8909   // Ref: "Hacker's Delight" by Henry Warren
8910   SDValue Tmp = DAG.getNode(
8911       ISD::AND, dl, VT, DAG.getNOT(dl, Op, VT),
8912       DAG.getNode(ISD::SUB, dl, VT, Op, DAG.getConstant(1, dl, VT)));
8913 
8914   // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
8915   if (isOperationLegal(ISD::CTLZ, VT) && !isOperationLegal(ISD::CTPOP, VT)) {
8916     return DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(NumBitsPerElt, dl, VT),
8917                        DAG.getNode(ISD::CTLZ, dl, VT, Tmp));
8918   }
8919 
8920   return DAG.getNode(ISD::CTPOP, dl, VT, Tmp);
8921 }
8922 
8923 SDValue TargetLowering::expandVPCTTZ(SDNode *Node, SelectionDAG &DAG) const {
8924   SDValue Op = Node->getOperand(0);
8925   SDValue Mask = Node->getOperand(1);
8926   SDValue VL = Node->getOperand(2);
8927   SDLoc dl(Node);
8928   EVT VT = Node->getValueType(0);
8929 
8930   // Same as the vector part of expandCTTZ, use: popcount(~x & (x - 1))
8931   SDValue Not = DAG.getNode(ISD::VP_XOR, dl, VT, Op,
8932                             DAG.getConstant(-1, dl, VT), Mask, VL);
8933   SDValue MinusOne = DAG.getNode(ISD::VP_SUB, dl, VT, Op,
8934                                  DAG.getConstant(1, dl, VT), Mask, VL);
8935   SDValue Tmp = DAG.getNode(ISD::VP_AND, dl, VT, Not, MinusOne, Mask, VL);
8936   return DAG.getNode(ISD::VP_CTPOP, dl, VT, Tmp, Mask, VL);
8937 }
8938 
8939 SDValue TargetLowering::expandABS(SDNode *N, SelectionDAG &DAG,
8940                                   bool IsNegative) const {
8941   SDLoc dl(N);
8942   EVT VT = N->getValueType(0);
8943   EVT ShVT = getShiftAmountTy(VT, DAG.getDataLayout());
8944   SDValue Op = N->getOperand(0);
8945 
8946   // abs(x) -> smax(x,sub(0,x))
8947   if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
8948       isOperationLegal(ISD::SMAX, VT)) {
8949     SDValue Zero = DAG.getConstant(0, dl, VT);
8950     return DAG.getNode(ISD::SMAX, dl, VT, Op,
8951                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
8952   }
8953 
8954   // abs(x) -> umin(x,sub(0,x))
8955   if (!IsNegative && isOperationLegal(ISD::SUB, VT) &&
8956       isOperationLegal(ISD::UMIN, VT)) {
8957     SDValue Zero = DAG.getConstant(0, dl, VT);
8958     Op = DAG.getFreeze(Op);
8959     return DAG.getNode(ISD::UMIN, dl, VT, Op,
8960                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
8961   }
8962 
8963   // 0 - abs(x) -> smin(x, sub(0,x))
8964   if (IsNegative && isOperationLegal(ISD::SUB, VT) &&
8965       isOperationLegal(ISD::SMIN, VT)) {
8966     Op = DAG.getFreeze(Op);
8967     SDValue Zero = DAG.getConstant(0, dl, VT);
8968     return DAG.getNode(ISD::SMIN, dl, VT, Op,
8969                        DAG.getNode(ISD::SUB, dl, VT, Zero, Op));
8970   }
8971 
8972   // Only expand vector types if we have the appropriate vector operations.
8973   if (VT.isVector() &&
8974       (!isOperationLegalOrCustom(ISD::SRA, VT) ||
8975        (!IsNegative && !isOperationLegalOrCustom(ISD::ADD, VT)) ||
8976        (IsNegative && !isOperationLegalOrCustom(ISD::SUB, VT)) ||
8977        !isOperationLegalOrCustomOrPromote(ISD::XOR, VT)))
8978     return SDValue();
8979 
8980   Op = DAG.getFreeze(Op);
8981   SDValue Shift =
8982       DAG.getNode(ISD::SRA, dl, VT, Op,
8983                   DAG.getConstant(VT.getScalarSizeInBits() - 1, dl, ShVT));
8984   SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, Op, Shift);
8985 
8986   // abs(x) -> Y = sra (X, size(X)-1); sub (xor (X, Y), Y)
8987   if (!IsNegative)
8988     return DAG.getNode(ISD::SUB, dl, VT, Xor, Shift);
8989 
8990   // 0 - abs(x) -> Y = sra (X, size(X)-1); sub (Y, xor (X, Y))
8991   return DAG.getNode(ISD::SUB, dl, VT, Shift, Xor);
8992 }
8993 
8994 SDValue TargetLowering::expandABD(SDNode *N, SelectionDAG &DAG) const {
8995   SDLoc dl(N);
8996   EVT VT = N->getValueType(0);
8997   SDValue LHS = DAG.getFreeze(N->getOperand(0));
8998   SDValue RHS = DAG.getFreeze(N->getOperand(1));
8999   bool IsSigned = N->getOpcode() == ISD::ABDS;
9000 
9001   // abds(lhs, rhs) -> sub(smax(lhs,rhs), smin(lhs,rhs))
9002   // abdu(lhs, rhs) -> sub(umax(lhs,rhs), umin(lhs,rhs))
9003   unsigned MaxOpc = IsSigned ? ISD::SMAX : ISD::UMAX;
9004   unsigned MinOpc = IsSigned ? ISD::SMIN : ISD::UMIN;
9005   if (isOperationLegal(MaxOpc, VT) && isOperationLegal(MinOpc, VT)) {
9006     SDValue Max = DAG.getNode(MaxOpc, dl, VT, LHS, RHS);
9007     SDValue Min = DAG.getNode(MinOpc, dl, VT, LHS, RHS);
9008     return DAG.getNode(ISD::SUB, dl, VT, Max, Min);
9009   }
9010 
9011   // abdu(lhs, rhs) -> or(usubsat(lhs,rhs), usubsat(rhs,lhs))
9012   if (!IsSigned && isOperationLegal(ISD::USUBSAT, VT))
9013     return DAG.getNode(ISD::OR, dl, VT,
9014                        DAG.getNode(ISD::USUBSAT, dl, VT, LHS, RHS),
9015                        DAG.getNode(ISD::USUBSAT, dl, VT, RHS, LHS));
9016 
9017   // abds(lhs, rhs) -> select(sgt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
9018   // abdu(lhs, rhs) -> select(ugt(lhs,rhs), sub(lhs,rhs), sub(rhs,lhs))
9019   EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
9020   ISD::CondCode CC = IsSigned ? ISD::CondCode::SETGT : ISD::CondCode::SETUGT;
9021   SDValue Cmp = DAG.getSetCC(dl, CCVT, LHS, RHS, CC);
9022   return DAG.getSelect(dl, VT, Cmp, DAG.getNode(ISD::SUB, dl, VT, LHS, RHS),
9023                        DAG.getNode(ISD::SUB, dl, VT, RHS, LHS));
9024 }
9025 
9026 SDValue TargetLowering::expandBSWAP(SDNode *N, SelectionDAG &DAG) const {
9027   SDLoc dl(N);
9028   EVT VT = N->getValueType(0);
9029   SDValue Op = N->getOperand(0);
9030 
9031   if (!VT.isSimple())
9032     return SDValue();
9033 
9034   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
9035   SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
9036   switch (VT.getSimpleVT().getScalarType().SimpleTy) {
9037   default:
9038     return SDValue();
9039   case MVT::i16:
9040     // Use a rotate by 8. This can be further expanded if necessary.
9041     return DAG.getNode(ISD::ROTL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
9042   case MVT::i32:
9043     Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
9044     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Op,
9045                        DAG.getConstant(0xFF00, dl, VT));
9046     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT));
9047     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
9048     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, dl, VT));
9049     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
9050     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
9051     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
9052     return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
9053   case MVT::i64:
9054     Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
9055     Tmp7 = DAG.getNode(ISD::AND, dl, VT, Op,
9056                        DAG.getConstant(255ULL<<8, dl, VT));
9057     Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT));
9058     Tmp6 = DAG.getNode(ISD::AND, dl, VT, Op,
9059                        DAG.getConstant(255ULL<<16, dl, VT));
9060     Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT));
9061     Tmp5 = DAG.getNode(ISD::AND, dl, VT, Op,
9062                        DAG.getConstant(255ULL<<24, dl, VT));
9063     Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT));
9064     Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, dl, SHVT));
9065     Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4,
9066                        DAG.getConstant(255ULL<<24, dl, VT));
9067     Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, dl, SHVT));
9068     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3,
9069                        DAG.getConstant(255ULL<<16, dl, VT));
9070     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, dl, SHVT));
9071     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2,
9072                        DAG.getConstant(255ULL<<8, dl, VT));
9073     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, dl, SHVT));
9074     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
9075     Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
9076     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
9077     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
9078     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
9079     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
9080     return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
9081   }
9082 }
9083 
9084 SDValue TargetLowering::expandVPBSWAP(SDNode *N, SelectionDAG &DAG) const {
9085   SDLoc dl(N);
9086   EVT VT = N->getValueType(0);
9087   SDValue Op = N->getOperand(0);
9088   SDValue Mask = N->getOperand(1);
9089   SDValue EVL = N->getOperand(2);
9090 
9091   if (!VT.isSimple())
9092     return SDValue();
9093 
9094   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
9095   SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
9096   switch (VT.getSimpleVT().getScalarType().SimpleTy) {
9097   default:
9098     return SDValue();
9099   case MVT::i16:
9100     Tmp1 = DAG.getNode(ISD::VP_SHL, dl, VT, Op, DAG.getConstant(8, dl, SHVT),
9101                        Mask, EVL);
9102     Tmp2 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(8, dl, SHVT),
9103                        Mask, EVL);
9104     return DAG.getNode(ISD::VP_OR, dl, VT, Tmp1, Tmp2, Mask, EVL);
9105   case MVT::i32:
9106     Tmp4 = DAG.getNode(ISD::VP_SHL, dl, VT, Op, DAG.getConstant(24, dl, SHVT),
9107                        Mask, EVL);
9108     Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Op, DAG.getConstant(0xFF00, dl, VT),
9109                        Mask, EVL);
9110     Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(8, dl, SHVT),
9111                        Mask, EVL);
9112     Tmp2 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(8, dl, SHVT),
9113                        Mask, EVL);
9114     Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2,
9115                        DAG.getConstant(0xFF00, dl, VT), Mask, EVL);
9116     Tmp1 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(24, dl, SHVT),
9117                        Mask, EVL);
9118     Tmp4 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp3, Mask, EVL);
9119     Tmp2 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp1, Mask, EVL);
9120     return DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp2, Mask, EVL);
9121   case MVT::i64:
9122     Tmp8 = DAG.getNode(ISD::VP_SHL, dl, VT, Op, DAG.getConstant(56, dl, SHVT),
9123                        Mask, EVL);
9124     Tmp7 = DAG.getNode(ISD::VP_AND, dl, VT, Op,
9125                        DAG.getConstant(255ULL << 8, dl, VT), Mask, EVL);
9126     Tmp7 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp7, DAG.getConstant(40, dl, SHVT),
9127                        Mask, EVL);
9128     Tmp6 = DAG.getNode(ISD::VP_AND, dl, VT, Op,
9129                        DAG.getConstant(255ULL << 16, dl, VT), Mask, EVL);
9130     Tmp6 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp6, DAG.getConstant(24, dl, SHVT),
9131                        Mask, EVL);
9132     Tmp5 = DAG.getNode(ISD::VP_AND, dl, VT, Op,
9133                        DAG.getConstant(255ULL << 24, dl, VT), Mask, EVL);
9134     Tmp5 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp5, DAG.getConstant(8, dl, SHVT),
9135                        Mask, EVL);
9136     Tmp4 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(8, dl, SHVT),
9137                        Mask, EVL);
9138     Tmp4 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp4,
9139                        DAG.getConstant(255ULL << 24, dl, VT), Mask, EVL);
9140     Tmp3 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(24, dl, SHVT),
9141                        Mask, EVL);
9142     Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp3,
9143                        DAG.getConstant(255ULL << 16, dl, VT), Mask, EVL);
9144     Tmp2 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(40, dl, SHVT),
9145                        Mask, EVL);
9146     Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2,
9147                        DAG.getConstant(255ULL << 8, dl, VT), Mask, EVL);
9148     Tmp1 = DAG.getNode(ISD::VP_LSHR, dl, VT, Op, DAG.getConstant(56, dl, SHVT),
9149                        Mask, EVL);
9150     Tmp8 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp8, Tmp7, Mask, EVL);
9151     Tmp6 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp6, Tmp5, Mask, EVL);
9152     Tmp4 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp3, Mask, EVL);
9153     Tmp2 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp1, Mask, EVL);
9154     Tmp8 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp8, Tmp6, Mask, EVL);
9155     Tmp4 = DAG.getNode(ISD::VP_OR, dl, VT, Tmp4, Tmp2, Mask, EVL);
9156     return DAG.getNode(ISD::VP_OR, dl, VT, Tmp8, Tmp4, Mask, EVL);
9157   }
9158 }
9159 
9160 SDValue TargetLowering::expandBITREVERSE(SDNode *N, SelectionDAG &DAG) const {
9161   SDLoc dl(N);
9162   EVT VT = N->getValueType(0);
9163   SDValue Op = N->getOperand(0);
9164   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
9165   unsigned Sz = VT.getScalarSizeInBits();
9166 
9167   SDValue Tmp, Tmp2, Tmp3;
9168 
9169   // If we can, perform BSWAP first and then the mask+swap the i4, then i2
9170   // and finally the i1 pairs.
9171   // TODO: We can easily support i4/i2 legal types if any target ever does.
9172   if (Sz >= 8 && isPowerOf2_32(Sz)) {
9173     // Create the masks - repeating the pattern every byte.
9174     APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
9175     APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
9176     APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
9177 
9178     // BSWAP if the type is wider than a single byte.
9179     Tmp = (Sz > 8 ? DAG.getNode(ISD::BSWAP, dl, VT, Op) : Op);
9180 
9181     // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
9182     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT));
9183     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask4, dl, VT));
9184     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT));
9185     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT));
9186     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
9187 
9188     // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
9189     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT));
9190     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask2, dl, VT));
9191     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT));
9192     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT));
9193     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
9194 
9195     // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
9196     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT));
9197     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Mask1, dl, VT));
9198     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT));
9199     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT));
9200     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp3);
9201     return Tmp;
9202   }
9203 
9204   Tmp = DAG.getConstant(0, dl, VT);
9205   for (unsigned I = 0, J = Sz-1; I < Sz; ++I, --J) {
9206     if (I < J)
9207       Tmp2 =
9208           DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(J - I, dl, SHVT));
9209     else
9210       Tmp2 =
9211           DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(I - J, dl, SHVT));
9212 
9213     APInt Shift = APInt::getOneBitSet(Sz, J);
9214     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(Shift, dl, VT));
9215     Tmp = DAG.getNode(ISD::OR, dl, VT, Tmp, Tmp2);
9216   }
9217 
9218   return Tmp;
9219 }
9220 
9221 SDValue TargetLowering::expandVPBITREVERSE(SDNode *N, SelectionDAG &DAG) const {
9222   assert(N->getOpcode() == ISD::VP_BITREVERSE);
9223 
9224   SDLoc dl(N);
9225   EVT VT = N->getValueType(0);
9226   SDValue Op = N->getOperand(0);
9227   SDValue Mask = N->getOperand(1);
9228   SDValue EVL = N->getOperand(2);
9229   EVT SHVT = getShiftAmountTy(VT, DAG.getDataLayout());
9230   unsigned Sz = VT.getScalarSizeInBits();
9231 
9232   SDValue Tmp, Tmp2, Tmp3;
9233 
9234   // If we can, perform BSWAP first and then the mask+swap the i4, then i2
9235   // and finally the i1 pairs.
9236   // TODO: We can easily support i4/i2 legal types if any target ever does.
9237   if (Sz >= 8 && isPowerOf2_32(Sz)) {
9238     // Create the masks - repeating the pattern every byte.
9239     APInt Mask4 = APInt::getSplat(Sz, APInt(8, 0x0F));
9240     APInt Mask2 = APInt::getSplat(Sz, APInt(8, 0x33));
9241     APInt Mask1 = APInt::getSplat(Sz, APInt(8, 0x55));
9242 
9243     // BSWAP if the type is wider than a single byte.
9244     Tmp = (Sz > 8 ? DAG.getNode(ISD::VP_BSWAP, dl, VT, Op, Mask, EVL) : Op);
9245 
9246     // swap i4: ((V >> 4) & 0x0F) | ((V & 0x0F) << 4)
9247     Tmp2 = DAG.getNode(ISD::VP_LSHR, dl, VT, Tmp, DAG.getConstant(4, dl, SHVT),
9248                        Mask, EVL);
9249     Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2,
9250                        DAG.getConstant(Mask4, dl, VT), Mask, EVL);
9251     Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp, DAG.getConstant(Mask4, dl, VT),
9252                        Mask, EVL);
9253     Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(4, dl, SHVT),
9254                        Mask, EVL);
9255     Tmp = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp3, Mask, EVL);
9256 
9257     // swap i2: ((V >> 2) & 0x33) | ((V & 0x33) << 2)
9258     Tmp2 = DAG.getNode(ISD::VP_LSHR, dl, VT, Tmp, DAG.getConstant(2, dl, SHVT),
9259                        Mask, EVL);
9260     Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2,
9261                        DAG.getConstant(Mask2, dl, VT), Mask, EVL);
9262     Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp, DAG.getConstant(Mask2, dl, VT),
9263                        Mask, EVL);
9264     Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(2, dl, SHVT),
9265                        Mask, EVL);
9266     Tmp = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp3, Mask, EVL);
9267 
9268     // swap i1: ((V >> 1) & 0x55) | ((V & 0x55) << 1)
9269     Tmp2 = DAG.getNode(ISD::VP_LSHR, dl, VT, Tmp, DAG.getConstant(1, dl, SHVT),
9270                        Mask, EVL);
9271     Tmp2 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp2,
9272                        DAG.getConstant(Mask1, dl, VT), Mask, EVL);
9273     Tmp3 = DAG.getNode(ISD::VP_AND, dl, VT, Tmp, DAG.getConstant(Mask1, dl, VT),
9274                        Mask, EVL);
9275     Tmp3 = DAG.getNode(ISD::VP_SHL, dl, VT, Tmp3, DAG.getConstant(1, dl, SHVT),
9276                        Mask, EVL);
9277     Tmp = DAG.getNode(ISD::VP_OR, dl, VT, Tmp2, Tmp3, Mask, EVL);
9278     return Tmp;
9279   }
9280   return SDValue();
9281 }
9282 
9283 std::pair<SDValue, SDValue>
9284 TargetLowering::scalarizeVectorLoad(LoadSDNode *LD,
9285                                     SelectionDAG &DAG) const {
9286   SDLoc SL(LD);
9287   SDValue Chain = LD->getChain();
9288   SDValue BasePTR = LD->getBasePtr();
9289   EVT SrcVT = LD->getMemoryVT();
9290   EVT DstVT = LD->getValueType(0);
9291   ISD::LoadExtType ExtType = LD->getExtensionType();
9292 
9293   if (SrcVT.isScalableVector())
9294     report_fatal_error("Cannot scalarize scalable vector loads");
9295 
9296   unsigned NumElem = SrcVT.getVectorNumElements();
9297 
9298   EVT SrcEltVT = SrcVT.getScalarType();
9299   EVT DstEltVT = DstVT.getScalarType();
9300 
9301   // A vector must always be stored in memory as-is, i.e. without any padding
9302   // between the elements, since various code depend on it, e.g. in the
9303   // handling of a bitcast of a vector type to int, which may be done with a
9304   // vector store followed by an integer load. A vector that does not have
9305   // elements that are byte-sized must therefore be stored as an integer
9306   // built out of the extracted vector elements.
9307   if (!SrcEltVT.isByteSized()) {
9308     unsigned NumLoadBits = SrcVT.getStoreSizeInBits();
9309     EVT LoadVT = EVT::getIntegerVT(*DAG.getContext(), NumLoadBits);
9310 
9311     unsigned NumSrcBits = SrcVT.getSizeInBits();
9312     EVT SrcIntVT = EVT::getIntegerVT(*DAG.getContext(), NumSrcBits);
9313 
9314     unsigned SrcEltBits = SrcEltVT.getSizeInBits();
9315     SDValue SrcEltBitMask = DAG.getConstant(
9316         APInt::getLowBitsSet(NumLoadBits, SrcEltBits), SL, LoadVT);
9317 
9318     // Load the whole vector and avoid masking off the top bits as it makes
9319     // the codegen worse.
9320     SDValue Load =
9321         DAG.getExtLoad(ISD::EXTLOAD, SL, LoadVT, Chain, BasePTR,
9322                        LD->getPointerInfo(), SrcIntVT, LD->getOriginalAlign(),
9323                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
9324 
9325     SmallVector<SDValue, 8> Vals;
9326     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
9327       unsigned ShiftIntoIdx =
9328           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
9329       SDValue ShiftAmount =
9330           DAG.getShiftAmountConstant(ShiftIntoIdx * SrcEltVT.getSizeInBits(),
9331                                      LoadVT, SL, /*LegalTypes=*/false);
9332       SDValue ShiftedElt = DAG.getNode(ISD::SRL, SL, LoadVT, Load, ShiftAmount);
9333       SDValue Elt =
9334           DAG.getNode(ISD::AND, SL, LoadVT, ShiftedElt, SrcEltBitMask);
9335       SDValue Scalar = DAG.getNode(ISD::TRUNCATE, SL, SrcEltVT, Elt);
9336 
9337       if (ExtType != ISD::NON_EXTLOAD) {
9338         unsigned ExtendOp = ISD::getExtForLoadExtType(false, ExtType);
9339         Scalar = DAG.getNode(ExtendOp, SL, DstEltVT, Scalar);
9340       }
9341 
9342       Vals.push_back(Scalar);
9343     }
9344 
9345     SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
9346     return std::make_pair(Value, Load.getValue(1));
9347   }
9348 
9349   unsigned Stride = SrcEltVT.getSizeInBits() / 8;
9350   assert(SrcEltVT.isByteSized());
9351 
9352   SmallVector<SDValue, 8> Vals;
9353   SmallVector<SDValue, 8> LoadChains;
9354 
9355   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
9356     SDValue ScalarLoad =
9357         DAG.getExtLoad(ExtType, SL, DstEltVT, Chain, BasePTR,
9358                        LD->getPointerInfo().getWithOffset(Idx * Stride),
9359                        SrcEltVT, LD->getOriginalAlign(),
9360                        LD->getMemOperand()->getFlags(), LD->getAAInfo());
9361 
9362     BasePTR = DAG.getObjectPtrOffset(SL, BasePTR, TypeSize::getFixed(Stride));
9363 
9364     Vals.push_back(ScalarLoad.getValue(0));
9365     LoadChains.push_back(ScalarLoad.getValue(1));
9366   }
9367 
9368   SDValue NewChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other, LoadChains);
9369   SDValue Value = DAG.getBuildVector(DstVT, SL, Vals);
9370 
9371   return std::make_pair(Value, NewChain);
9372 }
9373 
9374 SDValue TargetLowering::scalarizeVectorStore(StoreSDNode *ST,
9375                                              SelectionDAG &DAG) const {
9376   SDLoc SL(ST);
9377 
9378   SDValue Chain = ST->getChain();
9379   SDValue BasePtr = ST->getBasePtr();
9380   SDValue Value = ST->getValue();
9381   EVT StVT = ST->getMemoryVT();
9382 
9383   if (StVT.isScalableVector())
9384     report_fatal_error("Cannot scalarize scalable vector stores");
9385 
9386   // The type of the data we want to save
9387   EVT RegVT = Value.getValueType();
9388   EVT RegSclVT = RegVT.getScalarType();
9389 
9390   // The type of data as saved in memory.
9391   EVT MemSclVT = StVT.getScalarType();
9392 
9393   unsigned NumElem = StVT.getVectorNumElements();
9394 
9395   // A vector must always be stored in memory as-is, i.e. without any padding
9396   // between the elements, since various code depend on it, e.g. in the
9397   // handling of a bitcast of a vector type to int, which may be done with a
9398   // vector store followed by an integer load. A vector that does not have
9399   // elements that are byte-sized must therefore be stored as an integer
9400   // built out of the extracted vector elements.
9401   if (!MemSclVT.isByteSized()) {
9402     unsigned NumBits = StVT.getSizeInBits();
9403     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), NumBits);
9404 
9405     SDValue CurrVal = DAG.getConstant(0, SL, IntVT);
9406 
9407     for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
9408       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
9409                                 DAG.getVectorIdxConstant(Idx, SL));
9410       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, MemSclVT, Elt);
9411       SDValue ExtElt = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Trunc);
9412       unsigned ShiftIntoIdx =
9413           (DAG.getDataLayout().isBigEndian() ? (NumElem - 1) - Idx : Idx);
9414       SDValue ShiftAmount =
9415           DAG.getConstant(ShiftIntoIdx * MemSclVT.getSizeInBits(), SL, IntVT);
9416       SDValue ShiftedElt =
9417           DAG.getNode(ISD::SHL, SL, IntVT, ExtElt, ShiftAmount);
9418       CurrVal = DAG.getNode(ISD::OR, SL, IntVT, CurrVal, ShiftedElt);
9419     }
9420 
9421     return DAG.getStore(Chain, SL, CurrVal, BasePtr, ST->getPointerInfo(),
9422                         ST->getOriginalAlign(), ST->getMemOperand()->getFlags(),
9423                         ST->getAAInfo());
9424   }
9425 
9426   // Store Stride in bytes
9427   unsigned Stride = MemSclVT.getSizeInBits() / 8;
9428   assert(Stride && "Zero stride!");
9429   // Extract each of the elements from the original vector and save them into
9430   // memory individually.
9431   SmallVector<SDValue, 8> Stores;
9432   for (unsigned Idx = 0; Idx < NumElem; ++Idx) {
9433     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, RegSclVT, Value,
9434                               DAG.getVectorIdxConstant(Idx, SL));
9435 
9436     SDValue Ptr =
9437         DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::getFixed(Idx * Stride));
9438 
9439     // This scalar TruncStore may be illegal, but we legalize it later.
9440     SDValue Store = DAG.getTruncStore(
9441         Chain, SL, Elt, Ptr, ST->getPointerInfo().getWithOffset(Idx * Stride),
9442         MemSclVT, ST->getOriginalAlign(), ST->getMemOperand()->getFlags(),
9443         ST->getAAInfo());
9444 
9445     Stores.push_back(Store);
9446   }
9447 
9448   return DAG.getNode(ISD::TokenFactor, SL, MVT::Other, Stores);
9449 }
9450 
9451 std::pair<SDValue, SDValue>
9452 TargetLowering::expandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG) const {
9453   assert(LD->getAddressingMode() == ISD::UNINDEXED &&
9454          "unaligned indexed loads not implemented!");
9455   SDValue Chain = LD->getChain();
9456   SDValue Ptr = LD->getBasePtr();
9457   EVT VT = LD->getValueType(0);
9458   EVT LoadedVT = LD->getMemoryVT();
9459   SDLoc dl(LD);
9460   auto &MF = DAG.getMachineFunction();
9461 
9462   if (VT.isFloatingPoint() || VT.isVector()) {
9463     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
9464     if (isTypeLegal(intVT) && isTypeLegal(LoadedVT)) {
9465       if (!isOperationLegalOrCustom(ISD::LOAD, intVT) &&
9466           LoadedVT.isVector()) {
9467         // Scalarize the load and let the individual components be handled.
9468         return scalarizeVectorLoad(LD, DAG);
9469       }
9470 
9471       // Expand to a (misaligned) integer load of the same size,
9472       // then bitconvert to floating point or vector.
9473       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr,
9474                                     LD->getMemOperand());
9475       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
9476       if (LoadedVT != VT)
9477         Result = DAG.getNode(VT.isFloatingPoint() ? ISD::FP_EXTEND :
9478                              ISD::ANY_EXTEND, dl, VT, Result);
9479 
9480       return std::make_pair(Result, newLoad.getValue(1));
9481     }
9482 
9483     // Copy the value to a (aligned) stack slot using (unaligned) integer
9484     // loads and stores, then do a (aligned) load from the stack slot.
9485     MVT RegVT = getRegisterType(*DAG.getContext(), intVT);
9486     unsigned LoadedBytes = LoadedVT.getStoreSize();
9487     unsigned RegBytes = RegVT.getSizeInBits() / 8;
9488     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
9489 
9490     // Make sure the stack slot is also aligned for the register type.
9491     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
9492     auto FrameIndex = cast<FrameIndexSDNode>(StackBase.getNode())->getIndex();
9493     SmallVector<SDValue, 8> Stores;
9494     SDValue StackPtr = StackBase;
9495     unsigned Offset = 0;
9496 
9497     EVT PtrVT = Ptr.getValueType();
9498     EVT StackPtrVT = StackPtr.getValueType();
9499 
9500     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
9501     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
9502 
9503     // Do all but one copies using the full register width.
9504     for (unsigned i = 1; i < NumRegs; i++) {
9505       // Load one integer register's worth from the original location.
9506       SDValue Load = DAG.getLoad(
9507           RegVT, dl, Chain, Ptr, LD->getPointerInfo().getWithOffset(Offset),
9508           LD->getOriginalAlign(), LD->getMemOperand()->getFlags(),
9509           LD->getAAInfo());
9510       // Follow the load with a store to the stack slot.  Remember the store.
9511       Stores.push_back(DAG.getStore(
9512           Load.getValue(1), dl, Load, StackPtr,
9513           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset)));
9514       // Increment the pointers.
9515       Offset += RegBytes;
9516 
9517       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
9518       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
9519     }
9520 
9521     // The last copy may be partial.  Do an extending load.
9522     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
9523                                   8 * (LoadedBytes - Offset));
9524     SDValue Load =
9525         DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
9526                        LD->getPointerInfo().getWithOffset(Offset), MemVT,
9527                        LD->getOriginalAlign(), LD->getMemOperand()->getFlags(),
9528                        LD->getAAInfo());
9529     // Follow the load with a store to the stack slot.  Remember the store.
9530     // On big-endian machines this requires a truncating store to ensure
9531     // that the bits end up in the right place.
9532     Stores.push_back(DAG.getTruncStore(
9533         Load.getValue(1), dl, Load, StackPtr,
9534         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), MemVT));
9535 
9536     // The order of the stores doesn't matter - say it with a TokenFactor.
9537     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9538 
9539     // Finally, perform the original load only redirected to the stack slot.
9540     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
9541                           MachinePointerInfo::getFixedStack(MF, FrameIndex, 0),
9542                           LoadedVT);
9543 
9544     // Callers expect a MERGE_VALUES node.
9545     return std::make_pair(Load, TF);
9546   }
9547 
9548   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
9549          "Unaligned load of unsupported type.");
9550 
9551   // Compute the new VT that is half the size of the old one.  This is an
9552   // integer MVT.
9553   unsigned NumBits = LoadedVT.getSizeInBits();
9554   EVT NewLoadedVT;
9555   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
9556   NumBits >>= 1;
9557 
9558   Align Alignment = LD->getOriginalAlign();
9559   unsigned IncrementSize = NumBits / 8;
9560   ISD::LoadExtType HiExtType = LD->getExtensionType();
9561 
9562   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
9563   if (HiExtType == ISD::NON_EXTLOAD)
9564     HiExtType = ISD::ZEXTLOAD;
9565 
9566   // Load the value in two parts
9567   SDValue Lo, Hi;
9568   if (DAG.getDataLayout().isLittleEndian()) {
9569     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
9570                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
9571                         LD->getAAInfo());
9572 
9573     Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
9574     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
9575                         LD->getPointerInfo().getWithOffset(IncrementSize),
9576                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
9577                         LD->getAAInfo());
9578   } else {
9579     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
9580                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
9581                         LD->getAAInfo());
9582 
9583     Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
9584     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
9585                         LD->getPointerInfo().getWithOffset(IncrementSize),
9586                         NewLoadedVT, Alignment, LD->getMemOperand()->getFlags(),
9587                         LD->getAAInfo());
9588   }
9589 
9590   // aggregate the two parts
9591   SDValue ShiftAmount =
9592       DAG.getConstant(NumBits, dl, getShiftAmountTy(Hi.getValueType(),
9593                                                     DAG.getDataLayout()));
9594   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
9595   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
9596 
9597   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
9598                              Hi.getValue(1));
9599 
9600   return std::make_pair(Result, TF);
9601 }
9602 
9603 SDValue TargetLowering::expandUnalignedStore(StoreSDNode *ST,
9604                                              SelectionDAG &DAG) const {
9605   assert(ST->getAddressingMode() == ISD::UNINDEXED &&
9606          "unaligned indexed stores not implemented!");
9607   SDValue Chain = ST->getChain();
9608   SDValue Ptr = ST->getBasePtr();
9609   SDValue Val = ST->getValue();
9610   EVT VT = Val.getValueType();
9611   Align Alignment = ST->getOriginalAlign();
9612   auto &MF = DAG.getMachineFunction();
9613   EVT StoreMemVT = ST->getMemoryVT();
9614 
9615   SDLoc dl(ST);
9616   if (StoreMemVT.isFloatingPoint() || StoreMemVT.isVector()) {
9617     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9618     if (isTypeLegal(intVT)) {
9619       if (!isOperationLegalOrCustom(ISD::STORE, intVT) &&
9620           StoreMemVT.isVector()) {
9621         // Scalarize the store and let the individual components be handled.
9622         SDValue Result = scalarizeVectorStore(ST, DAG);
9623         return Result;
9624       }
9625       // Expand to a bitconvert of the value to the integer type of the
9626       // same size, then a (misaligned) int store.
9627       // FIXME: Does not handle truncating floating point stores!
9628       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
9629       Result = DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
9630                             Alignment, ST->getMemOperand()->getFlags());
9631       return Result;
9632     }
9633     // Do a (aligned) store to a stack slot, then copy from the stack slot
9634     // to the final destination using (unaligned) integer loads and stores.
9635     MVT RegVT = getRegisterType(
9636         *DAG.getContext(),
9637         EVT::getIntegerVT(*DAG.getContext(), StoreMemVT.getSizeInBits()));
9638     EVT PtrVT = Ptr.getValueType();
9639     unsigned StoredBytes = StoreMemVT.getStoreSize();
9640     unsigned RegBytes = RegVT.getSizeInBits() / 8;
9641     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
9642 
9643     // Make sure the stack slot is also aligned for the register type.
9644     SDValue StackPtr = DAG.CreateStackTemporary(StoreMemVT, RegVT);
9645     auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
9646 
9647     // Perform the original store, only redirected to the stack slot.
9648     SDValue Store = DAG.getTruncStore(
9649         Chain, dl, Val, StackPtr,
9650         MachinePointerInfo::getFixedStack(MF, FrameIndex, 0), StoreMemVT);
9651 
9652     EVT StackPtrVT = StackPtr.getValueType();
9653 
9654     SDValue PtrIncrement = DAG.getConstant(RegBytes, dl, PtrVT);
9655     SDValue StackPtrIncrement = DAG.getConstant(RegBytes, dl, StackPtrVT);
9656     SmallVector<SDValue, 8> Stores;
9657     unsigned Offset = 0;
9658 
9659     // Do all but one copies using the full register width.
9660     for (unsigned i = 1; i < NumRegs; i++) {
9661       // Load one integer register's worth from the stack slot.
9662       SDValue Load = DAG.getLoad(
9663           RegVT, dl, Store, StackPtr,
9664           MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset));
9665       // Store it to the final location.  Remember the store.
9666       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
9667                                     ST->getPointerInfo().getWithOffset(Offset),
9668                                     ST->getOriginalAlign(),
9669                                     ST->getMemOperand()->getFlags()));
9670       // Increment the pointers.
9671       Offset += RegBytes;
9672       StackPtr = DAG.getObjectPtrOffset(dl, StackPtr, StackPtrIncrement);
9673       Ptr = DAG.getObjectPtrOffset(dl, Ptr, PtrIncrement);
9674     }
9675 
9676     // The last store may be partial.  Do a truncating store.  On big-endian
9677     // machines this requires an extending load from the stack slot to ensure
9678     // that the bits are in the right place.
9679     EVT LoadMemVT =
9680         EVT::getIntegerVT(*DAG.getContext(), 8 * (StoredBytes - Offset));
9681 
9682     // Load from the stack slot.
9683     SDValue Load = DAG.getExtLoad(
9684         ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
9685         MachinePointerInfo::getFixedStack(MF, FrameIndex, Offset), LoadMemVT);
9686 
9687     Stores.push_back(
9688         DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
9689                           ST->getPointerInfo().getWithOffset(Offset), LoadMemVT,
9690                           ST->getOriginalAlign(),
9691                           ST->getMemOperand()->getFlags(), ST->getAAInfo()));
9692     // The order of the stores doesn't matter - say it with a TokenFactor.
9693     SDValue Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Stores);
9694     return Result;
9695   }
9696 
9697   assert(StoreMemVT.isInteger() && !StoreMemVT.isVector() &&
9698          "Unaligned store of unknown type.");
9699   // Get the half-size VT
9700   EVT NewStoredVT = StoreMemVT.getHalfSizedIntegerVT(*DAG.getContext());
9701   unsigned NumBits = NewStoredVT.getFixedSizeInBits();
9702   unsigned IncrementSize = NumBits / 8;
9703 
9704   // Divide the stored value in two parts.
9705   SDValue ShiftAmount = DAG.getConstant(
9706       NumBits, dl, getShiftAmountTy(Val.getValueType(), DAG.getDataLayout()));
9707   SDValue Lo = Val;
9708   // If Val is a constant, replace the upper bits with 0. The SRL will constant
9709   // fold and not use the upper bits. A smaller constant may be easier to
9710   // materialize.
9711   if (auto *C = dyn_cast<ConstantSDNode>(Lo); C && !C->isOpaque())
9712     Lo = DAG.getNode(
9713         ISD::AND, dl, VT, Lo,
9714         DAG.getConstant(APInt::getLowBitsSet(VT.getSizeInBits(), NumBits), dl,
9715                         VT));
9716   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
9717 
9718   // Store the two parts
9719   SDValue Store1, Store2;
9720   Store1 = DAG.getTruncStore(Chain, dl,
9721                              DAG.getDataLayout().isLittleEndian() ? Lo : Hi,
9722                              Ptr, ST->getPointerInfo(), NewStoredVT, Alignment,
9723                              ST->getMemOperand()->getFlags());
9724 
9725   Ptr = DAG.getObjectPtrOffset(dl, Ptr, TypeSize::getFixed(IncrementSize));
9726   Store2 = DAG.getTruncStore(
9727       Chain, dl, DAG.getDataLayout().isLittleEndian() ? Hi : Lo, Ptr,
9728       ST->getPointerInfo().getWithOffset(IncrementSize), NewStoredVT, Alignment,
9729       ST->getMemOperand()->getFlags(), ST->getAAInfo());
9730 
9731   SDValue Result =
9732       DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
9733   return Result;
9734 }
9735 
9736 SDValue
9737 TargetLowering::IncrementMemoryAddress(SDValue Addr, SDValue Mask,
9738                                        const SDLoc &DL, EVT DataVT,
9739                                        SelectionDAG &DAG,
9740                                        bool IsCompressedMemory) const {
9741   SDValue Increment;
9742   EVT AddrVT = Addr.getValueType();
9743   EVT MaskVT = Mask.getValueType();
9744   assert(DataVT.getVectorElementCount() == MaskVT.getVectorElementCount() &&
9745          "Incompatible types of Data and Mask");
9746   if (IsCompressedMemory) {
9747     if (DataVT.isScalableVector())
9748       report_fatal_error(
9749           "Cannot currently handle compressed memory with scalable vectors");
9750     // Incrementing the pointer according to number of '1's in the mask.
9751     EVT MaskIntVT = EVT::getIntegerVT(*DAG.getContext(), MaskVT.getSizeInBits());
9752     SDValue MaskInIntReg = DAG.getBitcast(MaskIntVT, Mask);
9753     if (MaskIntVT.getSizeInBits() < 32) {
9754       MaskInIntReg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, MaskInIntReg);
9755       MaskIntVT = MVT::i32;
9756     }
9757 
9758     // Count '1's with POPCNT.
9759     Increment = DAG.getNode(ISD::CTPOP, DL, MaskIntVT, MaskInIntReg);
9760     Increment = DAG.getZExtOrTrunc(Increment, DL, AddrVT);
9761     // Scale is an element size in bytes.
9762     SDValue Scale = DAG.getConstant(DataVT.getScalarSizeInBits() / 8, DL,
9763                                     AddrVT);
9764     Increment = DAG.getNode(ISD::MUL, DL, AddrVT, Increment, Scale);
9765   } else if (DataVT.isScalableVector()) {
9766     Increment = DAG.getVScale(DL, AddrVT,
9767                               APInt(AddrVT.getFixedSizeInBits(),
9768                                     DataVT.getStoreSize().getKnownMinValue()));
9769   } else
9770     Increment = DAG.getConstant(DataVT.getStoreSize(), DL, AddrVT);
9771 
9772   return DAG.getNode(ISD::ADD, DL, AddrVT, Addr, Increment);
9773 }
9774 
9775 static SDValue clampDynamicVectorIndex(SelectionDAG &DAG, SDValue Idx,
9776                                        EVT VecVT, const SDLoc &dl,
9777                                        ElementCount SubEC) {
9778   assert(!(SubEC.isScalable() && VecVT.isFixedLengthVector()) &&
9779          "Cannot index a scalable vector within a fixed-width vector");
9780 
9781   unsigned NElts = VecVT.getVectorMinNumElements();
9782   unsigned NumSubElts = SubEC.getKnownMinValue();
9783   EVT IdxVT = Idx.getValueType();
9784 
9785   if (VecVT.isScalableVector() && !SubEC.isScalable()) {
9786     // If this is a constant index and we know the value plus the number of the
9787     // elements in the subvector minus one is less than the minimum number of
9788     // elements then it's safe to return Idx.
9789     if (auto *IdxCst = dyn_cast<ConstantSDNode>(Idx))
9790       if (IdxCst->getZExtValue() + (NumSubElts - 1) < NElts)
9791         return Idx;
9792     SDValue VS =
9793         DAG.getVScale(dl, IdxVT, APInt(IdxVT.getFixedSizeInBits(), NElts));
9794     unsigned SubOpcode = NumSubElts <= NElts ? ISD::SUB : ISD::USUBSAT;
9795     SDValue Sub = DAG.getNode(SubOpcode, dl, IdxVT, VS,
9796                               DAG.getConstant(NumSubElts, dl, IdxVT));
9797     return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx, Sub);
9798   }
9799   if (isPowerOf2_32(NElts) && NumSubElts == 1) {
9800     APInt Imm = APInt::getLowBitsSet(IdxVT.getSizeInBits(), Log2_32(NElts));
9801     return DAG.getNode(ISD::AND, dl, IdxVT, Idx,
9802                        DAG.getConstant(Imm, dl, IdxVT));
9803   }
9804   unsigned MaxIndex = NumSubElts < NElts ? NElts - NumSubElts : 0;
9805   return DAG.getNode(ISD::UMIN, dl, IdxVT, Idx,
9806                      DAG.getConstant(MaxIndex, dl, IdxVT));
9807 }
9808 
9809 SDValue TargetLowering::getVectorElementPointer(SelectionDAG &DAG,
9810                                                 SDValue VecPtr, EVT VecVT,
9811                                                 SDValue Index) const {
9812   return getVectorSubVecPointer(
9813       DAG, VecPtr, VecVT,
9814       EVT::getVectorVT(*DAG.getContext(), VecVT.getVectorElementType(), 1),
9815       Index);
9816 }
9817 
9818 SDValue TargetLowering::getVectorSubVecPointer(SelectionDAG &DAG,
9819                                                SDValue VecPtr, EVT VecVT,
9820                                                EVT SubVecVT,
9821                                                SDValue Index) const {
9822   SDLoc dl(Index);
9823   // Make sure the index type is big enough to compute in.
9824   Index = DAG.getZExtOrTrunc(Index, dl, VecPtr.getValueType());
9825 
9826   EVT EltVT = VecVT.getVectorElementType();
9827 
9828   // Calculate the element offset and add it to the pointer.
9829   unsigned EltSize = EltVT.getFixedSizeInBits() / 8; // FIXME: should be ABI size.
9830   assert(EltSize * 8 == EltVT.getFixedSizeInBits() &&
9831          "Converting bits to bytes lost precision");
9832   assert(SubVecVT.getVectorElementType() == EltVT &&
9833          "Sub-vector must be a vector with matching element type");
9834   Index = clampDynamicVectorIndex(DAG, Index, VecVT, dl,
9835                                   SubVecVT.getVectorElementCount());
9836 
9837   EVT IdxVT = Index.getValueType();
9838   if (SubVecVT.isScalableVector())
9839     Index =
9840         DAG.getNode(ISD::MUL, dl, IdxVT, Index,
9841                     DAG.getVScale(dl, IdxVT, APInt(IdxVT.getSizeInBits(), 1)));
9842 
9843   Index = DAG.getNode(ISD::MUL, dl, IdxVT, Index,
9844                       DAG.getConstant(EltSize, dl, IdxVT));
9845   return DAG.getMemBasePlusOffset(VecPtr, Index, dl);
9846 }
9847 
9848 //===----------------------------------------------------------------------===//
9849 // Implementation of Emulated TLS Model
9850 //===----------------------------------------------------------------------===//
9851 
9852 SDValue TargetLowering::LowerToTLSEmulatedModel(const GlobalAddressSDNode *GA,
9853                                                 SelectionDAG &DAG) const {
9854   // Access to address of TLS varialbe xyz is lowered to a function call:
9855   //   __emutls_get_address( address of global variable named "__emutls_v.xyz" )
9856   EVT PtrVT = getPointerTy(DAG.getDataLayout());
9857   PointerType *VoidPtrType = PointerType::get(*DAG.getContext(), 0);
9858   SDLoc dl(GA);
9859 
9860   ArgListTy Args;
9861   ArgListEntry Entry;
9862   std::string NameString = ("__emutls_v." + GA->getGlobal()->getName()).str();
9863   Module *VariableModule = const_cast<Module*>(GA->getGlobal()->getParent());
9864   StringRef EmuTlsVarName(NameString);
9865   GlobalVariable *EmuTlsVar = VariableModule->getNamedGlobal(EmuTlsVarName);
9866   assert(EmuTlsVar && "Cannot find EmuTlsVar ");
9867   Entry.Node = DAG.getGlobalAddress(EmuTlsVar, dl, PtrVT);
9868   Entry.Ty = VoidPtrType;
9869   Args.push_back(Entry);
9870 
9871   SDValue EmuTlsGetAddr = DAG.getExternalSymbol("__emutls_get_address", PtrVT);
9872 
9873   TargetLowering::CallLoweringInfo CLI(DAG);
9874   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode());
9875   CLI.setLibCallee(CallingConv::C, VoidPtrType, EmuTlsGetAddr, std::move(Args));
9876   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
9877 
9878   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
9879   // At last for X86 targets, maybe good for other targets too?
9880   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
9881   MFI.setAdjustsStack(true); // Is this only for X86 target?
9882   MFI.setHasCalls(true);
9883 
9884   assert((GA->getOffset() == 0) &&
9885          "Emulated TLS must have zero offset in GlobalAddressSDNode");
9886   return CallResult.first;
9887 }
9888 
9889 SDValue TargetLowering::lowerCmpEqZeroToCtlzSrl(SDValue Op,
9890                                                 SelectionDAG &DAG) const {
9891   assert((Op->getOpcode() == ISD::SETCC) && "Input has to be a SETCC node.");
9892   if (!isCtlzFast())
9893     return SDValue();
9894   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
9895   SDLoc dl(Op);
9896   if (isNullConstant(Op.getOperand(1)) && CC == ISD::SETEQ) {
9897     EVT VT = Op.getOperand(0).getValueType();
9898     SDValue Zext = Op.getOperand(0);
9899     if (VT.bitsLT(MVT::i32)) {
9900       VT = MVT::i32;
9901       Zext = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Op.getOperand(0));
9902     }
9903     unsigned Log2b = Log2_32(VT.getSizeInBits());
9904     SDValue Clz = DAG.getNode(ISD::CTLZ, dl, VT, Zext);
9905     SDValue Scc = DAG.getNode(ISD::SRL, dl, VT, Clz,
9906                               DAG.getConstant(Log2b, dl, MVT::i32));
9907     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Scc);
9908   }
9909   return SDValue();
9910 }
9911 
9912 SDValue TargetLowering::expandIntMINMAX(SDNode *Node, SelectionDAG &DAG) const {
9913   SDValue Op0 = Node->getOperand(0);
9914   SDValue Op1 = Node->getOperand(1);
9915   EVT VT = Op0.getValueType();
9916   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
9917   unsigned Opcode = Node->getOpcode();
9918   SDLoc DL(Node);
9919 
9920   // umax(x,1) --> sub(x,cmpeq(x,0)) iff cmp result is allbits
9921   if (Opcode == ISD::UMAX && llvm::isOneOrOneSplat(Op1, true) && BoolVT == VT &&
9922       getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
9923     Op0 = DAG.getFreeze(Op0);
9924     SDValue Zero = DAG.getConstant(0, DL, VT);
9925     return DAG.getNode(ISD::SUB, DL, VT, Op0,
9926                        DAG.getSetCC(DL, VT, Op0, Zero, ISD::SETEQ));
9927   }
9928 
9929   // umin(x,y) -> sub(x,usubsat(x,y))
9930   // TODO: Missing freeze(Op0)?
9931   if (Opcode == ISD::UMIN && isOperationLegal(ISD::SUB, VT) &&
9932       isOperationLegal(ISD::USUBSAT, VT)) {
9933     return DAG.getNode(ISD::SUB, DL, VT, Op0,
9934                        DAG.getNode(ISD::USUBSAT, DL, VT, Op0, Op1));
9935   }
9936 
9937   // umax(x,y) -> add(x,usubsat(y,x))
9938   // TODO: Missing freeze(Op0)?
9939   if (Opcode == ISD::UMAX && isOperationLegal(ISD::ADD, VT) &&
9940       isOperationLegal(ISD::USUBSAT, VT)) {
9941     return DAG.getNode(ISD::ADD, DL, VT, Op0,
9942                        DAG.getNode(ISD::USUBSAT, DL, VT, Op1, Op0));
9943   }
9944 
9945   // FIXME: Should really try to split the vector in case it's legal on a
9946   // subvector.
9947   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
9948     return DAG.UnrollVectorOp(Node);
9949 
9950   // Attempt to find an existing SETCC node that we can reuse.
9951   // TODO: Do we need a generic doesSETCCNodeExist?
9952   // TODO: Missing freeze(Op0)/freeze(Op1)?
9953   auto buildMinMax = [&](ISD::CondCode PrefCC, ISD::CondCode AltCC,
9954                          ISD::CondCode PrefCommuteCC,
9955                          ISD::CondCode AltCommuteCC) {
9956     SDVTList BoolVTList = DAG.getVTList(BoolVT);
9957     for (ISD::CondCode CC : {PrefCC, AltCC}) {
9958       if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
9959                             {Op0, Op1, DAG.getCondCode(CC)})) {
9960         SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
9961         return DAG.getSelect(DL, VT, Cond, Op0, Op1);
9962       }
9963     }
9964     for (ISD::CondCode CC : {PrefCommuteCC, AltCommuteCC}) {
9965       if (DAG.doesNodeExist(ISD::SETCC, BoolVTList,
9966                             {Op0, Op1, DAG.getCondCode(CC)})) {
9967         SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, CC);
9968         return DAG.getSelect(DL, VT, Cond, Op1, Op0);
9969       }
9970     }
9971     SDValue Cond = DAG.getSetCC(DL, BoolVT, Op0, Op1, PrefCC);
9972     return DAG.getSelect(DL, VT, Cond, Op0, Op1);
9973   };
9974 
9975   // Expand Y = MAX(A, B) -> Y = (A > B) ? A : B
9976   //                      -> Y = (A < B) ? B : A
9977   //                      -> Y = (A >= B) ? A : B
9978   //                      -> Y = (A <= B) ? B : A
9979   switch (Opcode) {
9980   case ISD::SMAX:
9981     return buildMinMax(ISD::SETGT, ISD::SETGE, ISD::SETLT, ISD::SETLE);
9982   case ISD::SMIN:
9983     return buildMinMax(ISD::SETLT, ISD::SETLE, ISD::SETGT, ISD::SETGE);
9984   case ISD::UMAX:
9985     return buildMinMax(ISD::SETUGT, ISD::SETUGE, ISD::SETULT, ISD::SETULE);
9986   case ISD::UMIN:
9987     return buildMinMax(ISD::SETULT, ISD::SETULE, ISD::SETUGT, ISD::SETUGE);
9988   }
9989 
9990   llvm_unreachable("How did we get here?");
9991 }
9992 
9993 SDValue TargetLowering::expandAddSubSat(SDNode *Node, SelectionDAG &DAG) const {
9994   unsigned Opcode = Node->getOpcode();
9995   SDValue LHS = Node->getOperand(0);
9996   SDValue RHS = Node->getOperand(1);
9997   EVT VT = LHS.getValueType();
9998   SDLoc dl(Node);
9999 
10000   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
10001   assert(VT.isInteger() && "Expected operands to be integers");
10002 
10003   // usub.sat(a, b) -> umax(a, b) - b
10004   if (Opcode == ISD::USUBSAT && isOperationLegal(ISD::UMAX, VT)) {
10005     SDValue Max = DAG.getNode(ISD::UMAX, dl, VT, LHS, RHS);
10006     return DAG.getNode(ISD::SUB, dl, VT, Max, RHS);
10007   }
10008 
10009   // uadd.sat(a, b) -> umin(a, ~b) + b
10010   if (Opcode == ISD::UADDSAT && isOperationLegal(ISD::UMIN, VT)) {
10011     SDValue InvRHS = DAG.getNOT(dl, RHS, VT);
10012     SDValue Min = DAG.getNode(ISD::UMIN, dl, VT, LHS, InvRHS);
10013     return DAG.getNode(ISD::ADD, dl, VT, Min, RHS);
10014   }
10015 
10016   unsigned OverflowOp;
10017   switch (Opcode) {
10018   case ISD::SADDSAT:
10019     OverflowOp = ISD::SADDO;
10020     break;
10021   case ISD::UADDSAT:
10022     OverflowOp = ISD::UADDO;
10023     break;
10024   case ISD::SSUBSAT:
10025     OverflowOp = ISD::SSUBO;
10026     break;
10027   case ISD::USUBSAT:
10028     OverflowOp = ISD::USUBO;
10029     break;
10030   default:
10031     llvm_unreachable("Expected method to receive signed or unsigned saturation "
10032                      "addition or subtraction node.");
10033   }
10034 
10035   // FIXME: Should really try to split the vector in case it's legal on a
10036   // subvector.
10037   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
10038     return DAG.UnrollVectorOp(Node);
10039 
10040   unsigned BitWidth = LHS.getScalarValueSizeInBits();
10041   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10042   SDValue Result = DAG.getNode(OverflowOp, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
10043   SDValue SumDiff = Result.getValue(0);
10044   SDValue Overflow = Result.getValue(1);
10045   SDValue Zero = DAG.getConstant(0, dl, VT);
10046   SDValue AllOnes = DAG.getAllOnesConstant(dl, VT);
10047 
10048   if (Opcode == ISD::UADDSAT) {
10049     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
10050       // (LHS + RHS) | OverflowMask
10051       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
10052       return DAG.getNode(ISD::OR, dl, VT, SumDiff, OverflowMask);
10053     }
10054     // Overflow ? 0xffff.... : (LHS + RHS)
10055     return DAG.getSelect(dl, VT, Overflow, AllOnes, SumDiff);
10056   }
10057 
10058   if (Opcode == ISD::USUBSAT) {
10059     if (getBooleanContents(VT) == ZeroOrNegativeOneBooleanContent) {
10060       // (LHS - RHS) & ~OverflowMask
10061       SDValue OverflowMask = DAG.getSExtOrTrunc(Overflow, dl, VT);
10062       SDValue Not = DAG.getNOT(dl, OverflowMask, VT);
10063       return DAG.getNode(ISD::AND, dl, VT, SumDiff, Not);
10064     }
10065     // Overflow ? 0 : (LHS - RHS)
10066     return DAG.getSelect(dl, VT, Overflow, Zero, SumDiff);
10067   }
10068 
10069   if (Opcode == ISD::SADDSAT || Opcode == ISD::SSUBSAT) {
10070     APInt MinVal = APInt::getSignedMinValue(BitWidth);
10071     APInt MaxVal = APInt::getSignedMaxValue(BitWidth);
10072 
10073     KnownBits KnownLHS = DAG.computeKnownBits(LHS);
10074     KnownBits KnownRHS = DAG.computeKnownBits(RHS);
10075 
10076     // If either of the operand signs are known, then they are guaranteed to
10077     // only saturate in one direction. If non-negative they will saturate
10078     // towards SIGNED_MAX, if negative they will saturate towards SIGNED_MIN.
10079     //
10080     // In the case of ISD::SSUBSAT, 'x - y' is equivalent to 'x + (-y)', so the
10081     // sign of 'y' has to be flipped.
10082 
10083     bool LHSIsNonNegative = KnownLHS.isNonNegative();
10084     bool RHSIsNonNegative = Opcode == ISD::SADDSAT ? KnownRHS.isNonNegative()
10085                                                    : KnownRHS.isNegative();
10086     if (LHSIsNonNegative || RHSIsNonNegative) {
10087       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
10088       return DAG.getSelect(dl, VT, Overflow, SatMax, SumDiff);
10089     }
10090 
10091     bool LHSIsNegative = KnownLHS.isNegative();
10092     bool RHSIsNegative = Opcode == ISD::SADDSAT ? KnownRHS.isNegative()
10093                                                 : KnownRHS.isNonNegative();
10094     if (LHSIsNegative || RHSIsNegative) {
10095       SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
10096       return DAG.getSelect(dl, VT, Overflow, SatMin, SumDiff);
10097     }
10098   }
10099 
10100   // Overflow ? (SumDiff >> BW) ^ MinVal : SumDiff
10101   APInt MinVal = APInt::getSignedMinValue(BitWidth);
10102   SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
10103   SDValue Shift = DAG.getNode(ISD::SRA, dl, VT, SumDiff,
10104                               DAG.getConstant(BitWidth - 1, dl, VT));
10105   Result = DAG.getNode(ISD::XOR, dl, VT, Shift, SatMin);
10106   return DAG.getSelect(dl, VT, Overflow, Result, SumDiff);
10107 }
10108 
10109 SDValue TargetLowering::expandShlSat(SDNode *Node, SelectionDAG &DAG) const {
10110   unsigned Opcode = Node->getOpcode();
10111   bool IsSigned = Opcode == ISD::SSHLSAT;
10112   SDValue LHS = Node->getOperand(0);
10113   SDValue RHS = Node->getOperand(1);
10114   EVT VT = LHS.getValueType();
10115   SDLoc dl(Node);
10116 
10117   assert((Node->getOpcode() == ISD::SSHLSAT ||
10118           Node->getOpcode() == ISD::USHLSAT) &&
10119           "Expected a SHLSAT opcode");
10120   assert(VT == RHS.getValueType() && "Expected operands to be the same type");
10121   assert(VT.isInteger() && "Expected operands to be integers");
10122 
10123   if (VT.isVector() && !isOperationLegalOrCustom(ISD::VSELECT, VT))
10124     return DAG.UnrollVectorOp(Node);
10125 
10126   // If LHS != (LHS << RHS) >> RHS, we have overflow and must saturate.
10127 
10128   unsigned BW = VT.getScalarSizeInBits();
10129   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10130   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, LHS, RHS);
10131   SDValue Orig =
10132       DAG.getNode(IsSigned ? ISD::SRA : ISD::SRL, dl, VT, Result, RHS);
10133 
10134   SDValue SatVal;
10135   if (IsSigned) {
10136     SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(BW), dl, VT);
10137     SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(BW), dl, VT);
10138     SDValue Cond =
10139         DAG.getSetCC(dl, BoolVT, LHS, DAG.getConstant(0, dl, VT), ISD::SETLT);
10140     SatVal = DAG.getSelect(dl, VT, Cond, SatMin, SatMax);
10141   } else {
10142     SatVal = DAG.getConstant(APInt::getMaxValue(BW), dl, VT);
10143   }
10144   SDValue Cond = DAG.getSetCC(dl, BoolVT, LHS, Orig, ISD::SETNE);
10145   return DAG.getSelect(dl, VT, Cond, SatVal, Result);
10146 }
10147 
10148 SDValue
10149 TargetLowering::expandFixedPointMul(SDNode *Node, SelectionDAG &DAG) const {
10150   assert((Node->getOpcode() == ISD::SMULFIX ||
10151           Node->getOpcode() == ISD::UMULFIX ||
10152           Node->getOpcode() == ISD::SMULFIXSAT ||
10153           Node->getOpcode() == ISD::UMULFIXSAT) &&
10154          "Expected a fixed point multiplication opcode");
10155 
10156   SDLoc dl(Node);
10157   SDValue LHS = Node->getOperand(0);
10158   SDValue RHS = Node->getOperand(1);
10159   EVT VT = LHS.getValueType();
10160   unsigned Scale = Node->getConstantOperandVal(2);
10161   bool Saturating = (Node->getOpcode() == ISD::SMULFIXSAT ||
10162                      Node->getOpcode() == ISD::UMULFIXSAT);
10163   bool Signed = (Node->getOpcode() == ISD::SMULFIX ||
10164                  Node->getOpcode() == ISD::SMULFIXSAT);
10165   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10166   unsigned VTSize = VT.getScalarSizeInBits();
10167 
10168   if (!Scale) {
10169     // [us]mul.fix(a, b, 0) -> mul(a, b)
10170     if (!Saturating) {
10171       if (isOperationLegalOrCustom(ISD::MUL, VT))
10172         return DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
10173     } else if (Signed && isOperationLegalOrCustom(ISD::SMULO, VT)) {
10174       SDValue Result =
10175           DAG.getNode(ISD::SMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
10176       SDValue Product = Result.getValue(0);
10177       SDValue Overflow = Result.getValue(1);
10178       SDValue Zero = DAG.getConstant(0, dl, VT);
10179 
10180       APInt MinVal = APInt::getSignedMinValue(VTSize);
10181       APInt MaxVal = APInt::getSignedMaxValue(VTSize);
10182       SDValue SatMin = DAG.getConstant(MinVal, dl, VT);
10183       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
10184       // Xor the inputs, if resulting sign bit is 0 the product will be
10185       // positive, else negative.
10186       SDValue Xor = DAG.getNode(ISD::XOR, dl, VT, LHS, RHS);
10187       SDValue ProdNeg = DAG.getSetCC(dl, BoolVT, Xor, Zero, ISD::SETLT);
10188       Result = DAG.getSelect(dl, VT, ProdNeg, SatMin, SatMax);
10189       return DAG.getSelect(dl, VT, Overflow, Result, Product);
10190     } else if (!Signed && isOperationLegalOrCustom(ISD::UMULO, VT)) {
10191       SDValue Result =
10192           DAG.getNode(ISD::UMULO, dl, DAG.getVTList(VT, BoolVT), LHS, RHS);
10193       SDValue Product = Result.getValue(0);
10194       SDValue Overflow = Result.getValue(1);
10195 
10196       APInt MaxVal = APInt::getMaxValue(VTSize);
10197       SDValue SatMax = DAG.getConstant(MaxVal, dl, VT);
10198       return DAG.getSelect(dl, VT, Overflow, SatMax, Product);
10199     }
10200   }
10201 
10202   assert(((Signed && Scale < VTSize) || (!Signed && Scale <= VTSize)) &&
10203          "Expected scale to be less than the number of bits if signed or at "
10204          "most the number of bits if unsigned.");
10205   assert(LHS.getValueType() == RHS.getValueType() &&
10206          "Expected both operands to be the same type");
10207 
10208   // Get the upper and lower bits of the result.
10209   SDValue Lo, Hi;
10210   unsigned LoHiOp = Signed ? ISD::SMUL_LOHI : ISD::UMUL_LOHI;
10211   unsigned HiOp = Signed ? ISD::MULHS : ISD::MULHU;
10212   if (isOperationLegalOrCustom(LoHiOp, VT)) {
10213     SDValue Result = DAG.getNode(LoHiOp, dl, DAG.getVTList(VT, VT), LHS, RHS);
10214     Lo = Result.getValue(0);
10215     Hi = Result.getValue(1);
10216   } else if (isOperationLegalOrCustom(HiOp, VT)) {
10217     Lo = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
10218     Hi = DAG.getNode(HiOp, dl, VT, LHS, RHS);
10219   } else if (VT.isVector()) {
10220     return SDValue();
10221   } else {
10222     report_fatal_error("Unable to expand fixed point multiplication.");
10223   }
10224 
10225   if (Scale == VTSize)
10226     // Result is just the top half since we'd be shifting by the width of the
10227     // operand. Overflow impossible so this works for both UMULFIX and
10228     // UMULFIXSAT.
10229     return Hi;
10230 
10231   // The result will need to be shifted right by the scale since both operands
10232   // are scaled. The result is given to us in 2 halves, so we only want part of
10233   // both in the result.
10234   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
10235   SDValue Result = DAG.getNode(ISD::FSHR, dl, VT, Hi, Lo,
10236                                DAG.getConstant(Scale, dl, ShiftTy));
10237   if (!Saturating)
10238     return Result;
10239 
10240   if (!Signed) {
10241     // Unsigned overflow happened if the upper (VTSize - Scale) bits (of the
10242     // widened multiplication) aren't all zeroes.
10243 
10244     // Saturate to max if ((Hi >> Scale) != 0),
10245     // which is the same as if (Hi > ((1 << Scale) - 1))
10246     APInt MaxVal = APInt::getMaxValue(VTSize);
10247     SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale),
10248                                       dl, VT);
10249     Result = DAG.getSelectCC(dl, Hi, LowMask,
10250                              DAG.getConstant(MaxVal, dl, VT), Result,
10251                              ISD::SETUGT);
10252 
10253     return Result;
10254   }
10255 
10256   // Signed overflow happened if the upper (VTSize - Scale + 1) bits (of the
10257   // widened multiplication) aren't all ones or all zeroes.
10258 
10259   SDValue SatMin = DAG.getConstant(APInt::getSignedMinValue(VTSize), dl, VT);
10260   SDValue SatMax = DAG.getConstant(APInt::getSignedMaxValue(VTSize), dl, VT);
10261 
10262   if (Scale == 0) {
10263     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, Lo,
10264                                DAG.getConstant(VTSize - 1, dl, ShiftTy));
10265     SDValue Overflow = DAG.getSetCC(dl, BoolVT, Hi, Sign, ISD::SETNE);
10266     // Saturated to SatMin if wide product is negative, and SatMax if wide
10267     // product is positive ...
10268     SDValue Zero = DAG.getConstant(0, dl, VT);
10269     SDValue ResultIfOverflow = DAG.getSelectCC(dl, Hi, Zero, SatMin, SatMax,
10270                                                ISD::SETLT);
10271     // ... but only if we overflowed.
10272     return DAG.getSelect(dl, VT, Overflow, ResultIfOverflow, Result);
10273   }
10274 
10275   //  We handled Scale==0 above so all the bits to examine is in Hi.
10276 
10277   // Saturate to max if ((Hi >> (Scale - 1)) > 0),
10278   // which is the same as if (Hi > (1 << (Scale - 1)) - 1)
10279   SDValue LowMask = DAG.getConstant(APInt::getLowBitsSet(VTSize, Scale - 1),
10280                                     dl, VT);
10281   Result = DAG.getSelectCC(dl, Hi, LowMask, SatMax, Result, ISD::SETGT);
10282   // Saturate to min if (Hi >> (Scale - 1)) < -1),
10283   // which is the same as if (HI < (-1 << (Scale - 1))
10284   SDValue HighMask =
10285       DAG.getConstant(APInt::getHighBitsSet(VTSize, VTSize - Scale + 1),
10286                       dl, VT);
10287   Result = DAG.getSelectCC(dl, Hi, HighMask, SatMin, Result, ISD::SETLT);
10288   return Result;
10289 }
10290 
10291 SDValue
10292 TargetLowering::expandFixedPointDiv(unsigned Opcode, const SDLoc &dl,
10293                                     SDValue LHS, SDValue RHS,
10294                                     unsigned Scale, SelectionDAG &DAG) const {
10295   assert((Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT ||
10296           Opcode == ISD::UDIVFIX || Opcode == ISD::UDIVFIXSAT) &&
10297          "Expected a fixed point division opcode");
10298 
10299   EVT VT = LHS.getValueType();
10300   bool Signed = Opcode == ISD::SDIVFIX || Opcode == ISD::SDIVFIXSAT;
10301   bool Saturating = Opcode == ISD::SDIVFIXSAT || Opcode == ISD::UDIVFIXSAT;
10302   EVT BoolVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10303 
10304   // If there is enough room in the type to upscale the LHS or downscale the
10305   // RHS before the division, we can perform it in this type without having to
10306   // resize. For signed operations, the LHS headroom is the number of
10307   // redundant sign bits, and for unsigned ones it is the number of zeroes.
10308   // The headroom for the RHS is the number of trailing zeroes.
10309   unsigned LHSLead = Signed ? DAG.ComputeNumSignBits(LHS) - 1
10310                             : DAG.computeKnownBits(LHS).countMinLeadingZeros();
10311   unsigned RHSTrail = DAG.computeKnownBits(RHS).countMinTrailingZeros();
10312 
10313   // For signed saturating operations, we need to be able to detect true integer
10314   // division overflow; that is, when you have MIN / -EPS. However, this
10315   // is undefined behavior and if we emit divisions that could take such
10316   // values it may cause undesired behavior (arithmetic exceptions on x86, for
10317   // example).
10318   // Avoid this by requiring an extra bit so that we never get this case.
10319   // FIXME: This is a bit unfortunate as it means that for an 8-bit 7-scale
10320   // signed saturating division, we need to emit a whopping 32-bit division.
10321   if (LHSLead + RHSTrail < Scale + (unsigned)(Saturating && Signed))
10322     return SDValue();
10323 
10324   unsigned LHSShift = std::min(LHSLead, Scale);
10325   unsigned RHSShift = Scale - LHSShift;
10326 
10327   // At this point, we know that if we shift the LHS up by LHSShift and the
10328   // RHS down by RHSShift, we can emit a regular division with a final scaling
10329   // factor of Scale.
10330 
10331   EVT ShiftTy = getShiftAmountTy(VT, DAG.getDataLayout());
10332   if (LHSShift)
10333     LHS = DAG.getNode(ISD::SHL, dl, VT, LHS,
10334                       DAG.getConstant(LHSShift, dl, ShiftTy));
10335   if (RHSShift)
10336     RHS = DAG.getNode(Signed ? ISD::SRA : ISD::SRL, dl, VT, RHS,
10337                       DAG.getConstant(RHSShift, dl, ShiftTy));
10338 
10339   SDValue Quot;
10340   if (Signed) {
10341     // For signed operations, if the resulting quotient is negative and the
10342     // remainder is nonzero, subtract 1 from the quotient to round towards
10343     // negative infinity.
10344     SDValue Rem;
10345     // FIXME: Ideally we would always produce an SDIVREM here, but if the
10346     // type isn't legal, SDIVREM cannot be expanded. There is no reason why
10347     // we couldn't just form a libcall, but the type legalizer doesn't do it.
10348     if (isTypeLegal(VT) &&
10349         isOperationLegalOrCustom(ISD::SDIVREM, VT)) {
10350       Quot = DAG.getNode(ISD::SDIVREM, dl,
10351                          DAG.getVTList(VT, VT),
10352                          LHS, RHS);
10353       Rem = Quot.getValue(1);
10354       Quot = Quot.getValue(0);
10355     } else {
10356       Quot = DAG.getNode(ISD::SDIV, dl, VT,
10357                          LHS, RHS);
10358       Rem = DAG.getNode(ISD::SREM, dl, VT,
10359                         LHS, RHS);
10360     }
10361     SDValue Zero = DAG.getConstant(0, dl, VT);
10362     SDValue RemNonZero = DAG.getSetCC(dl, BoolVT, Rem, Zero, ISD::SETNE);
10363     SDValue LHSNeg = DAG.getSetCC(dl, BoolVT, LHS, Zero, ISD::SETLT);
10364     SDValue RHSNeg = DAG.getSetCC(dl, BoolVT, RHS, Zero, ISD::SETLT);
10365     SDValue QuotNeg = DAG.getNode(ISD::XOR, dl, BoolVT, LHSNeg, RHSNeg);
10366     SDValue Sub1 = DAG.getNode(ISD::SUB, dl, VT, Quot,
10367                                DAG.getConstant(1, dl, VT));
10368     Quot = DAG.getSelect(dl, VT,
10369                          DAG.getNode(ISD::AND, dl, BoolVT, RemNonZero, QuotNeg),
10370                          Sub1, Quot);
10371   } else
10372     Quot = DAG.getNode(ISD::UDIV, dl, VT,
10373                        LHS, RHS);
10374 
10375   return Quot;
10376 }
10377 
10378 void TargetLowering::expandUADDSUBO(
10379     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
10380   SDLoc dl(Node);
10381   SDValue LHS = Node->getOperand(0);
10382   SDValue RHS = Node->getOperand(1);
10383   bool IsAdd = Node->getOpcode() == ISD::UADDO;
10384 
10385   // If UADDO_CARRY/SUBO_CARRY is legal, use that instead.
10386   unsigned OpcCarry = IsAdd ? ISD::UADDO_CARRY : ISD::USUBO_CARRY;
10387   if (isOperationLegalOrCustom(OpcCarry, Node->getValueType(0))) {
10388     SDValue CarryIn = DAG.getConstant(0, dl, Node->getValueType(1));
10389     SDValue NodeCarry = DAG.getNode(OpcCarry, dl, Node->getVTList(),
10390                                     { LHS, RHS, CarryIn });
10391     Result = SDValue(NodeCarry.getNode(), 0);
10392     Overflow = SDValue(NodeCarry.getNode(), 1);
10393     return;
10394   }
10395 
10396   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
10397                             LHS.getValueType(), LHS, RHS);
10398 
10399   EVT ResultType = Node->getValueType(1);
10400   EVT SetCCType = getSetCCResultType(
10401       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
10402   SDValue SetCC;
10403   if (IsAdd && isOneConstant(RHS)) {
10404     // Special case: uaddo X, 1 overflowed if X+1 is 0. This potential reduces
10405     // the live range of X. We assume comparing with 0 is cheap.
10406     // The general case (X + C) < C is not necessarily beneficial. Although we
10407     // reduce the live range of X, we may introduce the materialization of
10408     // constant C.
10409     SetCC =
10410         DAG.getSetCC(dl, SetCCType, Result,
10411                      DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETEQ);
10412   } else if (IsAdd && isAllOnesConstant(RHS)) {
10413     // Special case: uaddo X, -1 overflows if X != 0.
10414     SetCC =
10415         DAG.getSetCC(dl, SetCCType, LHS,
10416                      DAG.getConstant(0, dl, Node->getValueType(0)), ISD::SETNE);
10417   } else {
10418     ISD::CondCode CC = IsAdd ? ISD::SETULT : ISD::SETUGT;
10419     SetCC = DAG.getSetCC(dl, SetCCType, Result, LHS, CC);
10420   }
10421   Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
10422 }
10423 
10424 void TargetLowering::expandSADDSUBO(
10425     SDNode *Node, SDValue &Result, SDValue &Overflow, SelectionDAG &DAG) const {
10426   SDLoc dl(Node);
10427   SDValue LHS = Node->getOperand(0);
10428   SDValue RHS = Node->getOperand(1);
10429   bool IsAdd = Node->getOpcode() == ISD::SADDO;
10430 
10431   Result = DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, dl,
10432                             LHS.getValueType(), LHS, RHS);
10433 
10434   EVT ResultType = Node->getValueType(1);
10435   EVT OType = getSetCCResultType(
10436       DAG.getDataLayout(), *DAG.getContext(), Node->getValueType(0));
10437 
10438   // If SADDSAT/SSUBSAT is legal, compare results to detect overflow.
10439   unsigned OpcSat = IsAdd ? ISD::SADDSAT : ISD::SSUBSAT;
10440   if (isOperationLegal(OpcSat, LHS.getValueType())) {
10441     SDValue Sat = DAG.getNode(OpcSat, dl, LHS.getValueType(), LHS, RHS);
10442     SDValue SetCC = DAG.getSetCC(dl, OType, Result, Sat, ISD::SETNE);
10443     Overflow = DAG.getBoolExtOrTrunc(SetCC, dl, ResultType, ResultType);
10444     return;
10445   }
10446 
10447   SDValue Zero = DAG.getConstant(0, dl, LHS.getValueType());
10448 
10449   // For an addition, the result should be less than one of the operands (LHS)
10450   // if and only if the other operand (RHS) is negative, otherwise there will
10451   // be overflow.
10452   // For a subtraction, the result should be less than one of the operands
10453   // (LHS) if and only if the other operand (RHS) is (non-zero) positive,
10454   // otherwise there will be overflow.
10455   SDValue ResultLowerThanLHS = DAG.getSetCC(dl, OType, Result, LHS, ISD::SETLT);
10456   SDValue ConditionRHS =
10457       DAG.getSetCC(dl, OType, RHS, Zero, IsAdd ? ISD::SETLT : ISD::SETGT);
10458 
10459   Overflow = DAG.getBoolExtOrTrunc(
10460       DAG.getNode(ISD::XOR, dl, OType, ConditionRHS, ResultLowerThanLHS), dl,
10461       ResultType, ResultType);
10462 }
10463 
10464 bool TargetLowering::expandMULO(SDNode *Node, SDValue &Result,
10465                                 SDValue &Overflow, SelectionDAG &DAG) const {
10466   SDLoc dl(Node);
10467   EVT VT = Node->getValueType(0);
10468   EVT SetCCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
10469   SDValue LHS = Node->getOperand(0);
10470   SDValue RHS = Node->getOperand(1);
10471   bool isSigned = Node->getOpcode() == ISD::SMULO;
10472 
10473   // For power-of-two multiplications we can use a simpler shift expansion.
10474   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
10475     const APInt &C = RHSC->getAPIntValue();
10476     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
10477     if (C.isPowerOf2()) {
10478       // smulo(x, signed_min) is same as umulo(x, signed_min).
10479       bool UseArithShift = isSigned && !C.isMinSignedValue();
10480       EVT ShiftAmtTy = getShiftAmountTy(VT, DAG.getDataLayout());
10481       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), dl, ShiftAmtTy);
10482       Result = DAG.getNode(ISD::SHL, dl, VT, LHS, ShiftAmt);
10483       Overflow = DAG.getSetCC(dl, SetCCVT,
10484           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
10485                       dl, VT, Result, ShiftAmt),
10486           LHS, ISD::SETNE);
10487       return true;
10488     }
10489   }
10490 
10491   EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getScalarSizeInBits() * 2);
10492   if (VT.isVector())
10493     WideVT =
10494         EVT::getVectorVT(*DAG.getContext(), WideVT, VT.getVectorElementCount());
10495 
10496   SDValue BottomHalf;
10497   SDValue TopHalf;
10498   static const unsigned Ops[2][3] =
10499       { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
10500         { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
10501   if (isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
10502     BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
10503     TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
10504   } else if (isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
10505     BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
10506                              RHS);
10507     TopHalf = BottomHalf.getValue(1);
10508   } else if (isTypeLegal(WideVT)) {
10509     LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
10510     RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
10511     SDValue Mul = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
10512     BottomHalf = DAG.getNode(ISD::TRUNCATE, dl, VT, Mul);
10513     SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits(), dl,
10514         getShiftAmountTy(WideVT, DAG.getDataLayout()));
10515     TopHalf = DAG.getNode(ISD::TRUNCATE, dl, VT,
10516                           DAG.getNode(ISD::SRL, dl, WideVT, Mul, ShiftAmt));
10517   } else {
10518     if (VT.isVector())
10519       return false;
10520 
10521     // We can fall back to a libcall with an illegal type for the MUL if we
10522     // have a libcall big enough.
10523     // Also, we can fall back to a division in some cases, but that's a big
10524     // performance hit in the general case.
10525     RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
10526     if (WideVT == MVT::i16)
10527       LC = RTLIB::MUL_I16;
10528     else if (WideVT == MVT::i32)
10529       LC = RTLIB::MUL_I32;
10530     else if (WideVT == MVT::i64)
10531       LC = RTLIB::MUL_I64;
10532     else if (WideVT == MVT::i128)
10533       LC = RTLIB::MUL_I128;
10534     assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
10535 
10536     SDValue HiLHS;
10537     SDValue HiRHS;
10538     if (isSigned) {
10539       // The high part is obtained by SRA'ing all but one of the bits of low
10540       // part.
10541       unsigned LoSize = VT.getFixedSizeInBits();
10542       HiLHS =
10543           DAG.getNode(ISD::SRA, dl, VT, LHS,
10544                       DAG.getConstant(LoSize - 1, dl,
10545                                       getPointerTy(DAG.getDataLayout())));
10546       HiRHS =
10547           DAG.getNode(ISD::SRA, dl, VT, RHS,
10548                       DAG.getConstant(LoSize - 1, dl,
10549                                       getPointerTy(DAG.getDataLayout())));
10550     } else {
10551         HiLHS = DAG.getConstant(0, dl, VT);
10552         HiRHS = DAG.getConstant(0, dl, VT);
10553     }
10554 
10555     // Here we're passing the 2 arguments explicitly as 4 arguments that are
10556     // pre-lowered to the correct types. This all depends upon WideVT not
10557     // being a legal type for the architecture and thus has to be split to
10558     // two arguments.
10559     SDValue Ret;
10560     TargetLowering::MakeLibCallOptions CallOptions;
10561     CallOptions.setSExt(isSigned);
10562     CallOptions.setIsPostTypeLegalization(true);
10563     if (shouldSplitFunctionArgumentsAsLittleEndian(DAG.getDataLayout())) {
10564       // Halves of WideVT are packed into registers in different order
10565       // depending on platform endianness. This is usually handled by
10566       // the C calling convention, but we can't defer to it in
10567       // the legalizer.
10568       SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
10569       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
10570     } else {
10571       SDValue Args[] = { HiLHS, LHS, HiRHS, RHS };
10572       Ret = makeLibCall(DAG, LC, WideVT, Args, CallOptions, dl).first;
10573     }
10574     assert(Ret.getOpcode() == ISD::MERGE_VALUES &&
10575            "Ret value is a collection of constituent nodes holding result.");
10576     if (DAG.getDataLayout().isLittleEndian()) {
10577       // Same as above.
10578       BottomHalf = Ret.getOperand(0);
10579       TopHalf = Ret.getOperand(1);
10580     } else {
10581       BottomHalf = Ret.getOperand(1);
10582       TopHalf = Ret.getOperand(0);
10583     }
10584   }
10585 
10586   Result = BottomHalf;
10587   if (isSigned) {
10588     SDValue ShiftAmt = DAG.getConstant(
10589         VT.getScalarSizeInBits() - 1, dl,
10590         getShiftAmountTy(BottomHalf.getValueType(), DAG.getDataLayout()));
10591     SDValue Sign = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, ShiftAmt);
10592     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf, Sign, ISD::SETNE);
10593   } else {
10594     Overflow = DAG.getSetCC(dl, SetCCVT, TopHalf,
10595                             DAG.getConstant(0, dl, VT), ISD::SETNE);
10596   }
10597 
10598   // Truncate the result if SetCC returns a larger type than needed.
10599   EVT RType = Node->getValueType(1);
10600   if (RType.bitsLT(Overflow.getValueType()))
10601     Overflow = DAG.getNode(ISD::TRUNCATE, dl, RType, Overflow);
10602 
10603   assert(RType.getSizeInBits() == Overflow.getValueSizeInBits() &&
10604          "Unexpected result type for S/UMULO legalization");
10605   return true;
10606 }
10607 
10608 SDValue TargetLowering::expandVecReduce(SDNode *Node, SelectionDAG &DAG) const {
10609   SDLoc dl(Node);
10610   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
10611   SDValue Op = Node->getOperand(0);
10612   EVT VT = Op.getValueType();
10613 
10614   if (VT.isScalableVector())
10615     report_fatal_error(
10616         "Expanding reductions for scalable vectors is undefined.");
10617 
10618   // Try to use a shuffle reduction for power of two vectors.
10619   if (VT.isPow2VectorType()) {
10620     while (VT.getVectorNumElements() > 1) {
10621       EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
10622       if (!isOperationLegalOrCustom(BaseOpcode, HalfVT))
10623         break;
10624 
10625       SDValue Lo, Hi;
10626       std::tie(Lo, Hi) = DAG.SplitVector(Op, dl);
10627       Op = DAG.getNode(BaseOpcode, dl, HalfVT, Lo, Hi);
10628       VT = HalfVT;
10629     }
10630   }
10631 
10632   EVT EltVT = VT.getVectorElementType();
10633   unsigned NumElts = VT.getVectorNumElements();
10634 
10635   SmallVector<SDValue, 8> Ops;
10636   DAG.ExtractVectorElements(Op, Ops, 0, NumElts);
10637 
10638   SDValue Res = Ops[0];
10639   for (unsigned i = 1; i < NumElts; i++)
10640     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Node->getFlags());
10641 
10642   // Result type may be wider than element type.
10643   if (EltVT != Node->getValueType(0))
10644     Res = DAG.getNode(ISD::ANY_EXTEND, dl, Node->getValueType(0), Res);
10645   return Res;
10646 }
10647 
10648 SDValue TargetLowering::expandVecReduceSeq(SDNode *Node, SelectionDAG &DAG) const {
10649   SDLoc dl(Node);
10650   SDValue AccOp = Node->getOperand(0);
10651   SDValue VecOp = Node->getOperand(1);
10652   SDNodeFlags Flags = Node->getFlags();
10653 
10654   EVT VT = VecOp.getValueType();
10655   EVT EltVT = VT.getVectorElementType();
10656 
10657   if (VT.isScalableVector())
10658     report_fatal_error(
10659         "Expanding reductions for scalable vectors is undefined.");
10660 
10661   unsigned NumElts = VT.getVectorNumElements();
10662 
10663   SmallVector<SDValue, 8> Ops;
10664   DAG.ExtractVectorElements(VecOp, Ops, 0, NumElts);
10665 
10666   unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Node->getOpcode());
10667 
10668   SDValue Res = AccOp;
10669   for (unsigned i = 0; i < NumElts; i++)
10670     Res = DAG.getNode(BaseOpcode, dl, EltVT, Res, Ops[i], Flags);
10671 
10672   return Res;
10673 }
10674 
10675 bool TargetLowering::expandREM(SDNode *Node, SDValue &Result,
10676                                SelectionDAG &DAG) const {
10677   EVT VT = Node->getValueType(0);
10678   SDLoc dl(Node);
10679   bool isSigned = Node->getOpcode() == ISD::SREM;
10680   unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
10681   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
10682   SDValue Dividend = Node->getOperand(0);
10683   SDValue Divisor = Node->getOperand(1);
10684   if (isOperationLegalOrCustom(DivRemOpc, VT)) {
10685     SDVTList VTs = DAG.getVTList(VT, VT);
10686     Result = DAG.getNode(DivRemOpc, dl, VTs, Dividend, Divisor).getValue(1);
10687     return true;
10688   }
10689   if (isOperationLegalOrCustom(DivOpc, VT)) {
10690     // X % Y -> X-X/Y*Y
10691     SDValue Divide = DAG.getNode(DivOpc, dl, VT, Dividend, Divisor);
10692     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Divide, Divisor);
10693     Result = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
10694     return true;
10695   }
10696   return false;
10697 }
10698 
10699 SDValue TargetLowering::expandFP_TO_INT_SAT(SDNode *Node,
10700                                             SelectionDAG &DAG) const {
10701   bool IsSigned = Node->getOpcode() == ISD::FP_TO_SINT_SAT;
10702   SDLoc dl(SDValue(Node, 0));
10703   SDValue Src = Node->getOperand(0);
10704 
10705   // DstVT is the result type, while SatVT is the size to which we saturate
10706   EVT SrcVT = Src.getValueType();
10707   EVT DstVT = Node->getValueType(0);
10708 
10709   EVT SatVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
10710   unsigned SatWidth = SatVT.getScalarSizeInBits();
10711   unsigned DstWidth = DstVT.getScalarSizeInBits();
10712   assert(SatWidth <= DstWidth &&
10713          "Expected saturation width smaller than result width");
10714 
10715   // Determine minimum and maximum integer values and their corresponding
10716   // floating-point values.
10717   APInt MinInt, MaxInt;
10718   if (IsSigned) {
10719     MinInt = APInt::getSignedMinValue(SatWidth).sext(DstWidth);
10720     MaxInt = APInt::getSignedMaxValue(SatWidth).sext(DstWidth);
10721   } else {
10722     MinInt = APInt::getMinValue(SatWidth).zext(DstWidth);
10723     MaxInt = APInt::getMaxValue(SatWidth).zext(DstWidth);
10724   }
10725 
10726   // We cannot risk emitting FP_TO_XINT nodes with a source VT of [b]f16, as
10727   // libcall emission cannot handle this. Large result types will fail.
10728   if (SrcVT == MVT::f16 || SrcVT == MVT::bf16) {
10729     Src = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Src);
10730     SrcVT = Src.getValueType();
10731   }
10732 
10733   APFloat MinFloat(DAG.EVTToAPFloatSemantics(SrcVT));
10734   APFloat MaxFloat(DAG.EVTToAPFloatSemantics(SrcVT));
10735 
10736   APFloat::opStatus MinStatus =
10737       MinFloat.convertFromAPInt(MinInt, IsSigned, APFloat::rmTowardZero);
10738   APFloat::opStatus MaxStatus =
10739       MaxFloat.convertFromAPInt(MaxInt, IsSigned, APFloat::rmTowardZero);
10740   bool AreExactFloatBounds = !(MinStatus & APFloat::opStatus::opInexact) &&
10741                              !(MaxStatus & APFloat::opStatus::opInexact);
10742 
10743   SDValue MinFloatNode = DAG.getConstantFP(MinFloat, dl, SrcVT);
10744   SDValue MaxFloatNode = DAG.getConstantFP(MaxFloat, dl, SrcVT);
10745 
10746   // If the integer bounds are exactly representable as floats and min/max are
10747   // legal, emit a min+max+fptoi sequence. Otherwise we have to use a sequence
10748   // of comparisons and selects.
10749   bool MinMaxLegal = isOperationLegal(ISD::FMINNUM, SrcVT) &&
10750                      isOperationLegal(ISD::FMAXNUM, SrcVT);
10751   if (AreExactFloatBounds && MinMaxLegal) {
10752     SDValue Clamped = Src;
10753 
10754     // Clamp Src by MinFloat from below. If Src is NaN the result is MinFloat.
10755     Clamped = DAG.getNode(ISD::FMAXNUM, dl, SrcVT, Clamped, MinFloatNode);
10756     // Clamp by MaxFloat from above. NaN cannot occur.
10757     Clamped = DAG.getNode(ISD::FMINNUM, dl, SrcVT, Clamped, MaxFloatNode);
10758     // Convert clamped value to integer.
10759     SDValue FpToInt = DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT,
10760                                   dl, DstVT, Clamped);
10761 
10762     // In the unsigned case we're done, because we mapped NaN to MinFloat,
10763     // which will cast to zero.
10764     if (!IsSigned)
10765       return FpToInt;
10766 
10767     // Otherwise, select 0 if Src is NaN.
10768     SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
10769     EVT SetCCVT =
10770         getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
10771     SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
10772     return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, FpToInt);
10773   }
10774 
10775   SDValue MinIntNode = DAG.getConstant(MinInt, dl, DstVT);
10776   SDValue MaxIntNode = DAG.getConstant(MaxInt, dl, DstVT);
10777 
10778   // Result of direct conversion. The assumption here is that the operation is
10779   // non-trapping and it's fine to apply it to an out-of-range value if we
10780   // select it away later.
10781   SDValue FpToInt =
10782       DAG.getNode(IsSigned ? ISD::FP_TO_SINT : ISD::FP_TO_UINT, dl, DstVT, Src);
10783 
10784   SDValue Select = FpToInt;
10785 
10786   EVT SetCCVT =
10787       getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), SrcVT);
10788 
10789   // If Src ULT MinFloat, select MinInt. In particular, this also selects
10790   // MinInt if Src is NaN.
10791   SDValue ULT = DAG.getSetCC(dl, SetCCVT, Src, MinFloatNode, ISD::SETULT);
10792   Select = DAG.getSelect(dl, DstVT, ULT, MinIntNode, Select);
10793   // If Src OGT MaxFloat, select MaxInt.
10794   SDValue OGT = DAG.getSetCC(dl, SetCCVT, Src, MaxFloatNode, ISD::SETOGT);
10795   Select = DAG.getSelect(dl, DstVT, OGT, MaxIntNode, Select);
10796 
10797   // In the unsigned case we are done, because we mapped NaN to MinInt, which
10798   // is already zero.
10799   if (!IsSigned)
10800     return Select;
10801 
10802   // Otherwise, select 0 if Src is NaN.
10803   SDValue ZeroInt = DAG.getConstant(0, dl, DstVT);
10804   SDValue IsNan = DAG.getSetCC(dl, SetCCVT, Src, Src, ISD::CondCode::SETUO);
10805   return DAG.getSelect(dl, DstVT, IsNan, ZeroInt, Select);
10806 }
10807 
10808 SDValue TargetLowering::expandVectorSplice(SDNode *Node,
10809                                            SelectionDAG &DAG) const {
10810   assert(Node->getOpcode() == ISD::VECTOR_SPLICE && "Unexpected opcode!");
10811   assert(Node->getValueType(0).isScalableVector() &&
10812          "Fixed length vector types expected to use SHUFFLE_VECTOR!");
10813 
10814   EVT VT = Node->getValueType(0);
10815   SDValue V1 = Node->getOperand(0);
10816   SDValue V2 = Node->getOperand(1);
10817   int64_t Imm = cast<ConstantSDNode>(Node->getOperand(2))->getSExtValue();
10818   SDLoc DL(Node);
10819 
10820   // Expand through memory thusly:
10821   //  Alloca CONCAT_VECTORS_TYPES(V1, V2) Ptr
10822   //  Store V1, Ptr
10823   //  Store V2, Ptr + sizeof(V1)
10824   //  If (Imm < 0)
10825   //    TrailingElts = -Imm
10826   //    Ptr = Ptr + sizeof(V1) - (TrailingElts * sizeof(VT.Elt))
10827   //  else
10828   //    Ptr = Ptr + (Imm * sizeof(VT.Elt))
10829   //  Res = Load Ptr
10830 
10831   Align Alignment = DAG.getReducedAlign(VT, /*UseABI=*/false);
10832 
10833   EVT MemVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
10834                                VT.getVectorElementCount() * 2);
10835   SDValue StackPtr = DAG.CreateStackTemporary(MemVT.getStoreSize(), Alignment);
10836   EVT PtrVT = StackPtr.getValueType();
10837   auto &MF = DAG.getMachineFunction();
10838   auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
10839   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
10840 
10841   // Store the lo part of CONCAT_VECTORS(V1, V2)
10842   SDValue StoreV1 = DAG.getStore(DAG.getEntryNode(), DL, V1, StackPtr, PtrInfo);
10843   // Store the hi part of CONCAT_VECTORS(V1, V2)
10844   SDValue OffsetToV2 = DAG.getVScale(
10845       DL, PtrVT,
10846       APInt(PtrVT.getFixedSizeInBits(), VT.getStoreSize().getKnownMinValue()));
10847   SDValue StackPtr2 = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, OffsetToV2);
10848   SDValue StoreV2 = DAG.getStore(StoreV1, DL, V2, StackPtr2, PtrInfo);
10849 
10850   if (Imm >= 0) {
10851     // Load back the required element. getVectorElementPointer takes care of
10852     // clamping the index if it's out-of-bounds.
10853     StackPtr = getVectorElementPointer(DAG, StackPtr, VT, Node->getOperand(2));
10854     // Load the spliced result
10855     return DAG.getLoad(VT, DL, StoreV2, StackPtr,
10856                        MachinePointerInfo::getUnknownStack(MF));
10857   }
10858 
10859   uint64_t TrailingElts = -Imm;
10860 
10861   // NOTE: TrailingElts must be clamped so as not to read outside of V1:V2.
10862   TypeSize EltByteSize = VT.getVectorElementType().getStoreSize();
10863   SDValue TrailingBytes =
10864       DAG.getConstant(TrailingElts * EltByteSize, DL, PtrVT);
10865 
10866   if (TrailingElts > VT.getVectorMinNumElements()) {
10867     SDValue VLBytes =
10868         DAG.getVScale(DL, PtrVT,
10869                       APInt(PtrVT.getFixedSizeInBits(),
10870                             VT.getStoreSize().getKnownMinValue()));
10871     TrailingBytes = DAG.getNode(ISD::UMIN, DL, PtrVT, TrailingBytes, VLBytes);
10872   }
10873 
10874   // Calculate the start address of the spliced result.
10875   StackPtr2 = DAG.getNode(ISD::SUB, DL, PtrVT, StackPtr2, TrailingBytes);
10876 
10877   // Load the spliced result
10878   return DAG.getLoad(VT, DL, StoreV2, StackPtr2,
10879                      MachinePointerInfo::getUnknownStack(MF));
10880 }
10881 
10882 bool TargetLowering::LegalizeSetCCCondCode(SelectionDAG &DAG, EVT VT,
10883                                            SDValue &LHS, SDValue &RHS,
10884                                            SDValue &CC, SDValue Mask,
10885                                            SDValue EVL, bool &NeedInvert,
10886                                            const SDLoc &dl, SDValue &Chain,
10887                                            bool IsSignaling) const {
10888   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10889   MVT OpVT = LHS.getSimpleValueType();
10890   ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
10891   NeedInvert = false;
10892   assert(!EVL == !Mask && "VP Mask and EVL must either both be set or unset");
10893   bool IsNonVP = !EVL;
10894   switch (TLI.getCondCodeAction(CCCode, OpVT)) {
10895   default:
10896     llvm_unreachable("Unknown condition code action!");
10897   case TargetLowering::Legal:
10898     // Nothing to do.
10899     break;
10900   case TargetLowering::Expand: {
10901     ISD::CondCode InvCC = ISD::getSetCCSwappedOperands(CCCode);
10902     if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
10903       std::swap(LHS, RHS);
10904       CC = DAG.getCondCode(InvCC);
10905       return true;
10906     }
10907     // Swapping operands didn't work. Try inverting the condition.
10908     bool NeedSwap = false;
10909     InvCC = getSetCCInverse(CCCode, OpVT);
10910     if (!TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
10911       // If inverting the condition is not enough, try swapping operands
10912       // on top of it.
10913       InvCC = ISD::getSetCCSwappedOperands(InvCC);
10914       NeedSwap = true;
10915     }
10916     if (TLI.isCondCodeLegalOrCustom(InvCC, OpVT)) {
10917       CC = DAG.getCondCode(InvCC);
10918       NeedInvert = true;
10919       if (NeedSwap)
10920         std::swap(LHS, RHS);
10921       return true;
10922     }
10923 
10924     ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
10925     unsigned Opc = 0;
10926     switch (CCCode) {
10927     default:
10928       llvm_unreachable("Don't know how to expand this condition!");
10929     case ISD::SETUO:
10930       if (TLI.isCondCodeLegal(ISD::SETUNE, OpVT)) {
10931         CC1 = ISD::SETUNE;
10932         CC2 = ISD::SETUNE;
10933         Opc = ISD::OR;
10934         break;
10935       }
10936       assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) &&
10937              "If SETUE is expanded, SETOEQ or SETUNE must be legal!");
10938       NeedInvert = true;
10939       [[fallthrough]];
10940     case ISD::SETO:
10941       assert(TLI.isCondCodeLegal(ISD::SETOEQ, OpVT) &&
10942              "If SETO is expanded, SETOEQ must be legal!");
10943       CC1 = ISD::SETOEQ;
10944       CC2 = ISD::SETOEQ;
10945       Opc = ISD::AND;
10946       break;
10947     case ISD::SETONE:
10948     case ISD::SETUEQ:
10949       // If the SETUO or SETO CC isn't legal, we might be able to use
10950       // SETOGT || SETOLT, inverting the result for SETUEQ. We only need one
10951       // of SETOGT/SETOLT to be legal, the other can be emulated by swapping
10952       // the operands.
10953       CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
10954       if (!TLI.isCondCodeLegal(CC2, OpVT) &&
10955           (TLI.isCondCodeLegal(ISD::SETOGT, OpVT) ||
10956            TLI.isCondCodeLegal(ISD::SETOLT, OpVT))) {
10957         CC1 = ISD::SETOGT;
10958         CC2 = ISD::SETOLT;
10959         Opc = ISD::OR;
10960         NeedInvert = ((unsigned)CCCode & 0x8U);
10961         break;
10962       }
10963       [[fallthrough]];
10964     case ISD::SETOEQ:
10965     case ISD::SETOGT:
10966     case ISD::SETOGE:
10967     case ISD::SETOLT:
10968     case ISD::SETOLE:
10969     case ISD::SETUNE:
10970     case ISD::SETUGT:
10971     case ISD::SETUGE:
10972     case ISD::SETULT:
10973     case ISD::SETULE:
10974       // If we are floating point, assign and break, otherwise fall through.
10975       if (!OpVT.isInteger()) {
10976         // We can use the 4th bit to tell if we are the unordered
10977         // or ordered version of the opcode.
10978         CC2 = ((unsigned)CCCode & 0x8U) ? ISD::SETUO : ISD::SETO;
10979         Opc = ((unsigned)CCCode & 0x8U) ? ISD::OR : ISD::AND;
10980         CC1 = (ISD::CondCode)(((int)CCCode & 0x7) | 0x10);
10981         break;
10982       }
10983       // Fallthrough if we are unsigned integer.
10984       [[fallthrough]];
10985     case ISD::SETLE:
10986     case ISD::SETGT:
10987     case ISD::SETGE:
10988     case ISD::SETLT:
10989     case ISD::SETNE:
10990     case ISD::SETEQ:
10991       // If all combinations of inverting the condition and swapping operands
10992       // didn't work then we have no means to expand the condition.
10993       llvm_unreachable("Don't know how to expand this condition!");
10994     }
10995 
10996     SDValue SetCC1, SetCC2;
10997     if (CCCode != ISD::SETO && CCCode != ISD::SETUO) {
10998       // If we aren't the ordered or unorder operation,
10999       // then the pattern is (LHS CC1 RHS) Opc (LHS CC2 RHS).
11000       if (IsNonVP) {
11001         SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1, Chain, IsSignaling);
11002         SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2, Chain, IsSignaling);
11003       } else {
11004         SetCC1 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC1, Mask, EVL);
11005         SetCC2 = DAG.getSetCCVP(dl, VT, LHS, RHS, CC2, Mask, EVL);
11006       }
11007     } else {
11008       // Otherwise, the pattern is (LHS CC1 LHS) Opc (RHS CC2 RHS)
11009       if (IsNonVP) {
11010         SetCC1 = DAG.getSetCC(dl, VT, LHS, LHS, CC1, Chain, IsSignaling);
11011         SetCC2 = DAG.getSetCC(dl, VT, RHS, RHS, CC2, Chain, IsSignaling);
11012       } else {
11013         SetCC1 = DAG.getSetCCVP(dl, VT, LHS, LHS, CC1, Mask, EVL);
11014         SetCC2 = DAG.getSetCCVP(dl, VT, RHS, RHS, CC2, Mask, EVL);
11015       }
11016     }
11017     if (Chain)
11018       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, SetCC1.getValue(1),
11019                           SetCC2.getValue(1));
11020     if (IsNonVP)
11021       LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
11022     else {
11023       // Transform the binary opcode to the VP equivalent.
11024       assert((Opc == ISD::OR || Opc == ISD::AND) && "Unexpected opcode");
11025       Opc = Opc == ISD::OR ? ISD::VP_OR : ISD::VP_AND;
11026       LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2, Mask, EVL);
11027     }
11028     RHS = SDValue();
11029     CC = SDValue();
11030     return true;
11031   }
11032   }
11033   return false;
11034 }
11035