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