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