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