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