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