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