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