1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the SelectionDAG class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "SDNodeDbgValue.h"
16 #include "llvm/ADT/APFloat.h"
17 #include "llvm/ADT/APInt.h"
18 #include "llvm/ADT/APSInt.h"
19 #include "llvm/ADT/ArrayRef.h"
20 #include "llvm/ADT/BitVector.h"
21 #include "llvm/ADT/FoldingSet.h"
22 #include "llvm/ADT/None.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/CodeGen/ISDOpcodes.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineConstantPool.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineMemOperand.h"
35 #include "llvm/CodeGen/RuntimeLibcalls.h"
36 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
37 #include "llvm/CodeGen/SelectionDAGNodes.h"
38 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
39 #include "llvm/CodeGen/TargetLowering.h"
40 #include "llvm/CodeGen/TargetRegisterInfo.h"
41 #include "llvm/CodeGen/TargetSubtargetInfo.h"
42 #include "llvm/CodeGen/ValueTypes.h"
43 #include "llvm/IR/Constant.h"
44 #include "llvm/IR/Constants.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/DebugInfoMetadata.h"
47 #include "llvm/IR/DebugLoc.h"
48 #include "llvm/IR/DerivedTypes.h"
49 #include "llvm/IR/Function.h"
50 #include "llvm/IR/GlobalValue.h"
51 #include "llvm/IR/Metadata.h"
52 #include "llvm/IR/Type.h"
53 #include "llvm/IR/Value.h"
54 #include "llvm/Support/Casting.h"
55 #include "llvm/Support/CodeGen.h"
56 #include "llvm/Support/Compiler.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/ErrorHandling.h"
59 #include "llvm/Support/KnownBits.h"
60 #include "llvm/Support/MachineValueType.h"
61 #include "llvm/Support/ManagedStatic.h"
62 #include "llvm/Support/MathExtras.h"
63 #include "llvm/Support/Mutex.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include "llvm/Target/TargetMachine.h"
66 #include "llvm/Target/TargetOptions.h"
67 #include <algorithm>
68 #include <cassert>
69 #include <cstdint>
70 #include <cstdlib>
71 #include <limits>
72 #include <set>
73 #include <string>
74 #include <utility>
75 #include <vector>
76 
77 using namespace llvm;
78 
79 /// makeVTList - Return an instance of the SDVTList struct initialized with the
80 /// specified members.
81 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
82   SDVTList Res = {VTs, NumVTs};
83   return Res;
84 }
85 
86 // Default null implementations of the callbacks.
87 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
88 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
89 
90 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
91 
92 #define DEBUG_TYPE "selectiondag"
93 
94 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
95        cl::Hidden, cl::init(true),
96        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
97 
98 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
99        cl::desc("Number limit for gluing ld/st of memcpy."),
100        cl::Hidden, cl::init(0));
101 
102 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
103   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
104 }
105 
106 //===----------------------------------------------------------------------===//
107 //                              ConstantFPSDNode Class
108 //===----------------------------------------------------------------------===//
109 
110 /// isExactlyValue - We don't rely on operator== working on double values, as
111 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
112 /// As such, this method can be used to do an exact bit-for-bit comparison of
113 /// two floating point values.
114 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
115   return getValueAPF().bitwiseIsEqual(V);
116 }
117 
118 bool ConstantFPSDNode::isValueValidForType(EVT VT,
119                                            const APFloat& Val) {
120   assert(VT.isFloatingPoint() && "Can only convert between FP types");
121 
122   // convert modifies in place, so make a copy.
123   APFloat Val2 = APFloat(Val);
124   bool losesInfo;
125   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
126                       APFloat::rmNearestTiesToEven,
127                       &losesInfo);
128   return !losesInfo;
129 }
130 
131 //===----------------------------------------------------------------------===//
132 //                              ISD Namespace
133 //===----------------------------------------------------------------------===//
134 
135 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
136   auto *BV = dyn_cast<BuildVectorSDNode>(N);
137   if (!BV)
138     return false;
139 
140   APInt SplatUndef;
141   unsigned SplatBitSize;
142   bool HasUndefs;
143   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
144   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
145                              EltSize) &&
146          EltSize == SplatBitSize;
147 }
148 
149 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
150 // specializations of the more general isConstantSplatVector()?
151 
152 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
153   // Look through a bit convert.
154   while (N->getOpcode() == ISD::BITCAST)
155     N = N->getOperand(0).getNode();
156 
157   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
158 
159   unsigned i = 0, e = N->getNumOperands();
160 
161   // Skip over all of the undef values.
162   while (i != e && N->getOperand(i).isUndef())
163     ++i;
164 
165   // Do not accept an all-undef vector.
166   if (i == e) return false;
167 
168   // Do not accept build_vectors that aren't all constants or which have non-~0
169   // elements. We have to be a bit careful here, as the type of the constant
170   // may not be the same as the type of the vector elements due to type
171   // legalization (the elements are promoted to a legal type for the target and
172   // a vector of a type may be legal when the base element type is not).
173   // We only want to check enough bits to cover the vector elements, because
174   // we care if the resultant vector is all ones, not whether the individual
175   // constants are.
176   SDValue NotZero = N->getOperand(i);
177   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
178   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
179     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
180       return false;
181   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
182     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
183       return false;
184   } else
185     return false;
186 
187   // Okay, we have at least one ~0 value, check to see if the rest match or are
188   // undefs. Even with the above element type twiddling, this should be OK, as
189   // the same type legalization should have applied to all the elements.
190   for (++i; i != e; ++i)
191     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
192       return false;
193   return true;
194 }
195 
196 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
197   // Look through a bit convert.
198   while (N->getOpcode() == ISD::BITCAST)
199     N = N->getOperand(0).getNode();
200 
201   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
202 
203   bool IsAllUndef = true;
204   for (const SDValue &Op : N->op_values()) {
205     if (Op.isUndef())
206       continue;
207     IsAllUndef = false;
208     // Do not accept build_vectors that aren't all constants or which have non-0
209     // elements. We have to be a bit careful here, as the type of the constant
210     // may not be the same as the type of the vector elements due to type
211     // legalization (the elements are promoted to a legal type for the target
212     // and a vector of a type may be legal when the base element type is not).
213     // We only want to check enough bits to cover the vector elements, because
214     // we care if the resultant vector is all zeros, not whether the individual
215     // constants are.
216     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
217     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
218       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
219         return false;
220     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
221       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
222         return false;
223     } else
224       return false;
225   }
226 
227   // Do not accept an all-undef vector.
228   if (IsAllUndef)
229     return false;
230   return true;
231 }
232 
233 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
234   if (N->getOpcode() != ISD::BUILD_VECTOR)
235     return false;
236 
237   for (const SDValue &Op : N->op_values()) {
238     if (Op.isUndef())
239       continue;
240     if (!isa<ConstantSDNode>(Op))
241       return false;
242   }
243   return true;
244 }
245 
246 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
247   if (N->getOpcode() != ISD::BUILD_VECTOR)
248     return false;
249 
250   for (const SDValue &Op : N->op_values()) {
251     if (Op.isUndef())
252       continue;
253     if (!isa<ConstantFPSDNode>(Op))
254       return false;
255   }
256   return true;
257 }
258 
259 bool ISD::allOperandsUndef(const SDNode *N) {
260   // Return false if the node has no operands.
261   // This is "logically inconsistent" with the definition of "all" but
262   // is probably the desired behavior.
263   if (N->getNumOperands() == 0)
264     return false;
265 
266   for (const SDValue &Op : N->op_values())
267     if (!Op.isUndef())
268       return false;
269 
270   return true;
271 }
272 
273 bool ISD::matchUnaryPredicate(SDValue Op,
274                               std::function<bool(ConstantSDNode *)> Match,
275                               bool AllowUndefs) {
276   // FIXME: Add support for scalar UNDEF cases?
277   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
278     return Match(Cst);
279 
280   // FIXME: Add support for vector UNDEF cases?
281   if (ISD::BUILD_VECTOR != Op.getOpcode())
282     return false;
283 
284   EVT SVT = Op.getValueType().getScalarType();
285   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
286     if (AllowUndefs && Op.getOperand(i).isUndef()) {
287       if (!Match(nullptr))
288         return false;
289       continue;
290     }
291 
292     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
293     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
294       return false;
295   }
296   return true;
297 }
298 
299 bool ISD::matchBinaryPredicate(
300     SDValue LHS, SDValue RHS,
301     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
302     bool AllowUndefs) {
303   if (LHS.getValueType() != RHS.getValueType())
304     return false;
305 
306   // TODO: Add support for scalar UNDEF cases?
307   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
308     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
309       return Match(LHSCst, RHSCst);
310 
311   // TODO: Add support for vector UNDEF cases?
312   if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
313       ISD::BUILD_VECTOR != RHS.getOpcode())
314     return false;
315 
316   EVT SVT = LHS.getValueType().getScalarType();
317   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
318     SDValue LHSOp = LHS.getOperand(i);
319     SDValue RHSOp = RHS.getOperand(i);
320     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
321     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
322     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
323     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
324     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
325       return false;
326     if (LHSOp.getValueType() != SVT ||
327         LHSOp.getValueType() != RHSOp.getValueType())
328       return false;
329     if (!Match(LHSCst, RHSCst))
330       return false;
331   }
332   return true;
333 }
334 
335 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
336   switch (ExtType) {
337   case ISD::EXTLOAD:
338     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
339   case ISD::SEXTLOAD:
340     return ISD::SIGN_EXTEND;
341   case ISD::ZEXTLOAD:
342     return ISD::ZERO_EXTEND;
343   default:
344     break;
345   }
346 
347   llvm_unreachable("Invalid LoadExtType");
348 }
349 
350 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
351   // To perform this operation, we just need to swap the L and G bits of the
352   // operation.
353   unsigned OldL = (Operation >> 2) & 1;
354   unsigned OldG = (Operation >> 1) & 1;
355   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
356                        (OldL << 1) |       // New G bit
357                        (OldG << 2));       // New L bit.
358 }
359 
360 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
361   unsigned Operation = Op;
362   if (isInteger)
363     Operation ^= 7;   // Flip L, G, E bits, but not U.
364   else
365     Operation ^= 15;  // Flip all of the condition bits.
366 
367   if (Operation > ISD::SETTRUE2)
368     Operation &= ~8;  // Don't let N and U bits get set.
369 
370   return ISD::CondCode(Operation);
371 }
372 
373 /// For an integer comparison, return 1 if the comparison is a signed operation
374 /// and 2 if the result is an unsigned comparison. Return zero if the operation
375 /// does not depend on the sign of the input (setne and seteq).
376 static int isSignedOp(ISD::CondCode Opcode) {
377   switch (Opcode) {
378   default: llvm_unreachable("Illegal integer setcc operation!");
379   case ISD::SETEQ:
380   case ISD::SETNE: return 0;
381   case ISD::SETLT:
382   case ISD::SETLE:
383   case ISD::SETGT:
384   case ISD::SETGE: return 1;
385   case ISD::SETULT:
386   case ISD::SETULE:
387   case ISD::SETUGT:
388   case ISD::SETUGE: return 2;
389   }
390 }
391 
392 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
393                                        bool IsInteger) {
394   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
395     // Cannot fold a signed integer setcc with an unsigned integer setcc.
396     return ISD::SETCC_INVALID;
397 
398   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
399 
400   // If the N and U bits get set, then the resultant comparison DOES suddenly
401   // care about orderedness, and it is true when ordered.
402   if (Op > ISD::SETTRUE2)
403     Op &= ~16;     // Clear the U bit if the N bit is set.
404 
405   // Canonicalize illegal integer setcc's.
406   if (IsInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
407     Op = ISD::SETNE;
408 
409   return ISD::CondCode(Op);
410 }
411 
412 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
413                                         bool IsInteger) {
414   if (IsInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
415     // Cannot fold a signed setcc with an unsigned setcc.
416     return ISD::SETCC_INVALID;
417 
418   // Combine all of the condition bits.
419   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
420 
421   // Canonicalize illegal integer setcc's.
422   if (IsInteger) {
423     switch (Result) {
424     default: break;
425     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
426     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
427     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
428     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
429     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
430     }
431   }
432 
433   return Result;
434 }
435 
436 //===----------------------------------------------------------------------===//
437 //                           SDNode Profile Support
438 //===----------------------------------------------------------------------===//
439 
440 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
441 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
442   ID.AddInteger(OpC);
443 }
444 
445 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
446 /// solely with their pointer.
447 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
448   ID.AddPointer(VTList.VTs);
449 }
450 
451 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
452 static void AddNodeIDOperands(FoldingSetNodeID &ID,
453                               ArrayRef<SDValue> Ops) {
454   for (auto& Op : Ops) {
455     ID.AddPointer(Op.getNode());
456     ID.AddInteger(Op.getResNo());
457   }
458 }
459 
460 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
461 static void AddNodeIDOperands(FoldingSetNodeID &ID,
462                               ArrayRef<SDUse> Ops) {
463   for (auto& Op : Ops) {
464     ID.AddPointer(Op.getNode());
465     ID.AddInteger(Op.getResNo());
466   }
467 }
468 
469 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
470                           SDVTList VTList, ArrayRef<SDValue> OpList) {
471   AddNodeIDOpcode(ID, OpC);
472   AddNodeIDValueTypes(ID, VTList);
473   AddNodeIDOperands(ID, OpList);
474 }
475 
476 /// If this is an SDNode with special info, add this info to the NodeID data.
477 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
478   switch (N->getOpcode()) {
479   case ISD::TargetExternalSymbol:
480   case ISD::ExternalSymbol:
481   case ISD::MCSymbol:
482     llvm_unreachable("Should only be used on nodes with operands");
483   default: break;  // Normal nodes don't need extra info.
484   case ISD::TargetConstant:
485   case ISD::Constant: {
486     const ConstantSDNode *C = cast<ConstantSDNode>(N);
487     ID.AddPointer(C->getConstantIntValue());
488     ID.AddBoolean(C->isOpaque());
489     break;
490   }
491   case ISD::TargetConstantFP:
492   case ISD::ConstantFP:
493     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
494     break;
495   case ISD::TargetGlobalAddress:
496   case ISD::GlobalAddress:
497   case ISD::TargetGlobalTLSAddress:
498   case ISD::GlobalTLSAddress: {
499     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
500     ID.AddPointer(GA->getGlobal());
501     ID.AddInteger(GA->getOffset());
502     ID.AddInteger(GA->getTargetFlags());
503     break;
504   }
505   case ISD::BasicBlock:
506     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
507     break;
508   case ISD::Register:
509     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
510     break;
511   case ISD::RegisterMask:
512     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
513     break;
514   case ISD::SRCVALUE:
515     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
516     break;
517   case ISD::FrameIndex:
518   case ISD::TargetFrameIndex:
519     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
520     break;
521   case ISD::JumpTable:
522   case ISD::TargetJumpTable:
523     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
524     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
525     break;
526   case ISD::ConstantPool:
527   case ISD::TargetConstantPool: {
528     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
529     ID.AddInteger(CP->getAlignment());
530     ID.AddInteger(CP->getOffset());
531     if (CP->isMachineConstantPoolEntry())
532       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
533     else
534       ID.AddPointer(CP->getConstVal());
535     ID.AddInteger(CP->getTargetFlags());
536     break;
537   }
538   case ISD::TargetIndex: {
539     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
540     ID.AddInteger(TI->getIndex());
541     ID.AddInteger(TI->getOffset());
542     ID.AddInteger(TI->getTargetFlags());
543     break;
544   }
545   case ISD::LOAD: {
546     const LoadSDNode *LD = cast<LoadSDNode>(N);
547     ID.AddInteger(LD->getMemoryVT().getRawBits());
548     ID.AddInteger(LD->getRawSubclassData());
549     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
550     break;
551   }
552   case ISD::STORE: {
553     const StoreSDNode *ST = cast<StoreSDNode>(N);
554     ID.AddInteger(ST->getMemoryVT().getRawBits());
555     ID.AddInteger(ST->getRawSubclassData());
556     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
557     break;
558   }
559   case ISD::MLOAD: {
560     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
561     ID.AddInteger(MLD->getMemoryVT().getRawBits());
562     ID.AddInteger(MLD->getRawSubclassData());
563     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
564     break;
565   }
566   case ISD::MSTORE: {
567     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
568     ID.AddInteger(MST->getMemoryVT().getRawBits());
569     ID.AddInteger(MST->getRawSubclassData());
570     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
571     break;
572   }
573   case ISD::MGATHER: {
574     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
575     ID.AddInteger(MG->getMemoryVT().getRawBits());
576     ID.AddInteger(MG->getRawSubclassData());
577     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
578     break;
579   }
580   case ISD::MSCATTER: {
581     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
582     ID.AddInteger(MS->getMemoryVT().getRawBits());
583     ID.AddInteger(MS->getRawSubclassData());
584     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
585     break;
586   }
587   case ISD::ATOMIC_CMP_SWAP:
588   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
589   case ISD::ATOMIC_SWAP:
590   case ISD::ATOMIC_LOAD_ADD:
591   case ISD::ATOMIC_LOAD_SUB:
592   case ISD::ATOMIC_LOAD_AND:
593   case ISD::ATOMIC_LOAD_CLR:
594   case ISD::ATOMIC_LOAD_OR:
595   case ISD::ATOMIC_LOAD_XOR:
596   case ISD::ATOMIC_LOAD_NAND:
597   case ISD::ATOMIC_LOAD_MIN:
598   case ISD::ATOMIC_LOAD_MAX:
599   case ISD::ATOMIC_LOAD_UMIN:
600   case ISD::ATOMIC_LOAD_UMAX:
601   case ISD::ATOMIC_LOAD:
602   case ISD::ATOMIC_STORE: {
603     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
604     ID.AddInteger(AT->getMemoryVT().getRawBits());
605     ID.AddInteger(AT->getRawSubclassData());
606     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
607     break;
608   }
609   case ISD::PREFETCH: {
610     const MemSDNode *PF = cast<MemSDNode>(N);
611     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
612     break;
613   }
614   case ISD::VECTOR_SHUFFLE: {
615     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
616     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
617          i != e; ++i)
618       ID.AddInteger(SVN->getMaskElt(i));
619     break;
620   }
621   case ISD::TargetBlockAddress:
622   case ISD::BlockAddress: {
623     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
624     ID.AddPointer(BA->getBlockAddress());
625     ID.AddInteger(BA->getOffset());
626     ID.AddInteger(BA->getTargetFlags());
627     break;
628   }
629   } // end switch (N->getOpcode())
630 
631   // Target specific memory nodes could also have address spaces to check.
632   if (N->isTargetMemoryOpcode())
633     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
634 }
635 
636 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
637 /// data.
638 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
639   AddNodeIDOpcode(ID, N->getOpcode());
640   // Add the return value info.
641   AddNodeIDValueTypes(ID, N->getVTList());
642   // Add the operand info.
643   AddNodeIDOperands(ID, N->ops());
644 
645   // Handle SDNode leafs with special info.
646   AddNodeIDCustom(ID, N);
647 }
648 
649 //===----------------------------------------------------------------------===//
650 //                              SelectionDAG Class
651 //===----------------------------------------------------------------------===//
652 
653 /// doNotCSE - Return true if CSE should not be performed for this node.
654 static bool doNotCSE(SDNode *N) {
655   if (N->getValueType(0) == MVT::Glue)
656     return true; // Never CSE anything that produces a flag.
657 
658   switch (N->getOpcode()) {
659   default: break;
660   case ISD::HANDLENODE:
661   case ISD::EH_LABEL:
662     return true;   // Never CSE these nodes.
663   }
664 
665   // Check that remaining values produced are not flags.
666   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
667     if (N->getValueType(i) == MVT::Glue)
668       return true; // Never CSE anything that produces a flag.
669 
670   return false;
671 }
672 
673 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
674 /// SelectionDAG.
675 void SelectionDAG::RemoveDeadNodes() {
676   // Create a dummy node (which is not added to allnodes), that adds a reference
677   // to the root node, preventing it from being deleted.
678   HandleSDNode Dummy(getRoot());
679 
680   SmallVector<SDNode*, 128> DeadNodes;
681 
682   // Add all obviously-dead nodes to the DeadNodes worklist.
683   for (SDNode &Node : allnodes())
684     if (Node.use_empty())
685       DeadNodes.push_back(&Node);
686 
687   RemoveDeadNodes(DeadNodes);
688 
689   // If the root changed (e.g. it was a dead load, update the root).
690   setRoot(Dummy.getValue());
691 }
692 
693 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
694 /// given list, and any nodes that become unreachable as a result.
695 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
696 
697   // Process the worklist, deleting the nodes and adding their uses to the
698   // worklist.
699   while (!DeadNodes.empty()) {
700     SDNode *N = DeadNodes.pop_back_val();
701     // Skip to next node if we've already managed to delete the node. This could
702     // happen if replacing a node causes a node previously added to the node to
703     // be deleted.
704     if (N->getOpcode() == ISD::DELETED_NODE)
705       continue;
706 
707     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
708       DUL->NodeDeleted(N, nullptr);
709 
710     // Take the node out of the appropriate CSE map.
711     RemoveNodeFromCSEMaps(N);
712 
713     // Next, brutally remove the operand list.  This is safe to do, as there are
714     // no cycles in the graph.
715     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
716       SDUse &Use = *I++;
717       SDNode *Operand = Use.getNode();
718       Use.set(SDValue());
719 
720       // Now that we removed this operand, see if there are no uses of it left.
721       if (Operand->use_empty())
722         DeadNodes.push_back(Operand);
723     }
724 
725     DeallocateNode(N);
726   }
727 }
728 
729 void SelectionDAG::RemoveDeadNode(SDNode *N){
730   SmallVector<SDNode*, 16> DeadNodes(1, N);
731 
732   // Create a dummy node that adds a reference to the root node, preventing
733   // it from being deleted.  (This matters if the root is an operand of the
734   // dead node.)
735   HandleSDNode Dummy(getRoot());
736 
737   RemoveDeadNodes(DeadNodes);
738 }
739 
740 void SelectionDAG::DeleteNode(SDNode *N) {
741   // First take this out of the appropriate CSE map.
742   RemoveNodeFromCSEMaps(N);
743 
744   // Finally, remove uses due to operands of this node, remove from the
745   // AllNodes list, and delete the node.
746   DeleteNodeNotInCSEMaps(N);
747 }
748 
749 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
750   assert(N->getIterator() != AllNodes.begin() &&
751          "Cannot delete the entry node!");
752   assert(N->use_empty() && "Cannot delete a node that is not dead!");
753 
754   // Drop all of the operands and decrement used node's use counts.
755   N->DropOperands();
756 
757   DeallocateNode(N);
758 }
759 
760 void SDDbgInfo::erase(const SDNode *Node) {
761   DbgValMapType::iterator I = DbgValMap.find(Node);
762   if (I == DbgValMap.end())
763     return;
764   for (auto &Val: I->second)
765     Val->setIsInvalidated();
766   DbgValMap.erase(I);
767 }
768 
769 void SelectionDAG::DeallocateNode(SDNode *N) {
770   // If we have operands, deallocate them.
771   removeOperands(N);
772 
773   NodeAllocator.Deallocate(AllNodes.remove(N));
774 
775   // Set the opcode to DELETED_NODE to help catch bugs when node
776   // memory is reallocated.
777   // FIXME: There are places in SDag that have grown a dependency on the opcode
778   // value in the released node.
779   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
780   N->NodeType = ISD::DELETED_NODE;
781 
782   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
783   // them and forget about that node.
784   DbgInfo->erase(N);
785 }
786 
787 #ifndef NDEBUG
788 /// VerifySDNode - Sanity check the given SDNode.  Aborts if it is invalid.
789 static void VerifySDNode(SDNode *N) {
790   switch (N->getOpcode()) {
791   default:
792     break;
793   case ISD::BUILD_PAIR: {
794     EVT VT = N->getValueType(0);
795     assert(N->getNumValues() == 1 && "Too many results!");
796     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
797            "Wrong return type!");
798     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
799     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
800            "Mismatched operand types!");
801     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
802            "Wrong operand type!");
803     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
804            "Wrong return type size");
805     break;
806   }
807   case ISD::BUILD_VECTOR: {
808     assert(N->getNumValues() == 1 && "Too many results!");
809     assert(N->getValueType(0).isVector() && "Wrong return type!");
810     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
811            "Wrong number of operands!");
812     EVT EltVT = N->getValueType(0).getVectorElementType();
813     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
814       assert((I->getValueType() == EltVT ||
815              (EltVT.isInteger() && I->getValueType().isInteger() &&
816               EltVT.bitsLE(I->getValueType()))) &&
817             "Wrong operand type!");
818       assert(I->getValueType() == N->getOperand(0).getValueType() &&
819              "Operands must all have the same type");
820     }
821     break;
822   }
823   }
824 }
825 #endif // NDEBUG
826 
827 /// Insert a newly allocated node into the DAG.
828 ///
829 /// Handles insertion into the all nodes list and CSE map, as well as
830 /// verification and other common operations when a new node is allocated.
831 void SelectionDAG::InsertNode(SDNode *N) {
832   AllNodes.push_back(N);
833 #ifndef NDEBUG
834   N->PersistentId = NextPersistentId++;
835   VerifySDNode(N);
836 #endif
837 }
838 
839 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
840 /// correspond to it.  This is useful when we're about to delete or repurpose
841 /// the node.  We don't want future request for structurally identical nodes
842 /// to return N anymore.
843 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
844   bool Erased = false;
845   switch (N->getOpcode()) {
846   case ISD::HANDLENODE: return false;  // noop.
847   case ISD::CONDCODE:
848     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
849            "Cond code doesn't exist!");
850     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
851     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
852     break;
853   case ISD::ExternalSymbol:
854     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
855     break;
856   case ISD::TargetExternalSymbol: {
857     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
858     Erased = TargetExternalSymbols.erase(
859                std::pair<std::string,unsigned char>(ESN->getSymbol(),
860                                                     ESN->getTargetFlags()));
861     break;
862   }
863   case ISD::MCSymbol: {
864     auto *MCSN = cast<MCSymbolSDNode>(N);
865     Erased = MCSymbols.erase(MCSN->getMCSymbol());
866     break;
867   }
868   case ISD::VALUETYPE: {
869     EVT VT = cast<VTSDNode>(N)->getVT();
870     if (VT.isExtended()) {
871       Erased = ExtendedValueTypeNodes.erase(VT);
872     } else {
873       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
874       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
875     }
876     break;
877   }
878   default:
879     // Remove it from the CSE Map.
880     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
881     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
882     Erased = CSEMap.RemoveNode(N);
883     break;
884   }
885 #ifndef NDEBUG
886   // Verify that the node was actually in one of the CSE maps, unless it has a
887   // flag result (which cannot be CSE'd) or is one of the special cases that are
888   // not subject to CSE.
889   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
890       !N->isMachineOpcode() && !doNotCSE(N)) {
891     N->dump(this);
892     dbgs() << "\n";
893     llvm_unreachable("Node is not in map!");
894   }
895 #endif
896   return Erased;
897 }
898 
899 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
900 /// maps and modified in place. Add it back to the CSE maps, unless an identical
901 /// node already exists, in which case transfer all its users to the existing
902 /// node. This transfer can potentially trigger recursive merging.
903 void
904 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
905   // For node types that aren't CSE'd, just act as if no identical node
906   // already exists.
907   if (!doNotCSE(N)) {
908     SDNode *Existing = CSEMap.GetOrInsertNode(N);
909     if (Existing != N) {
910       // If there was already an existing matching node, use ReplaceAllUsesWith
911       // to replace the dead one with the existing one.  This can cause
912       // recursive merging of other unrelated nodes down the line.
913       ReplaceAllUsesWith(N, Existing);
914 
915       // N is now dead. Inform the listeners and delete it.
916       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
917         DUL->NodeDeleted(N, Existing);
918       DeleteNodeNotInCSEMaps(N);
919       return;
920     }
921   }
922 
923   // If the node doesn't already exist, we updated it.  Inform listeners.
924   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
925     DUL->NodeUpdated(N);
926 }
927 
928 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
929 /// were replaced with those specified.  If this node is never memoized,
930 /// return null, otherwise return a pointer to the slot it would take.  If a
931 /// node already exists with these operands, the slot will be non-null.
932 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
933                                            void *&InsertPos) {
934   if (doNotCSE(N))
935     return nullptr;
936 
937   SDValue Ops[] = { Op };
938   FoldingSetNodeID ID;
939   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
940   AddNodeIDCustom(ID, N);
941   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
942   if (Node)
943     Node->intersectFlagsWith(N->getFlags());
944   return Node;
945 }
946 
947 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
948 /// were replaced with those specified.  If this node is never memoized,
949 /// return null, otherwise return a pointer to the slot it would take.  If a
950 /// node already exists with these operands, the slot will be non-null.
951 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
952                                            SDValue Op1, SDValue Op2,
953                                            void *&InsertPos) {
954   if (doNotCSE(N))
955     return nullptr;
956 
957   SDValue Ops[] = { Op1, Op2 };
958   FoldingSetNodeID ID;
959   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
960   AddNodeIDCustom(ID, N);
961   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
962   if (Node)
963     Node->intersectFlagsWith(N->getFlags());
964   return Node;
965 }
966 
967 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
968 /// were replaced with those specified.  If this node is never memoized,
969 /// return null, otherwise return a pointer to the slot it would take.  If a
970 /// node already exists with these operands, the slot will be non-null.
971 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
972                                            void *&InsertPos) {
973   if (doNotCSE(N))
974     return nullptr;
975 
976   FoldingSetNodeID ID;
977   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
978   AddNodeIDCustom(ID, N);
979   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
980   if (Node)
981     Node->intersectFlagsWith(N->getFlags());
982   return Node;
983 }
984 
985 unsigned SelectionDAG::getEVTAlignment(EVT VT) const {
986   Type *Ty = VT == MVT::iPTR ?
987                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
988                    VT.getTypeForEVT(*getContext());
989 
990   return getDataLayout().getABITypeAlignment(Ty);
991 }
992 
993 // EntryNode could meaningfully have debug info if we can find it...
994 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
995     : TM(tm), OptLevel(OL),
996       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
997       Root(getEntryNode()) {
998   InsertNode(&EntryNode);
999   DbgInfo = new SDDbgInfo();
1000 }
1001 
1002 void SelectionDAG::init(MachineFunction &NewMF,
1003                         OptimizationRemarkEmitter &NewORE,
1004                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1005                         LegacyDivergenceAnalysis * Divergence) {
1006   MF = &NewMF;
1007   SDAGISelPass = PassPtr;
1008   ORE = &NewORE;
1009   TLI = getSubtarget().getTargetLowering();
1010   TSI = getSubtarget().getSelectionDAGInfo();
1011   LibInfo = LibraryInfo;
1012   Context = &MF->getFunction().getContext();
1013   DA = Divergence;
1014 }
1015 
1016 SelectionDAG::~SelectionDAG() {
1017   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1018   allnodes_clear();
1019   OperandRecycler.clear(OperandAllocator);
1020   delete DbgInfo;
1021 }
1022 
1023 void SelectionDAG::allnodes_clear() {
1024   assert(&*AllNodes.begin() == &EntryNode);
1025   AllNodes.remove(AllNodes.begin());
1026   while (!AllNodes.empty())
1027     DeallocateNode(&AllNodes.front());
1028 #ifndef NDEBUG
1029   NextPersistentId = 0;
1030 #endif
1031 }
1032 
1033 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1034                                           void *&InsertPos) {
1035   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1036   if (N) {
1037     switch (N->getOpcode()) {
1038     default: break;
1039     case ISD::Constant:
1040     case ISD::ConstantFP:
1041       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1042                        "debug location.  Use another overload.");
1043     }
1044   }
1045   return N;
1046 }
1047 
1048 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1049                                           const SDLoc &DL, void *&InsertPos) {
1050   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1051   if (N) {
1052     switch (N->getOpcode()) {
1053     case ISD::Constant:
1054     case ISD::ConstantFP:
1055       // Erase debug location from the node if the node is used at several
1056       // different places. Do not propagate one location to all uses as it
1057       // will cause a worse single stepping debugging experience.
1058       if (N->getDebugLoc() != DL.getDebugLoc())
1059         N->setDebugLoc(DebugLoc());
1060       break;
1061     default:
1062       // When the node's point of use is located earlier in the instruction
1063       // sequence than its prior point of use, update its debug info to the
1064       // earlier location.
1065       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1066         N->setDebugLoc(DL.getDebugLoc());
1067       break;
1068     }
1069   }
1070   return N;
1071 }
1072 
1073 void SelectionDAG::clear() {
1074   allnodes_clear();
1075   OperandRecycler.clear(OperandAllocator);
1076   OperandAllocator.Reset();
1077   CSEMap.clear();
1078 
1079   ExtendedValueTypeNodes.clear();
1080   ExternalSymbols.clear();
1081   TargetExternalSymbols.clear();
1082   MCSymbols.clear();
1083   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1084             static_cast<CondCodeSDNode*>(nullptr));
1085   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1086             static_cast<SDNode*>(nullptr));
1087 
1088   EntryNode.UseList = nullptr;
1089   InsertNode(&EntryNode);
1090   Root = getEntryNode();
1091   DbgInfo->clear();
1092 }
1093 
1094 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1095   return VT.bitsGT(Op.getValueType())
1096              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1097              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1098 }
1099 
1100 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1101   return VT.bitsGT(Op.getValueType()) ?
1102     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1103     getNode(ISD::TRUNCATE, DL, VT, Op);
1104 }
1105 
1106 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1107   return VT.bitsGT(Op.getValueType()) ?
1108     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1109     getNode(ISD::TRUNCATE, DL, VT, Op);
1110 }
1111 
1112 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1113   return VT.bitsGT(Op.getValueType()) ?
1114     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1115     getNode(ISD::TRUNCATE, DL, VT, Op);
1116 }
1117 
1118 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1119                                         EVT OpVT) {
1120   if (VT.bitsLE(Op.getValueType()))
1121     return getNode(ISD::TRUNCATE, SL, VT, Op);
1122 
1123   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1124   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1125 }
1126 
1127 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1128   assert(!VT.isVector() &&
1129          "getZeroExtendInReg should use the vector element type instead of "
1130          "the vector type!");
1131   if (Op.getValueType().getScalarType() == VT) return Op;
1132   unsigned BitWidth = Op.getScalarValueSizeInBits();
1133   APInt Imm = APInt::getLowBitsSet(BitWidth,
1134                                    VT.getSizeInBits());
1135   return getNode(ISD::AND, DL, Op.getValueType(), Op,
1136                  getConstant(Imm, DL, Op.getValueType()));
1137 }
1138 
1139 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
1140 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1141   EVT EltVT = VT.getScalarType();
1142   SDValue NegOne =
1143     getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1144   return getNode(ISD::XOR, DL, VT, Val, NegOne);
1145 }
1146 
1147 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1148   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1149   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1150 }
1151 
1152 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1153                                       EVT OpVT) {
1154   if (!V)
1155     return getConstant(0, DL, VT);
1156 
1157   switch (TLI->getBooleanContents(OpVT)) {
1158   case TargetLowering::ZeroOrOneBooleanContent:
1159   case TargetLowering::UndefinedBooleanContent:
1160     return getConstant(1, DL, VT);
1161   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1162     return getAllOnesConstant(DL, VT);
1163   }
1164   llvm_unreachable("Unexpected boolean content enum!");
1165 }
1166 
1167 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1168                                   bool isT, bool isO) {
1169   EVT EltVT = VT.getScalarType();
1170   assert((EltVT.getSizeInBits() >= 64 ||
1171          (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1172          "getConstant with a uint64_t value that doesn't fit in the type!");
1173   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1174 }
1175 
1176 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1177                                   bool isT, bool isO) {
1178   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1179 }
1180 
1181 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1182                                   EVT VT, bool isT, bool isO) {
1183   assert(VT.isInteger() && "Cannot create FP integer constant!");
1184 
1185   EVT EltVT = VT.getScalarType();
1186   const ConstantInt *Elt = &Val;
1187 
1188   // In some cases the vector type is legal but the element type is illegal and
1189   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1190   // inserted value (the type does not need to match the vector element type).
1191   // Any extra bits introduced will be truncated away.
1192   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1193       TargetLowering::TypePromoteInteger) {
1194    EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1195    APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1196    Elt = ConstantInt::get(*getContext(), NewVal);
1197   }
1198   // In other cases the element type is illegal and needs to be expanded, for
1199   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1200   // the value into n parts and use a vector type with n-times the elements.
1201   // Then bitcast to the type requested.
1202   // Legalizing constants too early makes the DAGCombiner's job harder so we
1203   // only legalize if the DAG tells us we must produce legal types.
1204   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1205            TLI->getTypeAction(*getContext(), EltVT) ==
1206            TargetLowering::TypeExpandInteger) {
1207     const APInt &NewVal = Elt->getValue();
1208     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1209     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1210     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1211     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1212 
1213     // Check the temporary vector is the correct size. If this fails then
1214     // getTypeToTransformTo() probably returned a type whose size (in bits)
1215     // isn't a power-of-2 factor of the requested type size.
1216     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1217 
1218     SmallVector<SDValue, 2> EltParts;
1219     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1220       EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1221                                            .zextOrTrunc(ViaEltSizeInBits), DL,
1222                                      ViaEltVT, isT, isO));
1223     }
1224 
1225     // EltParts is currently in little endian order. If we actually want
1226     // big-endian order then reverse it now.
1227     if (getDataLayout().isBigEndian())
1228       std::reverse(EltParts.begin(), EltParts.end());
1229 
1230     // The elements must be reversed when the element order is different
1231     // to the endianness of the elements (because the BITCAST is itself a
1232     // vector shuffle in this situation). However, we do not need any code to
1233     // perform this reversal because getConstant() is producing a vector
1234     // splat.
1235     // This situation occurs in MIPS MSA.
1236 
1237     SmallVector<SDValue, 8> Ops;
1238     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1239       Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1240 
1241     SDValue V = getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1242     return V;
1243   }
1244 
1245   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1246          "APInt size does not match type size!");
1247   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1248   FoldingSetNodeID ID;
1249   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1250   ID.AddPointer(Elt);
1251   ID.AddBoolean(isO);
1252   void *IP = nullptr;
1253   SDNode *N = nullptr;
1254   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1255     if (!VT.isVector())
1256       return SDValue(N, 0);
1257 
1258   if (!N) {
1259     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1260     CSEMap.InsertNode(N, IP);
1261     InsertNode(N);
1262     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1263   }
1264 
1265   SDValue Result(N, 0);
1266   if (VT.isVector())
1267     Result = getSplatBuildVector(VT, DL, Result);
1268 
1269   return Result;
1270 }
1271 
1272 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1273                                         bool isTarget) {
1274   return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
1275 }
1276 
1277 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1278                                     bool isTarget) {
1279   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1280 }
1281 
1282 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1283                                     EVT VT, bool isTarget) {
1284   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1285 
1286   EVT EltVT = VT.getScalarType();
1287 
1288   // Do the map lookup using the actual bit pattern for the floating point
1289   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1290   // we don't have issues with SNANs.
1291   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1292   FoldingSetNodeID ID;
1293   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1294   ID.AddPointer(&V);
1295   void *IP = nullptr;
1296   SDNode *N = nullptr;
1297   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1298     if (!VT.isVector())
1299       return SDValue(N, 0);
1300 
1301   if (!N) {
1302     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1303     CSEMap.InsertNode(N, IP);
1304     InsertNode(N);
1305   }
1306 
1307   SDValue Result(N, 0);
1308   if (VT.isVector())
1309     Result = getSplatBuildVector(VT, DL, Result);
1310   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1311   return Result;
1312 }
1313 
1314 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1315                                     bool isTarget) {
1316   EVT EltVT = VT.getScalarType();
1317   if (EltVT == MVT::f32)
1318     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1319   else if (EltVT == MVT::f64)
1320     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1321   else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1322            EltVT == MVT::f16) {
1323     bool Ignored;
1324     APFloat APF = APFloat(Val);
1325     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1326                 &Ignored);
1327     return getConstantFP(APF, DL, VT, isTarget);
1328   } else
1329     llvm_unreachable("Unsupported type in getConstantFP");
1330 }
1331 
1332 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1333                                        EVT VT, int64_t Offset, bool isTargetGA,
1334                                        unsigned char TargetFlags) {
1335   assert((TargetFlags == 0 || isTargetGA) &&
1336          "Cannot set target flags on target-independent globals");
1337 
1338   // Truncate (with sign-extension) the offset value to the pointer size.
1339   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1340   if (BitWidth < 64)
1341     Offset = SignExtend64(Offset, BitWidth);
1342 
1343   unsigned Opc;
1344   if (GV->isThreadLocal())
1345     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1346   else
1347     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1348 
1349   FoldingSetNodeID ID;
1350   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1351   ID.AddPointer(GV);
1352   ID.AddInteger(Offset);
1353   ID.AddInteger(TargetFlags);
1354   void *IP = nullptr;
1355   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1356     return SDValue(E, 0);
1357 
1358   auto *N = newSDNode<GlobalAddressSDNode>(
1359       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1360   CSEMap.InsertNode(N, IP);
1361     InsertNode(N);
1362   return SDValue(N, 0);
1363 }
1364 
1365 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1366   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1367   FoldingSetNodeID ID;
1368   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1369   ID.AddInteger(FI);
1370   void *IP = nullptr;
1371   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1372     return SDValue(E, 0);
1373 
1374   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1375   CSEMap.InsertNode(N, IP);
1376   InsertNode(N);
1377   return SDValue(N, 0);
1378 }
1379 
1380 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1381                                    unsigned char TargetFlags) {
1382   assert((TargetFlags == 0 || isTarget) &&
1383          "Cannot set target flags on target-independent jump tables");
1384   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1385   FoldingSetNodeID ID;
1386   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1387   ID.AddInteger(JTI);
1388   ID.AddInteger(TargetFlags);
1389   void *IP = nullptr;
1390   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1391     return SDValue(E, 0);
1392 
1393   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1394   CSEMap.InsertNode(N, IP);
1395   InsertNode(N);
1396   return SDValue(N, 0);
1397 }
1398 
1399 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1400                                       unsigned Alignment, int Offset,
1401                                       bool isTarget,
1402                                       unsigned char TargetFlags) {
1403   assert((TargetFlags == 0 || isTarget) &&
1404          "Cannot set target flags on target-independent globals");
1405   if (Alignment == 0)
1406     Alignment = MF->getFunction().optForSize()
1407                     ? getDataLayout().getABITypeAlignment(C->getType())
1408                     : getDataLayout().getPrefTypeAlignment(C->getType());
1409   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1410   FoldingSetNodeID ID;
1411   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1412   ID.AddInteger(Alignment);
1413   ID.AddInteger(Offset);
1414   ID.AddPointer(C);
1415   ID.AddInteger(TargetFlags);
1416   void *IP = nullptr;
1417   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1418     return SDValue(E, 0);
1419 
1420   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1421                                           TargetFlags);
1422   CSEMap.InsertNode(N, IP);
1423   InsertNode(N);
1424   return SDValue(N, 0);
1425 }
1426 
1427 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1428                                       unsigned Alignment, int Offset,
1429                                       bool isTarget,
1430                                       unsigned char TargetFlags) {
1431   assert((TargetFlags == 0 || isTarget) &&
1432          "Cannot set target flags on target-independent globals");
1433   if (Alignment == 0)
1434     Alignment = getDataLayout().getPrefTypeAlignment(C->getType());
1435   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1436   FoldingSetNodeID ID;
1437   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1438   ID.AddInteger(Alignment);
1439   ID.AddInteger(Offset);
1440   C->addSelectionDAGCSEId(ID);
1441   ID.AddInteger(TargetFlags);
1442   void *IP = nullptr;
1443   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1444     return SDValue(E, 0);
1445 
1446   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
1447                                           TargetFlags);
1448   CSEMap.InsertNode(N, IP);
1449   InsertNode(N);
1450   return SDValue(N, 0);
1451 }
1452 
1453 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1454                                      unsigned char TargetFlags) {
1455   FoldingSetNodeID ID;
1456   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1457   ID.AddInteger(Index);
1458   ID.AddInteger(Offset);
1459   ID.AddInteger(TargetFlags);
1460   void *IP = nullptr;
1461   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1462     return SDValue(E, 0);
1463 
1464   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1465   CSEMap.InsertNode(N, IP);
1466   InsertNode(N);
1467   return SDValue(N, 0);
1468 }
1469 
1470 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1471   FoldingSetNodeID ID;
1472   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1473   ID.AddPointer(MBB);
1474   void *IP = nullptr;
1475   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1476     return SDValue(E, 0);
1477 
1478   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1479   CSEMap.InsertNode(N, IP);
1480   InsertNode(N);
1481   return SDValue(N, 0);
1482 }
1483 
1484 SDValue SelectionDAG::getValueType(EVT VT) {
1485   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1486       ValueTypeNodes.size())
1487     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1488 
1489   SDNode *&N = VT.isExtended() ?
1490     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1491 
1492   if (N) return SDValue(N, 0);
1493   N = newSDNode<VTSDNode>(VT);
1494   InsertNode(N);
1495   return SDValue(N, 0);
1496 }
1497 
1498 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1499   SDNode *&N = ExternalSymbols[Sym];
1500   if (N) return SDValue(N, 0);
1501   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1502   InsertNode(N);
1503   return SDValue(N, 0);
1504 }
1505 
1506 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1507   SDNode *&N = MCSymbols[Sym];
1508   if (N)
1509     return SDValue(N, 0);
1510   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1511   InsertNode(N);
1512   return SDValue(N, 0);
1513 }
1514 
1515 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1516                                               unsigned char TargetFlags) {
1517   SDNode *&N =
1518     TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
1519                                                                TargetFlags)];
1520   if (N) return SDValue(N, 0);
1521   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1522   InsertNode(N);
1523   return SDValue(N, 0);
1524 }
1525 
1526 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1527   if ((unsigned)Cond >= CondCodeNodes.size())
1528     CondCodeNodes.resize(Cond+1);
1529 
1530   if (!CondCodeNodes[Cond]) {
1531     auto *N = newSDNode<CondCodeSDNode>(Cond);
1532     CondCodeNodes[Cond] = N;
1533     InsertNode(N);
1534   }
1535 
1536   return SDValue(CondCodeNodes[Cond], 0);
1537 }
1538 
1539 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1540 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
1541 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1542   std::swap(N1, N2);
1543   ShuffleVectorSDNode::commuteMask(M);
1544 }
1545 
1546 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1547                                        SDValue N2, ArrayRef<int> Mask) {
1548   assert(VT.getVectorNumElements() == Mask.size() &&
1549            "Must have the same number of vector elements as mask elements!");
1550   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1551          "Invalid VECTOR_SHUFFLE");
1552 
1553   // Canonicalize shuffle undef, undef -> undef
1554   if (N1.isUndef() && N2.isUndef())
1555     return getUNDEF(VT);
1556 
1557   // Validate that all indices in Mask are within the range of the elements
1558   // input to the shuffle.
1559   int NElts = Mask.size();
1560   assert(llvm::all_of(Mask,
1561                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1562          "Index out of range");
1563 
1564   // Copy the mask so we can do any needed cleanup.
1565   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1566 
1567   // Canonicalize shuffle v, v -> v, undef
1568   if (N1 == N2) {
1569     N2 = getUNDEF(VT);
1570     for (int i = 0; i != NElts; ++i)
1571       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1572   }
1573 
1574   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1575   if (N1.isUndef())
1576     commuteShuffle(N1, N2, MaskVec);
1577 
1578   if (TLI->hasVectorBlend()) {
1579     // If shuffling a splat, try to blend the splat instead. We do this here so
1580     // that even when this arises during lowering we don't have to re-handle it.
1581     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1582       BitVector UndefElements;
1583       SDValue Splat = BV->getSplatValue(&UndefElements);
1584       if (!Splat)
1585         return;
1586 
1587       for (int i = 0; i < NElts; ++i) {
1588         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1589           continue;
1590 
1591         // If this input comes from undef, mark it as such.
1592         if (UndefElements[MaskVec[i] - Offset]) {
1593           MaskVec[i] = -1;
1594           continue;
1595         }
1596 
1597         // If we can blend a non-undef lane, use that instead.
1598         if (!UndefElements[i])
1599           MaskVec[i] = i + Offset;
1600       }
1601     };
1602     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1603       BlendSplat(N1BV, 0);
1604     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1605       BlendSplat(N2BV, NElts);
1606   }
1607 
1608   // Canonicalize all index into lhs, -> shuffle lhs, undef
1609   // Canonicalize all index into rhs, -> shuffle rhs, undef
1610   bool AllLHS = true, AllRHS = true;
1611   bool N2Undef = N2.isUndef();
1612   for (int i = 0; i != NElts; ++i) {
1613     if (MaskVec[i] >= NElts) {
1614       if (N2Undef)
1615         MaskVec[i] = -1;
1616       else
1617         AllLHS = false;
1618     } else if (MaskVec[i] >= 0) {
1619       AllRHS = false;
1620     }
1621   }
1622   if (AllLHS && AllRHS)
1623     return getUNDEF(VT);
1624   if (AllLHS && !N2Undef)
1625     N2 = getUNDEF(VT);
1626   if (AllRHS) {
1627     N1 = getUNDEF(VT);
1628     commuteShuffle(N1, N2, MaskVec);
1629   }
1630   // Reset our undef status after accounting for the mask.
1631   N2Undef = N2.isUndef();
1632   // Re-check whether both sides ended up undef.
1633   if (N1.isUndef() && N2Undef)
1634     return getUNDEF(VT);
1635 
1636   // If Identity shuffle return that node.
1637   bool Identity = true, AllSame = true;
1638   for (int i = 0; i != NElts; ++i) {
1639     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1640     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1641   }
1642   if (Identity && NElts)
1643     return N1;
1644 
1645   // Shuffling a constant splat doesn't change the result.
1646   if (N2Undef) {
1647     SDValue V = N1;
1648 
1649     // Look through any bitcasts. We check that these don't change the number
1650     // (and size) of elements and just changes their types.
1651     while (V.getOpcode() == ISD::BITCAST)
1652       V = V->getOperand(0);
1653 
1654     // A splat should always show up as a build vector node.
1655     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1656       BitVector UndefElements;
1657       SDValue Splat = BV->getSplatValue(&UndefElements);
1658       // If this is a splat of an undef, shuffling it is also undef.
1659       if (Splat && Splat.isUndef())
1660         return getUNDEF(VT);
1661 
1662       bool SameNumElts =
1663           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1664 
1665       // We only have a splat which can skip shuffles if there is a splatted
1666       // value and no undef lanes rearranged by the shuffle.
1667       if (Splat && UndefElements.none()) {
1668         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1669         // number of elements match or the value splatted is a zero constant.
1670         if (SameNumElts)
1671           return N1;
1672         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1673           if (C->isNullValue())
1674             return N1;
1675       }
1676 
1677       // If the shuffle itself creates a splat, build the vector directly.
1678       if (AllSame && SameNumElts) {
1679         EVT BuildVT = BV->getValueType(0);
1680         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1681         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1682 
1683         // We may have jumped through bitcasts, so the type of the
1684         // BUILD_VECTOR may not match the type of the shuffle.
1685         if (BuildVT != VT)
1686           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1687         return NewBV;
1688       }
1689     }
1690   }
1691 
1692   FoldingSetNodeID ID;
1693   SDValue Ops[2] = { N1, N2 };
1694   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1695   for (int i = 0; i != NElts; ++i)
1696     ID.AddInteger(MaskVec[i]);
1697 
1698   void* IP = nullptr;
1699   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1700     return SDValue(E, 0);
1701 
1702   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1703   // SDNode doesn't have access to it.  This memory will be "leaked" when
1704   // the node is deallocated, but recovered when the NodeAllocator is released.
1705   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1706   llvm::copy(MaskVec, MaskAlloc);
1707 
1708   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1709                                            dl.getDebugLoc(), MaskAlloc);
1710   createOperands(N, Ops);
1711 
1712   CSEMap.InsertNode(N, IP);
1713   InsertNode(N);
1714   SDValue V = SDValue(N, 0);
1715   NewSDValueDbgMsg(V, "Creating new node: ", this);
1716   return V;
1717 }
1718 
1719 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1720   EVT VT = SV.getValueType(0);
1721   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1722   ShuffleVectorSDNode::commuteMask(MaskVec);
1723 
1724   SDValue Op0 = SV.getOperand(0);
1725   SDValue Op1 = SV.getOperand(1);
1726   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1727 }
1728 
1729 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1730   FoldingSetNodeID ID;
1731   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1732   ID.AddInteger(RegNo);
1733   void *IP = nullptr;
1734   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1735     return SDValue(E, 0);
1736 
1737   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1738   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
1739   CSEMap.InsertNode(N, IP);
1740   InsertNode(N);
1741   return SDValue(N, 0);
1742 }
1743 
1744 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1745   FoldingSetNodeID ID;
1746   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1747   ID.AddPointer(RegMask);
1748   void *IP = nullptr;
1749   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1750     return SDValue(E, 0);
1751 
1752   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1753   CSEMap.InsertNode(N, IP);
1754   InsertNode(N);
1755   return SDValue(N, 0);
1756 }
1757 
1758 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1759                                  MCSymbol *Label) {
1760   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
1761 }
1762 
1763 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
1764                                    SDValue Root, MCSymbol *Label) {
1765   FoldingSetNodeID ID;
1766   SDValue Ops[] = { Root };
1767   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
1768   ID.AddPointer(Label);
1769   void *IP = nullptr;
1770   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1771     return SDValue(E, 0);
1772 
1773   auto *N = newSDNode<LabelSDNode>(dl.getIROrder(), dl.getDebugLoc(), Label);
1774   createOperands(N, Ops);
1775 
1776   CSEMap.InsertNode(N, IP);
1777   InsertNode(N);
1778   return SDValue(N, 0);
1779 }
1780 
1781 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1782                                       int64_t Offset,
1783                                       bool isTarget,
1784                                       unsigned char TargetFlags) {
1785   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1786 
1787   FoldingSetNodeID ID;
1788   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1789   ID.AddPointer(BA);
1790   ID.AddInteger(Offset);
1791   ID.AddInteger(TargetFlags);
1792   void *IP = nullptr;
1793   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1794     return SDValue(E, 0);
1795 
1796   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
1797   CSEMap.InsertNode(N, IP);
1798   InsertNode(N);
1799   return SDValue(N, 0);
1800 }
1801 
1802 SDValue SelectionDAG::getSrcValue(const Value *V) {
1803   assert((!V || V->getType()->isPointerTy()) &&
1804          "SrcValue is not a pointer?");
1805 
1806   FoldingSetNodeID ID;
1807   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
1808   ID.AddPointer(V);
1809 
1810   void *IP = nullptr;
1811   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1812     return SDValue(E, 0);
1813 
1814   auto *N = newSDNode<SrcValueSDNode>(V);
1815   CSEMap.InsertNode(N, IP);
1816   InsertNode(N);
1817   return SDValue(N, 0);
1818 }
1819 
1820 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1821   FoldingSetNodeID ID;
1822   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
1823   ID.AddPointer(MD);
1824 
1825   void *IP = nullptr;
1826   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1827     return SDValue(E, 0);
1828 
1829   auto *N = newSDNode<MDNodeSDNode>(MD);
1830   CSEMap.InsertNode(N, IP);
1831   InsertNode(N);
1832   return SDValue(N, 0);
1833 }
1834 
1835 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
1836   if (VT == V.getValueType())
1837     return V;
1838 
1839   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
1840 }
1841 
1842 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
1843                                        unsigned SrcAS, unsigned DestAS) {
1844   SDValue Ops[] = {Ptr};
1845   FoldingSetNodeID ID;
1846   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
1847   ID.AddInteger(SrcAS);
1848   ID.AddInteger(DestAS);
1849 
1850   void *IP = nullptr;
1851   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1852     return SDValue(E, 0);
1853 
1854   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
1855                                            VT, SrcAS, DestAS);
1856   createOperands(N, Ops);
1857 
1858   CSEMap.InsertNode(N, IP);
1859   InsertNode(N);
1860   return SDValue(N, 0);
1861 }
1862 
1863 /// getShiftAmountOperand - Return the specified value casted to
1864 /// the target's desired shift amount type.
1865 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1866   EVT OpTy = Op.getValueType();
1867   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
1868   if (OpTy == ShTy || OpTy.isVector()) return Op;
1869 
1870   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
1871 }
1872 
1873 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
1874   SDLoc dl(Node);
1875   const TargetLowering &TLI = getTargetLoweringInfo();
1876   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1877   EVT VT = Node->getValueType(0);
1878   SDValue Tmp1 = Node->getOperand(0);
1879   SDValue Tmp2 = Node->getOperand(1);
1880   unsigned Align = Node->getConstantOperandVal(3);
1881 
1882   SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
1883                                Tmp2, MachinePointerInfo(V));
1884   SDValue VAList = VAListLoad;
1885 
1886   if (Align > TLI.getMinStackArgumentAlignment()) {
1887     assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1888 
1889     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1890                      getConstant(Align - 1, dl, VAList.getValueType()));
1891 
1892     VAList = getNode(ISD::AND, dl, VAList.getValueType(), VAList,
1893                      getConstant(-(int64_t)Align, dl, VAList.getValueType()));
1894   }
1895 
1896   // Increment the pointer, VAList, to the next vaarg
1897   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1898                  getConstant(getDataLayout().getTypeAllocSize(
1899                                                VT.getTypeForEVT(*getContext())),
1900                              dl, VAList.getValueType()));
1901   // Store the incremented VAList to the legalized pointer
1902   Tmp1 =
1903       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
1904   // Load the actual argument out of the pointer VAList
1905   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
1906 }
1907 
1908 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
1909   SDLoc dl(Node);
1910   const TargetLowering &TLI = getTargetLoweringInfo();
1911   // This defaults to loading a pointer from the input and storing it to the
1912   // output, returning the chain.
1913   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
1914   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
1915   SDValue Tmp1 =
1916       getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
1917               Node->getOperand(2), MachinePointerInfo(VS));
1918   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
1919                   MachinePointerInfo(VD));
1920 }
1921 
1922 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
1923   MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1924   unsigned ByteSize = VT.getStoreSize();
1925   Type *Ty = VT.getTypeForEVT(*getContext());
1926   unsigned StackAlign =
1927       std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign);
1928 
1929   int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
1930   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1931 }
1932 
1933 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
1934   unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
1935   Type *Ty1 = VT1.getTypeForEVT(*getContext());
1936   Type *Ty2 = VT2.getTypeForEVT(*getContext());
1937   const DataLayout &DL = getDataLayout();
1938   unsigned Align =
1939       std::max(DL.getPrefTypeAlignment(Ty1), DL.getPrefTypeAlignment(Ty2));
1940 
1941   MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
1942   int FrameIdx = MFI.CreateStackObject(Bytes, Align, false);
1943   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
1944 }
1945 
1946 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
1947                                 ISD::CondCode Cond, const SDLoc &dl) {
1948   EVT OpVT = N1.getValueType();
1949 
1950   // These setcc operations always fold.
1951   switch (Cond) {
1952   default: break;
1953   case ISD::SETFALSE:
1954   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
1955   case ISD::SETTRUE:
1956   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
1957 
1958   case ISD::SETOEQ:
1959   case ISD::SETOGT:
1960   case ISD::SETOGE:
1961   case ISD::SETOLT:
1962   case ISD::SETOLE:
1963   case ISD::SETONE:
1964   case ISD::SETO:
1965   case ISD::SETUO:
1966   case ISD::SETUEQ:
1967   case ISD::SETUNE:
1968     assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
1969     break;
1970   }
1971 
1972   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
1973     const APInt &C2 = N2C->getAPIntValue();
1974     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
1975       const APInt &C1 = N1C->getAPIntValue();
1976 
1977       switch (Cond) {
1978       default: llvm_unreachable("Unknown integer setcc!");
1979       case ISD::SETEQ:  return getBoolConstant(C1 == C2, dl, VT, OpVT);
1980       case ISD::SETNE:  return getBoolConstant(C1 != C2, dl, VT, OpVT);
1981       case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
1982       case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
1983       case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
1984       case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
1985       case ISD::SETLT:  return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
1986       case ISD::SETGT:  return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
1987       case ISD::SETLE:  return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
1988       case ISD::SETGE:  return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
1989       }
1990     }
1991   }
1992   if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1)) {
1993     if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2)) {
1994       APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
1995       switch (Cond) {
1996       default: break;
1997       case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
1998                           return getUNDEF(VT);
1999                         LLVM_FALLTHROUGH;
2000       case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2001                                                OpVT);
2002       case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2003                           return getUNDEF(VT);
2004                         LLVM_FALLTHROUGH;
2005       case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2006                                                R==APFloat::cmpLessThan, dl, VT,
2007                                                OpVT);
2008       case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2009                           return getUNDEF(VT);
2010                         LLVM_FALLTHROUGH;
2011       case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2012                                                OpVT);
2013       case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2014                           return getUNDEF(VT);
2015                         LLVM_FALLTHROUGH;
2016       case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2017                                                VT, OpVT);
2018       case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2019                           return getUNDEF(VT);
2020                         LLVM_FALLTHROUGH;
2021       case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2022                                                R==APFloat::cmpEqual, dl, VT,
2023                                                OpVT);
2024       case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2025                           return getUNDEF(VT);
2026                         LLVM_FALLTHROUGH;
2027       case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2028                                            R==APFloat::cmpEqual, dl, VT, OpVT);
2029       case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2030                                                OpVT);
2031       case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2032                                                OpVT);
2033       case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2034                                                R==APFloat::cmpEqual, dl, VT,
2035                                                OpVT);
2036       case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2037                                                OpVT);
2038       case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2039                                                R==APFloat::cmpLessThan, dl, VT,
2040                                                OpVT);
2041       case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2042                                                R==APFloat::cmpUnordered, dl, VT,
2043                                                OpVT);
2044       case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2045                                                VT, OpVT);
2046       case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2047                                                OpVT);
2048       }
2049     } else {
2050       // Ensure that the constant occurs on the RHS.
2051       ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2052       MVT CompVT = N1.getValueType().getSimpleVT();
2053       if (!TLI->isCondCodeLegal(SwappedCond, CompVT))
2054         return SDValue();
2055 
2056       return getSetCC(dl, VT, N2, N1, SwappedCond);
2057     }
2058   }
2059 
2060   // Could not fold it.
2061   return SDValue();
2062 }
2063 
2064 /// See if the specified operand can be simplified with the knowledge that only
2065 /// the bits specified by Mask are used.
2066 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &Mask) {
2067   switch (V.getOpcode()) {
2068   default:
2069     break;
2070   case ISD::Constant: {
2071     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
2072     assert(CV && "Const value should be ConstSDNode.");
2073     const APInt &CVal = CV->getAPIntValue();
2074     APInt NewVal = CVal & Mask;
2075     if (NewVal != CVal)
2076       return getConstant(NewVal, SDLoc(V), V.getValueType());
2077     break;
2078   }
2079   case ISD::OR:
2080   case ISD::XOR:
2081     // If the LHS or RHS don't contribute bits to the or, drop them.
2082     if (MaskedValueIsZero(V.getOperand(0), Mask))
2083       return V.getOperand(1);
2084     if (MaskedValueIsZero(V.getOperand(1), Mask))
2085       return V.getOperand(0);
2086     break;
2087   case ISD::SRL:
2088     // Only look at single-use SRLs.
2089     if (!V.getNode()->hasOneUse())
2090       break;
2091     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2092       // See if we can recursively simplify the LHS.
2093       unsigned Amt = RHSC->getZExtValue();
2094 
2095       // Watch out for shift count overflow though.
2096       if (Amt >= Mask.getBitWidth())
2097         break;
2098       APInt NewMask = Mask << Amt;
2099       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
2100         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2101                        V.getOperand(1));
2102     }
2103     break;
2104   case ISD::AND: {
2105     // X & -1 -> X (ignoring bits which aren't demanded).
2106     ConstantSDNode *AndVal = isConstOrConstSplat(V.getOperand(1));
2107     if (AndVal && Mask.isSubsetOf(AndVal->getAPIntValue()))
2108       return V.getOperand(0);
2109     break;
2110   }
2111   case ISD::ANY_EXTEND: {
2112     SDValue Src = V.getOperand(0);
2113     unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
2114     // Being conservative here - only peek through if we only demand bits in the
2115     // non-extended source (even though the extended bits are technically undef).
2116     if (Mask.getActiveBits() > SrcBitWidth)
2117       break;
2118     APInt SrcMask = Mask.trunc(SrcBitWidth);
2119     if (SDValue DemandedSrc = GetDemandedBits(Src, SrcMask))
2120       return getNode(ISD::ANY_EXTEND, SDLoc(V), V.getValueType(), DemandedSrc);
2121     break;
2122   }
2123   case ISD::SIGN_EXTEND_INREG:
2124     EVT ExVT = cast<VTSDNode>(V.getOperand(1))->getVT();
2125     unsigned ExVTBits = ExVT.getScalarSizeInBits();
2126 
2127     // If none of the extended bits are demanded, eliminate the sextinreg.
2128     if (Mask.getActiveBits() <= ExVTBits)
2129       return V.getOperand(0);
2130 
2131     break;
2132   }
2133   return SDValue();
2134 }
2135 
2136 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2137 /// use this predicate to simplify operations downstream.
2138 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2139   unsigned BitWidth = Op.getScalarValueSizeInBits();
2140   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2141 }
2142 
2143 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2144 /// this predicate to simplify operations downstream.  Mask is known to be zero
2145 /// for bits that V cannot have.
2146 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
2147                                      unsigned Depth) const {
2148   return Mask.isSubsetOf(computeKnownBits(Op, Depth).Zero);
2149 }
2150 
2151 /// isSplatValue - Return true if the vector V has the same value
2152 /// across all DemandedElts.
2153 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2154                                 APInt &UndefElts) {
2155   if (!DemandedElts)
2156     return false; // No demanded elts, better to assume we don't know anything.
2157 
2158   EVT VT = V.getValueType();
2159   assert(VT.isVector() && "Vector type expected");
2160 
2161   unsigned NumElts = VT.getVectorNumElements();
2162   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2163   UndefElts = APInt::getNullValue(NumElts);
2164 
2165   switch (V.getOpcode()) {
2166   case ISD::BUILD_VECTOR: {
2167     SDValue Scl;
2168     for (unsigned i = 0; i != NumElts; ++i) {
2169       SDValue Op = V.getOperand(i);
2170       if (Op.isUndef()) {
2171         UndefElts.setBit(i);
2172         continue;
2173       }
2174       if (!DemandedElts[i])
2175         continue;
2176       if (Scl && Scl != Op)
2177         return false;
2178       Scl = Op;
2179     }
2180     return true;
2181   }
2182   case ISD::VECTOR_SHUFFLE: {
2183     // Check if this is a shuffle node doing a splat.
2184     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2185     int SplatIndex = -1;
2186     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2187     for (int i = 0; i != (int)NumElts; ++i) {
2188       int M = Mask[i];
2189       if (M < 0) {
2190         UndefElts.setBit(i);
2191         continue;
2192       }
2193       if (!DemandedElts[i])
2194         continue;
2195       if (0 <= SplatIndex && SplatIndex != M)
2196         return false;
2197       SplatIndex = M;
2198     }
2199     return true;
2200   }
2201   case ISD::EXTRACT_SUBVECTOR: {
2202     SDValue Src = V.getOperand(0);
2203     ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(V.getOperand(1));
2204     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2205     if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2206       // Offset the demanded elts by the subvector index.
2207       uint64_t Idx = SubIdx->getZExtValue();
2208       APInt UndefSrcElts;
2209       APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2210       if (isSplatValue(Src, DemandedSrc, UndefSrcElts)) {
2211         UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2212         return true;
2213       }
2214     }
2215     break;
2216   }
2217   case ISD::ADD:
2218   case ISD::SUB:
2219   case ISD::AND: {
2220     APInt UndefLHS, UndefRHS;
2221     SDValue LHS = V.getOperand(0);
2222     SDValue RHS = V.getOperand(1);
2223     if (isSplatValue(LHS, DemandedElts, UndefLHS) &&
2224         isSplatValue(RHS, DemandedElts, UndefRHS)) {
2225       UndefElts = UndefLHS | UndefRHS;
2226       return true;
2227     }
2228     break;
2229   }
2230   }
2231 
2232   return false;
2233 }
2234 
2235 /// Helper wrapper to main isSplatValue function.
2236 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2237   EVT VT = V.getValueType();
2238   assert(VT.isVector() && "Vector type expected");
2239   unsigned NumElts = VT.getVectorNumElements();
2240 
2241   APInt UndefElts;
2242   APInt DemandedElts = APInt::getAllOnesValue(NumElts);
2243   return isSplatValue(V, DemandedElts, UndefElts) &&
2244          (AllowUndefs || !UndefElts);
2245 }
2246 
2247 /// Helper function that checks to see if a node is a constant or a
2248 /// build vector of splat constants at least within the demanded elts.
2249 static ConstantSDNode *isConstOrDemandedConstSplat(SDValue N,
2250                                                    const APInt &DemandedElts) {
2251   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
2252     return CN;
2253   if (N.getOpcode() != ISD::BUILD_VECTOR)
2254     return nullptr;
2255   EVT VT = N.getValueType();
2256   ConstantSDNode *Cst = nullptr;
2257   unsigned NumElts = VT.getVectorNumElements();
2258   assert(DemandedElts.getBitWidth() == NumElts && "Unexpected vector size");
2259   for (unsigned i = 0; i != NumElts; ++i) {
2260     if (!DemandedElts[i])
2261       continue;
2262     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(i));
2263     if (!C || (Cst && Cst->getAPIntValue() != C->getAPIntValue()) ||
2264         C->getValueType(0) != VT.getScalarType())
2265       return nullptr;
2266     Cst = C;
2267   }
2268   return Cst;
2269 }
2270 
2271 /// If a SHL/SRA/SRL node has a constant or splat constant shift amount that
2272 /// is less than the element bit-width of the shift node, return it.
2273 static const APInt *getValidShiftAmountConstant(SDValue V) {
2274   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1))) {
2275     // Shifting more than the bitwidth is not valid.
2276     const APInt &ShAmt = SA->getAPIntValue();
2277     if (ShAmt.ult(V.getScalarValueSizeInBits()))
2278       return &ShAmt;
2279   }
2280   return nullptr;
2281 }
2282 
2283 /// Determine which bits of Op are known to be either zero or one and return
2284 /// them in Known. For vectors, the known bits are those that are shared by
2285 /// every vector element.
2286 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2287   EVT VT = Op.getValueType();
2288   APInt DemandedElts = VT.isVector()
2289                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2290                            : APInt(1, 1);
2291   return computeKnownBits(Op, DemandedElts, Depth);
2292 }
2293 
2294 /// Determine which bits of Op are known to be either zero or one and return
2295 /// them in Known. The DemandedElts argument allows us to only collect the known
2296 /// bits that are shared by the requested vector elements.
2297 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2298                                          unsigned Depth) const {
2299   unsigned BitWidth = Op.getScalarValueSizeInBits();
2300 
2301   KnownBits Known(BitWidth);   // Don't know anything.
2302 
2303   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2304     // We know all of the bits for a constant!
2305     Known.One = C->getAPIntValue();
2306     Known.Zero = ~Known.One;
2307     return Known;
2308   }
2309   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2310     // We know all of the bits for a constant fp!
2311     Known.One = C->getValueAPF().bitcastToAPInt();
2312     Known.Zero = ~Known.One;
2313     return Known;
2314   }
2315 
2316   if (Depth == 6)
2317     return Known;  // Limit search depth.
2318 
2319   KnownBits Known2;
2320   unsigned NumElts = DemandedElts.getBitWidth();
2321   assert((!Op.getValueType().isVector() ||
2322           NumElts == Op.getValueType().getVectorNumElements()) &&
2323          "Unexpected vector size");
2324 
2325   if (!DemandedElts)
2326     return Known;  // No demanded elts, better to assume we don't know anything.
2327 
2328   unsigned Opcode = Op.getOpcode();
2329   switch (Opcode) {
2330   case ISD::BUILD_VECTOR:
2331     // Collect the known bits that are shared by every demanded vector element.
2332     Known.Zero.setAllBits(); Known.One.setAllBits();
2333     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2334       if (!DemandedElts[i])
2335         continue;
2336 
2337       SDValue SrcOp = Op.getOperand(i);
2338       Known2 = computeKnownBits(SrcOp, Depth + 1);
2339 
2340       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2341       if (SrcOp.getValueSizeInBits() != BitWidth) {
2342         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2343                "Expected BUILD_VECTOR implicit truncation");
2344         Known2 = Known2.trunc(BitWidth);
2345       }
2346 
2347       // Known bits are the values that are shared by every demanded element.
2348       Known.One &= Known2.One;
2349       Known.Zero &= Known2.Zero;
2350 
2351       // If we don't know any bits, early out.
2352       if (Known.isUnknown())
2353         break;
2354     }
2355     break;
2356   case ISD::VECTOR_SHUFFLE: {
2357     // Collect the known bits that are shared by every vector element referenced
2358     // by the shuffle.
2359     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2360     Known.Zero.setAllBits(); Known.One.setAllBits();
2361     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2362     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2363     for (unsigned i = 0; i != NumElts; ++i) {
2364       if (!DemandedElts[i])
2365         continue;
2366 
2367       int M = SVN->getMaskElt(i);
2368       if (M < 0) {
2369         // For UNDEF elements, we don't know anything about the common state of
2370         // the shuffle result.
2371         Known.resetAll();
2372         DemandedLHS.clearAllBits();
2373         DemandedRHS.clearAllBits();
2374         break;
2375       }
2376 
2377       if ((unsigned)M < NumElts)
2378         DemandedLHS.setBit((unsigned)M % NumElts);
2379       else
2380         DemandedRHS.setBit((unsigned)M % NumElts);
2381     }
2382     // Known bits are the values that are shared by every demanded element.
2383     if (!!DemandedLHS) {
2384       SDValue LHS = Op.getOperand(0);
2385       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2386       Known.One &= Known2.One;
2387       Known.Zero &= Known2.Zero;
2388     }
2389     // If we don't know any bits, early out.
2390     if (Known.isUnknown())
2391       break;
2392     if (!!DemandedRHS) {
2393       SDValue RHS = Op.getOperand(1);
2394       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2395       Known.One &= Known2.One;
2396       Known.Zero &= Known2.Zero;
2397     }
2398     break;
2399   }
2400   case ISD::CONCAT_VECTORS: {
2401     // Split DemandedElts and test each of the demanded subvectors.
2402     Known.Zero.setAllBits(); Known.One.setAllBits();
2403     EVT SubVectorVT = Op.getOperand(0).getValueType();
2404     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2405     unsigned NumSubVectors = Op.getNumOperands();
2406     for (unsigned i = 0; i != NumSubVectors; ++i) {
2407       APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2408       DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2409       if (!!DemandedSub) {
2410         SDValue Sub = Op.getOperand(i);
2411         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2412         Known.One &= Known2.One;
2413         Known.Zero &= Known2.Zero;
2414       }
2415       // If we don't know any bits, early out.
2416       if (Known.isUnknown())
2417         break;
2418     }
2419     break;
2420   }
2421   case ISD::INSERT_SUBVECTOR: {
2422     // If we know the element index, demand any elements from the subvector and
2423     // the remainder from the src its inserted into, otherwise demand them all.
2424     SDValue Src = Op.getOperand(0);
2425     SDValue Sub = Op.getOperand(1);
2426     ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
2427     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2428     if (SubIdx && SubIdx->getAPIntValue().ule(NumElts - NumSubElts)) {
2429       Known.One.setAllBits();
2430       Known.Zero.setAllBits();
2431       uint64_t Idx = SubIdx->getZExtValue();
2432       APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2433       if (!!DemandedSubElts) {
2434         Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2435         if (Known.isUnknown())
2436           break; // early-out.
2437       }
2438       APInt SubMask = APInt::getBitsSet(NumElts, Idx, Idx + NumSubElts);
2439       APInt DemandedSrcElts = DemandedElts & ~SubMask;
2440       if (!!DemandedSrcElts) {
2441         Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2442         Known.One &= Known2.One;
2443         Known.Zero &= Known2.Zero;
2444       }
2445     } else {
2446       Known = computeKnownBits(Sub, Depth + 1);
2447       if (Known.isUnknown())
2448         break; // early-out.
2449       Known2 = computeKnownBits(Src, Depth + 1);
2450       Known.One &= Known2.One;
2451       Known.Zero &= Known2.Zero;
2452     }
2453     break;
2454   }
2455   case ISD::EXTRACT_SUBVECTOR: {
2456     // If we know the element index, just demand that subvector elements,
2457     // otherwise demand them all.
2458     SDValue Src = Op.getOperand(0);
2459     ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
2460     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2461     if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
2462       // Offset the demanded elts by the subvector index.
2463       uint64_t Idx = SubIdx->getZExtValue();
2464       APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2465       Known = computeKnownBits(Src, DemandedSrc, Depth + 1);
2466     } else {
2467       Known = computeKnownBits(Src, Depth + 1);
2468     }
2469     break;
2470   }
2471   case ISD::SCALAR_TO_VECTOR: {
2472     // We know about scalar_to_vector as much as we know about it source,
2473     // which becomes the first element of otherwise unknown vector.
2474     if (DemandedElts != 1)
2475       break;
2476 
2477     SDValue N0 = Op.getOperand(0);
2478     Known = computeKnownBits(N0, Depth + 1);
2479     if (N0.getValueSizeInBits() != BitWidth)
2480       Known = Known.trunc(BitWidth);
2481 
2482     break;
2483   }
2484   case ISD::BITCAST: {
2485     SDValue N0 = Op.getOperand(0);
2486     EVT SubVT = N0.getValueType();
2487     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2488 
2489     // Ignore bitcasts from unsupported types.
2490     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2491       break;
2492 
2493     // Fast handling of 'identity' bitcasts.
2494     if (BitWidth == SubBitWidth) {
2495       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2496       break;
2497     }
2498 
2499     bool IsLE = getDataLayout().isLittleEndian();
2500 
2501     // Bitcast 'small element' vector to 'large element' scalar/vector.
2502     if ((BitWidth % SubBitWidth) == 0) {
2503       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2504 
2505       // Collect known bits for the (larger) output by collecting the known
2506       // bits from each set of sub elements and shift these into place.
2507       // We need to separately call computeKnownBits for each set of
2508       // sub elements as the knownbits for each is likely to be different.
2509       unsigned SubScale = BitWidth / SubBitWidth;
2510       APInt SubDemandedElts(NumElts * SubScale, 0);
2511       for (unsigned i = 0; i != NumElts; ++i)
2512         if (DemandedElts[i])
2513           SubDemandedElts.setBit(i * SubScale);
2514 
2515       for (unsigned i = 0; i != SubScale; ++i) {
2516         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2517                          Depth + 1);
2518         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2519         Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts);
2520         Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts);
2521       }
2522     }
2523 
2524     // Bitcast 'large element' scalar/vector to 'small element' vector.
2525     if ((SubBitWidth % BitWidth) == 0) {
2526       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2527 
2528       // Collect known bits for the (smaller) output by collecting the known
2529       // bits from the overlapping larger input elements and extracting the
2530       // sub sections we actually care about.
2531       unsigned SubScale = SubBitWidth / BitWidth;
2532       APInt SubDemandedElts(NumElts / SubScale, 0);
2533       for (unsigned i = 0; i != NumElts; ++i)
2534         if (DemandedElts[i])
2535           SubDemandedElts.setBit(i / SubScale);
2536 
2537       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
2538 
2539       Known.Zero.setAllBits(); Known.One.setAllBits();
2540       for (unsigned i = 0; i != NumElts; ++i)
2541         if (DemandedElts[i]) {
2542           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
2543           unsigned Offset = (Shifts % SubScale) * BitWidth;
2544           Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2545           Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2546           // If we don't know any bits, early out.
2547           if (Known.isUnknown())
2548             break;
2549         }
2550     }
2551     break;
2552   }
2553   case ISD::AND:
2554     // If either the LHS or the RHS are Zero, the result is zero.
2555     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2556     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2557 
2558     // Output known-1 bits are only known if set in both the LHS & RHS.
2559     Known.One &= Known2.One;
2560     // Output known-0 are known to be clear if zero in either the LHS | RHS.
2561     Known.Zero |= Known2.Zero;
2562     break;
2563   case ISD::OR:
2564     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2565     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2566 
2567     // Output known-0 bits are only known if clear in both the LHS & RHS.
2568     Known.Zero &= Known2.Zero;
2569     // Output known-1 are known to be set if set in either the LHS | RHS.
2570     Known.One |= Known2.One;
2571     break;
2572   case ISD::XOR: {
2573     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2574     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2575 
2576     // Output known-0 bits are known if clear or set in both the LHS & RHS.
2577     APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
2578     // Output known-1 are known to be set if set in only one of the LHS, RHS.
2579     Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
2580     Known.Zero = KnownZeroOut;
2581     break;
2582   }
2583   case ISD::MUL: {
2584     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2585     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2586 
2587     // If low bits are zero in either operand, output low known-0 bits.
2588     // Also compute a conservative estimate for high known-0 bits.
2589     // More trickiness is possible, but this is sufficient for the
2590     // interesting case of alignment computation.
2591     unsigned TrailZ = Known.countMinTrailingZeros() +
2592                       Known2.countMinTrailingZeros();
2593     unsigned LeadZ =  std::max(Known.countMinLeadingZeros() +
2594                                Known2.countMinLeadingZeros(),
2595                                BitWidth) - BitWidth;
2596 
2597     Known.resetAll();
2598     Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
2599     Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
2600     break;
2601   }
2602   case ISD::UDIV: {
2603     // For the purposes of computing leading zeros we can conservatively
2604     // treat a udiv as a logical right shift by the power of 2 known to
2605     // be less than the denominator.
2606     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2607     unsigned LeadZ = Known2.countMinLeadingZeros();
2608 
2609     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2610     unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
2611     if (RHSMaxLeadingZeros != BitWidth)
2612       LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
2613 
2614     Known.Zero.setHighBits(LeadZ);
2615     break;
2616   }
2617   case ISD::SELECT:
2618   case ISD::VSELECT:
2619     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2620     // If we don't know any bits, early out.
2621     if (Known.isUnknown())
2622       break;
2623     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
2624 
2625     // Only known if known in both the LHS and RHS.
2626     Known.One &= Known2.One;
2627     Known.Zero &= Known2.Zero;
2628     break;
2629   case ISD::SELECT_CC:
2630     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
2631     // If we don't know any bits, early out.
2632     if (Known.isUnknown())
2633       break;
2634     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2635 
2636     // Only known if known in both the LHS and RHS.
2637     Known.One &= Known2.One;
2638     Known.Zero &= Known2.Zero;
2639     break;
2640   case ISD::SMULO:
2641   case ISD::UMULO:
2642   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
2643     if (Op.getResNo() != 1)
2644       break;
2645     // The boolean result conforms to getBooleanContents.
2646     // If we know the result of a setcc has the top bits zero, use this info.
2647     // We know that we have an integer-based boolean since these operations
2648     // are only available for integer.
2649     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2650             TargetLowering::ZeroOrOneBooleanContent &&
2651         BitWidth > 1)
2652       Known.Zero.setBitsFrom(1);
2653     break;
2654   case ISD::SETCC:
2655     // If we know the result of a setcc has the top bits zero, use this info.
2656     if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2657             TargetLowering::ZeroOrOneBooleanContent &&
2658         BitWidth > 1)
2659       Known.Zero.setBitsFrom(1);
2660     break;
2661   case ISD::SHL:
2662     if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2663       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2664       unsigned Shift = ShAmt->getZExtValue();
2665       Known.Zero <<= Shift;
2666       Known.One <<= Shift;
2667       // Low bits are known zero.
2668       Known.Zero.setLowBits(Shift);
2669     }
2670     break;
2671   case ISD::SRL:
2672     if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2673       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2674       unsigned Shift = ShAmt->getZExtValue();
2675       Known.Zero.lshrInPlace(Shift);
2676       Known.One.lshrInPlace(Shift);
2677       // High bits are known zero.
2678       Known.Zero.setHighBits(Shift);
2679     } else if (auto *BV = dyn_cast<BuildVectorSDNode>(Op.getOperand(1))) {
2680       // If the shift amount is a vector of constants see if we can bound
2681       // the number of upper zero bits.
2682       unsigned ShiftAmountMin = BitWidth;
2683       for (unsigned i = 0; i != BV->getNumOperands(); ++i) {
2684         if (auto *C = dyn_cast<ConstantSDNode>(BV->getOperand(i))) {
2685           const APInt &ShAmt = C->getAPIntValue();
2686           if (ShAmt.ult(BitWidth)) {
2687             ShiftAmountMin = std::min<unsigned>(ShiftAmountMin,
2688                                                 ShAmt.getZExtValue());
2689             continue;
2690           }
2691         }
2692         // Don't know anything.
2693         ShiftAmountMin = 0;
2694         break;
2695       }
2696 
2697       Known.Zero.setHighBits(ShiftAmountMin);
2698     }
2699     break;
2700   case ISD::SRA:
2701     if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
2702       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2703       unsigned Shift = ShAmt->getZExtValue();
2704       // Sign extend known zero/one bit (else is unknown).
2705       Known.Zero.ashrInPlace(Shift);
2706       Known.One.ashrInPlace(Shift);
2707     }
2708     break;
2709   case ISD::FSHL:
2710   case ISD::FSHR:
2711     if (ConstantSDNode *C =
2712             isConstOrDemandedConstSplat(Op.getOperand(2), DemandedElts)) {
2713       unsigned Amt = C->getAPIntValue().urem(BitWidth);
2714 
2715       // For fshl, 0-shift returns the 1st arg.
2716       // For fshr, 0-shift returns the 2nd arg.
2717       if (Amt == 0) {
2718         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
2719                                  DemandedElts, Depth + 1);
2720         break;
2721       }
2722 
2723       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
2724       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
2725       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2726       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2727       if (Opcode == ISD::FSHL) {
2728         Known.One <<= Amt;
2729         Known.Zero <<= Amt;
2730         Known2.One.lshrInPlace(BitWidth - Amt);
2731         Known2.Zero.lshrInPlace(BitWidth - Amt);
2732       } else {
2733         Known.One <<= BitWidth - Amt;
2734         Known.Zero <<= BitWidth - Amt;
2735         Known2.One.lshrInPlace(Amt);
2736         Known2.Zero.lshrInPlace(Amt);
2737       }
2738       Known.One |= Known2.One;
2739       Known.Zero |= Known2.Zero;
2740     }
2741     break;
2742   case ISD::SIGN_EXTEND_INREG: {
2743     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2744     unsigned EBits = EVT.getScalarSizeInBits();
2745 
2746     // Sign extension.  Compute the demanded bits in the result that are not
2747     // present in the input.
2748     APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
2749 
2750     APInt InSignMask = APInt::getSignMask(EBits);
2751     APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
2752 
2753     // If the sign extended bits are demanded, we know that the sign
2754     // bit is demanded.
2755     InSignMask = InSignMask.zext(BitWidth);
2756     if (NewBits.getBoolValue())
2757       InputDemandedBits |= InSignMask;
2758 
2759     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2760     Known.One &= InputDemandedBits;
2761     Known.Zero &= InputDemandedBits;
2762 
2763     // If the sign bit of the input is known set or clear, then we know the
2764     // top bits of the result.
2765     if (Known.Zero.intersects(InSignMask)) {        // Input sign bit known clear
2766       Known.Zero |= NewBits;
2767       Known.One  &= ~NewBits;
2768     } else if (Known.One.intersects(InSignMask)) {  // Input sign bit known set
2769       Known.One  |= NewBits;
2770       Known.Zero &= ~NewBits;
2771     } else {                              // Input sign bit unknown
2772       Known.Zero &= ~NewBits;
2773       Known.One  &= ~NewBits;
2774     }
2775     break;
2776   }
2777   case ISD::CTTZ:
2778   case ISD::CTTZ_ZERO_UNDEF: {
2779     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2780     // If we have a known 1, its position is our upper bound.
2781     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
2782     unsigned LowBits = Log2_32(PossibleTZ) + 1;
2783     Known.Zero.setBitsFrom(LowBits);
2784     break;
2785   }
2786   case ISD::CTLZ:
2787   case ISD::CTLZ_ZERO_UNDEF: {
2788     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2789     // If we have a known 1, its position is our upper bound.
2790     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
2791     unsigned LowBits = Log2_32(PossibleLZ) + 1;
2792     Known.Zero.setBitsFrom(LowBits);
2793     break;
2794   }
2795   case ISD::CTPOP: {
2796     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2797     // If we know some of the bits are zero, they can't be one.
2798     unsigned PossibleOnes = Known2.countMaxPopulation();
2799     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
2800     break;
2801   }
2802   case ISD::LOAD: {
2803     LoadSDNode *LD = cast<LoadSDNode>(Op);
2804     // If this is a ZEXTLoad and we are looking at the loaded value.
2805     if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
2806       EVT VT = LD->getMemoryVT();
2807       unsigned MemBits = VT.getScalarSizeInBits();
2808       Known.Zero.setBitsFrom(MemBits);
2809     } else if (const MDNode *Ranges = LD->getRanges()) {
2810       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
2811         computeKnownBitsFromRangeMetadata(*Ranges, Known);
2812     }
2813     break;
2814   }
2815   case ISD::ZERO_EXTEND_VECTOR_INREG: {
2816     EVT InVT = Op.getOperand(0).getValueType();
2817     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
2818     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
2819     Known = Known.zext(BitWidth);
2820     Known.Zero.setBitsFrom(InVT.getScalarSizeInBits());
2821     break;
2822   }
2823   case ISD::ZERO_EXTEND: {
2824     EVT InVT = Op.getOperand(0).getValueType();
2825     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2826     Known = Known.zext(BitWidth);
2827     Known.Zero.setBitsFrom(InVT.getScalarSizeInBits());
2828     break;
2829   }
2830   case ISD::SIGN_EXTEND_VECTOR_INREG: {
2831     EVT InVT = Op.getOperand(0).getValueType();
2832     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
2833     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
2834     // If the sign bit is known to be zero or one, then sext will extend
2835     // it to the top bits, else it will just zext.
2836     Known = Known.sext(BitWidth);
2837     break;
2838   }
2839   case ISD::SIGN_EXTEND: {
2840     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2841     // If the sign bit is known to be zero or one, then sext will extend
2842     // it to the top bits, else it will just zext.
2843     Known = Known.sext(BitWidth);
2844     break;
2845   }
2846   case ISD::ANY_EXTEND: {
2847     Known = computeKnownBits(Op.getOperand(0), Depth+1);
2848     Known = Known.zext(BitWidth);
2849     break;
2850   }
2851   case ISD::TRUNCATE: {
2852     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2853     Known = Known.trunc(BitWidth);
2854     break;
2855   }
2856   case ISD::AssertZext: {
2857     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
2858     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
2859     Known = computeKnownBits(Op.getOperand(0), Depth+1);
2860     Known.Zero |= (~InMask);
2861     Known.One  &= (~Known.Zero);
2862     break;
2863   }
2864   case ISD::FGETSIGN:
2865     // All bits are zero except the low bit.
2866     Known.Zero.setBitsFrom(1);
2867     break;
2868   case ISD::USUBO:
2869   case ISD::SSUBO:
2870     if (Op.getResNo() == 1) {
2871       // If we know the result of a setcc has the top bits zero, use this info.
2872       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2873               TargetLowering::ZeroOrOneBooleanContent &&
2874           BitWidth > 1)
2875         Known.Zero.setBitsFrom(1);
2876       break;
2877     }
2878     LLVM_FALLTHROUGH;
2879   case ISD::SUB:
2880   case ISD::SUBC: {
2881     if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0))) {
2882       // We know that the top bits of C-X are clear if X contains less bits
2883       // than C (i.e. no wrap-around can happen).  For example, 20-X is
2884       // positive if we can prove that X is >= 0 and < 16.
2885       if (CLHS->getAPIntValue().isNonNegative()) {
2886         unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
2887         // NLZ can't be BitWidth with no sign bit
2888         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
2889         Known2 = computeKnownBits(Op.getOperand(1), DemandedElts,
2890                          Depth + 1);
2891 
2892         // If all of the MaskV bits are known to be zero, then we know the
2893         // output top bits are zero, because we now know that the output is
2894         // from [0-C].
2895         if ((Known2.Zero & MaskV) == MaskV) {
2896           unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
2897           // Top bits known zero.
2898           Known.Zero.setHighBits(NLZ2);
2899         }
2900       }
2901     }
2902 
2903     // If low bits are know to be zero in both operands, then we know they are
2904     // going to be 0 in the result. Both addition and complement operations
2905     // preserve the low zero bits.
2906     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2907     unsigned KnownZeroLow = Known2.countMinTrailingZeros();
2908     if (KnownZeroLow == 0)
2909       break;
2910 
2911     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2912     KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros());
2913     Known.Zero.setLowBits(KnownZeroLow);
2914     break;
2915   }
2916   case ISD::UADDO:
2917   case ISD::SADDO:
2918   case ISD::ADDCARRY:
2919     if (Op.getResNo() == 1) {
2920       // If we know the result of a setcc has the top bits zero, use this info.
2921       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
2922               TargetLowering::ZeroOrOneBooleanContent &&
2923           BitWidth > 1)
2924         Known.Zero.setBitsFrom(1);
2925       break;
2926     }
2927     LLVM_FALLTHROUGH;
2928   case ISD::ADD:
2929   case ISD::ADDC:
2930   case ISD::ADDE: {
2931     // Output known-0 bits are known if clear or set in both the low clear bits
2932     // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
2933     // low 3 bits clear.
2934     // Output known-0 bits are also known if the top bits of each input are
2935     // known to be clear. For example, if one input has the top 10 bits clear
2936     // and the other has the top 8 bits clear, we know the top 7 bits of the
2937     // output must be clear.
2938     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2939     unsigned KnownZeroHigh = Known2.countMinLeadingZeros();
2940     unsigned KnownZeroLow = Known2.countMinTrailingZeros();
2941 
2942     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2943     KnownZeroHigh = std::min(KnownZeroHigh, Known2.countMinLeadingZeros());
2944     KnownZeroLow = std::min(KnownZeroLow, Known2.countMinTrailingZeros());
2945 
2946     if (Opcode == ISD::ADDE || Opcode == ISD::ADDCARRY) {
2947       // With ADDE and ADDCARRY, a carry bit may be added in, so we can only
2948       // use this information if we know (at least) that the low two bits are
2949       // clear. We then return to the caller that the low bit is unknown but
2950       // that other bits are known zero.
2951       if (KnownZeroLow >= 2)
2952         Known.Zero.setBits(1, KnownZeroLow);
2953       break;
2954     }
2955 
2956     Known.Zero.setLowBits(KnownZeroLow);
2957     if (KnownZeroHigh > 1)
2958       Known.Zero.setHighBits(KnownZeroHigh - 1);
2959     break;
2960   }
2961   case ISD::SREM:
2962     if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2963       const APInt &RA = Rem->getAPIntValue().abs();
2964       if (RA.isPowerOf2()) {
2965         APInt LowBits = RA - 1;
2966         Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2967 
2968         // The low bits of the first operand are unchanged by the srem.
2969         Known.Zero = Known2.Zero & LowBits;
2970         Known.One = Known2.One & LowBits;
2971 
2972         // If the first operand is non-negative or has all low bits zero, then
2973         // the upper bits are all zero.
2974         if (Known2.Zero[BitWidth-1] || ((Known2.Zero & LowBits) == LowBits))
2975           Known.Zero |= ~LowBits;
2976 
2977         // If the first operand is negative and not all low bits are zero, then
2978         // the upper bits are all one.
2979         if (Known2.One[BitWidth-1] && ((Known2.One & LowBits) != 0))
2980           Known.One |= ~LowBits;
2981         assert((Known.Zero & Known.One) == 0&&"Bits known to be one AND zero?");
2982       }
2983     }
2984     break;
2985   case ISD::UREM: {
2986     if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
2987       const APInt &RA = Rem->getAPIntValue();
2988       if (RA.isPowerOf2()) {
2989         APInt LowBits = (RA - 1);
2990         Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2991 
2992         // The upper bits are all zero, the lower ones are unchanged.
2993         Known.Zero = Known2.Zero | ~LowBits;
2994         Known.One = Known2.One & LowBits;
2995         break;
2996       }
2997     }
2998 
2999     // Since the result is less than or equal to either operand, any leading
3000     // zero bits in either operand must also exist in the result.
3001     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3002     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3003 
3004     uint32_t Leaders =
3005         std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
3006     Known.resetAll();
3007     Known.Zero.setHighBits(Leaders);
3008     break;
3009   }
3010   case ISD::EXTRACT_ELEMENT: {
3011     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3012     const unsigned Index = Op.getConstantOperandVal(1);
3013     const unsigned BitWidth = Op.getValueSizeInBits();
3014 
3015     // Remove low part of known bits mask
3016     Known.Zero = Known.Zero.getHiBits(Known.Zero.getBitWidth() - Index * BitWidth);
3017     Known.One = Known.One.getHiBits(Known.One.getBitWidth() - Index * BitWidth);
3018 
3019     // Remove high part of known bit mask
3020     Known = Known.trunc(BitWidth);
3021     break;
3022   }
3023   case ISD::EXTRACT_VECTOR_ELT: {
3024     SDValue InVec = Op.getOperand(0);
3025     SDValue EltNo = Op.getOperand(1);
3026     EVT VecVT = InVec.getValueType();
3027     const unsigned BitWidth = Op.getValueSizeInBits();
3028     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3029     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3030     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3031     // anything about the extended bits.
3032     if (BitWidth > EltBitWidth)
3033       Known = Known.trunc(EltBitWidth);
3034     ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3035     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) {
3036       // If we know the element index, just demand that vector element.
3037       unsigned Idx = ConstEltNo->getZExtValue();
3038       APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
3039       Known = computeKnownBits(InVec, DemandedElt, Depth + 1);
3040     } else {
3041       // Unknown element index, so ignore DemandedElts and demand them all.
3042       Known = computeKnownBits(InVec, Depth + 1);
3043     }
3044     if (BitWidth > EltBitWidth)
3045       Known = Known.zext(BitWidth);
3046     break;
3047   }
3048   case ISD::INSERT_VECTOR_ELT: {
3049     SDValue InVec = Op.getOperand(0);
3050     SDValue InVal = Op.getOperand(1);
3051     SDValue EltNo = Op.getOperand(2);
3052 
3053     ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3054     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3055       // If we know the element index, split the demand between the
3056       // source vector and the inserted element.
3057       Known.Zero = Known.One = APInt::getAllOnesValue(BitWidth);
3058       unsigned EltIdx = CEltNo->getZExtValue();
3059 
3060       // If we demand the inserted element then add its common known bits.
3061       if (DemandedElts[EltIdx]) {
3062         Known2 = computeKnownBits(InVal, Depth + 1);
3063         Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
3064         Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
3065       }
3066 
3067       // If we demand the source vector then add its common known bits, ensuring
3068       // that we don't demand the inserted element.
3069       APInt VectorElts = DemandedElts & ~(APInt::getOneBitSet(NumElts, EltIdx));
3070       if (!!VectorElts) {
3071         Known2 = computeKnownBits(InVec, VectorElts, Depth + 1);
3072         Known.One &= Known2.One;
3073         Known.Zero &= Known2.Zero;
3074       }
3075     } else {
3076       // Unknown element index, so ignore DemandedElts and demand them all.
3077       Known = computeKnownBits(InVec, Depth + 1);
3078       Known2 = computeKnownBits(InVal, Depth + 1);
3079       Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
3080       Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
3081     }
3082     break;
3083   }
3084   case ISD::BITREVERSE: {
3085     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3086     Known.Zero = Known2.Zero.reverseBits();
3087     Known.One = Known2.One.reverseBits();
3088     break;
3089   }
3090   case ISD::BSWAP: {
3091     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3092     Known.Zero = Known2.Zero.byteSwap();
3093     Known.One = Known2.One.byteSwap();
3094     break;
3095   }
3096   case ISD::ABS: {
3097     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3098 
3099     // If the source's MSB is zero then we know the rest of the bits already.
3100     if (Known2.isNonNegative()) {
3101       Known.Zero = Known2.Zero;
3102       Known.One = Known2.One;
3103       break;
3104     }
3105 
3106     // We only know that the absolute values's MSB will be zero iff there is
3107     // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
3108     Known2.One.clearSignBit();
3109     if (Known2.One.getBoolValue()) {
3110       Known.Zero = APInt::getSignMask(BitWidth);
3111       break;
3112     }
3113     break;
3114   }
3115   case ISD::UMIN: {
3116     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3117     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3118 
3119     // UMIN - we know that the result will have the maximum of the
3120     // known zero leading bits of the inputs.
3121     unsigned LeadZero = Known.countMinLeadingZeros();
3122     LeadZero = std::max(LeadZero, Known2.countMinLeadingZeros());
3123 
3124     Known.Zero &= Known2.Zero;
3125     Known.One &= Known2.One;
3126     Known.Zero.setHighBits(LeadZero);
3127     break;
3128   }
3129   case ISD::UMAX: {
3130     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3131     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3132 
3133     // UMAX - we know that the result will have the maximum of the
3134     // known one leading bits of the inputs.
3135     unsigned LeadOne = Known.countMinLeadingOnes();
3136     LeadOne = std::max(LeadOne, Known2.countMinLeadingOnes());
3137 
3138     Known.Zero &= Known2.Zero;
3139     Known.One &= Known2.One;
3140     Known.One.setHighBits(LeadOne);
3141     break;
3142   }
3143   case ISD::SMIN:
3144   case ISD::SMAX: {
3145     // If we have a clamp pattern, we know that the number of sign bits will be
3146     // the minimum of the clamp min/max range.
3147     bool IsMax = (Opcode == ISD::SMAX);
3148     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3149     if ((CstLow = isConstOrDemandedConstSplat(Op.getOperand(1), DemandedElts)))
3150       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3151         CstHigh = isConstOrDemandedConstSplat(Op.getOperand(0).getOperand(1),
3152                                               DemandedElts);
3153     if (CstLow && CstHigh) {
3154       if (!IsMax)
3155         std::swap(CstLow, CstHigh);
3156 
3157       const APInt &ValueLow = CstLow->getAPIntValue();
3158       const APInt &ValueHigh = CstHigh->getAPIntValue();
3159       if (ValueLow.sle(ValueHigh)) {
3160         unsigned LowSignBits = ValueLow.getNumSignBits();
3161         unsigned HighSignBits = ValueHigh.getNumSignBits();
3162         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3163         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3164           Known.One.setHighBits(MinSignBits);
3165           break;
3166         }
3167         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3168           Known.Zero.setHighBits(MinSignBits);
3169           break;
3170         }
3171       }
3172     }
3173 
3174     // Fallback - just get the shared known bits of the operands.
3175     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3176     if (Known.isUnknown()) break; // Early-out
3177     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3178     Known.Zero &= Known2.Zero;
3179     Known.One &= Known2.One;
3180     break;
3181   }
3182   case ISD::FrameIndex:
3183   case ISD::TargetFrameIndex:
3184     TLI->computeKnownBitsForFrameIndex(Op, Known, DemandedElts, *this, Depth);
3185     break;
3186 
3187   default:
3188     if (Opcode < ISD::BUILTIN_OP_END)
3189       break;
3190     LLVM_FALLTHROUGH;
3191   case ISD::INTRINSIC_WO_CHAIN:
3192   case ISD::INTRINSIC_W_CHAIN:
3193   case ISD::INTRINSIC_VOID:
3194     // Allow the target to implement this method for its nodes.
3195     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3196     break;
3197   }
3198 
3199   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3200   return Known;
3201 }
3202 
3203 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3204                                                              SDValue N1) const {
3205   // X + 0 never overflow
3206   if (isNullConstant(N1))
3207     return OFK_Never;
3208 
3209   KnownBits N1Known = computeKnownBits(N1);
3210   if (N1Known.Zero.getBoolValue()) {
3211     KnownBits N0Known = computeKnownBits(N0);
3212 
3213     bool overflow;
3214     (void)(~N0Known.Zero).uadd_ov(~N1Known.Zero, overflow);
3215     if (!overflow)
3216       return OFK_Never;
3217   }
3218 
3219   // mulhi + 1 never overflow
3220   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3221       (~N1Known.Zero & 0x01) == ~N1Known.Zero)
3222     return OFK_Never;
3223 
3224   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3225     KnownBits N0Known = computeKnownBits(N0);
3226 
3227     if ((~N0Known.Zero & 0x01) == ~N0Known.Zero)
3228       return OFK_Never;
3229   }
3230 
3231   return OFK_Sometime;
3232 }
3233 
3234 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3235   EVT OpVT = Val.getValueType();
3236   unsigned BitWidth = OpVT.getScalarSizeInBits();
3237 
3238   // Is the constant a known power of 2?
3239   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3240     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3241 
3242   // A left-shift of a constant one will have exactly one bit set because
3243   // shifting the bit off the end is undefined.
3244   if (Val.getOpcode() == ISD::SHL) {
3245     auto *C = isConstOrConstSplat(Val.getOperand(0));
3246     if (C && C->getAPIntValue() == 1)
3247       return true;
3248   }
3249 
3250   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3251   // one bit set.
3252   if (Val.getOpcode() == ISD::SRL) {
3253     auto *C = isConstOrConstSplat(Val.getOperand(0));
3254     if (C && C->getAPIntValue().isSignMask())
3255       return true;
3256   }
3257 
3258   // Are all operands of a build vector constant powers of two?
3259   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3260     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3261           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3262             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3263           return false;
3264         }))
3265       return true;
3266 
3267   // More could be done here, though the above checks are enough
3268   // to handle some common cases.
3269 
3270   // Fall back to computeKnownBits to catch other known cases.
3271   KnownBits Known = computeKnownBits(Val);
3272   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3273 }
3274 
3275 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3276   EVT VT = Op.getValueType();
3277   APInt DemandedElts = VT.isVector()
3278                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
3279                            : APInt(1, 1);
3280   return ComputeNumSignBits(Op, DemandedElts, Depth);
3281 }
3282 
3283 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3284                                           unsigned Depth) const {
3285   EVT VT = Op.getValueType();
3286   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3287   unsigned VTBits = VT.getScalarSizeInBits();
3288   unsigned NumElts = DemandedElts.getBitWidth();
3289   unsigned Tmp, Tmp2;
3290   unsigned FirstAnswer = 1;
3291 
3292   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3293     const APInt &Val = C->getAPIntValue();
3294     return Val.getNumSignBits();
3295   }
3296 
3297   if (Depth == 6)
3298     return 1;  // Limit search depth.
3299 
3300   if (!DemandedElts)
3301     return 1;  // No demanded elts, better to assume we don't know anything.
3302 
3303   unsigned Opcode = Op.getOpcode();
3304   switch (Opcode) {
3305   default: break;
3306   case ISD::AssertSext:
3307     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3308     return VTBits-Tmp+1;
3309   case ISD::AssertZext:
3310     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3311     return VTBits-Tmp;
3312 
3313   case ISD::BUILD_VECTOR:
3314     Tmp = VTBits;
3315     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3316       if (!DemandedElts[i])
3317         continue;
3318 
3319       SDValue SrcOp = Op.getOperand(i);
3320       Tmp2 = ComputeNumSignBits(Op.getOperand(i), Depth + 1);
3321 
3322       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3323       if (SrcOp.getValueSizeInBits() != VTBits) {
3324         assert(SrcOp.getValueSizeInBits() > VTBits &&
3325                "Expected BUILD_VECTOR implicit truncation");
3326         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3327         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3328       }
3329       Tmp = std::min(Tmp, Tmp2);
3330     }
3331     return Tmp;
3332 
3333   case ISD::VECTOR_SHUFFLE: {
3334     // Collect the minimum number of sign bits that are shared by every vector
3335     // element referenced by the shuffle.
3336     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3337     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3338     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3339     for (unsigned i = 0; i != NumElts; ++i) {
3340       int M = SVN->getMaskElt(i);
3341       if (!DemandedElts[i])
3342         continue;
3343       // For UNDEF elements, we don't know anything about the common state of
3344       // the shuffle result.
3345       if (M < 0)
3346         return 1;
3347       if ((unsigned)M < NumElts)
3348         DemandedLHS.setBit((unsigned)M % NumElts);
3349       else
3350         DemandedRHS.setBit((unsigned)M % NumElts);
3351     }
3352     Tmp = std::numeric_limits<unsigned>::max();
3353     if (!!DemandedLHS)
3354       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3355     if (!!DemandedRHS) {
3356       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3357       Tmp = std::min(Tmp, Tmp2);
3358     }
3359     // If we don't know anything, early out and try computeKnownBits fall-back.
3360     if (Tmp == 1)
3361       break;
3362     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3363     return Tmp;
3364   }
3365 
3366   case ISD::BITCAST: {
3367     SDValue N0 = Op.getOperand(0);
3368     EVT SrcVT = N0.getValueType();
3369     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3370 
3371     // Ignore bitcasts from unsupported types..
3372     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3373       break;
3374 
3375     // Fast handling of 'identity' bitcasts.
3376     if (VTBits == SrcBits)
3377       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3378 
3379     bool IsLE = getDataLayout().isLittleEndian();
3380 
3381     // Bitcast 'large element' scalar/vector to 'small element' vector.
3382     if ((SrcBits % VTBits) == 0) {
3383       assert(VT.isVector() && "Expected bitcast to vector");
3384 
3385       unsigned Scale = SrcBits / VTBits;
3386       APInt SrcDemandedElts(NumElts / Scale, 0);
3387       for (unsigned i = 0; i != NumElts; ++i)
3388         if (DemandedElts[i])
3389           SrcDemandedElts.setBit(i / Scale);
3390 
3391       // Fast case - sign splat can be simply split across the small elements.
3392       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3393       if (Tmp == SrcBits)
3394         return VTBits;
3395 
3396       // Slow case - determine how far the sign extends into each sub-element.
3397       Tmp2 = VTBits;
3398       for (unsigned i = 0; i != NumElts; ++i)
3399         if (DemandedElts[i]) {
3400           unsigned SubOffset = i % Scale;
3401           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3402           SubOffset = SubOffset * VTBits;
3403           if (Tmp <= SubOffset)
3404             return 1;
3405           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3406         }
3407       return Tmp2;
3408     }
3409     break;
3410   }
3411 
3412   case ISD::SIGN_EXTEND:
3413     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3414     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3415   case ISD::SIGN_EXTEND_INREG:
3416     // Max of the input and what this extends.
3417     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3418     Tmp = VTBits-Tmp+1;
3419     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3420     return std::max(Tmp, Tmp2);
3421   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3422     SDValue Src = Op.getOperand(0);
3423     EVT SrcVT = Src.getValueType();
3424     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3425     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3426     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3427   }
3428 
3429   case ISD::SRA:
3430     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3431     // SRA X, C   -> adds C sign bits.
3432     if (ConstantSDNode *C =
3433             isConstOrDemandedConstSplat(Op.getOperand(1), DemandedElts)) {
3434       APInt ShiftVal = C->getAPIntValue();
3435       ShiftVal += Tmp;
3436       Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
3437     }
3438     return Tmp;
3439   case ISD::SHL:
3440     if (ConstantSDNode *C =
3441             isConstOrDemandedConstSplat(Op.getOperand(1), DemandedElts)) {
3442       // shl destroys sign bits.
3443       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3444       if (C->getAPIntValue().uge(VTBits) ||      // Bad shift.
3445           C->getAPIntValue().uge(Tmp)) break;    // Shifted all sign bits out.
3446       return Tmp - C->getZExtValue();
3447     }
3448     break;
3449   case ISD::AND:
3450   case ISD::OR:
3451   case ISD::XOR:    // NOT is handled here.
3452     // Logical binary ops preserve the number of sign bits at the worst.
3453     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3454     if (Tmp != 1) {
3455       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3456       FirstAnswer = std::min(Tmp, Tmp2);
3457       // We computed what we know about the sign bits as our first
3458       // answer. Now proceed to the generic code that uses
3459       // computeKnownBits, and pick whichever answer is better.
3460     }
3461     break;
3462 
3463   case ISD::SELECT:
3464   case ISD::VSELECT:
3465     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3466     if (Tmp == 1) return 1;  // Early out.
3467     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3468     return std::min(Tmp, Tmp2);
3469   case ISD::SELECT_CC:
3470     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3471     if (Tmp == 1) return 1;  // Early out.
3472     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3473     return std::min(Tmp, Tmp2);
3474 
3475   case ISD::SMIN:
3476   case ISD::SMAX: {
3477     // If we have a clamp pattern, we know that the number of sign bits will be
3478     // the minimum of the clamp min/max range.
3479     bool IsMax = (Opcode == ISD::SMAX);
3480     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3481     if ((CstLow = isConstOrDemandedConstSplat(Op.getOperand(1), DemandedElts)))
3482       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3483         CstHigh = isConstOrDemandedConstSplat(Op.getOperand(0).getOperand(1),
3484                                               DemandedElts);
3485     if (CstLow && CstHigh) {
3486       if (!IsMax)
3487         std::swap(CstLow, CstHigh);
3488       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3489         Tmp = CstLow->getAPIntValue().getNumSignBits();
3490         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3491         return std::min(Tmp, Tmp2);
3492       }
3493     }
3494 
3495     // Fallback - just get the minimum number of sign bits of the operands.
3496     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3497     if (Tmp == 1)
3498       return 1;  // Early out.
3499     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3500     return std::min(Tmp, Tmp2);
3501   }
3502   case ISD::UMIN:
3503   case ISD::UMAX:
3504     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3505     if (Tmp == 1)
3506       return 1;  // Early out.
3507     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3508     return std::min(Tmp, Tmp2);
3509   case ISD::SADDO:
3510   case ISD::UADDO:
3511   case ISD::SSUBO:
3512   case ISD::USUBO:
3513   case ISD::SMULO:
3514   case ISD::UMULO:
3515     if (Op.getResNo() != 1)
3516       break;
3517     // The boolean result conforms to getBooleanContents.  Fall through.
3518     // If setcc returns 0/-1, all bits are sign bits.
3519     // We know that we have an integer-based boolean since these operations
3520     // are only available for integer.
3521     if (TLI->getBooleanContents(VT.isVector(), false) ==
3522         TargetLowering::ZeroOrNegativeOneBooleanContent)
3523       return VTBits;
3524     break;
3525   case ISD::SETCC:
3526     // If setcc returns 0/-1, all bits are sign bits.
3527     if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3528         TargetLowering::ZeroOrNegativeOneBooleanContent)
3529       return VTBits;
3530     break;
3531   case ISD::ROTL:
3532   case ISD::ROTR:
3533     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
3534       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3535 
3536       // Handle rotate right by N like a rotate left by 32-N.
3537       if (Opcode == ISD::ROTR)
3538         RotAmt = (VTBits - RotAmt) % VTBits;
3539 
3540       // If we aren't rotating out all of the known-in sign bits, return the
3541       // number that are left.  This handles rotl(sext(x), 1) for example.
3542       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3543       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3544     }
3545     break;
3546   case ISD::ADD:
3547   case ISD::ADDC:
3548     // Add can have at most one carry bit.  Thus we know that the output
3549     // is, at worst, one more bit than the inputs.
3550     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3551     if (Tmp == 1) return 1;  // Early out.
3552 
3553     // Special case decrementing a value (ADD X, -1):
3554     if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
3555       if (CRHS->isAllOnesValue()) {
3556         KnownBits Known = computeKnownBits(Op.getOperand(0), Depth+1);
3557 
3558         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3559         // sign bits set.
3560         if ((Known.Zero | 1).isAllOnesValue())
3561           return VTBits;
3562 
3563         // If we are subtracting one from a positive number, there is no carry
3564         // out of the result.
3565         if (Known.isNonNegative())
3566           return Tmp;
3567       }
3568 
3569     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3570     if (Tmp2 == 1) return 1;
3571     return std::min(Tmp, Tmp2)-1;
3572 
3573   case ISD::SUB:
3574     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
3575     if (Tmp2 == 1) return 1;
3576 
3577     // Handle NEG.
3578     if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
3579       if (CLHS->isNullValue()) {
3580         KnownBits Known = computeKnownBits(Op.getOperand(1), Depth+1);
3581         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3582         // sign bits set.
3583         if ((Known.Zero | 1).isAllOnesValue())
3584           return VTBits;
3585 
3586         // If the input is known to be positive (the sign bit is known clear),
3587         // the output of the NEG has the same number of sign bits as the input.
3588         if (Known.isNonNegative())
3589           return Tmp2;
3590 
3591         // Otherwise, we treat this like a SUB.
3592       }
3593 
3594     // Sub can have at most one carry bit.  Thus we know that the output
3595     // is, at worst, one more bit than the inputs.
3596     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3597     if (Tmp == 1) return 1;  // Early out.
3598     return std::min(Tmp, Tmp2)-1;
3599   case ISD::TRUNCATE: {
3600     // Check if the sign bits of source go down as far as the truncated value.
3601     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3602     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3603     if (NumSrcSignBits > (NumSrcBits - VTBits))
3604       return NumSrcSignBits - (NumSrcBits - VTBits);
3605     break;
3606   }
3607   case ISD::EXTRACT_ELEMENT: {
3608     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3609     const int BitWidth = Op.getValueSizeInBits();
3610     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3611 
3612     // Get reverse index (starting from 1), Op1 value indexes elements from
3613     // little end. Sign starts at big end.
3614     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3615 
3616     // If the sign portion ends in our element the subtraction gives correct
3617     // result. Otherwise it gives either negative or > bitwidth result
3618     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3619   }
3620   case ISD::INSERT_VECTOR_ELT: {
3621     SDValue InVec = Op.getOperand(0);
3622     SDValue InVal = Op.getOperand(1);
3623     SDValue EltNo = Op.getOperand(2);
3624     unsigned NumElts = InVec.getValueType().getVectorNumElements();
3625 
3626     ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3627     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3628       // If we know the element index, split the demand between the
3629       // source vector and the inserted element.
3630       unsigned EltIdx = CEltNo->getZExtValue();
3631 
3632       // If we demand the inserted element then get its sign bits.
3633       Tmp = std::numeric_limits<unsigned>::max();
3634       if (DemandedElts[EltIdx]) {
3635         // TODO - handle implicit truncation of inserted elements.
3636         if (InVal.getScalarValueSizeInBits() != VTBits)
3637           break;
3638         Tmp = ComputeNumSignBits(InVal, Depth + 1);
3639       }
3640 
3641       // If we demand the source vector then get its sign bits, and determine
3642       // the minimum.
3643       APInt VectorElts = DemandedElts;
3644       VectorElts.clearBit(EltIdx);
3645       if (!!VectorElts) {
3646         Tmp2 = ComputeNumSignBits(InVec, VectorElts, Depth + 1);
3647         Tmp = std::min(Tmp, Tmp2);
3648       }
3649     } else {
3650       // Unknown element index, so ignore DemandedElts and demand them all.
3651       Tmp = ComputeNumSignBits(InVec, Depth + 1);
3652       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
3653       Tmp = std::min(Tmp, Tmp2);
3654     }
3655     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3656     return Tmp;
3657   }
3658   case ISD::EXTRACT_VECTOR_ELT: {
3659     SDValue InVec = Op.getOperand(0);
3660     SDValue EltNo = Op.getOperand(1);
3661     EVT VecVT = InVec.getValueType();
3662     const unsigned BitWidth = Op.getValueSizeInBits();
3663     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3664     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3665 
3666     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3667     // anything about sign bits. But if the sizes match we can derive knowledge
3668     // about sign bits from the vector operand.
3669     if (BitWidth != EltBitWidth)
3670       break;
3671 
3672     // If we know the element index, just demand that vector element, else for
3673     // an unknown element index, ignore DemandedElts and demand them all.
3674     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3675     ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3676     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3677       DemandedSrcElts =
3678           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3679 
3680     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
3681   }
3682   case ISD::EXTRACT_SUBVECTOR: {
3683     // If we know the element index, just demand that subvector elements,
3684     // otherwise demand them all.
3685     SDValue Src = Op.getOperand(0);
3686     ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
3687     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
3688     if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
3689       // Offset the demanded elts by the subvector index.
3690       uint64_t Idx = SubIdx->getZExtValue();
3691       APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
3692       return ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
3693     }
3694     return ComputeNumSignBits(Src, Depth + 1);
3695   }
3696   case ISD::CONCAT_VECTORS:
3697     // Determine the minimum number of sign bits across all demanded
3698     // elts of the input vectors. Early out if the result is already 1.
3699     Tmp = std::numeric_limits<unsigned>::max();
3700     EVT SubVectorVT = Op.getOperand(0).getValueType();
3701     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
3702     unsigned NumSubVectors = Op.getNumOperands();
3703     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
3704       APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
3705       DemandedSub = DemandedSub.trunc(NumSubVectorElts);
3706       if (!DemandedSub)
3707         continue;
3708       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
3709       Tmp = std::min(Tmp, Tmp2);
3710     }
3711     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3712     return Tmp;
3713   }
3714 
3715   // If we are looking at the loaded value of the SDNode.
3716   if (Op.getResNo() == 0) {
3717     // Handle LOADX separately here. EXTLOAD case will fallthrough.
3718     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
3719       unsigned ExtType = LD->getExtensionType();
3720       switch (ExtType) {
3721         default: break;
3722         case ISD::SEXTLOAD:    // '17' bits known
3723           Tmp = LD->getMemoryVT().getScalarSizeInBits();
3724           return VTBits-Tmp+1;
3725         case ISD::ZEXTLOAD:    // '16' bits known
3726           Tmp = LD->getMemoryVT().getScalarSizeInBits();
3727           return VTBits-Tmp;
3728       }
3729     }
3730   }
3731 
3732   // Allow the target to implement this method for its nodes.
3733   if (Opcode >= ISD::BUILTIN_OP_END ||
3734       Opcode == ISD::INTRINSIC_WO_CHAIN ||
3735       Opcode == ISD::INTRINSIC_W_CHAIN ||
3736       Opcode == ISD::INTRINSIC_VOID) {
3737     unsigned NumBits =
3738         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
3739     if (NumBits > 1)
3740       FirstAnswer = std::max(FirstAnswer, NumBits);
3741   }
3742 
3743   // Finally, if we can prove that the top bits of the result are 0's or 1's,
3744   // use this information.
3745   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
3746 
3747   APInt Mask;
3748   if (Known.isNonNegative()) {        // sign bit is 0
3749     Mask = Known.Zero;
3750   } else if (Known.isNegative()) {  // sign bit is 1;
3751     Mask = Known.One;
3752   } else {
3753     // Nothing known.
3754     return FirstAnswer;
3755   }
3756 
3757   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
3758   // the number of identical bits in the top of the input value.
3759   Mask = ~Mask;
3760   Mask <<= Mask.getBitWidth()-VTBits;
3761   // Return # leading zeros.  We use 'min' here in case Val was zero before
3762   // shifting.  We don't want to return '64' as for an i32 "0".
3763   return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
3764 }
3765 
3766 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
3767   if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
3768       !isa<ConstantSDNode>(Op.getOperand(1)))
3769     return false;
3770 
3771   if (Op.getOpcode() == ISD::OR &&
3772       !MaskedValueIsZero(Op.getOperand(0),
3773                      cast<ConstantSDNode>(Op.getOperand(1))->getAPIntValue()))
3774     return false;
3775 
3776   return true;
3777 }
3778 
3779 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
3780   // If we're told that NaNs won't happen, assume they won't.
3781   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
3782     return true;
3783 
3784   if (Depth == 6)
3785     return false; // Limit search depth.
3786 
3787   // TODO: Handle vectors.
3788   // If the value is a constant, we can obviously see if it is a NaN or not.
3789   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
3790     return !C->getValueAPF().isNaN() ||
3791            (SNaN && !C->getValueAPF().isSignaling());
3792   }
3793 
3794   unsigned Opcode = Op.getOpcode();
3795   switch (Opcode) {
3796   case ISD::FADD:
3797   case ISD::FSUB:
3798   case ISD::FMUL:
3799   case ISD::FDIV:
3800   case ISD::FREM:
3801   case ISD::FSIN:
3802   case ISD::FCOS: {
3803     if (SNaN)
3804       return true;
3805     // TODO: Need isKnownNeverInfinity
3806     return false;
3807   }
3808   case ISD::FCANONICALIZE:
3809   case ISD::FEXP:
3810   case ISD::FEXP2:
3811   case ISD::FTRUNC:
3812   case ISD::FFLOOR:
3813   case ISD::FCEIL:
3814   case ISD::FROUND:
3815   case ISD::FRINT:
3816   case ISD::FNEARBYINT: {
3817     if (SNaN)
3818       return true;
3819     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
3820   }
3821   case ISD::FABS:
3822   case ISD::FNEG:
3823   case ISD::FCOPYSIGN: {
3824     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
3825   }
3826   case ISD::SELECT:
3827     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
3828            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
3829   case ISD::FP_EXTEND:
3830   case ISD::FP_ROUND: {
3831     if (SNaN)
3832       return true;
3833     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
3834   }
3835   case ISD::SINT_TO_FP:
3836   case ISD::UINT_TO_FP:
3837     return true;
3838   case ISD::FMA:
3839   case ISD::FMAD: {
3840     if (SNaN)
3841       return true;
3842     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
3843            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
3844            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
3845   }
3846   case ISD::FSQRT: // Need is known positive
3847   case ISD::FLOG:
3848   case ISD::FLOG2:
3849   case ISD::FLOG10:
3850   case ISD::FPOWI:
3851   case ISD::FPOW: {
3852     if (SNaN)
3853       return true;
3854     // TODO: Refine on operand
3855     return false;
3856   }
3857   case ISD::FMINNUM:
3858   case ISD::FMAXNUM: {
3859     // Only one needs to be known not-nan, since it will be returned if the
3860     // other ends up being one.
3861     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
3862            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
3863   }
3864   case ISD::FMINNUM_IEEE:
3865   case ISD::FMAXNUM_IEEE: {
3866     if (SNaN)
3867       return true;
3868     // This can return a NaN if either operand is an sNaN, or if both operands
3869     // are NaN.
3870     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
3871             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
3872            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
3873             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
3874   }
3875   case ISD::FMINIMUM:
3876   case ISD::FMAXIMUM: {
3877     // TODO: Does this quiet or return the origina NaN as-is?
3878     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
3879            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
3880   }
3881   case ISD::EXTRACT_VECTOR_ELT: {
3882     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
3883   }
3884   default:
3885     if (Opcode >= ISD::BUILTIN_OP_END ||
3886         Opcode == ISD::INTRINSIC_WO_CHAIN ||
3887         Opcode == ISD::INTRINSIC_W_CHAIN ||
3888         Opcode == ISD::INTRINSIC_VOID) {
3889       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
3890     }
3891 
3892     return false;
3893   }
3894 }
3895 
3896 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
3897   assert(Op.getValueType().isFloatingPoint() &&
3898          "Floating point type expected");
3899 
3900   // If the value is a constant, we can obviously see if it is a zero or not.
3901   // TODO: Add BuildVector support.
3902   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
3903     return !C->isZero();
3904   return false;
3905 }
3906 
3907 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
3908   assert(!Op.getValueType().isFloatingPoint() &&
3909          "Floating point types unsupported - use isKnownNeverZeroFloat");
3910 
3911   // If the value is a constant, we can obviously see if it is a zero or not.
3912   if (ISD::matchUnaryPredicate(
3913           Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
3914     return true;
3915 
3916   // TODO: Recognize more cases here.
3917   switch (Op.getOpcode()) {
3918   default: break;
3919   case ISD::OR:
3920     if (isKnownNeverZero(Op.getOperand(1)) ||
3921         isKnownNeverZero(Op.getOperand(0)))
3922       return true;
3923     break;
3924   }
3925 
3926   return false;
3927 }
3928 
3929 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
3930   // Check the obvious case.
3931   if (A == B) return true;
3932 
3933   // For for negative and positive zero.
3934   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
3935     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
3936       if (CA->isZero() && CB->isZero()) return true;
3937 
3938   // Otherwise they may not be equal.
3939   return false;
3940 }
3941 
3942 // FIXME: unify with llvm::haveNoCommonBitsSet.
3943 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
3944 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
3945   assert(A.getValueType() == B.getValueType() &&
3946          "Values must have the same type");
3947   return (computeKnownBits(A).Zero | computeKnownBits(B).Zero).isAllOnesValue();
3948 }
3949 
3950 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
3951                                 ArrayRef<SDValue> Ops,
3952                                 SelectionDAG &DAG) {
3953   int NumOps = Ops.size();
3954   assert(NumOps != 0 && "Can't build an empty vector!");
3955   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
3956          "Incorrect element count in BUILD_VECTOR!");
3957 
3958   // BUILD_VECTOR of UNDEFs is UNDEF.
3959   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
3960     return DAG.getUNDEF(VT);
3961 
3962   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
3963   SDValue IdentitySrc;
3964   bool IsIdentity = true;
3965   for (int i = 0; i != NumOps; ++i) {
3966     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
3967         Ops[i].getOperand(0).getValueType() != VT ||
3968         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
3969         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
3970         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
3971       IsIdentity = false;
3972       break;
3973     }
3974     IdentitySrc = Ops[i].getOperand(0);
3975   }
3976   if (IsIdentity)
3977     return IdentitySrc;
3978 
3979   return SDValue();
3980 }
3981 
3982 static SDValue FoldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
3983                                   ArrayRef<SDValue> Ops,
3984                                   SelectionDAG &DAG) {
3985   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
3986   assert(llvm::all_of(Ops,
3987                       [Ops](SDValue Op) {
3988                         return Ops[0].getValueType() == Op.getValueType();
3989                       }) &&
3990          "Concatenation of vectors with inconsistent value types!");
3991   assert((Ops.size() * Ops[0].getValueType().getVectorNumElements()) ==
3992              VT.getVectorNumElements() &&
3993          "Incorrect element count in vector concatenation!");
3994 
3995   if (Ops.size() == 1)
3996     return Ops[0];
3997 
3998   // Concat of UNDEFs is UNDEF.
3999   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4000     return DAG.getUNDEF(VT);
4001 
4002   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4003   // simplified to one big BUILD_VECTOR.
4004   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4005   EVT SVT = VT.getScalarType();
4006   SmallVector<SDValue, 16> Elts;
4007   for (SDValue Op : Ops) {
4008     EVT OpVT = Op.getValueType();
4009     if (Op.isUndef())
4010       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4011     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4012       Elts.append(Op->op_begin(), Op->op_end());
4013     else
4014       return SDValue();
4015   }
4016 
4017   // BUILD_VECTOR requires all inputs to be of the same type, find the
4018   // maximum type and extend them all.
4019   for (SDValue Op : Elts)
4020     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4021 
4022   if (SVT.bitsGT(VT.getScalarType()))
4023     for (SDValue &Op : Elts)
4024       Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4025                ? DAG.getZExtOrTrunc(Op, DL, SVT)
4026                : DAG.getSExtOrTrunc(Op, DL, SVT);
4027 
4028   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4029   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4030   return V;
4031 }
4032 
4033 /// Gets or creates the specified node.
4034 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4035   FoldingSetNodeID ID;
4036   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4037   void *IP = nullptr;
4038   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4039     return SDValue(E, 0);
4040 
4041   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4042                               getVTList(VT));
4043   CSEMap.InsertNode(N, IP);
4044 
4045   InsertNode(N);
4046   SDValue V = SDValue(N, 0);
4047   NewSDValueDbgMsg(V, "Creating new node: ", this);
4048   return V;
4049 }
4050 
4051 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4052                               SDValue Operand, const SDNodeFlags Flags) {
4053   // Constant fold unary operations with an integer constant operand. Even
4054   // opaque constant will be folded, because the folding of unary operations
4055   // doesn't create new constants with different values. Nevertheless, the
4056   // opaque flag is preserved during folding to prevent future folding with
4057   // other constants.
4058   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4059     const APInt &Val = C->getAPIntValue();
4060     switch (Opcode) {
4061     default: break;
4062     case ISD::SIGN_EXTEND:
4063       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4064                          C->isTargetOpcode(), C->isOpaque());
4065     case ISD::TRUNCATE:
4066       if (C->isOpaque())
4067         break;
4068       LLVM_FALLTHROUGH;
4069     case ISD::ANY_EXTEND:
4070     case ISD::ZERO_EXTEND:
4071       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4072                          C->isTargetOpcode(), C->isOpaque());
4073     case ISD::UINT_TO_FP:
4074     case ISD::SINT_TO_FP: {
4075       APFloat apf(EVTToAPFloatSemantics(VT),
4076                   APInt::getNullValue(VT.getSizeInBits()));
4077       (void)apf.convertFromAPInt(Val,
4078                                  Opcode==ISD::SINT_TO_FP,
4079                                  APFloat::rmNearestTiesToEven);
4080       return getConstantFP(apf, DL, VT);
4081     }
4082     case ISD::BITCAST:
4083       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4084         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4085       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4086         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4087       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4088         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4089       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4090         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4091       break;
4092     case ISD::ABS:
4093       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4094                          C->isOpaque());
4095     case ISD::BITREVERSE:
4096       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4097                          C->isOpaque());
4098     case ISD::BSWAP:
4099       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4100                          C->isOpaque());
4101     case ISD::CTPOP:
4102       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4103                          C->isOpaque());
4104     case ISD::CTLZ:
4105     case ISD::CTLZ_ZERO_UNDEF:
4106       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4107                          C->isOpaque());
4108     case ISD::CTTZ:
4109     case ISD::CTTZ_ZERO_UNDEF:
4110       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4111                          C->isOpaque());
4112     case ISD::FP16_TO_FP: {
4113       bool Ignored;
4114       APFloat FPV(APFloat::IEEEhalf(),
4115                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4116 
4117       // This can return overflow, underflow, or inexact; we don't care.
4118       // FIXME need to be more flexible about rounding mode.
4119       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4120                         APFloat::rmNearestTiesToEven, &Ignored);
4121       return getConstantFP(FPV, DL, VT);
4122     }
4123     }
4124   }
4125 
4126   // Constant fold unary operations with a floating point constant operand.
4127   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4128     APFloat V = C->getValueAPF();    // make copy
4129     switch (Opcode) {
4130     case ISD::FNEG:
4131       V.changeSign();
4132       return getConstantFP(V, DL, VT);
4133     case ISD::FABS:
4134       V.clearSign();
4135       return getConstantFP(V, DL, VT);
4136     case ISD::FCEIL: {
4137       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4138       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4139         return getConstantFP(V, DL, VT);
4140       break;
4141     }
4142     case ISD::FTRUNC: {
4143       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4144       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4145         return getConstantFP(V, DL, VT);
4146       break;
4147     }
4148     case ISD::FFLOOR: {
4149       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4150       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4151         return getConstantFP(V, DL, VT);
4152       break;
4153     }
4154     case ISD::FP_EXTEND: {
4155       bool ignored;
4156       // This can return overflow, underflow, or inexact; we don't care.
4157       // FIXME need to be more flexible about rounding mode.
4158       (void)V.convert(EVTToAPFloatSemantics(VT),
4159                       APFloat::rmNearestTiesToEven, &ignored);
4160       return getConstantFP(V, DL, VT);
4161     }
4162     case ISD::FP_TO_SINT:
4163     case ISD::FP_TO_UINT: {
4164       bool ignored;
4165       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4166       // FIXME need to be more flexible about rounding mode.
4167       APFloat::opStatus s =
4168           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4169       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4170         break;
4171       return getConstant(IntVal, DL, VT);
4172     }
4173     case ISD::BITCAST:
4174       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4175         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4176       else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4177         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4178       else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4179         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4180       break;
4181     case ISD::FP_TO_FP16: {
4182       bool Ignored;
4183       // This can return overflow, underflow, or inexact; we don't care.
4184       // FIXME need to be more flexible about rounding mode.
4185       (void)V.convert(APFloat::IEEEhalf(),
4186                       APFloat::rmNearestTiesToEven, &Ignored);
4187       return getConstant(V.bitcastToAPInt(), DL, VT);
4188     }
4189     }
4190   }
4191 
4192   // Constant fold unary operations with a vector integer or float operand.
4193   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
4194     if (BV->isConstant()) {
4195       switch (Opcode) {
4196       default:
4197         // FIXME: Entirely reasonable to perform folding of other unary
4198         // operations here as the need arises.
4199         break;
4200       case ISD::FNEG:
4201       case ISD::FABS:
4202       case ISD::FCEIL:
4203       case ISD::FTRUNC:
4204       case ISD::FFLOOR:
4205       case ISD::FP_EXTEND:
4206       case ISD::FP_TO_SINT:
4207       case ISD::FP_TO_UINT:
4208       case ISD::TRUNCATE:
4209       case ISD::ANY_EXTEND:
4210       case ISD::ZERO_EXTEND:
4211       case ISD::SIGN_EXTEND:
4212       case ISD::UINT_TO_FP:
4213       case ISD::SINT_TO_FP:
4214       case ISD::ABS:
4215       case ISD::BITREVERSE:
4216       case ISD::BSWAP:
4217       case ISD::CTLZ:
4218       case ISD::CTLZ_ZERO_UNDEF:
4219       case ISD::CTTZ:
4220       case ISD::CTTZ_ZERO_UNDEF:
4221       case ISD::CTPOP: {
4222         SDValue Ops = { Operand };
4223         if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4224           return Fold;
4225       }
4226       }
4227     }
4228   }
4229 
4230   unsigned OpOpcode = Operand.getNode()->getOpcode();
4231   switch (Opcode) {
4232   case ISD::TokenFactor:
4233   case ISD::MERGE_VALUES:
4234   case ISD::CONCAT_VECTORS:
4235     return Operand;         // Factor, merge or concat of one node?  No need.
4236   case ISD::BUILD_VECTOR: {
4237     // Attempt to simplify BUILD_VECTOR.
4238     SDValue Ops[] = {Operand};
4239     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4240       return V;
4241     break;
4242   }
4243   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4244   case ISD::FP_EXTEND:
4245     assert(VT.isFloatingPoint() &&
4246            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4247     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4248     assert((!VT.isVector() ||
4249             VT.getVectorNumElements() ==
4250             Operand.getValueType().getVectorNumElements()) &&
4251            "Vector element count mismatch!");
4252     assert(Operand.getValueType().bitsLT(VT) &&
4253            "Invalid fpext node, dst < src!");
4254     if (Operand.isUndef())
4255       return getUNDEF(VT);
4256     break;
4257   case ISD::SIGN_EXTEND:
4258     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4259            "Invalid SIGN_EXTEND!");
4260     if (Operand.getValueType() == VT) return Operand;   // noop extension
4261     assert((!VT.isVector() ||
4262             VT.getVectorNumElements() ==
4263             Operand.getValueType().getVectorNumElements()) &&
4264            "Vector element count mismatch!");
4265     assert(Operand.getValueType().bitsLT(VT) &&
4266            "Invalid sext node, dst < src!");
4267     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4268       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4269     else if (OpOpcode == ISD::UNDEF)
4270       // sext(undef) = 0, because the top bits will all be the same.
4271       return getConstant(0, DL, VT);
4272     break;
4273   case ISD::ZERO_EXTEND:
4274     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4275            "Invalid ZERO_EXTEND!");
4276     if (Operand.getValueType() == VT) return Operand;   // noop extension
4277     assert((!VT.isVector() ||
4278             VT.getVectorNumElements() ==
4279             Operand.getValueType().getVectorNumElements()) &&
4280            "Vector element count mismatch!");
4281     assert(Operand.getValueType().bitsLT(VT) &&
4282            "Invalid zext node, dst < src!");
4283     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
4284       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4285     else if (OpOpcode == ISD::UNDEF)
4286       // zext(undef) = 0, because the top bits will be zero.
4287       return getConstant(0, DL, VT);
4288     break;
4289   case ISD::ANY_EXTEND:
4290     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4291            "Invalid ANY_EXTEND!");
4292     if (Operand.getValueType() == VT) return Operand;   // noop extension
4293     assert((!VT.isVector() ||
4294             VT.getVectorNumElements() ==
4295             Operand.getValueType().getVectorNumElements()) &&
4296            "Vector element count mismatch!");
4297     assert(Operand.getValueType().bitsLT(VT) &&
4298            "Invalid anyext node, dst < src!");
4299 
4300     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4301         OpOpcode == ISD::ANY_EXTEND)
4302       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
4303       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4304     else if (OpOpcode == ISD::UNDEF)
4305       return getUNDEF(VT);
4306 
4307     // (ext (trunc x)) -> x
4308     if (OpOpcode == ISD::TRUNCATE) {
4309       SDValue OpOp = Operand.getOperand(0);
4310       if (OpOp.getValueType() == VT) {
4311         transferDbgValues(Operand, OpOp);
4312         return OpOp;
4313       }
4314     }
4315     break;
4316   case ISD::TRUNCATE:
4317     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4318            "Invalid TRUNCATE!");
4319     if (Operand.getValueType() == VT) return Operand;   // noop truncate
4320     assert((!VT.isVector() ||
4321             VT.getVectorNumElements() ==
4322             Operand.getValueType().getVectorNumElements()) &&
4323            "Vector element count mismatch!");
4324     assert(Operand.getValueType().bitsGT(VT) &&
4325            "Invalid truncate node, src < dst!");
4326     if (OpOpcode == ISD::TRUNCATE)
4327       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4328     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4329         OpOpcode == ISD::ANY_EXTEND) {
4330       // If the source is smaller than the dest, we still need an extend.
4331       if (Operand.getOperand(0).getValueType().getScalarType()
4332             .bitsLT(VT.getScalarType()))
4333         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4334       if (Operand.getOperand(0).getValueType().bitsGT(VT))
4335         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4336       return Operand.getOperand(0);
4337     }
4338     if (OpOpcode == ISD::UNDEF)
4339       return getUNDEF(VT);
4340     break;
4341   case ISD::ANY_EXTEND_VECTOR_INREG:
4342   case ISD::ZERO_EXTEND_VECTOR_INREG:
4343   case ISD::SIGN_EXTEND_VECTOR_INREG:
4344     assert(VT.isVector() && "This DAG node is restricted to vector types.");
4345     assert(Operand.getValueType().bitsLE(VT) &&
4346            "The input must be the same size or smaller than the result.");
4347     assert(VT.getVectorNumElements() <
4348              Operand.getValueType().getVectorNumElements() &&
4349            "The destination vector type must have fewer lanes than the input.");
4350     break;
4351   case ISD::ABS:
4352     assert(VT.isInteger() && VT == Operand.getValueType() &&
4353            "Invalid ABS!");
4354     if (OpOpcode == ISD::UNDEF)
4355       return getUNDEF(VT);
4356     break;
4357   case ISD::BSWAP:
4358     assert(VT.isInteger() && VT == Operand.getValueType() &&
4359            "Invalid BSWAP!");
4360     assert((VT.getScalarSizeInBits() % 16 == 0) &&
4361            "BSWAP types must be a multiple of 16 bits!");
4362     if (OpOpcode == ISD::UNDEF)
4363       return getUNDEF(VT);
4364     break;
4365   case ISD::BITREVERSE:
4366     assert(VT.isInteger() && VT == Operand.getValueType() &&
4367            "Invalid BITREVERSE!");
4368     if (OpOpcode == ISD::UNDEF)
4369       return getUNDEF(VT);
4370     break;
4371   case ISD::BITCAST:
4372     // Basic sanity checking.
4373     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
4374            "Cannot BITCAST between types of different sizes!");
4375     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
4376     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
4377       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
4378     if (OpOpcode == ISD::UNDEF)
4379       return getUNDEF(VT);
4380     break;
4381   case ISD::SCALAR_TO_VECTOR:
4382     assert(VT.isVector() && !Operand.getValueType().isVector() &&
4383            (VT.getVectorElementType() == Operand.getValueType() ||
4384             (VT.getVectorElementType().isInteger() &&
4385              Operand.getValueType().isInteger() &&
4386              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
4387            "Illegal SCALAR_TO_VECTOR node!");
4388     if (OpOpcode == ISD::UNDEF)
4389       return getUNDEF(VT);
4390     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4391     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
4392         isa<ConstantSDNode>(Operand.getOperand(1)) &&
4393         Operand.getConstantOperandVal(1) == 0 &&
4394         Operand.getOperand(0).getValueType() == VT)
4395       return Operand.getOperand(0);
4396     break;
4397   case ISD::FNEG:
4398     // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
4399     if ((getTarget().Options.UnsafeFPMath || Flags.hasNoSignedZeros()) &&
4400         OpOpcode == ISD::FSUB)
4401       return getNode(ISD::FSUB, DL, VT, Operand.getOperand(1),
4402                      Operand.getOperand(0), Flags);
4403     if (OpOpcode == ISD::FNEG)  // --X -> X
4404       return Operand.getOperand(0);
4405     break;
4406   case ISD::FABS:
4407     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
4408       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
4409     break;
4410   }
4411 
4412   SDNode *N;
4413   SDVTList VTs = getVTList(VT);
4414   SDValue Ops[] = {Operand};
4415   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
4416     FoldingSetNodeID ID;
4417     AddNodeIDNode(ID, Opcode, VTs, Ops);
4418     void *IP = nullptr;
4419     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4420       E->intersectFlagsWith(Flags);
4421       return SDValue(E, 0);
4422     }
4423 
4424     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4425     N->setFlags(Flags);
4426     createOperands(N, Ops);
4427     CSEMap.InsertNode(N, IP);
4428   } else {
4429     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4430     createOperands(N, Ops);
4431   }
4432 
4433   InsertNode(N);
4434   SDValue V = SDValue(N, 0);
4435   NewSDValueDbgMsg(V, "Creating new node: ", this);
4436   return V;
4437 }
4438 
4439 static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
4440                                         const APInt &C2) {
4441   switch (Opcode) {
4442   case ISD::ADD:  return std::make_pair(C1 + C2, true);
4443   case ISD::SUB:  return std::make_pair(C1 - C2, true);
4444   case ISD::MUL:  return std::make_pair(C1 * C2, true);
4445   case ISD::AND:  return std::make_pair(C1 & C2, true);
4446   case ISD::OR:   return std::make_pair(C1 | C2, true);
4447   case ISD::XOR:  return std::make_pair(C1 ^ C2, true);
4448   case ISD::SHL:  return std::make_pair(C1 << C2, true);
4449   case ISD::SRL:  return std::make_pair(C1.lshr(C2), true);
4450   case ISD::SRA:  return std::make_pair(C1.ashr(C2), true);
4451   case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
4452   case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
4453   case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
4454   case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
4455   case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
4456   case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
4457   case ISD::UDIV:
4458     if (!C2.getBoolValue())
4459       break;
4460     return std::make_pair(C1.udiv(C2), true);
4461   case ISD::UREM:
4462     if (!C2.getBoolValue())
4463       break;
4464     return std::make_pair(C1.urem(C2), true);
4465   case ISD::SDIV:
4466     if (!C2.getBoolValue())
4467       break;
4468     return std::make_pair(C1.sdiv(C2), true);
4469   case ISD::SREM:
4470     if (!C2.getBoolValue())
4471       break;
4472     return std::make_pair(C1.srem(C2), true);
4473   }
4474   return std::make_pair(APInt(1, 0), false);
4475 }
4476 
4477 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
4478                                              EVT VT, const ConstantSDNode *Cst1,
4479                                              const ConstantSDNode *Cst2) {
4480   if (Cst1->isOpaque() || Cst2->isOpaque())
4481     return SDValue();
4482 
4483   std::pair<APInt, bool> Folded = FoldValue(Opcode, Cst1->getAPIntValue(),
4484                                             Cst2->getAPIntValue());
4485   if (!Folded.second)
4486     return SDValue();
4487   return getConstant(Folded.first, DL, VT);
4488 }
4489 
4490 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
4491                                        const GlobalAddressSDNode *GA,
4492                                        const SDNode *N2) {
4493   if (GA->getOpcode() != ISD::GlobalAddress)
4494     return SDValue();
4495   if (!TLI->isOffsetFoldingLegal(GA))
4496     return SDValue();
4497   const ConstantSDNode *Cst2 = dyn_cast<ConstantSDNode>(N2);
4498   if (!Cst2)
4499     return SDValue();
4500   int64_t Offset = Cst2->getSExtValue();
4501   switch (Opcode) {
4502   case ISD::ADD: break;
4503   case ISD::SUB: Offset = -uint64_t(Offset); break;
4504   default: return SDValue();
4505   }
4506   return getGlobalAddress(GA->getGlobal(), SDLoc(Cst2), VT,
4507                           GA->getOffset() + uint64_t(Offset));
4508 }
4509 
4510 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
4511   switch (Opcode) {
4512   case ISD::SDIV:
4513   case ISD::UDIV:
4514   case ISD::SREM:
4515   case ISD::UREM: {
4516     // If a divisor is zero/undef or any element of a divisor vector is
4517     // zero/undef, the whole op is undef.
4518     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
4519     SDValue Divisor = Ops[1];
4520     if (Divisor.isUndef() || isNullConstant(Divisor))
4521       return true;
4522 
4523     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
4524            llvm::any_of(Divisor->op_values(),
4525                         [](SDValue V) { return V.isUndef() ||
4526                                         isNullConstant(V); });
4527     // TODO: Handle signed overflow.
4528   }
4529   // TODO: Handle oversized shifts.
4530   default:
4531     return false;
4532   }
4533 }
4534 
4535 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
4536                                              EVT VT, SDNode *Cst1,
4537                                              SDNode *Cst2) {
4538   // If the opcode is a target-specific ISD node, there's nothing we can
4539   // do here and the operand rules may not line up with the below, so
4540   // bail early.
4541   if (Opcode >= ISD::BUILTIN_OP_END)
4542     return SDValue();
4543 
4544   if (isUndef(Opcode, {SDValue(Cst1, 0), SDValue(Cst2, 0)}))
4545     return getUNDEF(VT);
4546 
4547   // Handle the case of two scalars.
4548   if (const ConstantSDNode *Scalar1 = dyn_cast<ConstantSDNode>(Cst1)) {
4549     if (const ConstantSDNode *Scalar2 = dyn_cast<ConstantSDNode>(Cst2)) {
4550       SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, Scalar1, Scalar2);
4551       assert((!Folded || !VT.isVector()) &&
4552              "Can't fold vectors ops with scalar operands");
4553       return Folded;
4554     }
4555   }
4556 
4557   // fold (add Sym, c) -> Sym+c
4558   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst1))
4559     return FoldSymbolOffset(Opcode, VT, GA, Cst2);
4560   if (TLI->isCommutativeBinOp(Opcode))
4561     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Cst2))
4562       return FoldSymbolOffset(Opcode, VT, GA, Cst1);
4563 
4564   // For vectors, extract each constant element and fold them individually.
4565   // Either input may be an undef value.
4566   auto *BV1 = dyn_cast<BuildVectorSDNode>(Cst1);
4567   if (!BV1 && !Cst1->isUndef())
4568     return SDValue();
4569   auto *BV2 = dyn_cast<BuildVectorSDNode>(Cst2);
4570   if (!BV2 && !Cst2->isUndef())
4571     return SDValue();
4572   // If both operands are undef, that's handled the same way as scalars.
4573   if (!BV1 && !BV2)
4574     return SDValue();
4575 
4576   assert((!BV1 || !BV2 || BV1->getNumOperands() == BV2->getNumOperands()) &&
4577          "Vector binop with different number of elements in operands?");
4578 
4579   EVT SVT = VT.getScalarType();
4580   EVT LegalSVT = SVT;
4581   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
4582     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
4583     if (LegalSVT.bitsLT(SVT))
4584       return SDValue();
4585   }
4586   SmallVector<SDValue, 4> Outputs;
4587   unsigned NumOps = BV1 ? BV1->getNumOperands() : BV2->getNumOperands();
4588   for (unsigned I = 0; I != NumOps; ++I) {
4589     SDValue V1 = BV1 ? BV1->getOperand(I) : getUNDEF(SVT);
4590     SDValue V2 = BV2 ? BV2->getOperand(I) : getUNDEF(SVT);
4591     if (SVT.isInteger()) {
4592       if (V1->getValueType(0).bitsGT(SVT))
4593         V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
4594       if (V2->getValueType(0).bitsGT(SVT))
4595         V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
4596     }
4597 
4598     if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
4599       return SDValue();
4600 
4601     // Fold one vector element.
4602     SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
4603     if (LegalSVT != SVT)
4604       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4605 
4606     // Scalar folding only succeeded if the result is a constant or UNDEF.
4607     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
4608         ScalarResult.getOpcode() != ISD::ConstantFP)
4609       return SDValue();
4610     Outputs.push_back(ScalarResult);
4611   }
4612 
4613   assert(VT.getVectorNumElements() == Outputs.size() &&
4614          "Vector size mismatch!");
4615 
4616   // We may have a vector type but a scalar result. Create a splat.
4617   Outputs.resize(VT.getVectorNumElements(), Outputs.back());
4618 
4619   // Build a big vector out of the scalar elements we generated.
4620   return getBuildVector(VT, SDLoc(), Outputs);
4621 }
4622 
4623 // TODO: Merge with FoldConstantArithmetic
4624 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
4625                                                    const SDLoc &DL, EVT VT,
4626                                                    ArrayRef<SDValue> Ops,
4627                                                    const SDNodeFlags Flags) {
4628   // If the opcode is a target-specific ISD node, there's nothing we can
4629   // do here and the operand rules may not line up with the below, so
4630   // bail early.
4631   if (Opcode >= ISD::BUILTIN_OP_END)
4632     return SDValue();
4633 
4634   if (isUndef(Opcode, Ops))
4635     return getUNDEF(VT);
4636 
4637   // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
4638   if (!VT.isVector())
4639     return SDValue();
4640 
4641   unsigned NumElts = VT.getVectorNumElements();
4642 
4643   auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
4644     return !Op.getValueType().isVector() ||
4645            Op.getValueType().getVectorNumElements() == NumElts;
4646   };
4647 
4648   auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
4649     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
4650     return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
4651            (BV && BV->isConstant());
4652   };
4653 
4654   // All operands must be vector types with the same number of elements as
4655   // the result type and must be either UNDEF or a build vector of constant
4656   // or UNDEF scalars.
4657   if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
4658       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
4659     return SDValue();
4660 
4661   // If we are comparing vectors, then the result needs to be a i1 boolean
4662   // that is then sign-extended back to the legal result type.
4663   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
4664 
4665   // Find legal integer scalar type for constant promotion and
4666   // ensure that its scalar size is at least as large as source.
4667   EVT LegalSVT = VT.getScalarType();
4668   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
4669     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
4670     if (LegalSVT.bitsLT(VT.getScalarType()))
4671       return SDValue();
4672   }
4673 
4674   // Constant fold each scalar lane separately.
4675   SmallVector<SDValue, 4> ScalarResults;
4676   for (unsigned i = 0; i != NumElts; i++) {
4677     SmallVector<SDValue, 4> ScalarOps;
4678     for (SDValue Op : Ops) {
4679       EVT InSVT = Op.getValueType().getScalarType();
4680       BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
4681       if (!InBV) {
4682         // We've checked that this is UNDEF or a constant of some kind.
4683         if (Op.isUndef())
4684           ScalarOps.push_back(getUNDEF(InSVT));
4685         else
4686           ScalarOps.push_back(Op);
4687         continue;
4688       }
4689 
4690       SDValue ScalarOp = InBV->getOperand(i);
4691       EVT ScalarVT = ScalarOp.getValueType();
4692 
4693       // Build vector (integer) scalar operands may need implicit
4694       // truncation - do this before constant folding.
4695       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
4696         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
4697 
4698       ScalarOps.push_back(ScalarOp);
4699     }
4700 
4701     // Constant fold the scalar operands.
4702     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
4703 
4704     // Legalize the (integer) scalar constant if necessary.
4705     if (LegalSVT != SVT)
4706       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
4707 
4708     // Scalar folding only succeeded if the result is a constant or UNDEF.
4709     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
4710         ScalarResult.getOpcode() != ISD::ConstantFP)
4711       return SDValue();
4712     ScalarResults.push_back(ScalarResult);
4713   }
4714 
4715   SDValue V = getBuildVector(VT, DL, ScalarResults);
4716   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
4717   return V;
4718 }
4719 
4720 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4721                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
4722   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4723   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4724   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4725   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
4726 
4727   // Canonicalize constant to RHS if commutative.
4728   if (TLI->isCommutativeBinOp(Opcode)) {
4729     if (N1C && !N2C) {
4730       std::swap(N1C, N2C);
4731       std::swap(N1, N2);
4732     } else if (N1CFP && !N2CFP) {
4733       std::swap(N1CFP, N2CFP);
4734       std::swap(N1, N2);
4735     }
4736   }
4737 
4738   switch (Opcode) {
4739   default: break;
4740   case ISD::TokenFactor:
4741     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
4742            N2.getValueType() == MVT::Other && "Invalid token factor!");
4743     // Fold trivial token factors.
4744     if (N1.getOpcode() == ISD::EntryToken) return N2;
4745     if (N2.getOpcode() == ISD::EntryToken) return N1;
4746     if (N1 == N2) return N1;
4747     break;
4748   case ISD::BUILD_VECTOR: {
4749     // Attempt to simplify BUILD_VECTOR.
4750     SDValue Ops[] = {N1, N2};
4751     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4752       return V;
4753     break;
4754   }
4755   case ISD::CONCAT_VECTORS: {
4756     // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
4757     SDValue Ops[] = {N1, N2};
4758     if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
4759       return V;
4760     break;
4761   }
4762   case ISD::AND:
4763     assert(VT.isInteger() && "This operator does not apply to FP types!");
4764     assert(N1.getValueType() == N2.getValueType() &&
4765            N1.getValueType() == VT && "Binary operator types must match!");
4766     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
4767     // worth handling here.
4768     if (N2C && N2C->isNullValue())
4769       return N2;
4770     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
4771       return N1;
4772     break;
4773   case ISD::OR:
4774   case ISD::XOR:
4775   case ISD::ADD:
4776   case ISD::SUB:
4777     assert(VT.isInteger() && "This operator does not apply to FP types!");
4778     assert(N1.getValueType() == N2.getValueType() &&
4779            N1.getValueType() == VT && "Binary operator types must match!");
4780     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
4781     // it's worth handling here.
4782     if (N2C && N2C->isNullValue())
4783       return N1;
4784     break;
4785   case ISD::UDIV:
4786   case ISD::UREM:
4787   case ISD::MULHU:
4788   case ISD::MULHS:
4789   case ISD::MUL:
4790   case ISD::SDIV:
4791   case ISD::SREM:
4792   case ISD::SMIN:
4793   case ISD::SMAX:
4794   case ISD::UMIN:
4795   case ISD::UMAX:
4796     assert(VT.isInteger() && "This operator does not apply to FP types!");
4797     assert(N1.getValueType() == N2.getValueType() &&
4798            N1.getValueType() == VT && "Binary operator types must match!");
4799     break;
4800   case ISD::FADD:
4801   case ISD::FSUB:
4802   case ISD::FMUL:
4803   case ISD::FDIV:
4804   case ISD::FREM:
4805     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
4806     assert(N1.getValueType() == N2.getValueType() &&
4807            N1.getValueType() == VT && "Binary operator types must match!");
4808     break;
4809   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
4810     assert(N1.getValueType() == VT &&
4811            N1.getValueType().isFloatingPoint() &&
4812            N2.getValueType().isFloatingPoint() &&
4813            "Invalid FCOPYSIGN!");
4814     break;
4815   case ISD::SHL:
4816   case ISD::SRA:
4817   case ISD::SRL:
4818     if (SDValue V = simplifyShift(N1, N2))
4819       return V;
4820     LLVM_FALLTHROUGH;
4821   case ISD::ROTL:
4822   case ISD::ROTR:
4823     assert(VT == N1.getValueType() &&
4824            "Shift operators return type must be the same as their first arg");
4825     assert(VT.isInteger() && N2.getValueType().isInteger() &&
4826            "Shifts only work on integers");
4827     assert((!VT.isVector() || VT == N2.getValueType()) &&
4828            "Vector shift amounts must be in the same as their first arg");
4829     // Verify that the shift amount VT is big enough to hold valid shift
4830     // amounts.  This catches things like trying to shift an i1024 value by an
4831     // i8, which is easy to fall into in generic code that uses
4832     // TLI.getShiftAmount().
4833     assert(N2.getValueSizeInBits() >= Log2_32_Ceil(N1.getValueSizeInBits()) &&
4834            "Invalid use of small shift amount with oversized value!");
4835 
4836     // Always fold shifts of i1 values so the code generator doesn't need to
4837     // handle them.  Since we know the size of the shift has to be less than the
4838     // size of the value, the shift/rotate count is guaranteed to be zero.
4839     if (VT == MVT::i1)
4840       return N1;
4841     if (N2C && N2C->isNullValue())
4842       return N1;
4843     break;
4844   case ISD::FP_ROUND_INREG: {
4845     EVT EVT = cast<VTSDNode>(N2)->getVT();
4846     assert(VT == N1.getValueType() && "Not an inreg round!");
4847     assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
4848            "Cannot FP_ROUND_INREG integer types");
4849     assert(EVT.isVector() == VT.isVector() &&
4850            "FP_ROUND_INREG type should be vector iff the operand "
4851            "type is vector!");
4852     assert((!EVT.isVector() ||
4853             EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4854            "Vector element counts must match in FP_ROUND_INREG");
4855     assert(EVT.bitsLE(VT) && "Not rounding down!");
4856     (void)EVT;
4857     if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
4858     break;
4859   }
4860   case ISD::FP_ROUND:
4861     assert(VT.isFloatingPoint() &&
4862            N1.getValueType().isFloatingPoint() &&
4863            VT.bitsLE(N1.getValueType()) &&
4864            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
4865            "Invalid FP_ROUND!");
4866     if (N1.getValueType() == VT) return N1;  // noop conversion.
4867     break;
4868   case ISD::AssertSext:
4869   case ISD::AssertZext: {
4870     EVT EVT = cast<VTSDNode>(N2)->getVT();
4871     assert(VT == N1.getValueType() && "Not an inreg extend!");
4872     assert(VT.isInteger() && EVT.isInteger() &&
4873            "Cannot *_EXTEND_INREG FP types");
4874     assert(!EVT.isVector() &&
4875            "AssertSExt/AssertZExt type should be the vector element type "
4876            "rather than the vector type!");
4877     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
4878     if (VT.getScalarType() == EVT) return N1; // noop assertion.
4879     break;
4880   }
4881   case ISD::SIGN_EXTEND_INREG: {
4882     EVT EVT = cast<VTSDNode>(N2)->getVT();
4883     assert(VT == N1.getValueType() && "Not an inreg extend!");
4884     assert(VT.isInteger() && EVT.isInteger() &&
4885            "Cannot *_EXTEND_INREG FP types");
4886     assert(EVT.isVector() == VT.isVector() &&
4887            "SIGN_EXTEND_INREG type should be vector iff the operand "
4888            "type is vector!");
4889     assert((!EVT.isVector() ||
4890             EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
4891            "Vector element counts must match in SIGN_EXTEND_INREG");
4892     assert(EVT.bitsLE(VT) && "Not extending!");
4893     if (EVT == VT) return N1;  // Not actually extending
4894 
4895     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
4896       unsigned FromBits = EVT.getScalarSizeInBits();
4897       Val <<= Val.getBitWidth() - FromBits;
4898       Val.ashrInPlace(Val.getBitWidth() - FromBits);
4899       return getConstant(Val, DL, ConstantVT);
4900     };
4901 
4902     if (N1C) {
4903       const APInt &Val = N1C->getAPIntValue();
4904       return SignExtendInReg(Val, VT);
4905     }
4906     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
4907       SmallVector<SDValue, 8> Ops;
4908       llvm::EVT OpVT = N1.getOperand(0).getValueType();
4909       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
4910         SDValue Op = N1.getOperand(i);
4911         if (Op.isUndef()) {
4912           Ops.push_back(getUNDEF(OpVT));
4913           continue;
4914         }
4915         ConstantSDNode *C = cast<ConstantSDNode>(Op);
4916         APInt Val = C->getAPIntValue();
4917         Ops.push_back(SignExtendInReg(Val, OpVT));
4918       }
4919       return getBuildVector(VT, DL, Ops);
4920     }
4921     break;
4922   }
4923   case ISD::EXTRACT_VECTOR_ELT:
4924     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
4925            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
4926              element type of the vector.");
4927 
4928     // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
4929     if (N1.isUndef())
4930       return getUNDEF(VT);
4931 
4932     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
4933     if (N2C && N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
4934       return getUNDEF(VT);
4935 
4936     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
4937     // expanding copies of large vectors from registers.
4938     if (N2C &&
4939         N1.getOpcode() == ISD::CONCAT_VECTORS &&
4940         N1.getNumOperands() > 0) {
4941       unsigned Factor =
4942         N1.getOperand(0).getValueType().getVectorNumElements();
4943       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
4944                      N1.getOperand(N2C->getZExtValue() / Factor),
4945                      getConstant(N2C->getZExtValue() % Factor, DL,
4946                                  N2.getValueType()));
4947     }
4948 
4949     // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
4950     // expanding large vector constants.
4951     if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
4952       SDValue Elt = N1.getOperand(N2C->getZExtValue());
4953 
4954       if (VT != Elt.getValueType())
4955         // If the vector element type is not legal, the BUILD_VECTOR operands
4956         // are promoted and implicitly truncated, and the result implicitly
4957         // extended. Make that explicit here.
4958         Elt = getAnyExtOrTrunc(Elt, DL, VT);
4959 
4960       return Elt;
4961     }
4962 
4963     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
4964     // operations are lowered to scalars.
4965     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
4966       // If the indices are the same, return the inserted element else
4967       // if the indices are known different, extract the element from
4968       // the original vector.
4969       SDValue N1Op2 = N1.getOperand(2);
4970       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
4971 
4972       if (N1Op2C && N2C) {
4973         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
4974           if (VT == N1.getOperand(1).getValueType())
4975             return N1.getOperand(1);
4976           else
4977             return getSExtOrTrunc(N1.getOperand(1), DL, VT);
4978         }
4979 
4980         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
4981       }
4982     }
4983 
4984     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
4985     // when vector types are scalarized and v1iX is legal.
4986     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx)
4987     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
4988         N1.getValueType().getVectorNumElements() == 1) {
4989       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
4990                      N1.getOperand(1));
4991     }
4992     break;
4993   case ISD::EXTRACT_ELEMENT:
4994     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
4995     assert(!N1.getValueType().isVector() && !VT.isVector() &&
4996            (N1.getValueType().isInteger() == VT.isInteger()) &&
4997            N1.getValueType() != VT &&
4998            "Wrong types for EXTRACT_ELEMENT!");
4999 
5000     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5001     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5002     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5003     if (N1.getOpcode() == ISD::BUILD_PAIR)
5004       return N1.getOperand(N2C->getZExtValue());
5005 
5006     // EXTRACT_ELEMENT of a constant int is also very common.
5007     if (N1C) {
5008       unsigned ElementSize = VT.getSizeInBits();
5009       unsigned Shift = ElementSize * N2C->getZExtValue();
5010       APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
5011       return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
5012     }
5013     break;
5014   case ISD::EXTRACT_SUBVECTOR:
5015     if (VT.isSimple() && N1.getValueType().isSimple()) {
5016       assert(VT.isVector() && N1.getValueType().isVector() &&
5017              "Extract subvector VTs must be a vectors!");
5018       assert(VT.getVectorElementType() ==
5019              N1.getValueType().getVectorElementType() &&
5020              "Extract subvector VTs must have the same element type!");
5021       assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
5022              "Extract subvector must be from larger vector to smaller vector!");
5023 
5024       if (N2C) {
5025         assert((VT.getVectorNumElements() + N2C->getZExtValue()
5026                 <= N1.getValueType().getVectorNumElements())
5027                && "Extract subvector overflow!");
5028       }
5029 
5030       // Trivial extraction.
5031       if (VT.getSimpleVT() == N1.getSimpleValueType())
5032         return N1;
5033 
5034       // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5035       if (N1.isUndef())
5036         return getUNDEF(VT);
5037 
5038       // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5039       // the concat have the same type as the extract.
5040       if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
5041           N1.getNumOperands() > 0 &&
5042           VT == N1.getOperand(0).getValueType()) {
5043         unsigned Factor = VT.getVectorNumElements();
5044         return N1.getOperand(N2C->getZExtValue() / Factor);
5045       }
5046 
5047       // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5048       // during shuffle legalization.
5049       if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5050           VT == N1.getOperand(1).getValueType())
5051         return N1.getOperand(1);
5052     }
5053     break;
5054   }
5055 
5056   // Perform trivial constant folding.
5057   if (SDValue SV =
5058           FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
5059     return SV;
5060 
5061   // Constant fold FP operations.
5062   bool HasFPExceptions = TLI->hasFloatingPointExceptions();
5063   if (N1CFP) {
5064     if (N2CFP) {
5065       APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
5066       APFloat::opStatus s;
5067       switch (Opcode) {
5068       case ISD::FADD:
5069         s = V1.add(V2, APFloat::rmNearestTiesToEven);
5070         if (!HasFPExceptions || s != APFloat::opInvalidOp)
5071           return getConstantFP(V1, DL, VT);
5072         break;
5073       case ISD::FSUB:
5074         s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
5075         if (!HasFPExceptions || s!=APFloat::opInvalidOp)
5076           return getConstantFP(V1, DL, VT);
5077         break;
5078       case ISD::FMUL:
5079         s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
5080         if (!HasFPExceptions || s!=APFloat::opInvalidOp)
5081           return getConstantFP(V1, DL, VT);
5082         break;
5083       case ISD::FDIV:
5084         s = V1.divide(V2, APFloat::rmNearestTiesToEven);
5085         if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
5086                                  s!=APFloat::opDivByZero)) {
5087           return getConstantFP(V1, DL, VT);
5088         }
5089         break;
5090       case ISD::FREM :
5091         s = V1.mod(V2);
5092         if (!HasFPExceptions || (s!=APFloat::opInvalidOp &&
5093                                  s!=APFloat::opDivByZero)) {
5094           return getConstantFP(V1, DL, VT);
5095         }
5096         break;
5097       case ISD::FCOPYSIGN:
5098         V1.copySign(V2);
5099         return getConstantFP(V1, DL, VT);
5100       default: break;
5101       }
5102     }
5103 
5104     if (Opcode == ISD::FP_ROUND) {
5105       APFloat V = N1CFP->getValueAPF();    // make copy
5106       bool ignored;
5107       // This can return overflow, underflow, or inexact; we don't care.
5108       // FIXME need to be more flexible about rounding mode.
5109       (void)V.convert(EVTToAPFloatSemantics(VT),
5110                       APFloat::rmNearestTiesToEven, &ignored);
5111       return getConstantFP(V, DL, VT);
5112     }
5113   }
5114 
5115   switch (Opcode) {
5116   case ISD::FADD:
5117   case ISD::FSUB:
5118   case ISD::FMUL:
5119   case ISD::FDIV:
5120   case ISD::FREM:
5121     // If both operands are undef, the result is undef. If 1 operand is undef,
5122     // the result is NaN. This should match the behavior of the IR optimizer.
5123     if (N1.isUndef() && N2.isUndef())
5124       return getUNDEF(VT);
5125     if (N1.isUndef() || N2.isUndef())
5126       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5127   }
5128 
5129   // Canonicalize an UNDEF to the RHS, even over a constant.
5130   if (N1.isUndef()) {
5131     if (TLI->isCommutativeBinOp(Opcode)) {
5132       std::swap(N1, N2);
5133     } else {
5134       switch (Opcode) {
5135       case ISD::FP_ROUND_INREG:
5136       case ISD::SIGN_EXTEND_INREG:
5137       case ISD::SUB:
5138         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
5139       case ISD::UDIV:
5140       case ISD::SDIV:
5141       case ISD::UREM:
5142       case ISD::SREM:
5143         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
5144       }
5145     }
5146   }
5147 
5148   // Fold a bunch of operators when the RHS is undef.
5149   if (N2.isUndef()) {
5150     switch (Opcode) {
5151     case ISD::XOR:
5152       if (N1.isUndef())
5153         // Handle undef ^ undef -> 0 special case. This is a common
5154         // idiom (misuse).
5155         return getConstant(0, DL, VT);
5156       LLVM_FALLTHROUGH;
5157     case ISD::ADD:
5158     case ISD::SUB:
5159     case ISD::UDIV:
5160     case ISD::SDIV:
5161     case ISD::UREM:
5162     case ISD::SREM:
5163       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
5164     case ISD::MUL:
5165     case ISD::AND:
5166       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
5167     case ISD::OR:
5168       return getAllOnesConstant(DL, VT);
5169     }
5170   }
5171 
5172   // Memoize this node if possible.
5173   SDNode *N;
5174   SDVTList VTs = getVTList(VT);
5175   SDValue Ops[] = {N1, N2};
5176   if (VT != MVT::Glue) {
5177     FoldingSetNodeID ID;
5178     AddNodeIDNode(ID, Opcode, VTs, Ops);
5179     void *IP = nullptr;
5180     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5181       E->intersectFlagsWith(Flags);
5182       return SDValue(E, 0);
5183     }
5184 
5185     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5186     N->setFlags(Flags);
5187     createOperands(N, Ops);
5188     CSEMap.InsertNode(N, IP);
5189   } else {
5190     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5191     createOperands(N, Ops);
5192   }
5193 
5194   InsertNode(N);
5195   SDValue V = SDValue(N, 0);
5196   NewSDValueDbgMsg(V, "Creating new node: ", this);
5197   return V;
5198 }
5199 
5200 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5201                               SDValue N1, SDValue N2, SDValue N3,
5202                               const SDNodeFlags Flags) {
5203   // Perform various simplifications.
5204   switch (Opcode) {
5205   case ISD::FMA: {
5206     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5207     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
5208            N3.getValueType() == VT && "FMA types must match!");
5209     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5210     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5211     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
5212     if (N1CFP && N2CFP && N3CFP) {
5213       APFloat  V1 = N1CFP->getValueAPF();
5214       const APFloat &V2 = N2CFP->getValueAPF();
5215       const APFloat &V3 = N3CFP->getValueAPF();
5216       APFloat::opStatus s =
5217         V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
5218       if (!TLI->hasFloatingPointExceptions() || s != APFloat::opInvalidOp)
5219         return getConstantFP(V1, DL, VT);
5220     }
5221     break;
5222   }
5223   case ISD::BUILD_VECTOR: {
5224     // Attempt to simplify BUILD_VECTOR.
5225     SDValue Ops[] = {N1, N2, N3};
5226     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5227       return V;
5228     break;
5229   }
5230   case ISD::CONCAT_VECTORS: {
5231     // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
5232     SDValue Ops[] = {N1, N2, N3};
5233     if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
5234       return V;
5235     break;
5236   }
5237   case ISD::SETCC: {
5238     assert(VT.isInteger() && "SETCC result type must be an integer!");
5239     assert(N1.getValueType() == N2.getValueType() &&
5240            "SETCC operands must have the same type!");
5241     assert(VT.isVector() == N1.getValueType().isVector() &&
5242            "SETCC type should be vector iff the operand type is vector!");
5243     assert((!VT.isVector() ||
5244             VT.getVectorNumElements() == N1.getValueType().getVectorNumElements()) &&
5245            "SETCC vector element counts must match!");
5246     // Use FoldSetCC to simplify SETCC's.
5247     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
5248       return V;
5249     // Vector constant folding.
5250     SDValue Ops[] = {N1, N2, N3};
5251     if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
5252       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
5253       return V;
5254     }
5255     break;
5256   }
5257   case ISD::SELECT:
5258   case ISD::VSELECT:
5259     if (SDValue V = simplifySelect(N1, N2, N3))
5260       return V;
5261     break;
5262   case ISD::VECTOR_SHUFFLE:
5263     llvm_unreachable("should use getVectorShuffle constructor!");
5264   case ISD::INSERT_VECTOR_ELT: {
5265     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
5266     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF
5267     if (N3C && N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
5268       return getUNDEF(VT);
5269     break;
5270   }
5271   case ISD::INSERT_SUBVECTOR: {
5272     SDValue Index = N3;
5273     if (VT.isSimple() && N1.getValueType().isSimple()
5274         && N2.getValueType().isSimple()) {
5275       assert(VT.isVector() && N1.getValueType().isVector() &&
5276              N2.getValueType().isVector() &&
5277              "Insert subvector VTs must be a vectors");
5278       assert(VT == N1.getValueType() &&
5279              "Dest and insert subvector source types must match!");
5280       assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
5281              "Insert subvector must be from smaller vector to larger vector!");
5282       if (isa<ConstantSDNode>(Index)) {
5283         assert((N2.getValueType().getVectorNumElements() +
5284                 cast<ConstantSDNode>(Index)->getZExtValue()
5285                 <= VT.getVectorNumElements())
5286                && "Insert subvector overflow!");
5287       }
5288 
5289       // Trivial insertion.
5290       if (VT.getSimpleVT() == N2.getSimpleValueType())
5291         return N2;
5292     }
5293     break;
5294   }
5295   case ISD::BITCAST:
5296     // Fold bit_convert nodes from a type to themselves.
5297     if (N1.getValueType() == VT)
5298       return N1;
5299     break;
5300   }
5301 
5302   // Memoize node if it doesn't produce a flag.
5303   SDNode *N;
5304   SDVTList VTs = getVTList(VT);
5305   SDValue Ops[] = {N1, N2, N3};
5306   if (VT != MVT::Glue) {
5307     FoldingSetNodeID ID;
5308     AddNodeIDNode(ID, Opcode, VTs, Ops);
5309     void *IP = nullptr;
5310     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5311       E->intersectFlagsWith(Flags);
5312       return SDValue(E, 0);
5313     }
5314 
5315     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5316     N->setFlags(Flags);
5317     createOperands(N, Ops);
5318     CSEMap.InsertNode(N, IP);
5319   } else {
5320     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5321     createOperands(N, Ops);
5322   }
5323 
5324   InsertNode(N);
5325   SDValue V = SDValue(N, 0);
5326   NewSDValueDbgMsg(V, "Creating new node: ", this);
5327   return V;
5328 }
5329 
5330 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5331                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
5332   SDValue Ops[] = { N1, N2, N3, N4 };
5333   return getNode(Opcode, DL, VT, Ops);
5334 }
5335 
5336 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5337                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
5338                               SDValue N5) {
5339   SDValue Ops[] = { N1, N2, N3, N4, N5 };
5340   return getNode(Opcode, DL, VT, Ops);
5341 }
5342 
5343 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
5344 /// the incoming stack arguments to be loaded from the stack.
5345 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
5346   SmallVector<SDValue, 8> ArgChains;
5347 
5348   // Include the original chain at the beginning of the list. When this is
5349   // used by target LowerCall hooks, this helps legalize find the
5350   // CALLSEQ_BEGIN node.
5351   ArgChains.push_back(Chain);
5352 
5353   // Add a chain value for each stack argument.
5354   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
5355        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
5356     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
5357       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
5358         if (FI->getIndex() < 0)
5359           ArgChains.push_back(SDValue(L, 1));
5360 
5361   // Build a tokenfactor for all the chains.
5362   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
5363 }
5364 
5365 /// getMemsetValue - Vectorized representation of the memset value
5366 /// operand.
5367 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
5368                               const SDLoc &dl) {
5369   assert(!Value.isUndef());
5370 
5371   unsigned NumBits = VT.getScalarSizeInBits();
5372   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
5373     assert(C->getAPIntValue().getBitWidth() == 8);
5374     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
5375     if (VT.isInteger()) {
5376       bool IsOpaque = VT.getSizeInBits() > 64 ||
5377           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
5378       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
5379     }
5380     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
5381                              VT);
5382   }
5383 
5384   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
5385   EVT IntVT = VT.getScalarType();
5386   if (!IntVT.isInteger())
5387     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
5388 
5389   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
5390   if (NumBits > 8) {
5391     // Use a multiplication with 0x010101... to extend the input to the
5392     // required length.
5393     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
5394     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
5395                         DAG.getConstant(Magic, dl, IntVT));
5396   }
5397 
5398   if (VT != Value.getValueType() && !VT.isInteger())
5399     Value = DAG.getBitcast(VT.getScalarType(), Value);
5400   if (VT != Value.getValueType())
5401     Value = DAG.getSplatBuildVector(VT, dl, Value);
5402 
5403   return Value;
5404 }
5405 
5406 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
5407 /// used when a memcpy is turned into a memset when the source is a constant
5408 /// string ptr.
5409 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
5410                                   const TargetLowering &TLI,
5411                                   const ConstantDataArraySlice &Slice) {
5412   // Handle vector with all elements zero.
5413   if (Slice.Array == nullptr) {
5414     if (VT.isInteger())
5415       return DAG.getConstant(0, dl, VT);
5416     else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
5417       return DAG.getConstantFP(0.0, dl, VT);
5418     else if (VT.isVector()) {
5419       unsigned NumElts = VT.getVectorNumElements();
5420       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5421       return DAG.getNode(ISD::BITCAST, dl, VT,
5422                          DAG.getConstant(0, dl,
5423                                          EVT::getVectorVT(*DAG.getContext(),
5424                                                           EltVT, NumElts)));
5425     } else
5426       llvm_unreachable("Expected type!");
5427   }
5428 
5429   assert(!VT.isVector() && "Can't handle vector type here!");
5430   unsigned NumVTBits = VT.getSizeInBits();
5431   unsigned NumVTBytes = NumVTBits / 8;
5432   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
5433 
5434   APInt Val(NumVTBits, 0);
5435   if (DAG.getDataLayout().isLittleEndian()) {
5436     for (unsigned i = 0; i != NumBytes; ++i)
5437       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
5438   } else {
5439     for (unsigned i = 0; i != NumBytes; ++i)
5440       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
5441   }
5442 
5443   // If the "cost" of materializing the integer immediate is less than the cost
5444   // of a load, then it is cost effective to turn the load into the immediate.
5445   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
5446   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
5447     return DAG.getConstant(Val, dl, VT);
5448   return SDValue(nullptr, 0);
5449 }
5450 
5451 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset,
5452                                            const SDLoc &DL) {
5453   EVT VT = Base.getValueType();
5454   return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT));
5455 }
5456 
5457 /// Returns true if memcpy source is constant data.
5458 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
5459   uint64_t SrcDelta = 0;
5460   GlobalAddressSDNode *G = nullptr;
5461   if (Src.getOpcode() == ISD::GlobalAddress)
5462     G = cast<GlobalAddressSDNode>(Src);
5463   else if (Src.getOpcode() == ISD::ADD &&
5464            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
5465            Src.getOperand(1).getOpcode() == ISD::Constant) {
5466     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
5467     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
5468   }
5469   if (!G)
5470     return false;
5471 
5472   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
5473                                   SrcDelta + G->getOffset());
5474 }
5475 
5476 /// Determines the optimal series of memory ops to replace the memset / memcpy.
5477 /// Return true if the number of memory ops is below the threshold (Limit).
5478 /// It returns the types of the sequence of memory ops to perform
5479 /// memset / memcpy by reference.
5480 static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
5481                                      unsigned Limit, uint64_t Size,
5482                                      unsigned DstAlign, unsigned SrcAlign,
5483                                      bool IsMemset,
5484                                      bool ZeroMemset,
5485                                      bool MemcpyStrSrc,
5486                                      bool AllowOverlap,
5487                                      unsigned DstAS, unsigned SrcAS,
5488                                      SelectionDAG &DAG,
5489                                      const TargetLowering &TLI) {
5490   assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
5491          "Expecting memcpy / memset source to meet alignment requirement!");
5492   // If 'SrcAlign' is zero, that means the memory operation does not need to
5493   // load the value, i.e. memset or memcpy from constant string. Otherwise,
5494   // it's the inferred alignment of the source. 'DstAlign', on the other hand,
5495   // is the specified alignment of the memory operation. If it is zero, that
5496   // means it's possible to change the alignment of the destination.
5497   // 'MemcpyStrSrc' indicates whether the memcpy source is constant so it does
5498   // not need to be loaded.
5499   EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
5500                                    IsMemset, ZeroMemset, MemcpyStrSrc,
5501                                    DAG.getMachineFunction());
5502 
5503   if (VT == MVT::Other) {
5504     // Use the largest integer type whose alignment constraints are satisfied.
5505     // We only need to check DstAlign here as SrcAlign is always greater or
5506     // equal to DstAlign (or zero).
5507     VT = MVT::i64;
5508     while (DstAlign && DstAlign < VT.getSizeInBits() / 8 &&
5509            !TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign))
5510       VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
5511     assert(VT.isInteger());
5512 
5513     // Find the largest legal integer type.
5514     MVT LVT = MVT::i64;
5515     while (!TLI.isTypeLegal(LVT))
5516       LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
5517     assert(LVT.isInteger());
5518 
5519     // If the type we've chosen is larger than the largest legal integer type
5520     // then use that instead.
5521     if (VT.bitsGT(LVT))
5522       VT = LVT;
5523   }
5524 
5525   unsigned NumMemOps = 0;
5526   while (Size != 0) {
5527     unsigned VTSize = VT.getSizeInBits() / 8;
5528     while (VTSize > Size) {
5529       // For now, only use non-vector load / store's for the left-over pieces.
5530       EVT NewVT = VT;
5531       unsigned NewVTSize;
5532 
5533       bool Found = false;
5534       if (VT.isVector() || VT.isFloatingPoint()) {
5535         NewVT = (VT.getSizeInBits() > 64) ? MVT::i64 : MVT::i32;
5536         if (TLI.isOperationLegalOrCustom(ISD::STORE, NewVT) &&
5537             TLI.isSafeMemOpType(NewVT.getSimpleVT()))
5538           Found = true;
5539         else if (NewVT == MVT::i64 &&
5540                  TLI.isOperationLegalOrCustom(ISD::STORE, MVT::f64) &&
5541                  TLI.isSafeMemOpType(MVT::f64)) {
5542           // i64 is usually not legal on 32-bit targets, but f64 may be.
5543           NewVT = MVT::f64;
5544           Found = true;
5545         }
5546       }
5547 
5548       if (!Found) {
5549         do {
5550           NewVT = (MVT::SimpleValueType)(NewVT.getSimpleVT().SimpleTy - 1);
5551           if (NewVT == MVT::i8)
5552             break;
5553         } while (!TLI.isSafeMemOpType(NewVT.getSimpleVT()));
5554       }
5555       NewVTSize = NewVT.getSizeInBits() / 8;
5556 
5557       // If the new VT cannot cover all of the remaining bits, then consider
5558       // issuing a (or a pair of) unaligned and overlapping load / store.
5559       bool Fast;
5560       if (NumMemOps && AllowOverlap && NewVTSize < Size &&
5561           TLI.allowsMisalignedMemoryAccesses(VT, DstAS, DstAlign, &Fast) &&
5562           Fast)
5563         VTSize = Size;
5564       else {
5565         VT = NewVT;
5566         VTSize = NewVTSize;
5567       }
5568     }
5569 
5570     if (++NumMemOps > Limit)
5571       return false;
5572 
5573     MemOps.push_back(VT);
5574     Size -= VTSize;
5575   }
5576 
5577   return true;
5578 }
5579 
5580 static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
5581   // On Darwin, -Os means optimize for size without hurting performance, so
5582   // only really optimize for size when -Oz (MinSize) is used.
5583   if (MF.getTarget().getTargetTriple().isOSDarwin())
5584     return MF.getFunction().optForMinSize();
5585   return MF.getFunction().optForSize();
5586 }
5587 
5588 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
5589                           SmallVector<SDValue, 32> &OutChains, unsigned From,
5590                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
5591                           SmallVector<SDValue, 16> &OutStoreChains) {
5592   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
5593   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
5594   SmallVector<SDValue, 16> GluedLoadChains;
5595   for (unsigned i = From; i < To; ++i) {
5596     OutChains.push_back(OutLoadChains[i]);
5597     GluedLoadChains.push_back(OutLoadChains[i]);
5598   }
5599 
5600   // Chain for all loads.
5601   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
5602                                   GluedLoadChains);
5603 
5604   for (unsigned i = From; i < To; ++i) {
5605     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
5606     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
5607                                   ST->getBasePtr(), ST->getMemoryVT(),
5608                                   ST->getMemOperand());
5609     OutChains.push_back(NewStore);
5610   }
5611 }
5612 
5613 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
5614                                        SDValue Chain, SDValue Dst, SDValue Src,
5615                                        uint64_t Size, unsigned Align,
5616                                        bool isVol, bool AlwaysInline,
5617                                        MachinePointerInfo DstPtrInfo,
5618                                        MachinePointerInfo SrcPtrInfo) {
5619   // Turn a memcpy of undef to nop.
5620   if (Src.isUndef())
5621     return Chain;
5622 
5623   // Expand memcpy to a series of load and store ops if the size operand falls
5624   // below a certain threshold.
5625   // TODO: In the AlwaysInline case, if the size is big then generate a loop
5626   // rather than maybe a humongous number of loads and stores.
5627   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5628   const DataLayout &DL = DAG.getDataLayout();
5629   LLVMContext &C = *DAG.getContext();
5630   std::vector<EVT> MemOps;
5631   bool DstAlignCanChange = false;
5632   MachineFunction &MF = DAG.getMachineFunction();
5633   MachineFrameInfo &MFI = MF.getFrameInfo();
5634   bool OptSize = shouldLowerMemFuncForSize(MF);
5635   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5636   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5637     DstAlignCanChange = true;
5638   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5639   if (Align > SrcAlign)
5640     SrcAlign = Align;
5641   ConstantDataArraySlice Slice;
5642   bool CopyFromConstant = isMemSrcFromConstant(Src, Slice);
5643   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
5644   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
5645 
5646   if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
5647                                 (DstAlignCanChange ? 0 : Align),
5648                                 (isZeroConstant ? 0 : SrcAlign),
5649                                 false, false, CopyFromConstant, true,
5650                                 DstPtrInfo.getAddrSpace(),
5651                                 SrcPtrInfo.getAddrSpace(),
5652                                 DAG, TLI))
5653     return SDValue();
5654 
5655   if (DstAlignCanChange) {
5656     Type *Ty = MemOps[0].getTypeForEVT(C);
5657     unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
5658 
5659     // Don't promote to an alignment that would require dynamic stack
5660     // realignment.
5661     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
5662     if (!TRI->needsStackRealignment(MF))
5663       while (NewAlign > Align &&
5664              DL.exceedsNaturalStackAlignment(NewAlign))
5665           NewAlign /= 2;
5666 
5667     if (NewAlign > Align) {
5668       // Give the stack frame object a larger alignment if needed.
5669       if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5670         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5671       Align = NewAlign;
5672     }
5673   }
5674 
5675   MachineMemOperand::Flags MMOFlags =
5676       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
5677   SmallVector<SDValue, 16> OutLoadChains;
5678   SmallVector<SDValue, 16> OutStoreChains;
5679   SmallVector<SDValue, 32> OutChains;
5680   unsigned NumMemOps = MemOps.size();
5681   uint64_t SrcOff = 0, DstOff = 0;
5682   for (unsigned i = 0; i != NumMemOps; ++i) {
5683     EVT VT = MemOps[i];
5684     unsigned VTSize = VT.getSizeInBits() / 8;
5685     SDValue Value, Store;
5686 
5687     if (VTSize > Size) {
5688       // Issuing an unaligned load / store pair  that overlaps with the previous
5689       // pair. Adjust the offset accordingly.
5690       assert(i == NumMemOps-1 && i != 0);
5691       SrcOff -= VTSize - Size;
5692       DstOff -= VTSize - Size;
5693     }
5694 
5695     if (CopyFromConstant &&
5696         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
5697       // It's unlikely a store of a vector immediate can be done in a single
5698       // instruction. It would require a load from a constantpool first.
5699       // We only handle zero vectors here.
5700       // FIXME: Handle other cases where store of vector immediate is done in
5701       // a single instruction.
5702       ConstantDataArraySlice SubSlice;
5703       if (SrcOff < Slice.Length) {
5704         SubSlice = Slice;
5705         SubSlice.move(SrcOff);
5706       } else {
5707         // This is an out-of-bounds access and hence UB. Pretend we read zero.
5708         SubSlice.Array = nullptr;
5709         SubSlice.Offset = 0;
5710         SubSlice.Length = VTSize;
5711       }
5712       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
5713       if (Value.getNode()) {
5714         Store = DAG.getStore(Chain, dl, Value,
5715                              DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5716                              DstPtrInfo.getWithOffset(DstOff), Align,
5717                              MMOFlags);
5718         OutChains.push_back(Store);
5719       }
5720     }
5721 
5722     if (!Store.getNode()) {
5723       // The type might not be legal for the target.  This should only happen
5724       // if the type is smaller than a legal type, as on PPC, so the right
5725       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
5726       // to Load/Store if NVT==VT.
5727       // FIXME does the case above also need this?
5728       EVT NVT = TLI.getTypeToTransformTo(C, VT);
5729       assert(NVT.bitsGE(VT));
5730 
5731       bool isDereferenceable =
5732         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
5733       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
5734       if (isDereferenceable)
5735         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
5736 
5737       Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
5738                              DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5739                              SrcPtrInfo.getWithOffset(SrcOff), VT,
5740                              MinAlign(SrcAlign, SrcOff), SrcMMOFlags);
5741       OutLoadChains.push_back(Value.getValue(1));
5742 
5743       Store = DAG.getTruncStore(
5744           Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5745           DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
5746       OutStoreChains.push_back(Store);
5747     }
5748     SrcOff += VTSize;
5749     DstOff += VTSize;
5750     Size -= VTSize;
5751   }
5752 
5753   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
5754                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
5755   unsigned NumLdStInMemcpy = OutStoreChains.size();
5756 
5757   if (NumLdStInMemcpy) {
5758     // It may be that memcpy might be converted to memset if it's memcpy
5759     // of constants. In such a case, we won't have loads and stores, but
5760     // just stores. In the absence of loads, there is nothing to gang up.
5761     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
5762       // If target does not care, just leave as it.
5763       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
5764         OutChains.push_back(OutLoadChains[i]);
5765         OutChains.push_back(OutStoreChains[i]);
5766       }
5767     } else {
5768       // Ld/St less than/equal limit set by target.
5769       if (NumLdStInMemcpy <= GluedLdStLimit) {
5770           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
5771                                         NumLdStInMemcpy, OutLoadChains,
5772                                         OutStoreChains);
5773       } else {
5774         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
5775         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
5776         unsigned GlueIter = 0;
5777 
5778         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
5779           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
5780           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
5781 
5782           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
5783                                        OutLoadChains, OutStoreChains);
5784           GlueIter += GluedLdStLimit;
5785         }
5786 
5787         // Residual ld/st.
5788         if (RemainingLdStInMemcpy) {
5789           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
5790                                         RemainingLdStInMemcpy, OutLoadChains,
5791                                         OutStoreChains);
5792         }
5793       }
5794     }
5795   }
5796   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5797 }
5798 
5799 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
5800                                         SDValue Chain, SDValue Dst, SDValue Src,
5801                                         uint64_t Size, unsigned Align,
5802                                         bool isVol, bool AlwaysInline,
5803                                         MachinePointerInfo DstPtrInfo,
5804                                         MachinePointerInfo SrcPtrInfo) {
5805   // Turn a memmove of undef to nop.
5806   if (Src.isUndef())
5807     return Chain;
5808 
5809   // Expand memmove to a series of load and store ops if the size operand falls
5810   // below a certain threshold.
5811   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5812   const DataLayout &DL = DAG.getDataLayout();
5813   LLVMContext &C = *DAG.getContext();
5814   std::vector<EVT> MemOps;
5815   bool DstAlignCanChange = false;
5816   MachineFunction &MF = DAG.getMachineFunction();
5817   MachineFrameInfo &MFI = MF.getFrameInfo();
5818   bool OptSize = shouldLowerMemFuncForSize(MF);
5819   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5820   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5821     DstAlignCanChange = true;
5822   unsigned SrcAlign = DAG.InferPtrAlignment(Src);
5823   if (Align > SrcAlign)
5824     SrcAlign = Align;
5825   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
5826 
5827   if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
5828                                 (DstAlignCanChange ? 0 : Align), SrcAlign,
5829                                 false, false, false, false,
5830                                 DstPtrInfo.getAddrSpace(),
5831                                 SrcPtrInfo.getAddrSpace(),
5832                                 DAG, TLI))
5833     return SDValue();
5834 
5835   if (DstAlignCanChange) {
5836     Type *Ty = MemOps[0].getTypeForEVT(C);
5837     unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
5838     if (NewAlign > Align) {
5839       // Give the stack frame object a larger alignment if needed.
5840       if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5841         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5842       Align = NewAlign;
5843     }
5844   }
5845 
5846   MachineMemOperand::Flags MMOFlags =
5847       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
5848   uint64_t SrcOff = 0, DstOff = 0;
5849   SmallVector<SDValue, 8> LoadValues;
5850   SmallVector<SDValue, 8> LoadChains;
5851   SmallVector<SDValue, 8> OutChains;
5852   unsigned NumMemOps = MemOps.size();
5853   for (unsigned i = 0; i < NumMemOps; i++) {
5854     EVT VT = MemOps[i];
5855     unsigned VTSize = VT.getSizeInBits() / 8;
5856     SDValue Value;
5857 
5858     bool isDereferenceable =
5859       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
5860     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
5861     if (isDereferenceable)
5862       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
5863 
5864     Value =
5865         DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
5866                     SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, SrcMMOFlags);
5867     LoadValues.push_back(Value);
5868     LoadChains.push_back(Value.getValue(1));
5869     SrcOff += VTSize;
5870   }
5871   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
5872   OutChains.clear();
5873   for (unsigned i = 0; i < NumMemOps; i++) {
5874     EVT VT = MemOps[i];
5875     unsigned VTSize = VT.getSizeInBits() / 8;
5876     SDValue Store;
5877 
5878     Store = DAG.getStore(Chain, dl, LoadValues[i],
5879                          DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5880                          DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
5881     OutChains.push_back(Store);
5882     DstOff += VTSize;
5883   }
5884 
5885   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5886 }
5887 
5888 /// Lower the call to 'memset' intrinsic function into a series of store
5889 /// operations.
5890 ///
5891 /// \param DAG Selection DAG where lowered code is placed.
5892 /// \param dl Link to corresponding IR location.
5893 /// \param Chain Control flow dependency.
5894 /// \param Dst Pointer to destination memory location.
5895 /// \param Src Value of byte to write into the memory.
5896 /// \param Size Number of bytes to write.
5897 /// \param Align Alignment of the destination in bytes.
5898 /// \param isVol True if destination is volatile.
5899 /// \param DstPtrInfo IR information on the memory pointer.
5900 /// \returns New head in the control flow, if lowering was successful, empty
5901 /// SDValue otherwise.
5902 ///
5903 /// The function tries to replace 'llvm.memset' intrinsic with several store
5904 /// operations and value calculation code. This is usually profitable for small
5905 /// memory size.
5906 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
5907                                SDValue Chain, SDValue Dst, SDValue Src,
5908                                uint64_t Size, unsigned Align, bool isVol,
5909                                MachinePointerInfo DstPtrInfo) {
5910   // Turn a memset of undef to nop.
5911   if (Src.isUndef())
5912     return Chain;
5913 
5914   // Expand memset to a series of load/store ops if the size operand
5915   // falls below a certain threshold.
5916   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5917   std::vector<EVT> MemOps;
5918   bool DstAlignCanChange = false;
5919   MachineFunction &MF = DAG.getMachineFunction();
5920   MachineFrameInfo &MFI = MF.getFrameInfo();
5921   bool OptSize = shouldLowerMemFuncForSize(MF);
5922   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
5923   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
5924     DstAlignCanChange = true;
5925   bool IsZeroVal =
5926     isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
5927   if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
5928                                 Size, (DstAlignCanChange ? 0 : Align), 0,
5929                                 true, IsZeroVal, false, true,
5930                                 DstPtrInfo.getAddrSpace(), ~0u,
5931                                 DAG, TLI))
5932     return SDValue();
5933 
5934   if (DstAlignCanChange) {
5935     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
5936     unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
5937     if (NewAlign > Align) {
5938       // Give the stack frame object a larger alignment if needed.
5939       if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
5940         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
5941       Align = NewAlign;
5942     }
5943   }
5944 
5945   SmallVector<SDValue, 8> OutChains;
5946   uint64_t DstOff = 0;
5947   unsigned NumMemOps = MemOps.size();
5948 
5949   // Find the largest store and generate the bit pattern for it.
5950   EVT LargestVT = MemOps[0];
5951   for (unsigned i = 1; i < NumMemOps; i++)
5952     if (MemOps[i].bitsGT(LargestVT))
5953       LargestVT = MemOps[i];
5954   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
5955 
5956   for (unsigned i = 0; i < NumMemOps; i++) {
5957     EVT VT = MemOps[i];
5958     unsigned VTSize = VT.getSizeInBits() / 8;
5959     if (VTSize > Size) {
5960       // Issuing an unaligned load / store pair  that overlaps with the previous
5961       // pair. Adjust the offset accordingly.
5962       assert(i == NumMemOps-1 && i != 0);
5963       DstOff -= VTSize - Size;
5964     }
5965 
5966     // If this store is smaller than the largest store see whether we can get
5967     // the smaller value for free with a truncate.
5968     SDValue Value = MemSetValue;
5969     if (VT.bitsLT(LargestVT)) {
5970       if (!LargestVT.isVector() && !VT.isVector() &&
5971           TLI.isTruncateFree(LargestVT, VT))
5972         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
5973       else
5974         Value = getMemsetValue(Src, VT, DAG, dl);
5975     }
5976     assert(Value.getValueType() == VT && "Value with wrong type.");
5977     SDValue Store = DAG.getStore(
5978         Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
5979         DstPtrInfo.getWithOffset(DstOff), Align,
5980         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
5981     OutChains.push_back(Store);
5982     DstOff += VT.getSizeInBits() / 8;
5983     Size -= VTSize;
5984   }
5985 
5986   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
5987 }
5988 
5989 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
5990                                             unsigned AS) {
5991   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
5992   // pointer operands can be losslessly bitcasted to pointers of address space 0
5993   if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
5994     report_fatal_error("cannot lower memory intrinsic in address space " +
5995                        Twine(AS));
5996   }
5997 }
5998 
5999 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6000                                 SDValue Src, SDValue Size, unsigned Align,
6001                                 bool isVol, bool AlwaysInline, bool isTailCall,
6002                                 MachinePointerInfo DstPtrInfo,
6003                                 MachinePointerInfo SrcPtrInfo) {
6004   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
6005 
6006   // Check to see if we should lower the memcpy to loads and stores first.
6007   // For cases within the target-specified limits, this is the best choice.
6008   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6009   if (ConstantSize) {
6010     // Memcpy with size zero? Just return the original chain.
6011     if (ConstantSize->isNullValue())
6012       return Chain;
6013 
6014     SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6015                                              ConstantSize->getZExtValue(),Align,
6016                                 isVol, false, DstPtrInfo, SrcPtrInfo);
6017     if (Result.getNode())
6018       return Result;
6019   }
6020 
6021   // Then check to see if we should lower the memcpy with target-specific
6022   // code. If the target chooses to do this, this is the next best.
6023   if (TSI) {
6024     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6025         *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
6026         DstPtrInfo, SrcPtrInfo);
6027     if (Result.getNode())
6028       return Result;
6029   }
6030 
6031   // If we really need inline code and the target declined to provide it,
6032   // use a (potentially long) sequence of loads and stores.
6033   if (AlwaysInline) {
6034     assert(ConstantSize && "AlwaysInline requires a constant size!");
6035     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6036                                    ConstantSize->getZExtValue(), Align, isVol,
6037                                    true, DstPtrInfo, SrcPtrInfo);
6038   }
6039 
6040   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6041   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6042 
6043   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6044   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6045   // respect volatile, so they may do things like read or write memory
6046   // beyond the given memory regions. But fixing this isn't easy, and most
6047   // people don't care.
6048 
6049   // Emit a library call.
6050   TargetLowering::ArgListTy Args;
6051   TargetLowering::ArgListEntry Entry;
6052   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6053   Entry.Node = Dst; Args.push_back(Entry);
6054   Entry.Node = Src; Args.push_back(Entry);
6055   Entry.Node = Size; Args.push_back(Entry);
6056   // FIXME: pass in SDLoc
6057   TargetLowering::CallLoweringInfo CLI(*this);
6058   CLI.setDebugLoc(dl)
6059       .setChain(Chain)
6060       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6061                     Dst.getValueType().getTypeForEVT(*getContext()),
6062                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
6063                                       TLI->getPointerTy(getDataLayout())),
6064                     std::move(Args))
6065       .setDiscardResult()
6066       .setTailCall(isTailCall);
6067 
6068   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6069   return CallResult.second;
6070 }
6071 
6072 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6073                                       SDValue Dst, unsigned DstAlign,
6074                                       SDValue Src, unsigned SrcAlign,
6075                                       SDValue Size, Type *SizeTy,
6076                                       unsigned ElemSz, bool isTailCall,
6077                                       MachinePointerInfo DstPtrInfo,
6078                                       MachinePointerInfo SrcPtrInfo) {
6079   // Emit a library call.
6080   TargetLowering::ArgListTy Args;
6081   TargetLowering::ArgListEntry Entry;
6082   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6083   Entry.Node = Dst;
6084   Args.push_back(Entry);
6085 
6086   Entry.Node = Src;
6087   Args.push_back(Entry);
6088 
6089   Entry.Ty = SizeTy;
6090   Entry.Node = Size;
6091   Args.push_back(Entry);
6092 
6093   RTLIB::Libcall LibraryCall =
6094       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6095   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6096     report_fatal_error("Unsupported element size");
6097 
6098   TargetLowering::CallLoweringInfo CLI(*this);
6099   CLI.setDebugLoc(dl)
6100       .setChain(Chain)
6101       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6102                     Type::getVoidTy(*getContext()),
6103                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6104                                       TLI->getPointerTy(getDataLayout())),
6105                     std::move(Args))
6106       .setDiscardResult()
6107       .setTailCall(isTailCall);
6108 
6109   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6110   return CallResult.second;
6111 }
6112 
6113 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6114                                  SDValue Src, SDValue Size, unsigned Align,
6115                                  bool isVol, bool isTailCall,
6116                                  MachinePointerInfo DstPtrInfo,
6117                                  MachinePointerInfo SrcPtrInfo) {
6118   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
6119 
6120   // Check to see if we should lower the memmove to loads and stores first.
6121   // For cases within the target-specified limits, this is the best choice.
6122   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6123   if (ConstantSize) {
6124     // Memmove with size zero? Just return the original chain.
6125     if (ConstantSize->isNullValue())
6126       return Chain;
6127 
6128     SDValue Result =
6129       getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
6130                                ConstantSize->getZExtValue(), Align, isVol,
6131                                false, DstPtrInfo, SrcPtrInfo);
6132     if (Result.getNode())
6133       return Result;
6134   }
6135 
6136   // Then check to see if we should lower the memmove with target-specific
6137   // code. If the target chooses to do this, this is the next best.
6138   if (TSI) {
6139     SDValue Result = TSI->EmitTargetCodeForMemmove(
6140         *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
6141     if (Result.getNode())
6142       return Result;
6143   }
6144 
6145   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6146   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6147 
6148   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6149   // not be safe.  See memcpy above for more details.
6150 
6151   // Emit a library call.
6152   TargetLowering::ArgListTy Args;
6153   TargetLowering::ArgListEntry Entry;
6154   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6155   Entry.Node = Dst; Args.push_back(Entry);
6156   Entry.Node = Src; Args.push_back(Entry);
6157   Entry.Node = Size; Args.push_back(Entry);
6158   // FIXME:  pass in SDLoc
6159   TargetLowering::CallLoweringInfo CLI(*this);
6160   CLI.setDebugLoc(dl)
6161       .setChain(Chain)
6162       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6163                     Dst.getValueType().getTypeForEVT(*getContext()),
6164                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
6165                                       TLI->getPointerTy(getDataLayout())),
6166                     std::move(Args))
6167       .setDiscardResult()
6168       .setTailCall(isTailCall);
6169 
6170   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6171   return CallResult.second;
6172 }
6173 
6174 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6175                                        SDValue Dst, unsigned DstAlign,
6176                                        SDValue Src, unsigned SrcAlign,
6177                                        SDValue Size, Type *SizeTy,
6178                                        unsigned ElemSz, bool isTailCall,
6179                                        MachinePointerInfo DstPtrInfo,
6180                                        MachinePointerInfo SrcPtrInfo) {
6181   // Emit a library call.
6182   TargetLowering::ArgListTy Args;
6183   TargetLowering::ArgListEntry Entry;
6184   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6185   Entry.Node = Dst;
6186   Args.push_back(Entry);
6187 
6188   Entry.Node = Src;
6189   Args.push_back(Entry);
6190 
6191   Entry.Ty = SizeTy;
6192   Entry.Node = Size;
6193   Args.push_back(Entry);
6194 
6195   RTLIB::Libcall LibraryCall =
6196       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6197   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6198     report_fatal_error("Unsupported element size");
6199 
6200   TargetLowering::CallLoweringInfo CLI(*this);
6201   CLI.setDebugLoc(dl)
6202       .setChain(Chain)
6203       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6204                     Type::getVoidTy(*getContext()),
6205                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6206                                       TLI->getPointerTy(getDataLayout())),
6207                     std::move(Args))
6208       .setDiscardResult()
6209       .setTailCall(isTailCall);
6210 
6211   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6212   return CallResult.second;
6213 }
6214 
6215 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
6216                                 SDValue Src, SDValue Size, unsigned Align,
6217                                 bool isVol, bool isTailCall,
6218                                 MachinePointerInfo DstPtrInfo) {
6219   assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
6220 
6221   // Check to see if we should lower the memset to stores first.
6222   // For cases within the target-specified limits, this is the best choice.
6223   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6224   if (ConstantSize) {
6225     // Memset with size zero? Just return the original chain.
6226     if (ConstantSize->isNullValue())
6227       return Chain;
6228 
6229     SDValue Result =
6230       getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
6231                       Align, isVol, DstPtrInfo);
6232 
6233     if (Result.getNode())
6234       return Result;
6235   }
6236 
6237   // Then check to see if we should lower the memset with target-specific
6238   // code. If the target chooses to do this, this is the next best.
6239   if (TSI) {
6240     SDValue Result = TSI->EmitTargetCodeForMemset(
6241         *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
6242     if (Result.getNode())
6243       return Result;
6244   }
6245 
6246   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6247 
6248   // Emit a library call.
6249   Type *IntPtrTy = getDataLayout().getIntPtrType(*getContext());
6250   TargetLowering::ArgListTy Args;
6251   TargetLowering::ArgListEntry Entry;
6252   Entry.Node = Dst; Entry.Ty = IntPtrTy;
6253   Args.push_back(Entry);
6254   Entry.Node = Src;
6255   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
6256   Args.push_back(Entry);
6257   Entry.Node = Size;
6258   Entry.Ty = IntPtrTy;
6259   Args.push_back(Entry);
6260 
6261   // FIXME: pass in SDLoc
6262   TargetLowering::CallLoweringInfo CLI(*this);
6263   CLI.setDebugLoc(dl)
6264       .setChain(Chain)
6265       .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
6266                     Dst.getValueType().getTypeForEVT(*getContext()),
6267                     getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
6268                                       TLI->getPointerTy(getDataLayout())),
6269                     std::move(Args))
6270       .setDiscardResult()
6271       .setTailCall(isTailCall);
6272 
6273   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6274   return CallResult.second;
6275 }
6276 
6277 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
6278                                       SDValue Dst, unsigned DstAlign,
6279                                       SDValue Value, SDValue Size, Type *SizeTy,
6280                                       unsigned ElemSz, bool isTailCall,
6281                                       MachinePointerInfo DstPtrInfo) {
6282   // Emit a library call.
6283   TargetLowering::ArgListTy Args;
6284   TargetLowering::ArgListEntry Entry;
6285   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6286   Entry.Node = Dst;
6287   Args.push_back(Entry);
6288 
6289   Entry.Ty = Type::getInt8Ty(*getContext());
6290   Entry.Node = Value;
6291   Args.push_back(Entry);
6292 
6293   Entry.Ty = SizeTy;
6294   Entry.Node = Size;
6295   Args.push_back(Entry);
6296 
6297   RTLIB::Libcall LibraryCall =
6298       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6299   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6300     report_fatal_error("Unsupported element size");
6301 
6302   TargetLowering::CallLoweringInfo CLI(*this);
6303   CLI.setDebugLoc(dl)
6304       .setChain(Chain)
6305       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6306                     Type::getVoidTy(*getContext()),
6307                     getExternalSymbol(TLI->getLibcallName(LibraryCall),
6308                                       TLI->getPointerTy(getDataLayout())),
6309                     std::move(Args))
6310       .setDiscardResult()
6311       .setTailCall(isTailCall);
6312 
6313   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6314   return CallResult.second;
6315 }
6316 
6317 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6318                                 SDVTList VTList, ArrayRef<SDValue> Ops,
6319                                 MachineMemOperand *MMO) {
6320   FoldingSetNodeID ID;
6321   ID.AddInteger(MemVT.getRawBits());
6322   AddNodeIDNode(ID, Opcode, VTList, Ops);
6323   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6324   void* IP = nullptr;
6325   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6326     cast<AtomicSDNode>(E)->refineAlignment(MMO);
6327     return SDValue(E, 0);
6328   }
6329 
6330   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6331                                     VTList, MemVT, MMO);
6332   createOperands(N, Ops);
6333 
6334   CSEMap.InsertNode(N, IP);
6335   InsertNode(N);
6336   return SDValue(N, 0);
6337 }
6338 
6339 SDValue SelectionDAG::getAtomicCmpSwap(
6340     unsigned Opcode, const SDLoc &dl, EVT MemVT, SDVTList VTs, SDValue Chain,
6341     SDValue Ptr, SDValue Cmp, SDValue Swp, MachinePointerInfo PtrInfo,
6342     unsigned Alignment, AtomicOrdering SuccessOrdering,
6343     AtomicOrdering FailureOrdering, SyncScope::ID SSID) {
6344   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
6345          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
6346   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
6347 
6348   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
6349     Alignment = getEVTAlignment(MemVT);
6350 
6351   MachineFunction &MF = getMachineFunction();
6352 
6353   // FIXME: Volatile isn't really correct; we should keep track of atomic
6354   // orderings in the memoperand.
6355   auto Flags = MachineMemOperand::MOVolatile | MachineMemOperand::MOLoad |
6356                MachineMemOperand::MOStore;
6357   MachineMemOperand *MMO =
6358     MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
6359                             AAMDNodes(), nullptr, SSID, SuccessOrdering,
6360                             FailureOrdering);
6361 
6362   return getAtomicCmpSwap(Opcode, dl, MemVT, VTs, Chain, Ptr, Cmp, Swp, MMO);
6363 }
6364 
6365 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
6366                                        EVT MemVT, SDVTList VTs, SDValue Chain,
6367                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
6368                                        MachineMemOperand *MMO) {
6369   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
6370          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
6371   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
6372 
6373   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
6374   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6375 }
6376 
6377 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6378                                 SDValue Chain, SDValue Ptr, SDValue Val,
6379                                 const Value *PtrVal, unsigned Alignment,
6380                                 AtomicOrdering Ordering,
6381                                 SyncScope::ID SSID) {
6382   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
6383     Alignment = getEVTAlignment(MemVT);
6384 
6385   MachineFunction &MF = getMachineFunction();
6386   // An atomic store does not load. An atomic load does not store.
6387   // (An atomicrmw obviously both loads and stores.)
6388   // For now, atomics are considered to be volatile always, and they are
6389   // chained as such.
6390   // FIXME: Volatile isn't really correct; we should keep track of atomic
6391   // orderings in the memoperand.
6392   auto Flags = MachineMemOperand::MOVolatile;
6393   if (Opcode != ISD::ATOMIC_STORE)
6394     Flags |= MachineMemOperand::MOLoad;
6395   if (Opcode != ISD::ATOMIC_LOAD)
6396     Flags |= MachineMemOperand::MOStore;
6397 
6398   MachineMemOperand *MMO =
6399     MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
6400                             MemVT.getStoreSize(), Alignment, AAMDNodes(),
6401                             nullptr, SSID, Ordering);
6402 
6403   return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
6404 }
6405 
6406 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6407                                 SDValue Chain, SDValue Ptr, SDValue Val,
6408                                 MachineMemOperand *MMO) {
6409   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
6410           Opcode == ISD::ATOMIC_LOAD_SUB ||
6411           Opcode == ISD::ATOMIC_LOAD_AND ||
6412           Opcode == ISD::ATOMIC_LOAD_CLR ||
6413           Opcode == ISD::ATOMIC_LOAD_OR ||
6414           Opcode == ISD::ATOMIC_LOAD_XOR ||
6415           Opcode == ISD::ATOMIC_LOAD_NAND ||
6416           Opcode == ISD::ATOMIC_LOAD_MIN ||
6417           Opcode == ISD::ATOMIC_LOAD_MAX ||
6418           Opcode == ISD::ATOMIC_LOAD_UMIN ||
6419           Opcode == ISD::ATOMIC_LOAD_UMAX ||
6420           Opcode == ISD::ATOMIC_SWAP ||
6421           Opcode == ISD::ATOMIC_STORE) &&
6422          "Invalid Atomic Op");
6423 
6424   EVT VT = Val.getValueType();
6425 
6426   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
6427                                                getVTList(VT, MVT::Other);
6428   SDValue Ops[] = {Chain, Ptr, Val};
6429   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6430 }
6431 
6432 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6433                                 EVT VT, SDValue Chain, SDValue Ptr,
6434                                 MachineMemOperand *MMO) {
6435   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
6436 
6437   SDVTList VTs = getVTList(VT, MVT::Other);
6438   SDValue Ops[] = {Chain, Ptr};
6439   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6440 }
6441 
6442 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
6443 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
6444   if (Ops.size() == 1)
6445     return Ops[0];
6446 
6447   SmallVector<EVT, 4> VTs;
6448   VTs.reserve(Ops.size());
6449   for (unsigned i = 0; i < Ops.size(); ++i)
6450     VTs.push_back(Ops[i].getValueType());
6451   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
6452 }
6453 
6454 SDValue SelectionDAG::getMemIntrinsicNode(
6455     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
6456     EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align,
6457     MachineMemOperand::Flags Flags, unsigned Size) {
6458   if (Align == 0)  // Ensure that codegen never sees alignment 0
6459     Align = getEVTAlignment(MemVT);
6460 
6461   if (!Size)
6462     Size = MemVT.getStoreSize();
6463 
6464   MachineFunction &MF = getMachineFunction();
6465   MachineMemOperand *MMO =
6466     MF.getMachineMemOperand(PtrInfo, Flags, Size, Align);
6467 
6468   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
6469 }
6470 
6471 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
6472                                           SDVTList VTList,
6473                                           ArrayRef<SDValue> Ops, EVT MemVT,
6474                                           MachineMemOperand *MMO) {
6475   assert((Opcode == ISD::INTRINSIC_VOID ||
6476           Opcode == ISD::INTRINSIC_W_CHAIN ||
6477           Opcode == ISD::PREFETCH ||
6478           Opcode == ISD::LIFETIME_START ||
6479           Opcode == ISD::LIFETIME_END ||
6480           ((int)Opcode <= std::numeric_limits<int>::max() &&
6481            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
6482          "Opcode is not a memory-accessing opcode!");
6483 
6484   // Memoize the node unless it returns a flag.
6485   MemIntrinsicSDNode *N;
6486   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
6487     FoldingSetNodeID ID;
6488     AddNodeIDNode(ID, Opcode, VTList, Ops);
6489     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
6490         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
6491     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6492     void *IP = nullptr;
6493     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6494       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
6495       return SDValue(E, 0);
6496     }
6497 
6498     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6499                                       VTList, MemVT, MMO);
6500     createOperands(N, Ops);
6501 
6502   CSEMap.InsertNode(N, IP);
6503   } else {
6504     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6505                                       VTList, MemVT, MMO);
6506     createOperands(N, Ops);
6507   }
6508   InsertNode(N);
6509   return SDValue(N, 0);
6510 }
6511 
6512 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
6513 /// MachinePointerInfo record from it.  This is particularly useful because the
6514 /// code generator has many cases where it doesn't bother passing in a
6515 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
6516 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
6517                                            SelectionDAG &DAG, SDValue Ptr,
6518                                            int64_t Offset = 0) {
6519   // If this is FI+Offset, we can model it.
6520   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
6521     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
6522                                              FI->getIndex(), Offset);
6523 
6524   // If this is (FI+Offset1)+Offset2, we can model it.
6525   if (Ptr.getOpcode() != ISD::ADD ||
6526       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
6527       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
6528     return Info;
6529 
6530   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6531   return MachinePointerInfo::getFixedStack(
6532       DAG.getMachineFunction(), FI,
6533       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
6534 }
6535 
6536 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
6537 /// MachinePointerInfo record from it.  This is particularly useful because the
6538 /// code generator has many cases where it doesn't bother passing in a
6539 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
6540 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
6541                                            SelectionDAG &DAG, SDValue Ptr,
6542                                            SDValue OffsetOp) {
6543   // If the 'Offset' value isn't a constant, we can't handle this.
6544   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
6545     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
6546   if (OffsetOp.isUndef())
6547     return InferPointerInfo(Info, DAG, Ptr);
6548   return Info;
6549 }
6550 
6551 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
6552                               EVT VT, const SDLoc &dl, SDValue Chain,
6553                               SDValue Ptr, SDValue Offset,
6554                               MachinePointerInfo PtrInfo, EVT MemVT,
6555                               unsigned Alignment,
6556                               MachineMemOperand::Flags MMOFlags,
6557                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
6558   assert(Chain.getValueType() == MVT::Other &&
6559         "Invalid chain type");
6560   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
6561     Alignment = getEVTAlignment(MemVT);
6562 
6563   MMOFlags |= MachineMemOperand::MOLoad;
6564   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
6565   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
6566   // clients.
6567   if (PtrInfo.V.isNull())
6568     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
6569 
6570   MachineFunction &MF = getMachineFunction();
6571   MachineMemOperand *MMO = MF.getMachineMemOperand(
6572       PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
6573   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
6574 }
6575 
6576 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
6577                               EVT VT, const SDLoc &dl, SDValue Chain,
6578                               SDValue Ptr, SDValue Offset, EVT MemVT,
6579                               MachineMemOperand *MMO) {
6580   if (VT == MemVT) {
6581     ExtType = ISD::NON_EXTLOAD;
6582   } else if (ExtType == ISD::NON_EXTLOAD) {
6583     assert(VT == MemVT && "Non-extending load from different memory type!");
6584   } else {
6585     // Extending load.
6586     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
6587            "Should only be an extending load, not truncating!");
6588     assert(VT.isInteger() == MemVT.isInteger() &&
6589            "Cannot convert from FP to Int or Int -> FP!");
6590     assert(VT.isVector() == MemVT.isVector() &&
6591            "Cannot use an ext load to convert to or from a vector!");
6592     assert((!VT.isVector() ||
6593             VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
6594            "Cannot use an ext load to change the number of vector elements!");
6595   }
6596 
6597   bool Indexed = AM != ISD::UNINDEXED;
6598   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
6599 
6600   SDVTList VTs = Indexed ?
6601     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
6602   SDValue Ops[] = { Chain, Ptr, Offset };
6603   FoldingSetNodeID ID;
6604   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
6605   ID.AddInteger(MemVT.getRawBits());
6606   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
6607       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
6608   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6609   void *IP = nullptr;
6610   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6611     cast<LoadSDNode>(E)->refineAlignment(MMO);
6612     return SDValue(E, 0);
6613   }
6614   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
6615                                   ExtType, MemVT, MMO);
6616   createOperands(N, Ops);
6617 
6618   CSEMap.InsertNode(N, IP);
6619   InsertNode(N);
6620   SDValue V(N, 0);
6621   NewSDValueDbgMsg(V, "Creating new node: ", this);
6622   return V;
6623 }
6624 
6625 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6626                               SDValue Ptr, MachinePointerInfo PtrInfo,
6627                               unsigned Alignment,
6628                               MachineMemOperand::Flags MMOFlags,
6629                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
6630   SDValue Undef = getUNDEF(Ptr.getValueType());
6631   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
6632                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
6633 }
6634 
6635 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6636                               SDValue Ptr, MachineMemOperand *MMO) {
6637   SDValue Undef = getUNDEF(Ptr.getValueType());
6638   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
6639                  VT, MMO);
6640 }
6641 
6642 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
6643                                  EVT VT, SDValue Chain, SDValue Ptr,
6644                                  MachinePointerInfo PtrInfo, EVT MemVT,
6645                                  unsigned Alignment,
6646                                  MachineMemOperand::Flags MMOFlags,
6647                                  const AAMDNodes &AAInfo) {
6648   SDValue Undef = getUNDEF(Ptr.getValueType());
6649   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
6650                  MemVT, Alignment, MMOFlags, AAInfo);
6651 }
6652 
6653 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
6654                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
6655                                  MachineMemOperand *MMO) {
6656   SDValue Undef = getUNDEF(Ptr.getValueType());
6657   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
6658                  MemVT, MMO);
6659 }
6660 
6661 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
6662                                      SDValue Base, SDValue Offset,
6663                                      ISD::MemIndexedMode AM) {
6664   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
6665   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
6666   // Don't propagate the invariant or dereferenceable flags.
6667   auto MMOFlags =
6668       LD->getMemOperand()->getFlags() &
6669       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
6670   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
6671                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
6672                  LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
6673                  LD->getAAInfo());
6674 }
6675 
6676 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6677                                SDValue Ptr, MachinePointerInfo PtrInfo,
6678                                unsigned Alignment,
6679                                MachineMemOperand::Flags MMOFlags,
6680                                const AAMDNodes &AAInfo) {
6681   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
6682   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
6683     Alignment = getEVTAlignment(Val.getValueType());
6684 
6685   MMOFlags |= MachineMemOperand::MOStore;
6686   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
6687 
6688   if (PtrInfo.V.isNull())
6689     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
6690 
6691   MachineFunction &MF = getMachineFunction();
6692   MachineMemOperand *MMO = MF.getMachineMemOperand(
6693       PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
6694   return getStore(Chain, dl, Val, Ptr, MMO);
6695 }
6696 
6697 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6698                                SDValue Ptr, MachineMemOperand *MMO) {
6699   assert(Chain.getValueType() == MVT::Other &&
6700         "Invalid chain type");
6701   EVT VT = Val.getValueType();
6702   SDVTList VTs = getVTList(MVT::Other);
6703   SDValue Undef = getUNDEF(Ptr.getValueType());
6704   SDValue Ops[] = { Chain, Val, Ptr, Undef };
6705   FoldingSetNodeID ID;
6706   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6707   ID.AddInteger(VT.getRawBits());
6708   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
6709       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
6710   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6711   void *IP = nullptr;
6712   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6713     cast<StoreSDNode>(E)->refineAlignment(MMO);
6714     return SDValue(E, 0);
6715   }
6716   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6717                                    ISD::UNINDEXED, false, VT, MMO);
6718   createOperands(N, Ops);
6719 
6720   CSEMap.InsertNode(N, IP);
6721   InsertNode(N);
6722   SDValue V(N, 0);
6723   NewSDValueDbgMsg(V, "Creating new node: ", this);
6724   return V;
6725 }
6726 
6727 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6728                                     SDValue Ptr, MachinePointerInfo PtrInfo,
6729                                     EVT SVT, unsigned Alignment,
6730                                     MachineMemOperand::Flags MMOFlags,
6731                                     const AAMDNodes &AAInfo) {
6732   assert(Chain.getValueType() == MVT::Other &&
6733         "Invalid chain type");
6734   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
6735     Alignment = getEVTAlignment(SVT);
6736 
6737   MMOFlags |= MachineMemOperand::MOStore;
6738   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
6739 
6740   if (PtrInfo.V.isNull())
6741     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
6742 
6743   MachineFunction &MF = getMachineFunction();
6744   MachineMemOperand *MMO = MF.getMachineMemOperand(
6745       PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
6746   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
6747 }
6748 
6749 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
6750                                     SDValue Ptr, EVT SVT,
6751                                     MachineMemOperand *MMO) {
6752   EVT VT = Val.getValueType();
6753 
6754   assert(Chain.getValueType() == MVT::Other &&
6755         "Invalid chain type");
6756   if (VT == SVT)
6757     return getStore(Chain, dl, Val, Ptr, MMO);
6758 
6759   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
6760          "Should only be a truncating store, not extending!");
6761   assert(VT.isInteger() == SVT.isInteger() &&
6762          "Can't do FP-INT conversion!");
6763   assert(VT.isVector() == SVT.isVector() &&
6764          "Cannot use trunc store to convert to or from a vector!");
6765   assert((!VT.isVector() ||
6766           VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
6767          "Cannot use trunc store to change the number of vector elements!");
6768 
6769   SDVTList VTs = getVTList(MVT::Other);
6770   SDValue Undef = getUNDEF(Ptr.getValueType());
6771   SDValue Ops[] = { Chain, Val, Ptr, Undef };
6772   FoldingSetNodeID ID;
6773   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6774   ID.AddInteger(SVT.getRawBits());
6775   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
6776       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
6777   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6778   void *IP = nullptr;
6779   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6780     cast<StoreSDNode>(E)->refineAlignment(MMO);
6781     return SDValue(E, 0);
6782   }
6783   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6784                                    ISD::UNINDEXED, true, SVT, MMO);
6785   createOperands(N, Ops);
6786 
6787   CSEMap.InsertNode(N, IP);
6788   InsertNode(N);
6789   SDValue V(N, 0);
6790   NewSDValueDbgMsg(V, "Creating new node: ", this);
6791   return V;
6792 }
6793 
6794 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
6795                                       SDValue Base, SDValue Offset,
6796                                       ISD::MemIndexedMode AM) {
6797   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
6798   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
6799   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
6800   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
6801   FoldingSetNodeID ID;
6802   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
6803   ID.AddInteger(ST->getMemoryVT().getRawBits());
6804   ID.AddInteger(ST->getRawSubclassData());
6805   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
6806   void *IP = nullptr;
6807   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
6808     return SDValue(E, 0);
6809 
6810   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
6811                                    ST->isTruncatingStore(), ST->getMemoryVT(),
6812                                    ST->getMemOperand());
6813   createOperands(N, Ops);
6814 
6815   CSEMap.InsertNode(N, IP);
6816   InsertNode(N);
6817   SDValue V(N, 0);
6818   NewSDValueDbgMsg(V, "Creating new node: ", this);
6819   return V;
6820 }
6821 
6822 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
6823                                     SDValue Ptr, SDValue Mask, SDValue PassThru,
6824                                     EVT MemVT, MachineMemOperand *MMO,
6825                                     ISD::LoadExtType ExtTy, bool isExpanding) {
6826   SDVTList VTs = getVTList(VT, MVT::Other);
6827   SDValue Ops[] = { Chain, Ptr, Mask, PassThru };
6828   FoldingSetNodeID ID;
6829   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
6830   ID.AddInteger(VT.getRawBits());
6831   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
6832       dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO));
6833   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6834   void *IP = nullptr;
6835   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6836     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
6837     return SDValue(E, 0);
6838   }
6839   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6840                                         ExtTy, isExpanding, MemVT, MMO);
6841   createOperands(N, Ops);
6842 
6843   CSEMap.InsertNode(N, IP);
6844   InsertNode(N);
6845   SDValue V(N, 0);
6846   NewSDValueDbgMsg(V, "Creating new node: ", this);
6847   return V;
6848 }
6849 
6850 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
6851                                      SDValue Val, SDValue Ptr, SDValue Mask,
6852                                      EVT MemVT, MachineMemOperand *MMO,
6853                                      bool IsTruncating, bool IsCompressing) {
6854   assert(Chain.getValueType() == MVT::Other &&
6855         "Invalid chain type");
6856   EVT VT = Val.getValueType();
6857   SDVTList VTs = getVTList(MVT::Other);
6858   SDValue Ops[] = { Chain, Val, Ptr, Mask };
6859   FoldingSetNodeID ID;
6860   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
6861   ID.AddInteger(VT.getRawBits());
6862   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
6863       dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO));
6864   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6865   void *IP = nullptr;
6866   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6867     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
6868     return SDValue(E, 0);
6869   }
6870   auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
6871                                          IsTruncating, IsCompressing, MemVT, MMO);
6872   createOperands(N, Ops);
6873 
6874   CSEMap.InsertNode(N, IP);
6875   InsertNode(N);
6876   SDValue V(N, 0);
6877   NewSDValueDbgMsg(V, "Creating new node: ", this);
6878   return V;
6879 }
6880 
6881 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
6882                                       ArrayRef<SDValue> Ops,
6883                                       MachineMemOperand *MMO) {
6884   assert(Ops.size() == 6 && "Incompatible number of operands");
6885 
6886   FoldingSetNodeID ID;
6887   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
6888   ID.AddInteger(VT.getRawBits());
6889   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
6890       dl.getIROrder(), VTs, VT, MMO));
6891   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6892   void *IP = nullptr;
6893   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6894     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
6895     return SDValue(E, 0);
6896   }
6897 
6898   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
6899                                           VTs, VT, MMO);
6900   createOperands(N, Ops);
6901 
6902   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
6903          "Incompatible type of the PassThru value in MaskedGatherSDNode");
6904   assert(N->getMask().getValueType().getVectorNumElements() ==
6905              N->getValueType(0).getVectorNumElements() &&
6906          "Vector width mismatch between mask and data");
6907   assert(N->getIndex().getValueType().getVectorNumElements() >=
6908              N->getValueType(0).getVectorNumElements() &&
6909          "Vector width mismatch between index and data");
6910   assert(isa<ConstantSDNode>(N->getScale()) &&
6911          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
6912          "Scale should be a constant power of 2");
6913 
6914   CSEMap.InsertNode(N, IP);
6915   InsertNode(N);
6916   SDValue V(N, 0);
6917   NewSDValueDbgMsg(V, "Creating new node: ", this);
6918   return V;
6919 }
6920 
6921 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
6922                                        ArrayRef<SDValue> Ops,
6923                                        MachineMemOperand *MMO) {
6924   assert(Ops.size() == 6 && "Incompatible number of operands");
6925 
6926   FoldingSetNodeID ID;
6927   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
6928   ID.AddInteger(VT.getRawBits());
6929   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
6930       dl.getIROrder(), VTs, VT, MMO));
6931   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6932   void *IP = nullptr;
6933   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6934     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
6935     return SDValue(E, 0);
6936   }
6937   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
6938                                            VTs, VT, MMO);
6939   createOperands(N, Ops);
6940 
6941   assert(N->getMask().getValueType().getVectorNumElements() ==
6942              N->getValue().getValueType().getVectorNumElements() &&
6943          "Vector width mismatch between mask and data");
6944   assert(N->getIndex().getValueType().getVectorNumElements() >=
6945              N->getValue().getValueType().getVectorNumElements() &&
6946          "Vector width mismatch between index and data");
6947   assert(isa<ConstantSDNode>(N->getScale()) &&
6948          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
6949          "Scale should be a constant power of 2");
6950 
6951   CSEMap.InsertNode(N, IP);
6952   InsertNode(N);
6953   SDValue V(N, 0);
6954   NewSDValueDbgMsg(V, "Creating new node: ", this);
6955   return V;
6956 }
6957 
6958 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
6959   // select undef, T, F --> T (if T is a constant), otherwise F
6960   // select, ?, undef, F --> F
6961   // select, ?, T, undef --> T
6962   if (Cond.isUndef())
6963     return isConstantValueOfAnyType(T) ? T : F;
6964   if (T.isUndef())
6965     return F;
6966   if (F.isUndef())
6967     return T;
6968 
6969   // select true, T, F --> T
6970   // select false, T, F --> F
6971   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
6972     return CondC->isNullValue() ? F : T;
6973 
6974   // TODO: This should simplify VSELECT with constant condition using something
6975   // like this (but check boolean contents to be complete?):
6976   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
6977   //    return T;
6978   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
6979   //    return F;
6980 
6981   // select ?, T, T --> T
6982   if (T == F)
6983     return T;
6984 
6985   return SDValue();
6986 }
6987 
6988 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
6989   // shift undef, Y --> 0 (can always assume that the undef value is 0)
6990   if (X.isUndef())
6991     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
6992   // shift X, undef --> undef (because it may shift by the bitwidth)
6993   if (Y.isUndef())
6994     return getUNDEF(X.getValueType());
6995 
6996   // shift 0, Y --> 0
6997   // shift X, 0 --> X
6998   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
6999     return X;
7000 
7001   // shift X, C >= bitwidth(X) --> undef
7002   // All vector elements must be too big (or undef) to avoid partial undefs.
7003   auto isShiftTooBig = [X](ConstantSDNode *Val) {
7004     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
7005   };
7006   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
7007     return getUNDEF(X.getValueType());
7008 
7009   return SDValue();
7010 }
7011 
7012 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
7013                                SDValue Ptr, SDValue SV, unsigned Align) {
7014   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
7015   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
7016 }
7017 
7018 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7019                               ArrayRef<SDUse> Ops) {
7020   switch (Ops.size()) {
7021   case 0: return getNode(Opcode, DL, VT);
7022   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
7023   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
7024   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
7025   default: break;
7026   }
7027 
7028   // Copy from an SDUse array into an SDValue array for use with
7029   // the regular getNode logic.
7030   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
7031   return getNode(Opcode, DL, VT, NewOps);
7032 }
7033 
7034 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7035                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7036   unsigned NumOps = Ops.size();
7037   switch (NumOps) {
7038   case 0: return getNode(Opcode, DL, VT);
7039   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
7040   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
7041   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
7042   default: break;
7043   }
7044 
7045   switch (Opcode) {
7046   default: break;
7047   case ISD::BUILD_VECTOR:
7048     // Attempt to simplify BUILD_VECTOR.
7049     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7050       return V;
7051     break;
7052   case ISD::CONCAT_VECTORS:
7053     // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
7054     if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
7055       return V;
7056     break;
7057   case ISD::SELECT_CC:
7058     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
7059     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
7060            "LHS and RHS of condition must have same type!");
7061     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7062            "True and False arms of SelectCC must have same type!");
7063     assert(Ops[2].getValueType() == VT &&
7064            "select_cc node must be of same type as true and false value!");
7065     break;
7066   case ISD::BR_CC:
7067     assert(NumOps == 5 && "BR_CC takes 5 operands!");
7068     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7069            "LHS/RHS of comparison should match types!");
7070     break;
7071   }
7072 
7073   // Memoize nodes.
7074   SDNode *N;
7075   SDVTList VTs = getVTList(VT);
7076 
7077   if (VT != MVT::Glue) {
7078     FoldingSetNodeID ID;
7079     AddNodeIDNode(ID, Opcode, VTs, Ops);
7080     void *IP = nullptr;
7081 
7082     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7083       return SDValue(E, 0);
7084 
7085     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7086     createOperands(N, Ops);
7087 
7088     CSEMap.InsertNode(N, IP);
7089   } else {
7090     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7091     createOperands(N, Ops);
7092   }
7093 
7094   InsertNode(N);
7095   SDValue V(N, 0);
7096   NewSDValueDbgMsg(V, "Creating new node: ", this);
7097   return V;
7098 }
7099 
7100 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7101                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
7102   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
7103 }
7104 
7105 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7106                               ArrayRef<SDValue> Ops) {
7107   if (VTList.NumVTs == 1)
7108     return getNode(Opcode, DL, VTList.VTs[0], Ops);
7109 
7110 #if 0
7111   switch (Opcode) {
7112   // FIXME: figure out how to safely handle things like
7113   // int foo(int x) { return 1 << (x & 255); }
7114   // int bar() { return foo(256); }
7115   case ISD::SRA_PARTS:
7116   case ISD::SRL_PARTS:
7117   case ISD::SHL_PARTS:
7118     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7119         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
7120       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7121     else if (N3.getOpcode() == ISD::AND)
7122       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
7123         // If the and is only masking out bits that cannot effect the shift,
7124         // eliminate the and.
7125         unsigned NumBits = VT.getScalarSizeInBits()*2;
7126         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
7127           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7128       }
7129     break;
7130   }
7131 #endif
7132 
7133   // Memoize the node unless it returns a flag.
7134   SDNode *N;
7135   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7136     FoldingSetNodeID ID;
7137     AddNodeIDNode(ID, Opcode, VTList, Ops);
7138     void *IP = nullptr;
7139     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7140       return SDValue(E, 0);
7141 
7142     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7143     createOperands(N, Ops);
7144     CSEMap.InsertNode(N, IP);
7145   } else {
7146     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7147     createOperands(N, Ops);
7148   }
7149   InsertNode(N);
7150   SDValue V(N, 0);
7151   NewSDValueDbgMsg(V, "Creating new node: ", this);
7152   return V;
7153 }
7154 
7155 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7156                               SDVTList VTList) {
7157   return getNode(Opcode, DL, VTList, None);
7158 }
7159 
7160 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7161                               SDValue N1) {
7162   SDValue Ops[] = { N1 };
7163   return getNode(Opcode, DL, VTList, Ops);
7164 }
7165 
7166 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7167                               SDValue N1, SDValue N2) {
7168   SDValue Ops[] = { N1, N2 };
7169   return getNode(Opcode, DL, VTList, Ops);
7170 }
7171 
7172 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7173                               SDValue N1, SDValue N2, SDValue N3) {
7174   SDValue Ops[] = { N1, N2, N3 };
7175   return getNode(Opcode, DL, VTList, Ops);
7176 }
7177 
7178 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7179                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
7180   SDValue Ops[] = { N1, N2, N3, N4 };
7181   return getNode(Opcode, DL, VTList, Ops);
7182 }
7183 
7184 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7185                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
7186                               SDValue N5) {
7187   SDValue Ops[] = { N1, N2, N3, N4, N5 };
7188   return getNode(Opcode, DL, VTList, Ops);
7189 }
7190 
7191 SDVTList SelectionDAG::getVTList(EVT VT) {
7192   return makeVTList(SDNode::getValueTypeList(VT), 1);
7193 }
7194 
7195 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
7196   FoldingSetNodeID ID;
7197   ID.AddInteger(2U);
7198   ID.AddInteger(VT1.getRawBits());
7199   ID.AddInteger(VT2.getRawBits());
7200 
7201   void *IP = nullptr;
7202   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7203   if (!Result) {
7204     EVT *Array = Allocator.Allocate<EVT>(2);
7205     Array[0] = VT1;
7206     Array[1] = VT2;
7207     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
7208     VTListMap.InsertNode(Result, IP);
7209   }
7210   return Result->getSDVTList();
7211 }
7212 
7213 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
7214   FoldingSetNodeID ID;
7215   ID.AddInteger(3U);
7216   ID.AddInteger(VT1.getRawBits());
7217   ID.AddInteger(VT2.getRawBits());
7218   ID.AddInteger(VT3.getRawBits());
7219 
7220   void *IP = nullptr;
7221   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7222   if (!Result) {
7223     EVT *Array = Allocator.Allocate<EVT>(3);
7224     Array[0] = VT1;
7225     Array[1] = VT2;
7226     Array[2] = VT3;
7227     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
7228     VTListMap.InsertNode(Result, IP);
7229   }
7230   return Result->getSDVTList();
7231 }
7232 
7233 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
7234   FoldingSetNodeID ID;
7235   ID.AddInteger(4U);
7236   ID.AddInteger(VT1.getRawBits());
7237   ID.AddInteger(VT2.getRawBits());
7238   ID.AddInteger(VT3.getRawBits());
7239   ID.AddInteger(VT4.getRawBits());
7240 
7241   void *IP = nullptr;
7242   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7243   if (!Result) {
7244     EVT *Array = Allocator.Allocate<EVT>(4);
7245     Array[0] = VT1;
7246     Array[1] = VT2;
7247     Array[2] = VT3;
7248     Array[3] = VT4;
7249     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
7250     VTListMap.InsertNode(Result, IP);
7251   }
7252   return Result->getSDVTList();
7253 }
7254 
7255 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
7256   unsigned NumVTs = VTs.size();
7257   FoldingSetNodeID ID;
7258   ID.AddInteger(NumVTs);
7259   for (unsigned index = 0; index < NumVTs; index++) {
7260     ID.AddInteger(VTs[index].getRawBits());
7261   }
7262 
7263   void *IP = nullptr;
7264   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7265   if (!Result) {
7266     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
7267     llvm::copy(VTs, Array);
7268     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
7269     VTListMap.InsertNode(Result, IP);
7270   }
7271   return Result->getSDVTList();
7272 }
7273 
7274 
7275 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
7276 /// specified operands.  If the resultant node already exists in the DAG,
7277 /// this does not modify the specified node, instead it returns the node that
7278 /// already exists.  If the resultant node does not exist in the DAG, the
7279 /// input node is returned.  As a degenerate case, if you specify the same
7280 /// input operands as the node already has, the input node is returned.
7281 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
7282   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
7283 
7284   // Check to see if there is no change.
7285   if (Op == N->getOperand(0)) return N;
7286 
7287   // See if the modified node already exists.
7288   void *InsertPos = nullptr;
7289   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
7290     return Existing;
7291 
7292   // Nope it doesn't.  Remove the node from its current place in the maps.
7293   if (InsertPos)
7294     if (!RemoveNodeFromCSEMaps(N))
7295       InsertPos = nullptr;
7296 
7297   // Now we update the operands.
7298   N->OperandList[0].set(Op);
7299 
7300   updateDivergence(N);
7301   // If this gets put into a CSE map, add it.
7302   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7303   return N;
7304 }
7305 
7306 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
7307   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
7308 
7309   // Check to see if there is no change.
7310   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
7311     return N;   // No operands changed, just return the input node.
7312 
7313   // See if the modified node already exists.
7314   void *InsertPos = nullptr;
7315   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
7316     return Existing;
7317 
7318   // Nope it doesn't.  Remove the node from its current place in the maps.
7319   if (InsertPos)
7320     if (!RemoveNodeFromCSEMaps(N))
7321       InsertPos = nullptr;
7322 
7323   // Now we update the operands.
7324   if (N->OperandList[0] != Op1)
7325     N->OperandList[0].set(Op1);
7326   if (N->OperandList[1] != Op2)
7327     N->OperandList[1].set(Op2);
7328 
7329   updateDivergence(N);
7330   // If this gets put into a CSE map, add it.
7331   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7332   return N;
7333 }
7334 
7335 SDNode *SelectionDAG::
7336 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
7337   SDValue Ops[] = { Op1, Op2, Op3 };
7338   return UpdateNodeOperands(N, Ops);
7339 }
7340 
7341 SDNode *SelectionDAG::
7342 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
7343                    SDValue Op3, SDValue Op4) {
7344   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
7345   return UpdateNodeOperands(N, Ops);
7346 }
7347 
7348 SDNode *SelectionDAG::
7349 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
7350                    SDValue Op3, SDValue Op4, SDValue Op5) {
7351   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
7352   return UpdateNodeOperands(N, Ops);
7353 }
7354 
7355 SDNode *SelectionDAG::
7356 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
7357   unsigned NumOps = Ops.size();
7358   assert(N->getNumOperands() == NumOps &&
7359          "Update with wrong number of operands");
7360 
7361   // If no operands changed just return the input node.
7362   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
7363     return N;
7364 
7365   // See if the modified node already exists.
7366   void *InsertPos = nullptr;
7367   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
7368     return Existing;
7369 
7370   // Nope it doesn't.  Remove the node from its current place in the maps.
7371   if (InsertPos)
7372     if (!RemoveNodeFromCSEMaps(N))
7373       InsertPos = nullptr;
7374 
7375   // Now we update the operands.
7376   for (unsigned i = 0; i != NumOps; ++i)
7377     if (N->OperandList[i] != Ops[i])
7378       N->OperandList[i].set(Ops[i]);
7379 
7380   updateDivergence(N);
7381   // If this gets put into a CSE map, add it.
7382   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7383   return N;
7384 }
7385 
7386 /// DropOperands - Release the operands and set this node to have
7387 /// zero operands.
7388 void SDNode::DropOperands() {
7389   // Unlike the code in MorphNodeTo that does this, we don't need to
7390   // watch for dead nodes here.
7391   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
7392     SDUse &Use = *I++;
7393     Use.set(SDValue());
7394   }
7395 }
7396 
7397 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
7398                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
7399   if (NewMemRefs.empty()) {
7400     N->clearMemRefs();
7401     return;
7402   }
7403 
7404   // Check if we can avoid allocating by storing a single reference directly.
7405   if (NewMemRefs.size() == 1) {
7406     N->MemRefs = NewMemRefs[0];
7407     N->NumMemRefs = 1;
7408     return;
7409   }
7410 
7411   MachineMemOperand **MemRefsBuffer =
7412       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
7413   llvm::copy(NewMemRefs, MemRefsBuffer);
7414   N->MemRefs = MemRefsBuffer;
7415   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
7416 }
7417 
7418 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
7419 /// machine opcode.
7420 ///
7421 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7422                                    EVT VT) {
7423   SDVTList VTs = getVTList(VT);
7424   return SelectNodeTo(N, MachineOpc, VTs, None);
7425 }
7426 
7427 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7428                                    EVT VT, SDValue Op1) {
7429   SDVTList VTs = getVTList(VT);
7430   SDValue Ops[] = { Op1 };
7431   return SelectNodeTo(N, MachineOpc, VTs, Ops);
7432 }
7433 
7434 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7435                                    EVT VT, SDValue Op1,
7436                                    SDValue Op2) {
7437   SDVTList VTs = getVTList(VT);
7438   SDValue Ops[] = { Op1, Op2 };
7439   return SelectNodeTo(N, MachineOpc, VTs, Ops);
7440 }
7441 
7442 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7443                                    EVT VT, SDValue Op1,
7444                                    SDValue Op2, SDValue Op3) {
7445   SDVTList VTs = getVTList(VT);
7446   SDValue Ops[] = { Op1, Op2, Op3 };
7447   return SelectNodeTo(N, MachineOpc, VTs, Ops);
7448 }
7449 
7450 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7451                                    EVT VT, ArrayRef<SDValue> Ops) {
7452   SDVTList VTs = getVTList(VT);
7453   return SelectNodeTo(N, MachineOpc, VTs, Ops);
7454 }
7455 
7456 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7457                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
7458   SDVTList VTs = getVTList(VT1, VT2);
7459   return SelectNodeTo(N, MachineOpc, VTs, Ops);
7460 }
7461 
7462 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7463                                    EVT VT1, EVT VT2) {
7464   SDVTList VTs = getVTList(VT1, VT2);
7465   return SelectNodeTo(N, MachineOpc, VTs, None);
7466 }
7467 
7468 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7469                                    EVT VT1, EVT VT2, EVT VT3,
7470                                    ArrayRef<SDValue> Ops) {
7471   SDVTList VTs = getVTList(VT1, VT2, VT3);
7472   return SelectNodeTo(N, MachineOpc, VTs, Ops);
7473 }
7474 
7475 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7476                                    EVT VT1, EVT VT2,
7477                                    SDValue Op1, SDValue Op2) {
7478   SDVTList VTs = getVTList(VT1, VT2);
7479   SDValue Ops[] = { Op1, Op2 };
7480   return SelectNodeTo(N, MachineOpc, VTs, Ops);
7481 }
7482 
7483 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
7484                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
7485   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
7486   // Reset the NodeID to -1.
7487   New->setNodeId(-1);
7488   if (New != N) {
7489     ReplaceAllUsesWith(N, New);
7490     RemoveDeadNode(N);
7491   }
7492   return New;
7493 }
7494 
7495 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
7496 /// the line number information on the merged node since it is not possible to
7497 /// preserve the information that operation is associated with multiple lines.
7498 /// This will make the debugger working better at -O0, were there is a higher
7499 /// probability having other instructions associated with that line.
7500 ///
7501 /// For IROrder, we keep the smaller of the two
7502 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
7503   DebugLoc NLoc = N->getDebugLoc();
7504   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
7505     N->setDebugLoc(DebugLoc());
7506   }
7507   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
7508   N->setIROrder(Order);
7509   return N;
7510 }
7511 
7512 /// MorphNodeTo - This *mutates* the specified node to have the specified
7513 /// return type, opcode, and operands.
7514 ///
7515 /// Note that MorphNodeTo returns the resultant node.  If there is already a
7516 /// node of the specified opcode and operands, it returns that node instead of
7517 /// the current one.  Note that the SDLoc need not be the same.
7518 ///
7519 /// Using MorphNodeTo is faster than creating a new node and swapping it in
7520 /// with ReplaceAllUsesWith both because it often avoids allocating a new
7521 /// node, and because it doesn't require CSE recalculation for any of
7522 /// the node's users.
7523 ///
7524 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
7525 /// As a consequence it isn't appropriate to use from within the DAG combiner or
7526 /// the legalizer which maintain worklists that would need to be updated when
7527 /// deleting things.
7528 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
7529                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
7530   // If an identical node already exists, use it.
7531   void *IP = nullptr;
7532   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
7533     FoldingSetNodeID ID;
7534     AddNodeIDNode(ID, Opc, VTs, Ops);
7535     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
7536       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
7537   }
7538 
7539   if (!RemoveNodeFromCSEMaps(N))
7540     IP = nullptr;
7541 
7542   // Start the morphing.
7543   N->NodeType = Opc;
7544   N->ValueList = VTs.VTs;
7545   N->NumValues = VTs.NumVTs;
7546 
7547   // Clear the operands list, updating used nodes to remove this from their
7548   // use list.  Keep track of any operands that become dead as a result.
7549   SmallPtrSet<SDNode*, 16> DeadNodeSet;
7550   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
7551     SDUse &Use = *I++;
7552     SDNode *Used = Use.getNode();
7553     Use.set(SDValue());
7554     if (Used->use_empty())
7555       DeadNodeSet.insert(Used);
7556   }
7557 
7558   // For MachineNode, initialize the memory references information.
7559   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
7560     MN->clearMemRefs();
7561 
7562   // Swap for an appropriately sized array from the recycler.
7563   removeOperands(N);
7564   createOperands(N, Ops);
7565 
7566   // Delete any nodes that are still dead after adding the uses for the
7567   // new operands.
7568   if (!DeadNodeSet.empty()) {
7569     SmallVector<SDNode *, 16> DeadNodes;
7570     for (SDNode *N : DeadNodeSet)
7571       if (N->use_empty())
7572         DeadNodes.push_back(N);
7573     RemoveDeadNodes(DeadNodes);
7574   }
7575 
7576   if (IP)
7577     CSEMap.InsertNode(N, IP);   // Memoize the new node.
7578   return N;
7579 }
7580 
7581 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
7582   unsigned OrigOpc = Node->getOpcode();
7583   unsigned NewOpc;
7584   bool IsUnary = false;
7585   bool IsTernary = false;
7586   switch (OrigOpc) {
7587   default:
7588     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
7589   case ISD::STRICT_FADD: NewOpc = ISD::FADD; break;
7590   case ISD::STRICT_FSUB: NewOpc = ISD::FSUB; break;
7591   case ISD::STRICT_FMUL: NewOpc = ISD::FMUL; break;
7592   case ISD::STRICT_FDIV: NewOpc = ISD::FDIV; break;
7593   case ISD::STRICT_FREM: NewOpc = ISD::FREM; break;
7594   case ISD::STRICT_FMA: NewOpc = ISD::FMA; IsTernary = true; break;
7595   case ISD::STRICT_FSQRT: NewOpc = ISD::FSQRT; IsUnary = true; break;
7596   case ISD::STRICT_FPOW: NewOpc = ISD::FPOW; break;
7597   case ISD::STRICT_FPOWI: NewOpc = ISD::FPOWI; break;
7598   case ISD::STRICT_FSIN: NewOpc = ISD::FSIN; IsUnary = true; break;
7599   case ISD::STRICT_FCOS: NewOpc = ISD::FCOS; IsUnary = true; break;
7600   case ISD::STRICT_FEXP: NewOpc = ISD::FEXP; IsUnary = true; break;
7601   case ISD::STRICT_FEXP2: NewOpc = ISD::FEXP2; IsUnary = true; break;
7602   case ISD::STRICT_FLOG: NewOpc = ISD::FLOG; IsUnary = true; break;
7603   case ISD::STRICT_FLOG10: NewOpc = ISD::FLOG10; IsUnary = true; break;
7604   case ISD::STRICT_FLOG2: NewOpc = ISD::FLOG2; IsUnary = true; break;
7605   case ISD::STRICT_FRINT: NewOpc = ISD::FRINT; IsUnary = true; break;
7606   case ISD::STRICT_FNEARBYINT:
7607     NewOpc = ISD::FNEARBYINT;
7608     IsUnary = true;
7609     break;
7610   case ISD::STRICT_FMAXNUM: NewOpc = ISD::FMAXNUM; break;
7611   case ISD::STRICT_FMINNUM: NewOpc = ISD::FMINNUM; break;
7612   case ISD::STRICT_FCEIL: NewOpc = ISD::FCEIL; IsUnary = true; break;
7613   case ISD::STRICT_FFLOOR: NewOpc = ISD::FFLOOR; IsUnary = true; break;
7614   case ISD::STRICT_FROUND: NewOpc = ISD::FROUND; IsUnary = true; break;
7615   case ISD::STRICT_FTRUNC: NewOpc = ISD::FTRUNC; IsUnary = true; break;
7616   }
7617 
7618   // We're taking this node out of the chain, so we need to re-link things.
7619   SDValue InputChain = Node->getOperand(0);
7620   SDValue OutputChain = SDValue(Node, 1);
7621   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
7622 
7623   SDVTList VTs = getVTList(Node->getOperand(1).getValueType());
7624   SDNode *Res = nullptr;
7625   if (IsUnary)
7626     Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1) });
7627   else if (IsTernary)
7628     Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1),
7629                                            Node->getOperand(2),
7630                                            Node->getOperand(3)});
7631   else
7632     Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1),
7633                                            Node->getOperand(2) });
7634 
7635   // MorphNodeTo can operate in two ways: if an existing node with the
7636   // specified operands exists, it can just return it.  Otherwise, it
7637   // updates the node in place to have the requested operands.
7638   if (Res == Node) {
7639     // If we updated the node in place, reset the node ID.  To the isel,
7640     // this should be just like a newly allocated machine node.
7641     Res->setNodeId(-1);
7642   } else {
7643     ReplaceAllUsesWith(Node, Res);
7644     RemoveDeadNode(Node);
7645   }
7646 
7647   return Res;
7648 }
7649 
7650 /// getMachineNode - These are used for target selectors to create a new node
7651 /// with specified return type(s), MachineInstr opcode, and operands.
7652 ///
7653 /// Note that getMachineNode returns the resultant node.  If there is already a
7654 /// node of the specified opcode and operands, it returns that node instead of
7655 /// the current one.
7656 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7657                                             EVT VT) {
7658   SDVTList VTs = getVTList(VT);
7659   return getMachineNode(Opcode, dl, VTs, None);
7660 }
7661 
7662 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7663                                             EVT VT, SDValue Op1) {
7664   SDVTList VTs = getVTList(VT);
7665   SDValue Ops[] = { Op1 };
7666   return getMachineNode(Opcode, dl, VTs, Ops);
7667 }
7668 
7669 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7670                                             EVT VT, SDValue Op1, SDValue Op2) {
7671   SDVTList VTs = getVTList(VT);
7672   SDValue Ops[] = { Op1, Op2 };
7673   return getMachineNode(Opcode, dl, VTs, Ops);
7674 }
7675 
7676 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7677                                             EVT VT, SDValue Op1, SDValue Op2,
7678                                             SDValue Op3) {
7679   SDVTList VTs = getVTList(VT);
7680   SDValue Ops[] = { Op1, Op2, Op3 };
7681   return getMachineNode(Opcode, dl, VTs, Ops);
7682 }
7683 
7684 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7685                                             EVT VT, ArrayRef<SDValue> Ops) {
7686   SDVTList VTs = getVTList(VT);
7687   return getMachineNode(Opcode, dl, VTs, Ops);
7688 }
7689 
7690 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7691                                             EVT VT1, EVT VT2, SDValue Op1,
7692                                             SDValue Op2) {
7693   SDVTList VTs = getVTList(VT1, VT2);
7694   SDValue Ops[] = { Op1, Op2 };
7695   return getMachineNode(Opcode, dl, VTs, Ops);
7696 }
7697 
7698 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7699                                             EVT VT1, EVT VT2, SDValue Op1,
7700                                             SDValue Op2, SDValue Op3) {
7701   SDVTList VTs = getVTList(VT1, VT2);
7702   SDValue Ops[] = { Op1, Op2, Op3 };
7703   return getMachineNode(Opcode, dl, VTs, Ops);
7704 }
7705 
7706 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7707                                             EVT VT1, EVT VT2,
7708                                             ArrayRef<SDValue> Ops) {
7709   SDVTList VTs = getVTList(VT1, VT2);
7710   return getMachineNode(Opcode, dl, VTs, Ops);
7711 }
7712 
7713 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7714                                             EVT VT1, EVT VT2, EVT VT3,
7715                                             SDValue Op1, SDValue Op2) {
7716   SDVTList VTs = getVTList(VT1, VT2, VT3);
7717   SDValue Ops[] = { Op1, Op2 };
7718   return getMachineNode(Opcode, dl, VTs, Ops);
7719 }
7720 
7721 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7722                                             EVT VT1, EVT VT2, EVT VT3,
7723                                             SDValue Op1, SDValue Op2,
7724                                             SDValue Op3) {
7725   SDVTList VTs = getVTList(VT1, VT2, VT3);
7726   SDValue Ops[] = { Op1, Op2, Op3 };
7727   return getMachineNode(Opcode, dl, VTs, Ops);
7728 }
7729 
7730 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7731                                             EVT VT1, EVT VT2, EVT VT3,
7732                                             ArrayRef<SDValue> Ops) {
7733   SDVTList VTs = getVTList(VT1, VT2, VT3);
7734   return getMachineNode(Opcode, dl, VTs, Ops);
7735 }
7736 
7737 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
7738                                             ArrayRef<EVT> ResultTys,
7739                                             ArrayRef<SDValue> Ops) {
7740   SDVTList VTs = getVTList(ResultTys);
7741   return getMachineNode(Opcode, dl, VTs, Ops);
7742 }
7743 
7744 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
7745                                             SDVTList VTs,
7746                                             ArrayRef<SDValue> Ops) {
7747   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
7748   MachineSDNode *N;
7749   void *IP = nullptr;
7750 
7751   if (DoCSE) {
7752     FoldingSetNodeID ID;
7753     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
7754     IP = nullptr;
7755     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
7756       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
7757     }
7758   }
7759 
7760   // Allocate a new MachineSDNode.
7761   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7762   createOperands(N, Ops);
7763 
7764   if (DoCSE)
7765     CSEMap.InsertNode(N, IP);
7766 
7767   InsertNode(N);
7768   return N;
7769 }
7770 
7771 /// getTargetExtractSubreg - A convenience function for creating
7772 /// TargetOpcode::EXTRACT_SUBREG nodes.
7773 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
7774                                              SDValue Operand) {
7775   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
7776   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
7777                                   VT, Operand, SRIdxVal);
7778   return SDValue(Subreg, 0);
7779 }
7780 
7781 /// getTargetInsertSubreg - A convenience function for creating
7782 /// TargetOpcode::INSERT_SUBREG nodes.
7783 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
7784                                             SDValue Operand, SDValue Subreg) {
7785   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
7786   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
7787                                   VT, Operand, Subreg, SRIdxVal);
7788   return SDValue(Result, 0);
7789 }
7790 
7791 /// getNodeIfExists - Get the specified node if it's already available, or
7792 /// else return NULL.
7793 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
7794                                       ArrayRef<SDValue> Ops,
7795                                       const SDNodeFlags Flags) {
7796   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
7797     FoldingSetNodeID ID;
7798     AddNodeIDNode(ID, Opcode, VTList, Ops);
7799     void *IP = nullptr;
7800     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
7801       E->intersectFlagsWith(Flags);
7802       return E;
7803     }
7804   }
7805   return nullptr;
7806 }
7807 
7808 /// getDbgValue - Creates a SDDbgValue node.
7809 ///
7810 /// SDNode
7811 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
7812                                       SDNode *N, unsigned R, bool IsIndirect,
7813                                       const DebugLoc &DL, unsigned O) {
7814   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7815          "Expected inlined-at fields to agree");
7816   return new (DbgInfo->getAlloc())
7817       SDDbgValue(Var, Expr, N, R, IsIndirect, DL, O);
7818 }
7819 
7820 /// Constant
7821 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
7822                                               DIExpression *Expr,
7823                                               const Value *C,
7824                                               const DebugLoc &DL, unsigned O) {
7825   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7826          "Expected inlined-at fields to agree");
7827   return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, DL, O);
7828 }
7829 
7830 /// FrameIndex
7831 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
7832                                                 DIExpression *Expr, unsigned FI,
7833                                                 bool IsIndirect,
7834                                                 const DebugLoc &DL,
7835                                                 unsigned O) {
7836   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7837          "Expected inlined-at fields to agree");
7838   return new (DbgInfo->getAlloc())
7839       SDDbgValue(Var, Expr, FI, IsIndirect, DL, O, SDDbgValue::FRAMEIX);
7840 }
7841 
7842 /// VReg
7843 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var,
7844                                           DIExpression *Expr,
7845                                           unsigned VReg, bool IsIndirect,
7846                                           const DebugLoc &DL, unsigned O) {
7847   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
7848          "Expected inlined-at fields to agree");
7849   return new (DbgInfo->getAlloc())
7850       SDDbgValue(Var, Expr, VReg, IsIndirect, DL, O, SDDbgValue::VREG);
7851 }
7852 
7853 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
7854                                      unsigned OffsetInBits, unsigned SizeInBits,
7855                                      bool InvalidateDbg) {
7856   SDNode *FromNode = From.getNode();
7857   SDNode *ToNode = To.getNode();
7858   assert(FromNode && ToNode && "Can't modify dbg values");
7859 
7860   // PR35338
7861   // TODO: assert(From != To && "Redundant dbg value transfer");
7862   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
7863   if (From == To || FromNode == ToNode)
7864     return;
7865 
7866   if (!FromNode->getHasDebugValue())
7867     return;
7868 
7869   SmallVector<SDDbgValue *, 2> ClonedDVs;
7870   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
7871     if (Dbg->getKind() != SDDbgValue::SDNODE || Dbg->isInvalidated())
7872       continue;
7873 
7874     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
7875 
7876     // Just transfer the dbg value attached to From.
7877     if (Dbg->getResNo() != From.getResNo())
7878       continue;
7879 
7880     DIVariable *Var = Dbg->getVariable();
7881     auto *Expr = Dbg->getExpression();
7882     // If a fragment is requested, update the expression.
7883     if (SizeInBits) {
7884       // When splitting a larger (e.g., sign-extended) value whose
7885       // lower bits are described with an SDDbgValue, do not attempt
7886       // to transfer the SDDbgValue to the upper bits.
7887       if (auto FI = Expr->getFragmentInfo())
7888         if (OffsetInBits + SizeInBits > FI->SizeInBits)
7889           continue;
7890       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
7891                                                              SizeInBits);
7892       if (!Fragment)
7893         continue;
7894       Expr = *Fragment;
7895     }
7896     // Clone the SDDbgValue and move it to To.
7897     SDDbgValue *Clone =
7898         getDbgValue(Var, Expr, ToNode, To.getResNo(), Dbg->isIndirect(),
7899                     Dbg->getDebugLoc(), Dbg->getOrder());
7900     ClonedDVs.push_back(Clone);
7901 
7902     if (InvalidateDbg) {
7903       // Invalidate value and indicate the SDDbgValue should not be emitted.
7904       Dbg->setIsInvalidated();
7905       Dbg->setIsEmitted();
7906     }
7907   }
7908 
7909   for (SDDbgValue *Dbg : ClonedDVs)
7910     AddDbgValue(Dbg, ToNode, false);
7911 }
7912 
7913 void SelectionDAG::salvageDebugInfo(SDNode &N) {
7914   if (!N.getHasDebugValue())
7915     return;
7916 
7917   SmallVector<SDDbgValue *, 2> ClonedDVs;
7918   for (auto DV : GetDbgValues(&N)) {
7919     if (DV->isInvalidated())
7920       continue;
7921     switch (N.getOpcode()) {
7922     default:
7923       break;
7924     case ISD::ADD:
7925       SDValue N0 = N.getOperand(0);
7926       SDValue N1 = N.getOperand(1);
7927       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
7928           isConstantIntBuildVectorOrConstantInt(N1)) {
7929         uint64_t Offset = N.getConstantOperandVal(1);
7930         // Rewrite an ADD constant node into a DIExpression. Since we are
7931         // performing arithmetic to compute the variable's *value* in the
7932         // DIExpression, we need to mark the expression with a
7933         // DW_OP_stack_value.
7934         auto *DIExpr = DV->getExpression();
7935         DIExpr = DIExpression::prepend(DIExpr, DIExpression::NoDeref, Offset,
7936                                        DIExpression::NoDeref,
7937                                        DIExpression::WithStackValue);
7938         SDDbgValue *Clone =
7939             getDbgValue(DV->getVariable(), DIExpr, N0.getNode(), N0.getResNo(),
7940                         DV->isIndirect(), DV->getDebugLoc(), DV->getOrder());
7941         ClonedDVs.push_back(Clone);
7942         DV->setIsInvalidated();
7943         DV->setIsEmitted();
7944         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
7945                    N0.getNode()->dumprFull(this);
7946                    dbgs() << " into " << *DIExpr << '\n');
7947       }
7948     }
7949   }
7950 
7951   for (SDDbgValue *Dbg : ClonedDVs)
7952     AddDbgValue(Dbg, Dbg->getSDNode(), false);
7953 }
7954 
7955 /// Creates a SDDbgLabel node.
7956 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
7957                                       const DebugLoc &DL, unsigned O) {
7958   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
7959          "Expected inlined-at fields to agree");
7960   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
7961 }
7962 
7963 namespace {
7964 
7965 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
7966 /// pointed to by a use iterator is deleted, increment the use iterator
7967 /// so that it doesn't dangle.
7968 ///
7969 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
7970   SDNode::use_iterator &UI;
7971   SDNode::use_iterator &UE;
7972 
7973   void NodeDeleted(SDNode *N, SDNode *E) override {
7974     // Increment the iterator as needed.
7975     while (UI != UE && N == *UI)
7976       ++UI;
7977   }
7978 
7979 public:
7980   RAUWUpdateListener(SelectionDAG &d,
7981                      SDNode::use_iterator &ui,
7982                      SDNode::use_iterator &ue)
7983     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
7984 };
7985 
7986 } // end anonymous namespace
7987 
7988 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
7989 /// This can cause recursive merging of nodes in the DAG.
7990 ///
7991 /// This version assumes From has a single result value.
7992 ///
7993 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
7994   SDNode *From = FromN.getNode();
7995   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
7996          "Cannot replace with this method!");
7997   assert(From != To.getNode() && "Cannot replace uses of with self");
7998 
7999   // Preserve Debug Values
8000   transferDbgValues(FromN, To);
8001 
8002   // Iterate over all the existing uses of From. New uses will be added
8003   // to the beginning of the use list, which we avoid visiting.
8004   // This specifically avoids visiting uses of From that arise while the
8005   // replacement is happening, because any such uses would be the result
8006   // of CSE: If an existing node looks like From after one of its operands
8007   // is replaced by To, we don't want to replace of all its users with To
8008   // too. See PR3018 for more info.
8009   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8010   RAUWUpdateListener Listener(*this, UI, UE);
8011   while (UI != UE) {
8012     SDNode *User = *UI;
8013 
8014     // This node is about to morph, remove its old self from the CSE maps.
8015     RemoveNodeFromCSEMaps(User);
8016 
8017     // A user can appear in a use list multiple times, and when this
8018     // happens the uses are usually next to each other in the list.
8019     // To help reduce the number of CSE recomputations, process all
8020     // the uses of this user that we can find this way.
8021     do {
8022       SDUse &Use = UI.getUse();
8023       ++UI;
8024       Use.set(To);
8025       if (To->isDivergent() != From->isDivergent())
8026         updateDivergence(User);
8027     } while (UI != UE && *UI == User);
8028     // Now that we have modified User, add it back to the CSE maps.  If it
8029     // already exists there, recursively merge the results together.
8030     AddModifiedNodeToCSEMaps(User);
8031   }
8032 
8033   // If we just RAUW'd the root, take note.
8034   if (FromN == getRoot())
8035     setRoot(To);
8036 }
8037 
8038 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8039 /// This can cause recursive merging of nodes in the DAG.
8040 ///
8041 /// This version assumes that for each value of From, there is a
8042 /// corresponding value in To in the same position with the same type.
8043 ///
8044 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
8045 #ifndef NDEBUG
8046   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8047     assert((!From->hasAnyUseOfValue(i) ||
8048             From->getValueType(i) == To->getValueType(i)) &&
8049            "Cannot use this version of ReplaceAllUsesWith!");
8050 #endif
8051 
8052   // Handle the trivial case.
8053   if (From == To)
8054     return;
8055 
8056   // Preserve Debug Info. Only do this if there's a use.
8057   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8058     if (From->hasAnyUseOfValue(i)) {
8059       assert((i < To->getNumValues()) && "Invalid To location");
8060       transferDbgValues(SDValue(From, i), SDValue(To, i));
8061     }
8062 
8063   // Iterate over just the existing users of From. See the comments in
8064   // the ReplaceAllUsesWith above.
8065   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8066   RAUWUpdateListener Listener(*this, UI, UE);
8067   while (UI != UE) {
8068     SDNode *User = *UI;
8069 
8070     // This node is about to morph, remove its old self from the CSE maps.
8071     RemoveNodeFromCSEMaps(User);
8072 
8073     // A user can appear in a use list multiple times, and when this
8074     // happens the uses are usually next to each other in the list.
8075     // To help reduce the number of CSE recomputations, process all
8076     // the uses of this user that we can find this way.
8077     do {
8078       SDUse &Use = UI.getUse();
8079       ++UI;
8080       Use.setNode(To);
8081       if (To->isDivergent() != From->isDivergent())
8082         updateDivergence(User);
8083     } while (UI != UE && *UI == User);
8084 
8085     // Now that we have modified User, add it back to the CSE maps.  If it
8086     // already exists there, recursively merge the results together.
8087     AddModifiedNodeToCSEMaps(User);
8088   }
8089 
8090   // If we just RAUW'd the root, take note.
8091   if (From == getRoot().getNode())
8092     setRoot(SDValue(To, getRoot().getResNo()));
8093 }
8094 
8095 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8096 /// This can cause recursive merging of nodes in the DAG.
8097 ///
8098 /// This version can replace From with any result values.  To must match the
8099 /// number and types of values returned by From.
8100 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
8101   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
8102     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
8103 
8104   // Preserve Debug Info.
8105   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8106     transferDbgValues(SDValue(From, i), To[i]);
8107 
8108   // Iterate over just the existing users of From. See the comments in
8109   // the ReplaceAllUsesWith above.
8110   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8111   RAUWUpdateListener Listener(*this, UI, UE);
8112   while (UI != UE) {
8113     SDNode *User = *UI;
8114 
8115     // This node is about to morph, remove its old self from the CSE maps.
8116     RemoveNodeFromCSEMaps(User);
8117 
8118     // A user can appear in a use list multiple times, and when this happens the
8119     // uses are usually next to each other in the list.  To help reduce the
8120     // number of CSE and divergence recomputations, process all the uses of this
8121     // user that we can find this way.
8122     bool To_IsDivergent = false;
8123     do {
8124       SDUse &Use = UI.getUse();
8125       const SDValue &ToOp = To[Use.getResNo()];
8126       ++UI;
8127       Use.set(ToOp);
8128       To_IsDivergent |= ToOp->isDivergent();
8129     } while (UI != UE && *UI == User);
8130 
8131     if (To_IsDivergent != From->isDivergent())
8132       updateDivergence(User);
8133 
8134     // Now that we have modified User, add it back to the CSE maps.  If it
8135     // already exists there, recursively merge the results together.
8136     AddModifiedNodeToCSEMaps(User);
8137   }
8138 
8139   // If we just RAUW'd the root, take note.
8140   if (From == getRoot().getNode())
8141     setRoot(SDValue(To[getRoot().getResNo()]));
8142 }
8143 
8144 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
8145 /// uses of other values produced by From.getNode() alone.  The Deleted
8146 /// vector is handled the same way as for ReplaceAllUsesWith.
8147 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
8148   // Handle the really simple, really trivial case efficiently.
8149   if (From == To) return;
8150 
8151   // Handle the simple, trivial, case efficiently.
8152   if (From.getNode()->getNumValues() == 1) {
8153     ReplaceAllUsesWith(From, To);
8154     return;
8155   }
8156 
8157   // Preserve Debug Info.
8158   transferDbgValues(From, To);
8159 
8160   // Iterate over just the existing users of From. See the comments in
8161   // the ReplaceAllUsesWith above.
8162   SDNode::use_iterator UI = From.getNode()->use_begin(),
8163                        UE = From.getNode()->use_end();
8164   RAUWUpdateListener Listener(*this, UI, UE);
8165   while (UI != UE) {
8166     SDNode *User = *UI;
8167     bool UserRemovedFromCSEMaps = false;
8168 
8169     // A user can appear in a use list multiple times, and when this
8170     // happens the uses are usually next to each other in the list.
8171     // To help reduce the number of CSE recomputations, process all
8172     // the uses of this user that we can find this way.
8173     do {
8174       SDUse &Use = UI.getUse();
8175 
8176       // Skip uses of different values from the same node.
8177       if (Use.getResNo() != From.getResNo()) {
8178         ++UI;
8179         continue;
8180       }
8181 
8182       // If this node hasn't been modified yet, it's still in the CSE maps,
8183       // so remove its old self from the CSE maps.
8184       if (!UserRemovedFromCSEMaps) {
8185         RemoveNodeFromCSEMaps(User);
8186         UserRemovedFromCSEMaps = true;
8187       }
8188 
8189       ++UI;
8190       Use.set(To);
8191       if (To->isDivergent() != From->isDivergent())
8192         updateDivergence(User);
8193     } while (UI != UE && *UI == User);
8194     // We are iterating over all uses of the From node, so if a use
8195     // doesn't use the specific value, no changes are made.
8196     if (!UserRemovedFromCSEMaps)
8197       continue;
8198 
8199     // Now that we have modified User, add it back to the CSE maps.  If it
8200     // already exists there, recursively merge the results together.
8201     AddModifiedNodeToCSEMaps(User);
8202   }
8203 
8204   // If we just RAUW'd the root, take note.
8205   if (From == getRoot())
8206     setRoot(To);
8207 }
8208 
8209 namespace {
8210 
8211   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
8212   /// to record information about a use.
8213   struct UseMemo {
8214     SDNode *User;
8215     unsigned Index;
8216     SDUse *Use;
8217   };
8218 
8219   /// operator< - Sort Memos by User.
8220   bool operator<(const UseMemo &L, const UseMemo &R) {
8221     return (intptr_t)L.User < (intptr_t)R.User;
8222   }
8223 
8224 } // end anonymous namespace
8225 
8226 void SelectionDAG::updateDivergence(SDNode * N)
8227 {
8228   if (TLI->isSDNodeAlwaysUniform(N))
8229     return;
8230   bool IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
8231   for (auto &Op : N->ops()) {
8232     if (Op.Val.getValueType() != MVT::Other)
8233       IsDivergent |= Op.getNode()->isDivergent();
8234   }
8235   if (N->SDNodeBits.IsDivergent != IsDivergent) {
8236     N->SDNodeBits.IsDivergent = IsDivergent;
8237     for (auto U : N->uses()) {
8238       updateDivergence(U);
8239     }
8240   }
8241 }
8242 
8243 
8244 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode*>& Order) {
8245   DenseMap<SDNode *, unsigned> Degree;
8246   Order.reserve(AllNodes.size());
8247   for (auto & N : allnodes()) {
8248     unsigned NOps = N.getNumOperands();
8249     Degree[&N] = NOps;
8250     if (0 == NOps)
8251       Order.push_back(&N);
8252   }
8253   for (std::vector<SDNode *>::iterator I = Order.begin();
8254   I!=Order.end();++I) {
8255     SDNode * N = *I;
8256     for (auto U : N->uses()) {
8257       unsigned &UnsortedOps = Degree[U];
8258       if (0 == --UnsortedOps)
8259         Order.push_back(U);
8260     }
8261   }
8262 }
8263 
8264 #ifndef NDEBUG
8265 void SelectionDAG::VerifyDAGDiverence()
8266 {
8267   std::vector<SDNode*> TopoOrder;
8268   CreateTopologicalOrder(TopoOrder);
8269   const TargetLowering &TLI = getTargetLoweringInfo();
8270   DenseMap<const SDNode *, bool> DivergenceMap;
8271   for (auto &N : allnodes()) {
8272     DivergenceMap[&N] = false;
8273   }
8274   for (auto N : TopoOrder) {
8275     bool IsDivergent = DivergenceMap[N];
8276     bool IsSDNodeDivergent = TLI.isSDNodeSourceOfDivergence(N, FLI, DA);
8277     for (auto &Op : N->ops()) {
8278       if (Op.Val.getValueType() != MVT::Other)
8279         IsSDNodeDivergent |= DivergenceMap[Op.getNode()];
8280     }
8281     if (!IsDivergent && IsSDNodeDivergent && !TLI.isSDNodeAlwaysUniform(N)) {
8282       DivergenceMap[N] = true;
8283     }
8284   }
8285   for (auto &N : allnodes()) {
8286     (void)N;
8287     assert(DivergenceMap[&N] == N.isDivergent() &&
8288            "Divergence bit inconsistency detected\n");
8289   }
8290 }
8291 #endif
8292 
8293 
8294 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
8295 /// uses of other values produced by From.getNode() alone.  The same value
8296 /// may appear in both the From and To list.  The Deleted vector is
8297 /// handled the same way as for ReplaceAllUsesWith.
8298 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
8299                                               const SDValue *To,
8300                                               unsigned Num){
8301   // Handle the simple, trivial case efficiently.
8302   if (Num == 1)
8303     return ReplaceAllUsesOfValueWith(*From, *To);
8304 
8305   transferDbgValues(*From, *To);
8306 
8307   // Read up all the uses and make records of them. This helps
8308   // processing new uses that are introduced during the
8309   // replacement process.
8310   SmallVector<UseMemo, 4> Uses;
8311   for (unsigned i = 0; i != Num; ++i) {
8312     unsigned FromResNo = From[i].getResNo();
8313     SDNode *FromNode = From[i].getNode();
8314     for (SDNode::use_iterator UI = FromNode->use_begin(),
8315          E = FromNode->use_end(); UI != E; ++UI) {
8316       SDUse &Use = UI.getUse();
8317       if (Use.getResNo() == FromResNo) {
8318         UseMemo Memo = { *UI, i, &Use };
8319         Uses.push_back(Memo);
8320       }
8321     }
8322   }
8323 
8324   // Sort the uses, so that all the uses from a given User are together.
8325   llvm::sort(Uses);
8326 
8327   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
8328        UseIndex != UseIndexEnd; ) {
8329     // We know that this user uses some value of From.  If it is the right
8330     // value, update it.
8331     SDNode *User = Uses[UseIndex].User;
8332 
8333     // This node is about to morph, remove its old self from the CSE maps.
8334     RemoveNodeFromCSEMaps(User);
8335 
8336     // The Uses array is sorted, so all the uses for a given User
8337     // are next to each other in the list.
8338     // To help reduce the number of CSE recomputations, process all
8339     // the uses of this user that we can find this way.
8340     do {
8341       unsigned i = Uses[UseIndex].Index;
8342       SDUse &Use = *Uses[UseIndex].Use;
8343       ++UseIndex;
8344 
8345       Use.set(To[i]);
8346     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
8347 
8348     // Now that we have modified User, add it back to the CSE maps.  If it
8349     // already exists there, recursively merge the results together.
8350     AddModifiedNodeToCSEMaps(User);
8351   }
8352 }
8353 
8354 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
8355 /// based on their topological order. It returns the maximum id and a vector
8356 /// of the SDNodes* in assigned order by reference.
8357 unsigned SelectionDAG::AssignTopologicalOrder() {
8358   unsigned DAGSize = 0;
8359 
8360   // SortedPos tracks the progress of the algorithm. Nodes before it are
8361   // sorted, nodes after it are unsorted. When the algorithm completes
8362   // it is at the end of the list.
8363   allnodes_iterator SortedPos = allnodes_begin();
8364 
8365   // Visit all the nodes. Move nodes with no operands to the front of
8366   // the list immediately. Annotate nodes that do have operands with their
8367   // operand count. Before we do this, the Node Id fields of the nodes
8368   // may contain arbitrary values. After, the Node Id fields for nodes
8369   // before SortedPos will contain the topological sort index, and the
8370   // Node Id fields for nodes At SortedPos and after will contain the
8371   // count of outstanding operands.
8372   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
8373     SDNode *N = &*I++;
8374     checkForCycles(N, this);
8375     unsigned Degree = N->getNumOperands();
8376     if (Degree == 0) {
8377       // A node with no uses, add it to the result array immediately.
8378       N->setNodeId(DAGSize++);
8379       allnodes_iterator Q(N);
8380       if (Q != SortedPos)
8381         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
8382       assert(SortedPos != AllNodes.end() && "Overran node list");
8383       ++SortedPos;
8384     } else {
8385       // Temporarily use the Node Id as scratch space for the degree count.
8386       N->setNodeId(Degree);
8387     }
8388   }
8389 
8390   // Visit all the nodes. As we iterate, move nodes into sorted order,
8391   // such that by the time the end is reached all nodes will be sorted.
8392   for (SDNode &Node : allnodes()) {
8393     SDNode *N = &Node;
8394     checkForCycles(N, this);
8395     // N is in sorted position, so all its uses have one less operand
8396     // that needs to be sorted.
8397     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
8398          UI != UE; ++UI) {
8399       SDNode *P = *UI;
8400       unsigned Degree = P->getNodeId();
8401       assert(Degree != 0 && "Invalid node degree");
8402       --Degree;
8403       if (Degree == 0) {
8404         // All of P's operands are sorted, so P may sorted now.
8405         P->setNodeId(DAGSize++);
8406         if (P->getIterator() != SortedPos)
8407           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
8408         assert(SortedPos != AllNodes.end() && "Overran node list");
8409         ++SortedPos;
8410       } else {
8411         // Update P's outstanding operand count.
8412         P->setNodeId(Degree);
8413       }
8414     }
8415     if (Node.getIterator() == SortedPos) {
8416 #ifndef NDEBUG
8417       allnodes_iterator I(N);
8418       SDNode *S = &*++I;
8419       dbgs() << "Overran sorted position:\n";
8420       S->dumprFull(this); dbgs() << "\n";
8421       dbgs() << "Checking if this is due to cycles\n";
8422       checkForCycles(this, true);
8423 #endif
8424       llvm_unreachable(nullptr);
8425     }
8426   }
8427 
8428   assert(SortedPos == AllNodes.end() &&
8429          "Topological sort incomplete!");
8430   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
8431          "First node in topological sort is not the entry token!");
8432   assert(AllNodes.front().getNodeId() == 0 &&
8433          "First node in topological sort has non-zero id!");
8434   assert(AllNodes.front().getNumOperands() == 0 &&
8435          "First node in topological sort has operands!");
8436   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
8437          "Last node in topologic sort has unexpected id!");
8438   assert(AllNodes.back().use_empty() &&
8439          "Last node in topologic sort has users!");
8440   assert(DAGSize == allnodes_size() && "Node count mismatch!");
8441   return DAGSize;
8442 }
8443 
8444 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
8445 /// value is produced by SD.
8446 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
8447   if (SD) {
8448     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
8449     SD->setHasDebugValue(true);
8450   }
8451   DbgInfo->add(DB, SD, isParameter);
8452 }
8453 
8454 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) {
8455   DbgInfo->add(DB);
8456 }
8457 
8458 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
8459                                                    SDValue NewMemOp) {
8460   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
8461   // The new memory operation must have the same position as the old load in
8462   // terms of memory dependency. Create a TokenFactor for the old load and new
8463   // memory operation and update uses of the old load's output chain to use that
8464   // TokenFactor.
8465   SDValue OldChain = SDValue(OldLoad, 1);
8466   SDValue NewChain = SDValue(NewMemOp.getNode(), 1);
8467   if (!OldLoad->hasAnyUseOfValue(1))
8468     return NewChain;
8469 
8470   SDValue TokenFactor =
8471       getNode(ISD::TokenFactor, SDLoc(OldLoad), MVT::Other, OldChain, NewChain);
8472   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
8473   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain);
8474   return TokenFactor;
8475 }
8476 
8477 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
8478                                                      Function **OutFunction) {
8479   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
8480 
8481   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8482   auto *Module = MF->getFunction().getParent();
8483   auto *Function = Module->getFunction(Symbol);
8484 
8485   if (OutFunction != nullptr)
8486       *OutFunction = Function;
8487 
8488   if (Function != nullptr) {
8489     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
8490     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
8491   }
8492 
8493   std::string ErrorStr;
8494   raw_string_ostream ErrorFormatter(ErrorStr);
8495 
8496   ErrorFormatter << "Undefined external symbol ";
8497   ErrorFormatter << '"' << Symbol << '"';
8498   ErrorFormatter.flush();
8499 
8500   report_fatal_error(ErrorStr);
8501 }
8502 
8503 //===----------------------------------------------------------------------===//
8504 //                              SDNode Class
8505 //===----------------------------------------------------------------------===//
8506 
8507 bool llvm::isNullConstant(SDValue V) {
8508   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
8509   return Const != nullptr && Const->isNullValue();
8510 }
8511 
8512 bool llvm::isNullFPConstant(SDValue V) {
8513   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
8514   return Const != nullptr && Const->isZero() && !Const->isNegative();
8515 }
8516 
8517 bool llvm::isAllOnesConstant(SDValue V) {
8518   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
8519   return Const != nullptr && Const->isAllOnesValue();
8520 }
8521 
8522 bool llvm::isOneConstant(SDValue V) {
8523   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
8524   return Const != nullptr && Const->isOne();
8525 }
8526 
8527 SDValue llvm::peekThroughBitcasts(SDValue V) {
8528   while (V.getOpcode() == ISD::BITCAST)
8529     V = V.getOperand(0);
8530   return V;
8531 }
8532 
8533 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
8534   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
8535     V = V.getOperand(0);
8536   return V;
8537 }
8538 
8539 bool llvm::isBitwiseNot(SDValue V) {
8540   if (V.getOpcode() != ISD::XOR)
8541     return false;
8542   ConstantSDNode *C = isConstOrConstSplat(peekThroughBitcasts(V.getOperand(1)));
8543   return C && C->isAllOnesValue();
8544 }
8545 
8546 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs) {
8547   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
8548     return CN;
8549 
8550   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
8551     BitVector UndefElements;
8552     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
8553 
8554     // BuildVectors can truncate their operands. Ignore that case here.
8555     if (CN && (UndefElements.none() || AllowUndefs) &&
8556         CN->getValueType(0) == N.getValueType().getScalarType())
8557       return CN;
8558   }
8559 
8560   return nullptr;
8561 }
8562 
8563 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
8564   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
8565     return CN;
8566 
8567   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
8568     BitVector UndefElements;
8569     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
8570     if (CN && (UndefElements.none() || AllowUndefs))
8571       return CN;
8572   }
8573 
8574   return nullptr;
8575 }
8576 
8577 bool llvm::isNullOrNullSplat(SDValue N) {
8578   // TODO: may want to use peekThroughBitcast() here.
8579   ConstantSDNode *C = isConstOrConstSplat(N);
8580   return C && C->isNullValue();
8581 }
8582 
8583 bool llvm::isOneOrOneSplat(SDValue N) {
8584   // TODO: may want to use peekThroughBitcast() here.
8585   unsigned BitWidth = N.getScalarValueSizeInBits();
8586   ConstantSDNode *C = isConstOrConstSplat(N);
8587   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
8588 }
8589 
8590 bool llvm::isAllOnesOrAllOnesSplat(SDValue N) {
8591   N = peekThroughBitcasts(N);
8592   unsigned BitWidth = N.getScalarValueSizeInBits();
8593   ConstantSDNode *C = isConstOrConstSplat(N);
8594   return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
8595 }
8596 
8597 HandleSDNode::~HandleSDNode() {
8598   DropOperands();
8599 }
8600 
8601 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
8602                                          const DebugLoc &DL,
8603                                          const GlobalValue *GA, EVT VT,
8604                                          int64_t o, unsigned char TF)
8605     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
8606   TheGlobal = GA;
8607 }
8608 
8609 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
8610                                          EVT VT, unsigned SrcAS,
8611                                          unsigned DestAS)
8612     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
8613       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
8614 
8615 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
8616                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
8617     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
8618   MemSDNodeBits.IsVolatile = MMO->isVolatile();
8619   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
8620   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
8621   MemSDNodeBits.IsInvariant = MMO->isInvariant();
8622 
8623   // We check here that the size of the memory operand fits within the size of
8624   // the MMO. This is because the MMO might indicate only a possible address
8625   // range instead of specifying the affected memory addresses precisely.
8626   assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
8627 }
8628 
8629 /// Profile - Gather unique data for the node.
8630 ///
8631 void SDNode::Profile(FoldingSetNodeID &ID) const {
8632   AddNodeIDNode(ID, this);
8633 }
8634 
8635 namespace {
8636 
8637   struct EVTArray {
8638     std::vector<EVT> VTs;
8639 
8640     EVTArray() {
8641       VTs.reserve(MVT::LAST_VALUETYPE);
8642       for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
8643         VTs.push_back(MVT((MVT::SimpleValueType)i));
8644     }
8645   };
8646 
8647 } // end anonymous namespace
8648 
8649 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
8650 static ManagedStatic<EVTArray> SimpleVTArray;
8651 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
8652 
8653 /// getValueTypeList - Return a pointer to the specified value type.
8654 ///
8655 const EVT *SDNode::getValueTypeList(EVT VT) {
8656   if (VT.isExtended()) {
8657     sys::SmartScopedLock<true> Lock(*VTMutex);
8658     return &(*EVTs->insert(VT).first);
8659   } else {
8660     assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
8661            "Value type out of range!");
8662     return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
8663   }
8664 }
8665 
8666 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
8667 /// indicated value.  This method ignores uses of other values defined by this
8668 /// operation.
8669 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
8670   assert(Value < getNumValues() && "Bad value!");
8671 
8672   // TODO: Only iterate over uses of a given value of the node
8673   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
8674     if (UI.getUse().getResNo() == Value) {
8675       if (NUses == 0)
8676         return false;
8677       --NUses;
8678     }
8679   }
8680 
8681   // Found exactly the right number of uses?
8682   return NUses == 0;
8683 }
8684 
8685 /// hasAnyUseOfValue - Return true if there are any use of the indicated
8686 /// value. This method ignores uses of other values defined by this operation.
8687 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
8688   assert(Value < getNumValues() && "Bad value!");
8689 
8690   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
8691     if (UI.getUse().getResNo() == Value)
8692       return true;
8693 
8694   return false;
8695 }
8696 
8697 /// isOnlyUserOf - Return true if this node is the only use of N.
8698 bool SDNode::isOnlyUserOf(const SDNode *N) const {
8699   bool Seen = false;
8700   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
8701     SDNode *User = *I;
8702     if (User == this)
8703       Seen = true;
8704     else
8705       return false;
8706   }
8707 
8708   return Seen;
8709 }
8710 
8711 /// Return true if the only users of N are contained in Nodes.
8712 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
8713   bool Seen = false;
8714   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
8715     SDNode *User = *I;
8716     if (llvm::any_of(Nodes,
8717                      [&User](const SDNode *Node) { return User == Node; }))
8718       Seen = true;
8719     else
8720       return false;
8721   }
8722 
8723   return Seen;
8724 }
8725 
8726 /// isOperand - Return true if this node is an operand of N.
8727 bool SDValue::isOperandOf(const SDNode *N) const {
8728   for (const SDValue &Op : N->op_values())
8729     if (*this == Op)
8730       return true;
8731   return false;
8732 }
8733 
8734 bool SDNode::isOperandOf(const SDNode *N) const {
8735   for (const SDValue &Op : N->op_values())
8736     if (this == Op.getNode())
8737       return true;
8738   return false;
8739 }
8740 
8741 /// reachesChainWithoutSideEffects - Return true if this operand (which must
8742 /// be a chain) reaches the specified operand without crossing any
8743 /// side-effecting instructions on any chain path.  In practice, this looks
8744 /// through token factors and non-volatile loads.  In order to remain efficient,
8745 /// this only looks a couple of nodes in, it does not do an exhaustive search.
8746 ///
8747 /// Note that we only need to examine chains when we're searching for
8748 /// side-effects; SelectionDAG requires that all side-effects are represented
8749 /// by chains, even if another operand would force a specific ordering. This
8750 /// constraint is necessary to allow transformations like splitting loads.
8751 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
8752                                              unsigned Depth) const {
8753   if (*this == Dest) return true;
8754 
8755   // Don't search too deeply, we just want to be able to see through
8756   // TokenFactor's etc.
8757   if (Depth == 0) return false;
8758 
8759   // If this is a token factor, all inputs to the TF happen in parallel.
8760   if (getOpcode() == ISD::TokenFactor) {
8761     // First, try a shallow search.
8762     if (is_contained((*this)->ops(), Dest)) {
8763       // We found the chain we want as an operand of this TokenFactor.
8764       // Essentially, we reach the chain without side-effects if we could
8765       // serialize the TokenFactor into a simple chain of operations with
8766       // Dest as the last operation. This is automatically true if the
8767       // chain has one use: there are no other ordering constraints.
8768       // If the chain has more than one use, we give up: some other
8769       // use of Dest might force a side-effect between Dest and the current
8770       // node.
8771       if (Dest.hasOneUse())
8772         return true;
8773     }
8774     // Next, try a deep search: check whether every operand of the TokenFactor
8775     // reaches Dest.
8776     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
8777       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
8778     });
8779   }
8780 
8781   // Loads don't have side effects, look through them.
8782   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
8783     if (!Ld->isVolatile())
8784       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
8785   }
8786   return false;
8787 }
8788 
8789 bool SDNode::hasPredecessor(const SDNode *N) const {
8790   SmallPtrSet<const SDNode *, 32> Visited;
8791   SmallVector<const SDNode *, 16> Worklist;
8792   Worklist.push_back(this);
8793   return hasPredecessorHelper(N, Visited, Worklist);
8794 }
8795 
8796 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
8797   this->Flags.intersectWith(Flags);
8798 }
8799 
8800 SDValue
8801 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
8802                                   ArrayRef<ISD::NodeType> CandidateBinOps) {
8803   // The pattern must end in an extract from index 0.
8804   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8805       !isNullConstant(Extract->getOperand(1)))
8806     return SDValue();
8807 
8808   SDValue Op = Extract->getOperand(0);
8809   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
8810 
8811   // Match against one of the candidate binary ops.
8812   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
8813         return Op.getOpcode() == unsigned(BinOp);
8814       }))
8815     return SDValue();
8816 
8817   // At each stage, we're looking for something that looks like:
8818   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
8819   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
8820   //                               i32 undef, i32 undef, i32 undef, i32 undef>
8821   // %a = binop <8 x i32> %op, %s
8822   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
8823   // we expect something like:
8824   // <4,5,6,7,u,u,u,u>
8825   // <2,3,u,u,u,u,u,u>
8826   // <1,u,u,u,u,u,u,u>
8827   unsigned CandidateBinOp = Op.getOpcode();
8828   for (unsigned i = 0; i < Stages; ++i) {
8829     if (Op.getOpcode() != CandidateBinOp)
8830       return SDValue();
8831 
8832     SDValue Op0 = Op.getOperand(0);
8833     SDValue Op1 = Op.getOperand(1);
8834 
8835     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
8836     if (Shuffle) {
8837       Op = Op1;
8838     } else {
8839       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
8840       Op = Op0;
8841     }
8842 
8843     // The first operand of the shuffle should be the same as the other operand
8844     // of the binop.
8845     if (!Shuffle || Shuffle->getOperand(0) != Op)
8846       return SDValue();
8847 
8848     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
8849     for (int Index = 0, MaskEnd = 1 << i; Index < MaskEnd; ++Index)
8850       if (Shuffle->getMaskElt(Index) != MaskEnd + Index)
8851         return SDValue();
8852   }
8853 
8854   BinOp = (ISD::NodeType)CandidateBinOp;
8855   return Op;
8856 }
8857 
8858 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
8859   assert(N->getNumValues() == 1 &&
8860          "Can't unroll a vector with multiple results!");
8861 
8862   EVT VT = N->getValueType(0);
8863   unsigned NE = VT.getVectorNumElements();
8864   EVT EltVT = VT.getVectorElementType();
8865   SDLoc dl(N);
8866 
8867   SmallVector<SDValue, 8> Scalars;
8868   SmallVector<SDValue, 4> Operands(N->getNumOperands());
8869 
8870   // If ResNE is 0, fully unroll the vector op.
8871   if (ResNE == 0)
8872     ResNE = NE;
8873   else if (NE > ResNE)
8874     NE = ResNE;
8875 
8876   unsigned i;
8877   for (i= 0; i != NE; ++i) {
8878     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
8879       SDValue Operand = N->getOperand(j);
8880       EVT OperandVT = Operand.getValueType();
8881       if (OperandVT.isVector()) {
8882         // A vector operand; extract a single element.
8883         EVT OperandEltVT = OperandVT.getVectorElementType();
8884         Operands[j] =
8885             getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
8886                     getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
8887       } else {
8888         // A scalar operand; just use it as is.
8889         Operands[j] = Operand;
8890       }
8891     }
8892 
8893     switch (N->getOpcode()) {
8894     default: {
8895       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
8896                                 N->getFlags()));
8897       break;
8898     }
8899     case ISD::VSELECT:
8900       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
8901       break;
8902     case ISD::SHL:
8903     case ISD::SRA:
8904     case ISD::SRL:
8905     case ISD::ROTL:
8906     case ISD::ROTR:
8907       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
8908                                getShiftAmountOperand(Operands[0].getValueType(),
8909                                                      Operands[1])));
8910       break;
8911     case ISD::SIGN_EXTEND_INREG:
8912     case ISD::FP_ROUND_INREG: {
8913       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
8914       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
8915                                 Operands[0],
8916                                 getValueType(ExtVT)));
8917     }
8918     }
8919   }
8920 
8921   for (; i < ResNE; ++i)
8922     Scalars.push_back(getUNDEF(EltVT));
8923 
8924   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
8925   return getBuildVector(VecVT, dl, Scalars);
8926 }
8927 
8928 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
8929                                                   LoadSDNode *Base,
8930                                                   unsigned Bytes,
8931                                                   int Dist) const {
8932   if (LD->isVolatile() || Base->isVolatile())
8933     return false;
8934   if (LD->isIndexed() || Base->isIndexed())
8935     return false;
8936   if (LD->getChain() != Base->getChain())
8937     return false;
8938   EVT VT = LD->getValueType(0);
8939   if (VT.getSizeInBits() / 8 != Bytes)
8940     return false;
8941 
8942   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
8943   auto LocDecomp = BaseIndexOffset::match(LD, *this);
8944 
8945   int64_t Offset = 0;
8946   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
8947     return (Dist * Bytes == Offset);
8948   return false;
8949 }
8950 
8951 /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
8952 /// it cannot be inferred.
8953 unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
8954   // If this is a GlobalAddress + cst, return the alignment.
8955   const GlobalValue *GV;
8956   int64_t GVOffset = 0;
8957   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
8958     unsigned IdxWidth = getDataLayout().getIndexTypeSizeInBits(GV->getType());
8959     KnownBits Known(IdxWidth);
8960     llvm::computeKnownBits(GV, Known, getDataLayout());
8961     unsigned AlignBits = Known.countMinTrailingZeros();
8962     unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
8963     if (Align)
8964       return MinAlign(Align, GVOffset);
8965   }
8966 
8967   // If this is a direct reference to a stack slot, use information about the
8968   // stack slot's alignment.
8969   int FrameIdx = 1 << 31;
8970   int64_t FrameOffset = 0;
8971   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
8972     FrameIdx = FI->getIndex();
8973   } else if (isBaseWithConstantOffset(Ptr) &&
8974              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
8975     // Handle FI+Cst
8976     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
8977     FrameOffset = Ptr.getConstantOperandVal(1);
8978   }
8979 
8980   if (FrameIdx != (1 << 31)) {
8981     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
8982     unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
8983                                     FrameOffset);
8984     return FIInfoAlign;
8985   }
8986 
8987   return 0;
8988 }
8989 
8990 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
8991 /// which is split (or expanded) into two not necessarily identical pieces.
8992 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
8993   // Currently all types are split in half.
8994   EVT LoVT, HiVT;
8995   if (!VT.isVector())
8996     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
8997   else
8998     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
8999 
9000   return std::make_pair(LoVT, HiVT);
9001 }
9002 
9003 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
9004 /// low/high part.
9005 std::pair<SDValue, SDValue>
9006 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
9007                           const EVT &HiVT) {
9008   assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
9009          N.getValueType().getVectorNumElements() &&
9010          "More vector elements requested than available!");
9011   SDValue Lo, Hi;
9012   Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
9013                getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
9014   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
9015                getConstant(LoVT.getVectorNumElements(), DL,
9016                            TLI->getVectorIdxTy(getDataLayout())));
9017   return std::make_pair(Lo, Hi);
9018 }
9019 
9020 void SelectionDAG::ExtractVectorElements(SDValue Op,
9021                                          SmallVectorImpl<SDValue> &Args,
9022                                          unsigned Start, unsigned Count) {
9023   EVT VT = Op.getValueType();
9024   if (Count == 0)
9025     Count = VT.getVectorNumElements();
9026 
9027   EVT EltVT = VT.getVectorElementType();
9028   EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
9029   SDLoc SL(Op);
9030   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
9031     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9032                            Op, getConstant(i, SL, IdxTy)));
9033   }
9034 }
9035 
9036 // getAddressSpace - Return the address space this GlobalAddress belongs to.
9037 unsigned GlobalAddressSDNode::getAddressSpace() const {
9038   return getGlobal()->getType()->getAddressSpace();
9039 }
9040 
9041 Type *ConstantPoolSDNode::getType() const {
9042   if (isMachineConstantPoolEntry())
9043     return Val.MachineCPVal->getType();
9044   return Val.ConstVal->getType();
9045 }
9046 
9047 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
9048                                         unsigned &SplatBitSize,
9049                                         bool &HasAnyUndefs,
9050                                         unsigned MinSplatBits,
9051                                         bool IsBigEndian) const {
9052   EVT VT = getValueType(0);
9053   assert(VT.isVector() && "Expected a vector type");
9054   unsigned VecWidth = VT.getSizeInBits();
9055   if (MinSplatBits > VecWidth)
9056     return false;
9057 
9058   // FIXME: The widths are based on this node's type, but build vectors can
9059   // truncate their operands.
9060   SplatValue = APInt(VecWidth, 0);
9061   SplatUndef = APInt(VecWidth, 0);
9062 
9063   // Get the bits. Bits with undefined values (when the corresponding element
9064   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
9065   // in SplatValue. If any of the values are not constant, give up and return
9066   // false.
9067   unsigned int NumOps = getNumOperands();
9068   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
9069   unsigned EltWidth = VT.getScalarSizeInBits();
9070 
9071   for (unsigned j = 0; j < NumOps; ++j) {
9072     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
9073     SDValue OpVal = getOperand(i);
9074     unsigned BitPos = j * EltWidth;
9075 
9076     if (OpVal.isUndef())
9077       SplatUndef.setBits(BitPos, BitPos + EltWidth);
9078     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
9079       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
9080     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
9081       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
9082     else
9083       return false;
9084   }
9085 
9086   // The build_vector is all constants or undefs. Find the smallest element
9087   // size that splats the vector.
9088   HasAnyUndefs = (SplatUndef != 0);
9089 
9090   // FIXME: This does not work for vectors with elements less than 8 bits.
9091   while (VecWidth > 8) {
9092     unsigned HalfSize = VecWidth / 2;
9093     APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
9094     APInt LowValue = SplatValue.trunc(HalfSize);
9095     APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
9096     APInt LowUndef = SplatUndef.trunc(HalfSize);
9097 
9098     // If the two halves do not match (ignoring undef bits), stop here.
9099     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
9100         MinSplatBits > HalfSize)
9101       break;
9102 
9103     SplatValue = HighValue | LowValue;
9104     SplatUndef = HighUndef & LowUndef;
9105 
9106     VecWidth = HalfSize;
9107   }
9108 
9109   SplatBitSize = VecWidth;
9110   return true;
9111 }
9112 
9113 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
9114   if (UndefElements) {
9115     UndefElements->clear();
9116     UndefElements->resize(getNumOperands());
9117   }
9118   SDValue Splatted;
9119   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
9120     SDValue Op = getOperand(i);
9121     if (Op.isUndef()) {
9122       if (UndefElements)
9123         (*UndefElements)[i] = true;
9124     } else if (!Splatted) {
9125       Splatted = Op;
9126     } else if (Splatted != Op) {
9127       return SDValue();
9128     }
9129   }
9130 
9131   if (!Splatted) {
9132     assert(getOperand(0).isUndef() &&
9133            "Can only have a splat without a constant for all undefs.");
9134     return getOperand(0);
9135   }
9136 
9137   return Splatted;
9138 }
9139 
9140 ConstantSDNode *
9141 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
9142   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
9143 }
9144 
9145 ConstantFPSDNode *
9146 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
9147   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
9148 }
9149 
9150 int32_t
9151 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
9152                                                    uint32_t BitWidth) const {
9153   if (ConstantFPSDNode *CN =
9154           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
9155     bool IsExact;
9156     APSInt IntVal(BitWidth);
9157     const APFloat &APF = CN->getValueAPF();
9158     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
9159             APFloat::opOK ||
9160         !IsExact)
9161       return -1;
9162 
9163     return IntVal.exactLogBase2();
9164   }
9165   return -1;
9166 }
9167 
9168 bool BuildVectorSDNode::isConstant() const {
9169   for (const SDValue &Op : op_values()) {
9170     unsigned Opc = Op.getOpcode();
9171     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
9172       return false;
9173   }
9174   return true;
9175 }
9176 
9177 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
9178   // Find the first non-undef value in the shuffle mask.
9179   unsigned i, e;
9180   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
9181     /* search */;
9182 
9183   assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
9184 
9185   // Make sure all remaining elements are either undef or the same as the first
9186   // non-undef value.
9187   for (int Idx = Mask[i]; i != e; ++i)
9188     if (Mask[i] >= 0 && Mask[i] != Idx)
9189       return false;
9190   return true;
9191 }
9192 
9193 // Returns the SDNode if it is a constant integer BuildVector
9194 // or constant integer.
9195 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
9196   if (isa<ConstantSDNode>(N))
9197     return N.getNode();
9198   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
9199     return N.getNode();
9200   // Treat a GlobalAddress supporting constant offset folding as a
9201   // constant integer.
9202   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
9203     if (GA->getOpcode() == ISD::GlobalAddress &&
9204         TLI->isOffsetFoldingLegal(GA))
9205       return GA;
9206   return nullptr;
9207 }
9208 
9209 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
9210   if (isa<ConstantFPSDNode>(N))
9211     return N.getNode();
9212 
9213   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
9214     return N.getNode();
9215 
9216   return nullptr;
9217 }
9218 
9219 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
9220   assert(!Node->OperandList && "Node already has operands");
9221   assert(std::numeric_limits<decltype(SDNode::NumOperands)>::max() >
9222              Vals.size() &&
9223          "too many operands to fit into SDNode");
9224   SDUse *Ops = OperandRecycler.allocate(
9225       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
9226 
9227   bool IsDivergent = false;
9228   for (unsigned I = 0; I != Vals.size(); ++I) {
9229     Ops[I].setUser(Node);
9230     Ops[I].setInitial(Vals[I]);
9231     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
9232       IsDivergent = IsDivergent || Ops[I].getNode()->isDivergent();
9233   }
9234   Node->NumOperands = Vals.size();
9235   Node->OperandList = Ops;
9236   IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
9237   if (!TLI->isSDNodeAlwaysUniform(Node))
9238     Node->SDNodeBits.IsDivergent = IsDivergent;
9239   checkForCycles(Node);
9240 }
9241 
9242 #ifndef NDEBUG
9243 static void checkForCyclesHelper(const SDNode *N,
9244                                  SmallPtrSetImpl<const SDNode*> &Visited,
9245                                  SmallPtrSetImpl<const SDNode*> &Checked,
9246                                  const llvm::SelectionDAG *DAG) {
9247   // If this node has already been checked, don't check it again.
9248   if (Checked.count(N))
9249     return;
9250 
9251   // If a node has already been visited on this depth-first walk, reject it as
9252   // a cycle.
9253   if (!Visited.insert(N).second) {
9254     errs() << "Detected cycle in SelectionDAG\n";
9255     dbgs() << "Offending node:\n";
9256     N->dumprFull(DAG); dbgs() << "\n";
9257     abort();
9258   }
9259 
9260   for (const SDValue &Op : N->op_values())
9261     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
9262 
9263   Checked.insert(N);
9264   Visited.erase(N);
9265 }
9266 #endif
9267 
9268 void llvm::checkForCycles(const llvm::SDNode *N,
9269                           const llvm::SelectionDAG *DAG,
9270                           bool force) {
9271 #ifndef NDEBUG
9272   bool check = force;
9273 #ifdef EXPENSIVE_CHECKS
9274   check = true;
9275 #endif  // EXPENSIVE_CHECKS
9276   if (check) {
9277     assert(N && "Checking nonexistent SDNode");
9278     SmallPtrSet<const SDNode*, 32> visited;
9279     SmallPtrSet<const SDNode*, 32> checked;
9280     checkForCyclesHelper(N, visited, checked, DAG);
9281   }
9282 #endif  // !NDEBUG
9283 }
9284 
9285 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
9286   checkForCycles(DAG->getRoot().getNode(), DAG, force);
9287 }
9288