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