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