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