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