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