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