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