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