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