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