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