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