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