1 //===- SelectionDAG.cpp - Implement the SelectionDAG data structures ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the SelectionDAG class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/CodeGen/SelectionDAG.h"
14 #include "SDNodeDbgValue.h"
15 #include "llvm/ADT/APFloat.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/APSInt.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/FoldingSet.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/SmallPtrSet.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/ADT/Twine.h"
27 #include "llvm/Analysis/BlockFrequencyInfo.h"
28 #include "llvm/Analysis/MemoryLocation.h"
29 #include "llvm/Analysis/ProfileSummaryInfo.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/CodeGen/ISDOpcodes.h"
32 #include "llvm/CodeGen/MachineBasicBlock.h"
33 #include "llvm/CodeGen/MachineConstantPool.h"
34 #include "llvm/CodeGen/MachineFrameInfo.h"
35 #include "llvm/CodeGen/MachineFunction.h"
36 #include "llvm/CodeGen/MachineMemOperand.h"
37 #include "llvm/CodeGen/RuntimeLibcalls.h"
38 #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
39 #include "llvm/CodeGen/SelectionDAGNodes.h"
40 #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
41 #include "llvm/CodeGen/TargetFrameLowering.h"
42 #include "llvm/CodeGen/TargetLowering.h"
43 #include "llvm/CodeGen/TargetRegisterInfo.h"
44 #include "llvm/CodeGen/TargetSubtargetInfo.h"
45 #include "llvm/CodeGen/ValueTypes.h"
46 #include "llvm/IR/Constant.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DebugInfoMetadata.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/DiagnosticInfo.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GlobalValue.h"
55 #include "llvm/IR/Metadata.h"
56 #include "llvm/IR/Type.h"
57 #include "llvm/IR/Value.h"
58 #include "llvm/Support/Casting.h"
59 #include "llvm/Support/CodeGen.h"
60 #include "llvm/Support/Compiler.h"
61 #include "llvm/Support/Debug.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Support/KnownBits.h"
64 #include "llvm/Support/MachineValueType.h"
65 #include "llvm/Support/ManagedStatic.h"
66 #include "llvm/Support/MathExtras.h"
67 #include "llvm/Support/Mutex.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Target/TargetMachine.h"
70 #include "llvm/Target/TargetOptions.h"
71 #include "llvm/Transforms/Utils/CheriSetBounds.h"
72 #include "llvm/Transforms/Utils/SizeOpts.h"
73 #include <algorithm>
74 #include <cassert>
75 #include <cstdint>
76 #include <cstdlib>
77 #include <limits>
78 #include <set>
79 #include <string>
80 #include <utility>
81 #include <vector>
82 
83 using namespace llvm;
84 
85 /// makeVTList - Return an instance of the SDVTList struct initialized with the
86 /// specified members.
makeVTList(const EVT * VTs,unsigned NumVTs)87 static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
88   SDVTList Res = {VTs, NumVTs};
89   return Res;
90 }
91 
92 // Default null implementations of the callbacks.
NodeDeleted(SDNode *,SDNode *)93 void SelectionDAG::DAGUpdateListener::NodeDeleted(SDNode*, SDNode*) {}
NodeUpdated(SDNode *)94 void SelectionDAG::DAGUpdateListener::NodeUpdated(SDNode*) {}
NodeInserted(SDNode *)95 void SelectionDAG::DAGUpdateListener::NodeInserted(SDNode *) {}
96 
anchor()97 void SelectionDAG::DAGNodeDeletedListener::anchor() {}
98 
99 #define DEBUG_TYPE "selectiondag"
100 
101 static cl::opt<bool> EnableMemCpyDAGOpt("enable-memcpy-dag-opt",
102        cl::Hidden, cl::init(true),
103        cl::desc("Gang up loads and stores generated by inlining of memcpy"));
104 
105 static cl::opt<int> MaxLdStGlue("ldstmemcpy-glue-max",
106        cl::desc("Number limit for gluing ld/st of memcpy."),
107        cl::Hidden, cl::init(0));
108 
NewSDValueDbgMsg(SDValue V,StringRef Msg,SelectionDAG * G)109 static void NewSDValueDbgMsg(SDValue V, StringRef Msg, SelectionDAG *G) {
110   LLVM_DEBUG(dbgs() << Msg; V.getNode()->dump(G););
111 }
112 
113 //===----------------------------------------------------------------------===//
114 //                              ConstantFPSDNode Class
115 //===----------------------------------------------------------------------===//
116 
117 /// isExactlyValue - We don't rely on operator== working on double values, as
118 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
119 /// As such, this method can be used to do an exact bit-for-bit comparison of
120 /// two floating point values.
isExactlyValue(const APFloat & V) const121 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
122   return getValueAPF().bitwiseIsEqual(V);
123 }
124 
isValueValidForType(EVT VT,const APFloat & Val)125 bool ConstantFPSDNode::isValueValidForType(EVT VT,
126                                            const APFloat& Val) {
127   assert(VT.isFloatingPoint() && "Can only convert between FP types");
128 
129   // convert modifies in place, so make a copy.
130   APFloat Val2 = APFloat(Val);
131   bool losesInfo;
132   (void) Val2.convert(SelectionDAG::EVTToAPFloatSemantics(VT),
133                       APFloat::rmNearestTiesToEven,
134                       &losesInfo);
135   return !losesInfo;
136 }
137 
138 //===----------------------------------------------------------------------===//
139 //                              ISD Namespace
140 //===----------------------------------------------------------------------===//
141 
isConstantSplatVector(const SDNode * N,APInt & SplatVal)142 bool ISD::isConstantSplatVector(const SDNode *N, APInt &SplatVal) {
143   auto *BV = dyn_cast<BuildVectorSDNode>(N);
144   if (!BV)
145     return false;
146 
147   APInt SplatUndef;
148   unsigned SplatBitSize;
149   bool HasUndefs;
150   unsigned EltSize = N->getValueType(0).getVectorElementType().getSizeInBits();
151   return BV->isConstantSplat(SplatVal, SplatUndef, SplatBitSize, HasUndefs,
152                              EltSize) &&
153          EltSize == SplatBitSize;
154 }
155 
156 // FIXME: AllOnes and AllZeros duplicate a lot of code. Could these be
157 // specializations of the more general isConstantSplatVector()?
158 
isBuildVectorAllOnes(const SDNode * N)159 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
160   // Look through a bit convert.
161   while (N->getOpcode() == ISD::BITCAST)
162     N = N->getOperand(0).getNode();
163 
164   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
165 
166   unsigned i = 0, e = N->getNumOperands();
167 
168   // Skip over all of the undef values.
169   while (i != e && N->getOperand(i).isUndef())
170     ++i;
171 
172   // Do not accept an all-undef vector.
173   if (i == e) return false;
174 
175   // Do not accept build_vectors that aren't all constants or which have non-~0
176   // elements. We have to be a bit careful here, as the type of the constant
177   // may not be the same as the type of the vector elements due to type
178   // legalization (the elements are promoted to a legal type for the target and
179   // a vector of a type may be legal when the base element type is not).
180   // We only want to check enough bits to cover the vector elements, because
181   // we care if the resultant vector is all ones, not whether the individual
182   // constants are.
183   SDValue NotZero = N->getOperand(i);
184   unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
185   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(NotZero)) {
186     if (CN->getAPIntValue().countTrailingOnes() < EltSize)
187       return false;
188   } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(NotZero)) {
189     if (CFPN->getValueAPF().bitcastToAPInt().countTrailingOnes() < EltSize)
190       return false;
191   } else
192     return false;
193 
194   // Okay, we have at least one ~0 value, check to see if the rest match or are
195   // undefs. Even with the above element type twiddling, this should be OK, as
196   // the same type legalization should have applied to all the elements.
197   for (++i; i != e; ++i)
198     if (N->getOperand(i) != NotZero && !N->getOperand(i).isUndef())
199       return false;
200   return true;
201 }
202 
isBuildVectorAllZeros(const SDNode * N)203 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
204   // Look through a bit convert.
205   while (N->getOpcode() == ISD::BITCAST)
206     N = N->getOperand(0).getNode();
207 
208   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
209 
210   bool IsAllUndef = true;
211   for (const SDValue &Op : N->op_values()) {
212     if (Op.isUndef())
213       continue;
214     IsAllUndef = false;
215     // Do not accept build_vectors that aren't all constants or which have non-0
216     // elements. We have to be a bit careful here, as the type of the constant
217     // may not be the same as the type of the vector elements due to type
218     // legalization (the elements are promoted to a legal type for the target
219     // and a vector of a type may be legal when the base element type is not).
220     // We only want to check enough bits to cover the vector elements, because
221     // we care if the resultant vector is all zeros, not whether the individual
222     // constants are.
223     unsigned EltSize = N->getValueType(0).getScalarSizeInBits();
224     if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op)) {
225       if (CN->getAPIntValue().countTrailingZeros() < EltSize)
226         return false;
227     } else if (ConstantFPSDNode *CFPN = dyn_cast<ConstantFPSDNode>(Op)) {
228       if (CFPN->getValueAPF().bitcastToAPInt().countTrailingZeros() < EltSize)
229         return false;
230     } else
231       return false;
232   }
233 
234   // Do not accept an all-undef vector.
235   if (IsAllUndef)
236     return false;
237   return true;
238 }
239 
isBuildVectorOfConstantSDNodes(const SDNode * N)240 bool ISD::isBuildVectorOfConstantSDNodes(const SDNode *N) {
241   if (N->getOpcode() != ISD::BUILD_VECTOR)
242     return false;
243 
244   for (const SDValue &Op : N->op_values()) {
245     if (Op.isUndef())
246       continue;
247     if (!isa<ConstantSDNode>(Op))
248       return false;
249   }
250   return true;
251 }
252 
isBuildVectorOfConstantFPSDNodes(const SDNode * N)253 bool ISD::isBuildVectorOfConstantFPSDNodes(const SDNode *N) {
254   if (N->getOpcode() != ISD::BUILD_VECTOR)
255     return false;
256 
257   for (const SDValue &Op : N->op_values()) {
258     if (Op.isUndef())
259       continue;
260     if (!isa<ConstantFPSDNode>(Op))
261       return false;
262   }
263   return true;
264 }
265 
allOperandsUndef(const SDNode * N)266 bool ISD::allOperandsUndef(const SDNode *N) {
267   // Return false if the node has no operands.
268   // This is "logically inconsistent" with the definition of "all" but
269   // is probably the desired behavior.
270   if (N->getNumOperands() == 0)
271     return false;
272   return all_of(N->op_values(), [](SDValue Op) { return Op.isUndef(); });
273 }
274 
matchUnaryPredicate(SDValue Op,std::function<bool (ConstantSDNode *)> Match,bool AllowUndefs)275 bool ISD::matchUnaryPredicate(SDValue Op,
276                               std::function<bool(ConstantSDNode *)> Match,
277                               bool AllowUndefs) {
278   // FIXME: Add support for scalar UNDEF cases?
279   if (auto *Cst = dyn_cast<ConstantSDNode>(Op))
280     return Match(Cst);
281 
282   // FIXME: Add support for vector UNDEF cases?
283   if (ISD::BUILD_VECTOR != Op.getOpcode())
284     return false;
285 
286   EVT SVT = Op.getValueType().getScalarType();
287   for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
288     if (AllowUndefs && Op.getOperand(i).isUndef()) {
289       if (!Match(nullptr))
290         return false;
291       continue;
292     }
293 
294     auto *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(i));
295     if (!Cst || Cst->getValueType(0) != SVT || !Match(Cst))
296       return false;
297   }
298   return true;
299 }
300 
matchBinaryPredicate(SDValue LHS,SDValue RHS,std::function<bool (ConstantSDNode *,ConstantSDNode *)> Match,bool AllowUndefs,bool AllowTypeMismatch)301 bool ISD::matchBinaryPredicate(
302     SDValue LHS, SDValue RHS,
303     std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
304     bool AllowUndefs, bool AllowTypeMismatch) {
305   if (!AllowTypeMismatch && LHS.getValueType() != RHS.getValueType())
306     return false;
307 
308   // TODO: Add support for scalar UNDEF cases?
309   if (auto *LHSCst = dyn_cast<ConstantSDNode>(LHS))
310     if (auto *RHSCst = dyn_cast<ConstantSDNode>(RHS))
311       return Match(LHSCst, RHSCst);
312 
313   // TODO: Add support for vector UNDEF cases?
314   if (ISD::BUILD_VECTOR != LHS.getOpcode() ||
315       ISD::BUILD_VECTOR != RHS.getOpcode())
316     return false;
317 
318   EVT SVT = LHS.getValueType().getScalarType();
319   for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
320     SDValue LHSOp = LHS.getOperand(i);
321     SDValue RHSOp = RHS.getOperand(i);
322     bool LHSUndef = AllowUndefs && LHSOp.isUndef();
323     bool RHSUndef = AllowUndefs && RHSOp.isUndef();
324     auto *LHSCst = dyn_cast<ConstantSDNode>(LHSOp);
325     auto *RHSCst = dyn_cast<ConstantSDNode>(RHSOp);
326     if ((!LHSCst && !LHSUndef) || (!RHSCst && !RHSUndef))
327       return false;
328     if (!AllowTypeMismatch && (LHSOp.getValueType() != SVT ||
329                                LHSOp.getValueType() != RHSOp.getValueType()))
330       return false;
331     if (!Match(LHSCst, RHSCst))
332       return false;
333   }
334   return true;
335 }
336 
getExtForLoadExtType(bool IsFP,ISD::LoadExtType ExtType)337 ISD::NodeType ISD::getExtForLoadExtType(bool IsFP, ISD::LoadExtType ExtType) {
338   switch (ExtType) {
339   case ISD::EXTLOAD:
340     return IsFP ? ISD::FP_EXTEND : ISD::ANY_EXTEND;
341   case ISD::SEXTLOAD:
342     return ISD::SIGN_EXTEND;
343   case ISD::ZEXTLOAD:
344     return ISD::ZERO_EXTEND;
345   default:
346     break;
347   }
348 
349   llvm_unreachable("Invalid LoadExtType");
350 }
351 
getSetCCSwappedOperands(ISD::CondCode Operation)352 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
353   // To perform this operation, we just need to swap the L and G bits of the
354   // operation.
355   unsigned OldL = (Operation >> 2) & 1;
356   unsigned OldG = (Operation >> 1) & 1;
357   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
358                        (OldL << 1) |       // New G bit
359                        (OldG << 2));       // New L bit.
360 }
361 
getSetCCInverseImpl(ISD::CondCode Op,bool isIntegerLike)362 static ISD::CondCode getSetCCInverseImpl(ISD::CondCode Op, bool isIntegerLike) {
363   unsigned Operation = Op;
364   if (isIntegerLike)
365     Operation ^= 7;   // Flip L, G, E bits, but not U.
366   else
367     Operation ^= 15;  // Flip all of the condition bits.
368 
369   if (Operation > ISD::SETTRUE2)
370     Operation &= ~8;  // Don't let N and U bits get set.
371 
372   return ISD::CondCode(Operation);
373 }
374 
getSetCCInverse(ISD::CondCode Op,EVT Type)375 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, EVT Type) {
376   return getSetCCInverseImpl(Op, Type.isInteger() || Type.isFatPointer());
377 }
378 
getSetCCInverse(ISD::CondCode Op,bool isIntegerLike)379 ISD::CondCode ISD::GlobalISel::getSetCCInverse(ISD::CondCode Op,
380                                                bool isIntegerLike) {
381   return getSetCCInverseImpl(Op, isIntegerLike);
382 }
383 
384 /// For an integer comparison, return 1 if the comparison is a signed operation
385 /// and 2 if the result is an unsigned comparison. Return zero if the operation
386 /// does not depend on the sign of the input (setne and seteq).
isSignedOp(ISD::CondCode Opcode)387 static int isSignedOp(ISD::CondCode Opcode) {
388   switch (Opcode) {
389   default: llvm_unreachable("Illegal integer setcc operation!");
390   case ISD::SETEQ:
391   case ISD::SETNE: return 0;
392   case ISD::SETLT:
393   case ISD::SETLE:
394   case ISD::SETGT:
395   case ISD::SETGE: return 1;
396   case ISD::SETULT:
397   case ISD::SETULE:
398   case ISD::SETUGT:
399   case ISD::SETUGE: return 2;
400   }
401 }
402 
getSetCCOrOperation(ISD::CondCode Op1,ISD::CondCode Op2,EVT Type)403 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
404                                        EVT Type) {
405   bool IsIntegerLike = Type.isInteger() || Type.isFatPointer();
406   if (IsIntegerLike && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
407     // Cannot fold a signed integer setcc with an unsigned integer setcc.
408     return ISD::SETCC_INVALID;
409 
410   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
411 
412   // If the N and U bits get set, then the resultant comparison DOES suddenly
413   // care about orderedness, and it is true when ordered.
414   if (Op > ISD::SETTRUE2)
415     Op &= ~16;     // Clear the U bit if the N bit is set.
416 
417   // Canonicalize illegal integer setcc's.
418   if (IsIntegerLike && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
419     Op = ISD::SETNE;
420 
421   return ISD::CondCode(Op);
422 }
423 
getSetCCAndOperation(ISD::CondCode Op1,ISD::CondCode Op2,EVT Type)424 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
425                                         EVT Type) {
426   bool IsIntegerLike = Type.isInteger() || Type.isFatPointer();
427   if (IsIntegerLike && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
428     // Cannot fold a signed setcc with an unsigned setcc.
429     return ISD::SETCC_INVALID;
430 
431   // Combine all of the condition bits.
432   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
433 
434   // Canonicalize illegal integer setcc's.
435   if (IsIntegerLike) {
436     switch (Result) {
437     default: break;
438     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
439     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
440     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
441     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
442     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
443     }
444   }
445 
446   return Result;
447 }
448 
449 //===----------------------------------------------------------------------===//
450 //                           SDNode Profile Support
451 //===----------------------------------------------------------------------===//
452 
453 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
AddNodeIDOpcode(FoldingSetNodeID & ID,unsigned OpC)454 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
455   ID.AddInteger(OpC);
456 }
457 
458 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
459 /// solely with their pointer.
AddNodeIDValueTypes(FoldingSetNodeID & ID,SDVTList VTList)460 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
461   ID.AddPointer(VTList.VTs);
462 }
463 
464 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
AddNodeIDOperands(FoldingSetNodeID & ID,ArrayRef<SDValue> Ops)465 static void AddNodeIDOperands(FoldingSetNodeID &ID,
466                               ArrayRef<SDValue> Ops) {
467   for (auto& Op : Ops) {
468     ID.AddPointer(Op.getNode());
469     ID.AddInteger(Op.getResNo());
470   }
471 }
472 
473 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
AddNodeIDOperands(FoldingSetNodeID & ID,ArrayRef<SDUse> Ops)474 static void AddNodeIDOperands(FoldingSetNodeID &ID,
475                               ArrayRef<SDUse> Ops) {
476   for (auto& Op : Ops) {
477     ID.AddPointer(Op.getNode());
478     ID.AddInteger(Op.getResNo());
479   }
480 }
481 
AddNodeIDNode(FoldingSetNodeID & ID,unsigned short OpC,SDVTList VTList,ArrayRef<SDValue> OpList)482 static void AddNodeIDNode(FoldingSetNodeID &ID, unsigned short OpC,
483                           SDVTList VTList, ArrayRef<SDValue> OpList) {
484   AddNodeIDOpcode(ID, OpC);
485   AddNodeIDValueTypes(ID, VTList);
486   AddNodeIDOperands(ID, OpList);
487 }
488 
489 /// If this is an SDNode with special info, add this info to the NodeID data.
AddNodeIDCustom(FoldingSetNodeID & ID,const SDNode * N)490 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
491   switch (N->getOpcode()) {
492   case ISD::TargetExternalSymbol:
493   case ISD::ExternalSymbol:
494   case ISD::MCSymbol:
495     llvm_unreachable("Should only be used on nodes with operands");
496   default: break;  // Normal nodes don't need extra info.
497   case ISD::TargetConstant:
498   case ISD::Constant: {
499     const ConstantSDNode *C = cast<ConstantSDNode>(N);
500     ID.AddPointer(C->getConstantIntValue());
501     ID.AddBoolean(C->isOpaque());
502     break;
503   }
504   case ISD::TargetConstantFP:
505   case ISD::ConstantFP:
506     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
507     break;
508   case ISD::TargetGlobalAddress:
509   case ISD::GlobalAddress:
510   case ISD::TargetGlobalTLSAddress:
511   case ISD::GlobalTLSAddress: {
512     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
513     ID.AddPointer(GA->getGlobal());
514     ID.AddInteger(GA->getOffset());
515     ID.AddInteger(GA->getTargetFlags());
516     break;
517   }
518   case ISD::BasicBlock:
519     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
520     break;
521   case ISD::Register:
522     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
523     break;
524   case ISD::RegisterMask:
525     ID.AddPointer(cast<RegisterMaskSDNode>(N)->getRegMask());
526     break;
527   case ISD::SRCVALUE:
528     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
529     break;
530   case ISD::FrameIndex:
531   case ISD::TargetFrameIndex:
532     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
533     break;
534   case ISD::LIFETIME_START:
535   case ISD::LIFETIME_END:
536     if (cast<LifetimeSDNode>(N)->hasOffset()) {
537       ID.AddInteger(cast<LifetimeSDNode>(N)->getSize());
538       ID.AddInteger(cast<LifetimeSDNode>(N)->getOffset());
539     }
540     break;
541   case ISD::JumpTable:
542   case ISD::TargetJumpTable:
543     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
544     ID.AddInteger(cast<JumpTableSDNode>(N)->getTargetFlags());
545     break;
546   case ISD::ConstantPool:
547   case ISD::TargetConstantPool: {
548     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
549     ID.AddInteger(CP->getAlign().value());
550     ID.AddInteger(CP->getOffset());
551     if (CP->isMachineConstantPoolEntry())
552       CP->getMachineCPVal()->addSelectionDAGCSEId(ID);
553     else
554       ID.AddPointer(CP->getConstVal());
555     ID.AddInteger(CP->getTargetFlags());
556     break;
557   }
558   case ISD::TargetIndex: {
559     const TargetIndexSDNode *TI = cast<TargetIndexSDNode>(N);
560     ID.AddInteger(TI->getIndex());
561     ID.AddInteger(TI->getOffset());
562     ID.AddInteger(TI->getTargetFlags());
563     break;
564   }
565   case ISD::LOAD: {
566     const LoadSDNode *LD = cast<LoadSDNode>(N);
567     ID.AddInteger(LD->getMemoryVT().getRawBits());
568     ID.AddInteger(LD->getRawSubclassData());
569     ID.AddInteger(LD->getPointerInfo().getAddrSpace());
570     break;
571   }
572   case ISD::STORE: {
573     const StoreSDNode *ST = cast<StoreSDNode>(N);
574     ID.AddInteger(ST->getMemoryVT().getRawBits());
575     ID.AddInteger(ST->getRawSubclassData());
576     ID.AddInteger(ST->getPointerInfo().getAddrSpace());
577     break;
578   }
579   case ISD::MLOAD: {
580     const MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
581     ID.AddInteger(MLD->getMemoryVT().getRawBits());
582     ID.AddInteger(MLD->getRawSubclassData());
583     ID.AddInteger(MLD->getPointerInfo().getAddrSpace());
584     break;
585   }
586   case ISD::MSTORE: {
587     const MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
588     ID.AddInteger(MST->getMemoryVT().getRawBits());
589     ID.AddInteger(MST->getRawSubclassData());
590     ID.AddInteger(MST->getPointerInfo().getAddrSpace());
591     break;
592   }
593   case ISD::MGATHER: {
594     const MaskedGatherSDNode *MG = cast<MaskedGatherSDNode>(N);
595     ID.AddInteger(MG->getMemoryVT().getRawBits());
596     ID.AddInteger(MG->getRawSubclassData());
597     ID.AddInteger(MG->getPointerInfo().getAddrSpace());
598     break;
599   }
600   case ISD::MSCATTER: {
601     const MaskedScatterSDNode *MS = cast<MaskedScatterSDNode>(N);
602     ID.AddInteger(MS->getMemoryVT().getRawBits());
603     ID.AddInteger(MS->getRawSubclassData());
604     ID.AddInteger(MS->getPointerInfo().getAddrSpace());
605     break;
606   }
607   case ISD::ATOMIC_CMP_SWAP:
608   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
609   case ISD::ATOMIC_SWAP:
610   case ISD::ATOMIC_LOAD_ADD:
611   case ISD::ATOMIC_LOAD_SUB:
612   case ISD::ATOMIC_LOAD_AND:
613   case ISD::ATOMIC_LOAD_CLR:
614   case ISD::ATOMIC_LOAD_OR:
615   case ISD::ATOMIC_LOAD_XOR:
616   case ISD::ATOMIC_LOAD_NAND:
617   case ISD::ATOMIC_LOAD_MIN:
618   case ISD::ATOMIC_LOAD_MAX:
619   case ISD::ATOMIC_LOAD_UMIN:
620   case ISD::ATOMIC_LOAD_UMAX:
621   case ISD::ATOMIC_LOAD:
622   case ISD::ATOMIC_STORE: {
623     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
624     ID.AddInteger(AT->getMemoryVT().getRawBits());
625     ID.AddInteger(AT->getRawSubclassData());
626     ID.AddInteger(AT->getPointerInfo().getAddrSpace());
627     break;
628   }
629   case ISD::PREFETCH: {
630     const MemSDNode *PF = cast<MemSDNode>(N);
631     ID.AddInteger(PF->getPointerInfo().getAddrSpace());
632     break;
633   }
634   case ISD::VECTOR_SHUFFLE: {
635     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
636     for (unsigned i = 0, e = N->getValueType(0).getVectorNumElements();
637          i != e; ++i)
638       ID.AddInteger(SVN->getMaskElt(i));
639     break;
640   }
641   case ISD::TargetBlockAddress:
642   case ISD::BlockAddress: {
643     const BlockAddressSDNode *BA = cast<BlockAddressSDNode>(N);
644     ID.AddPointer(BA->getBlockAddress());
645     ID.AddInteger(BA->getOffset());
646     ID.AddInteger(BA->getTargetFlags());
647     break;
648   }
649   } // end switch (N->getOpcode())
650 
651   // Target specific memory nodes could also have address spaces to check.
652   if (N->isTargetMemoryOpcode())
653     ID.AddInteger(cast<MemSDNode>(N)->getPointerInfo().getAddrSpace());
654 }
655 
656 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
657 /// data.
AddNodeIDNode(FoldingSetNodeID & ID,const SDNode * N)658 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
659   AddNodeIDOpcode(ID, N->getOpcode());
660   // Add the return value info.
661   AddNodeIDValueTypes(ID, N->getVTList());
662   // Add the operand info.
663   AddNodeIDOperands(ID, N->ops());
664 
665   // Handle SDNode leafs with special info.
666   AddNodeIDCustom(ID, N);
667 }
668 
669 //===----------------------------------------------------------------------===//
670 //                              SelectionDAG Class
671 //===----------------------------------------------------------------------===//
672 
673 /// doNotCSE - Return true if CSE should not be performed for this node.
doNotCSE(SDNode * N)674 static bool doNotCSE(SDNode *N) {
675   if (N->getValueType(0) == MVT::Glue)
676     return true; // Never CSE anything that produces a flag.
677 
678   switch (N->getOpcode()) {
679   default: break;
680   case ISD::HANDLENODE:
681   case ISD::EH_LABEL:
682     return true;   // Never CSE these nodes.
683   }
684 
685   // Check that remaining values produced are not flags.
686   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
687     if (N->getValueType(i) == MVT::Glue)
688       return true; // Never CSE anything that produces a flag.
689 
690   return false;
691 }
692 
693 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
694 /// SelectionDAG.
RemoveDeadNodes()695 void SelectionDAG::RemoveDeadNodes() {
696   // Create a dummy node (which is not added to allnodes), that adds a reference
697   // to the root node, preventing it from being deleted.
698   HandleSDNode Dummy(getRoot());
699 
700   SmallVector<SDNode*, 128> DeadNodes;
701 
702   // Add all obviously-dead nodes to the DeadNodes worklist.
703   for (SDNode &Node : allnodes())
704     if (Node.use_empty())
705       DeadNodes.push_back(&Node);
706 
707   RemoveDeadNodes(DeadNodes);
708 
709   // If the root changed (e.g. it was a dead load, update the root).
710   setRoot(Dummy.getValue());
711 }
712 
713 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
714 /// given list, and any nodes that become unreachable as a result.
RemoveDeadNodes(SmallVectorImpl<SDNode * > & DeadNodes)715 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes) {
716 
717   // Process the worklist, deleting the nodes and adding their uses to the
718   // worklist.
719   while (!DeadNodes.empty()) {
720     SDNode *N = DeadNodes.pop_back_val();
721     // Skip to next node if we've already managed to delete the node. This could
722     // happen if replacing a node causes a node previously added to the node to
723     // be deleted.
724     if (N->getOpcode() == ISD::DELETED_NODE)
725       continue;
726 
727     for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
728       DUL->NodeDeleted(N, nullptr);
729 
730     // Take the node out of the appropriate CSE map.
731     RemoveNodeFromCSEMaps(N);
732 
733     // Next, brutally remove the operand list.  This is safe to do, as there are
734     // no cycles in the graph.
735     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
736       SDUse &Use = *I++;
737       SDNode *Operand = Use.getNode();
738       Use.set(SDValue());
739 
740       // Now that we removed this operand, see if there are no uses of it left.
741       if (Operand->use_empty())
742         DeadNodes.push_back(Operand);
743     }
744 
745     DeallocateNode(N);
746   }
747 }
748 
RemoveDeadNode(SDNode * N)749 void SelectionDAG::RemoveDeadNode(SDNode *N){
750   SmallVector<SDNode*, 16> DeadNodes(1, N);
751 
752   // Create a dummy node that adds a reference to the root node, preventing
753   // it from being deleted.  (This matters if the root is an operand of the
754   // dead node.)
755   HandleSDNode Dummy(getRoot());
756 
757   RemoveDeadNodes(DeadNodes);
758 }
759 
DeleteNode(SDNode * N)760 void SelectionDAG::DeleteNode(SDNode *N) {
761   // First take this out of the appropriate CSE map.
762   RemoveNodeFromCSEMaps(N);
763 
764   // Finally, remove uses due to operands of this node, remove from the
765   // AllNodes list, and delete the node.
766   DeleteNodeNotInCSEMaps(N);
767 }
768 
DeleteNodeNotInCSEMaps(SDNode * N)769 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
770   assert(N->getIterator() != AllNodes.begin() &&
771          "Cannot delete the entry node!");
772   assert(N->use_empty() && "Cannot delete a node that is not dead!");
773 
774   // Drop all of the operands and decrement used node's use counts.
775   N->DropOperands();
776 
777   DeallocateNode(N);
778 }
779 
erase(const SDNode * Node)780 void SDDbgInfo::erase(const SDNode *Node) {
781   DbgValMapType::iterator I = DbgValMap.find(Node);
782   if (I == DbgValMap.end())
783     return;
784   for (auto &Val: I->second)
785     Val->setIsInvalidated();
786   DbgValMap.erase(I);
787 }
788 
DeallocateNode(SDNode * N)789 void SelectionDAG::DeallocateNode(SDNode *N) {
790   // If we have operands, deallocate them.
791   removeOperands(N);
792 
793   NodeAllocator.Deallocate(AllNodes.remove(N));
794 
795   // Set the opcode to DELETED_NODE to help catch bugs when node
796   // memory is reallocated.
797   // FIXME: There are places in SDag that have grown a dependency on the opcode
798   // value in the released node.
799   __asan_unpoison_memory_region(&N->NodeType, sizeof(N->NodeType));
800   N->NodeType = ISD::DELETED_NODE;
801 
802   // If any of the SDDbgValue nodes refer to this SDNode, invalidate
803   // them and forget about that node.
804   DbgInfo->erase(N);
805 }
806 
807 #ifndef NDEBUG
808 /// VerifySDNode - Sanity check the given SDNode.  Aborts if it is invalid.
VerifySDNode(SDNode * N)809 static void VerifySDNode(SDNode *N) {
810   switch (N->getOpcode()) {
811   default:
812     break;
813   case ISD::BUILD_PAIR: {
814     EVT VT = N->getValueType(0);
815     assert(N->getNumValues() == 1 && "Too many results!");
816     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
817            "Wrong return type!");
818     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
819     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
820            "Mismatched operand types!");
821     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
822            "Wrong operand type!");
823     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
824            "Wrong return type size");
825     break;
826   }
827   case ISD::BUILD_VECTOR: {
828     assert(N->getNumValues() == 1 && "Too many results!");
829     assert(N->getValueType(0).isVector() && "Wrong return type!");
830     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
831            "Wrong number of operands!");
832     EVT EltVT = N->getValueType(0).getVectorElementType();
833     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
834       assert((I->getValueType() == EltVT ||
835              (EltVT.isInteger() && I->getValueType().isInteger() &&
836               EltVT.bitsLE(I->getValueType()))) &&
837             "Wrong operand type!");
838       assert(I->getValueType() == N->getOperand(0).getValueType() &&
839              "Operands must all have the same type");
840     }
841     break;
842   }
843   }
844 }
845 #endif // NDEBUG
846 
847 /// Insert a newly allocated node into the DAG.
848 ///
849 /// Handles insertion into the all nodes list and CSE map, as well as
850 /// verification and other common operations when a new node is allocated.
InsertNode(SDNode * N)851 void SelectionDAG::InsertNode(SDNode *N) {
852   AllNodes.push_back(N);
853 #ifndef NDEBUG
854   N->PersistentId = NextPersistentId++;
855   VerifySDNode(N);
856 #endif
857   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
858     DUL->NodeInserted(N);
859 }
860 
861 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
862 /// correspond to it.  This is useful when we're about to delete or repurpose
863 /// the node.  We don't want future request for structurally identical nodes
864 /// to return N anymore.
RemoveNodeFromCSEMaps(SDNode * N)865 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
866   bool Erased = false;
867   switch (N->getOpcode()) {
868   case ISD::HANDLENODE: return false;  // noop.
869   case ISD::CONDCODE:
870     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
871            "Cond code doesn't exist!");
872     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != nullptr;
873     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = nullptr;
874     break;
875   case ISD::ExternalSymbol:
876     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
877     break;
878   case ISD::TargetExternalSymbol: {
879     ExternalSymbolSDNode *ESN = cast<ExternalSymbolSDNode>(N);
880     Erased = TargetExternalSymbols.erase(std::pair<std::string, unsigned>(
881         ESN->getSymbol(), ESN->getTargetFlags()));
882     break;
883   }
884   case ISD::MCSymbol: {
885     auto *MCSN = cast<MCSymbolSDNode>(N);
886     Erased = MCSymbols.erase(MCSN->getMCSymbol());
887     break;
888   }
889   case ISD::VALUETYPE: {
890     EVT VT = cast<VTSDNode>(N)->getVT();
891     if (VT.isExtended()) {
892       Erased = ExtendedValueTypeNodes.erase(VT);
893     } else {
894       Erased = ValueTypeNodes[VT.getSimpleVT().SimpleTy] != nullptr;
895       ValueTypeNodes[VT.getSimpleVT().SimpleTy] = nullptr;
896     }
897     break;
898   }
899   default:
900     // Remove it from the CSE Map.
901     assert(N->getOpcode() != ISD::DELETED_NODE && "DELETED_NODE in CSEMap!");
902     assert(N->getOpcode() != ISD::EntryToken && "EntryToken in CSEMap!");
903     Erased = CSEMap.RemoveNode(N);
904     break;
905   }
906 #ifndef NDEBUG
907   // Verify that the node was actually in one of the CSE maps, unless it has a
908   // flag result (which cannot be CSE'd) or is one of the special cases that are
909   // not subject to CSE.
910   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Glue &&
911       !N->isMachineOpcode() && !doNotCSE(N)) {
912     N->dump(this);
913     dbgs() << "\n";
914     llvm_unreachable("Node is not in map!");
915   }
916 #endif
917   return Erased;
918 }
919 
920 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
921 /// maps and modified in place. Add it back to the CSE maps, unless an identical
922 /// node already exists, in which case transfer all its users to the existing
923 /// node. This transfer can potentially trigger recursive merging.
924 void
AddModifiedNodeToCSEMaps(SDNode * N)925 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N) {
926   // For node types that aren't CSE'd, just act as if no identical node
927   // already exists.
928   if (!doNotCSE(N)) {
929     SDNode *Existing = CSEMap.GetOrInsertNode(N);
930     if (Existing != N) {
931       // If there was already an existing matching node, use ReplaceAllUsesWith
932       // to replace the dead one with the existing one.  This can cause
933       // recursive merging of other unrelated nodes down the line.
934       ReplaceAllUsesWith(N, Existing);
935 
936       // N is now dead. Inform the listeners and delete it.
937       for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
938         DUL->NodeDeleted(N, Existing);
939       DeleteNodeNotInCSEMaps(N);
940       return;
941     }
942   }
943 
944   // If the node doesn't already exist, we updated it.  Inform listeners.
945   for (DAGUpdateListener *DUL = UpdateListeners; DUL; DUL = DUL->Next)
946     DUL->NodeUpdated(N);
947 }
948 
949 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
950 /// were replaced with those specified.  If this node is never memoized,
951 /// return null, otherwise return a pointer to the slot it would take.  If a
952 /// node already exists with these operands, the slot will be non-null.
FindModifiedNodeSlot(SDNode * N,SDValue Op,void * & InsertPos)953 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
954                                            void *&InsertPos) {
955   if (doNotCSE(N))
956     return nullptr;
957 
958   SDValue Ops[] = { Op };
959   FoldingSetNodeID ID;
960   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
961   AddNodeIDCustom(ID, N);
962   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
963   if (Node)
964     Node->intersectFlagsWith(N->getFlags());
965   return Node;
966 }
967 
968 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
969 /// were replaced with those specified.  If this node is never memoized,
970 /// return null, otherwise return a pointer to the slot it would take.  If a
971 /// node already exists with these operands, the slot will be non-null.
FindModifiedNodeSlot(SDNode * N,SDValue Op1,SDValue Op2,void * & InsertPos)972 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N,
973                                            SDValue Op1, SDValue Op2,
974                                            void *&InsertPos) {
975   if (doNotCSE(N))
976     return nullptr;
977 
978   SDValue Ops[] = { Op1, Op2 };
979   FoldingSetNodeID ID;
980   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
981   AddNodeIDCustom(ID, N);
982   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
983   if (Node)
984     Node->intersectFlagsWith(N->getFlags());
985   return Node;
986 }
987 
988 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
989 /// were replaced with those specified.  If this node is never memoized,
990 /// return null, otherwise return a pointer to the slot it would take.  If a
991 /// node already exists with these operands, the slot will be non-null.
FindModifiedNodeSlot(SDNode * N,ArrayRef<SDValue> Ops,void * & InsertPos)992 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, ArrayRef<SDValue> Ops,
993                                            void *&InsertPos) {
994   if (doNotCSE(N))
995     return nullptr;
996 
997   FoldingSetNodeID ID;
998   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops);
999   AddNodeIDCustom(ID, N);
1000   SDNode *Node = FindNodeOrInsertPos(ID, SDLoc(N), InsertPos);
1001   if (Node)
1002     Node->intersectFlagsWith(N->getFlags());
1003   return Node;
1004 }
1005 
getEVTAlign(EVT VT) const1006 Align SelectionDAG::getEVTAlign(EVT VT) const {
1007   Type *Ty = VT == MVT::iPTR ?
1008                    PointerType::get(Type::getInt8Ty(*getContext()), 0) :
1009                    VT.getTypeForEVT(*getContext());
1010 
1011   return getDataLayout().getABITypeAlign(Ty);
1012 }
1013 
1014 // EntryNode could meaningfully have debug info if we can find it...
SelectionDAG(const TargetMachine & tm,CodeGenOpt::Level OL)1015 SelectionDAG::SelectionDAG(const TargetMachine &tm, CodeGenOpt::Level OL)
1016     : TM(tm), OptLevel(OL),
1017       EntryNode(ISD::EntryToken, 0, DebugLoc(), getVTList(MVT::Other)),
1018       Root(getEntryNode()) {
1019   InsertNode(&EntryNode);
1020   DbgInfo = new SDDbgInfo();
1021 }
1022 
init(MachineFunction & NewMF,OptimizationRemarkEmitter & NewORE,Pass * PassPtr,const TargetLibraryInfo * LibraryInfo,LegacyDivergenceAnalysis * Divergence,ProfileSummaryInfo * PSIin,BlockFrequencyInfo * BFIin)1023 void SelectionDAG::init(MachineFunction &NewMF,
1024                         OptimizationRemarkEmitter &NewORE,
1025                         Pass *PassPtr, const TargetLibraryInfo *LibraryInfo,
1026                         LegacyDivergenceAnalysis * Divergence,
1027                         ProfileSummaryInfo *PSIin,
1028                         BlockFrequencyInfo *BFIin) {
1029   MF = &NewMF;
1030   SDAGISelPass = PassPtr;
1031   ORE = &NewORE;
1032   TLI = getSubtarget().getTargetLowering();
1033   TSI = getSubtarget().getSelectionDAGInfo();
1034   LibInfo = LibraryInfo;
1035   Context = &MF->getFunction().getContext();
1036   DA = Divergence;
1037   PSI = PSIin;
1038   BFI = BFIin;
1039 }
1040 
~SelectionDAG()1041 SelectionDAG::~SelectionDAG() {
1042   assert(!UpdateListeners && "Dangling registered DAGUpdateListeners");
1043   allnodes_clear();
1044   OperandRecycler.clear(OperandAllocator);
1045   delete DbgInfo;
1046 }
1047 
shouldOptForSize() const1048 bool SelectionDAG::shouldOptForSize() const {
1049   return MF->getFunction().hasOptSize() ||
1050       llvm::shouldOptimizeForSize(FLI->MBB->getBasicBlock(), PSI, BFI);
1051 }
1052 
allnodes_clear()1053 void SelectionDAG::allnodes_clear() {
1054   assert(&*AllNodes.begin() == &EntryNode);
1055   AllNodes.remove(AllNodes.begin());
1056   while (!AllNodes.empty())
1057     DeallocateNode(&AllNodes.front());
1058 #ifndef NDEBUG
1059   NextPersistentId = 0;
1060 #endif
1061 }
1062 
FindNodeOrInsertPos(const FoldingSetNodeID & ID,void * & InsertPos)1063 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1064                                           void *&InsertPos) {
1065   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1066   if (N) {
1067     switch (N->getOpcode()) {
1068     default: break;
1069     case ISD::Constant:
1070     case ISD::ConstantFP:
1071       llvm_unreachable("Querying for Constant and ConstantFP nodes requires "
1072                        "debug location.  Use another overload.");
1073     }
1074   }
1075   return N;
1076 }
1077 
FindNodeOrInsertPos(const FoldingSetNodeID & ID,const SDLoc & DL,void * & InsertPos)1078 SDNode *SelectionDAG::FindNodeOrInsertPos(const FoldingSetNodeID &ID,
1079                                           const SDLoc &DL, void *&InsertPos) {
1080   SDNode *N = CSEMap.FindNodeOrInsertPos(ID, InsertPos);
1081   if (N) {
1082     switch (N->getOpcode()) {
1083     case ISD::Constant:
1084     case ISD::ConstantFP:
1085       // Erase debug location from the node if the node is used at several
1086       // different places. Do not propagate one location to all uses as it
1087       // will cause a worse single stepping debugging experience.
1088       if (N->getDebugLoc() != DL.getDebugLoc())
1089         N->setDebugLoc(DebugLoc());
1090       break;
1091     default:
1092       // When the node's point of use is located earlier in the instruction
1093       // sequence than its prior point of use, update its debug info to the
1094       // earlier location.
1095       if (DL.getIROrder() && DL.getIROrder() < N->getIROrder())
1096         N->setDebugLoc(DL.getDebugLoc());
1097       break;
1098     }
1099   }
1100   return N;
1101 }
1102 
clear()1103 void SelectionDAG::clear() {
1104   allnodes_clear();
1105   OperandRecycler.clear(OperandAllocator);
1106   OperandAllocator.Reset();
1107   CSEMap.clear();
1108 
1109   ExtendedValueTypeNodes.clear();
1110   ExternalSymbols.clear();
1111   TargetExternalSymbols.clear();
1112   MCSymbols.clear();
1113   SDCallSiteDbgInfo.clear();
1114   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
1115             static_cast<CondCodeSDNode*>(nullptr));
1116   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
1117             static_cast<SDNode*>(nullptr));
1118 
1119   EntryNode.UseList = nullptr;
1120   InsertNode(&EntryNode);
1121   Root = getEntryNode();
1122   DbgInfo->clear();
1123 }
1124 
getFPExtendOrRound(SDValue Op,const SDLoc & DL,EVT VT)1125 SDValue SelectionDAG::getFPExtendOrRound(SDValue Op, const SDLoc &DL, EVT VT) {
1126   return VT.bitsGT(Op.getValueType())
1127              ? getNode(ISD::FP_EXTEND, DL, VT, Op)
1128              : getNode(ISD::FP_ROUND, DL, VT, Op, getIntPtrConstant(0, DL));
1129 }
1130 
1131 std::pair<SDValue, SDValue>
getStrictFPExtendOrRound(SDValue Op,SDValue Chain,const SDLoc & DL,EVT VT)1132 SelectionDAG::getStrictFPExtendOrRound(SDValue Op, SDValue Chain,
1133                                        const SDLoc &DL, EVT VT) {
1134   assert(!VT.bitsEq(Op.getValueType()) &&
1135          "Strict no-op FP extend/round not allowed.");
1136   SDValue Res =
1137       VT.bitsGT(Op.getValueType())
1138           ? getNode(ISD::STRICT_FP_EXTEND, DL, {VT, MVT::Other}, {Chain, Op})
1139           : getNode(ISD::STRICT_FP_ROUND, DL, {VT, MVT::Other},
1140                     {Chain, Op, getIntPtrConstant(0, DL)});
1141 
1142   return std::pair<SDValue, SDValue>(Res, SDValue(Res.getNode(), 1));
1143 }
1144 
getAnyExtOrTrunc(SDValue Op,const SDLoc & DL,EVT VT)1145 SDValue SelectionDAG::getAnyExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1146   return VT.bitsGT(Op.getValueType()) ?
1147     getNode(ISD::ANY_EXTEND, DL, VT, Op) :
1148     getNode(ISD::TRUNCATE, DL, VT, Op);
1149 }
1150 
getSExtOrTrunc(SDValue Op,const SDLoc & DL,EVT VT)1151 SDValue SelectionDAG::getSExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1152   return VT.bitsGT(Op.getValueType()) ?
1153     getNode(ISD::SIGN_EXTEND, DL, VT, Op) :
1154     getNode(ISD::TRUNCATE, DL, VT, Op);
1155 }
1156 
getZExtOrTrunc(SDValue Op,const SDLoc & DL,EVT VT)1157 SDValue SelectionDAG::getZExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1158   return VT.bitsGT(Op.getValueType()) ?
1159     getNode(ISD::ZERO_EXTEND, DL, VT, Op) :
1160     getNode(ISD::TRUNCATE, DL, VT, Op);
1161 }
1162 
getBoolExtOrTrunc(SDValue Op,const SDLoc & SL,EVT VT,EVT OpVT)1163 SDValue SelectionDAG::getBoolExtOrTrunc(SDValue Op, const SDLoc &SL, EVT VT,
1164                                         EVT OpVT) {
1165   if (VT.bitsLE(Op.getValueType()))
1166     return getNode(ISD::TRUNCATE, SL, VT, Op);
1167 
1168   TargetLowering::BooleanContent BType = TLI->getBooleanContents(OpVT);
1169   return getNode(TLI->getExtendForContent(BType), SL, VT, Op);
1170 }
1171 
getZeroExtendInReg(SDValue Op,const SDLoc & DL,EVT VT)1172 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1173   EVT OpVT = Op.getValueType();
1174   assert(VT.isInteger() && OpVT.isInteger() &&
1175          "Cannot getZeroExtendInReg FP types");
1176   assert(VT.isVector() == OpVT.isVector() &&
1177          "getZeroExtendInReg type should be vector iff the operand "
1178          "type is vector!");
1179   assert((!VT.isVector() ||
1180           VT.getVectorElementCount() == OpVT.getVectorElementCount()) &&
1181          "Vector element counts must match in getZeroExtendInReg");
1182   assert(VT.bitsLE(OpVT) && "Not extending!");
1183   if (OpVT == VT)
1184     return Op;
1185   APInt Imm = APInt::getLowBitsSet(OpVT.getScalarSizeInBits(),
1186                                    VT.getScalarSizeInBits());
1187   return getNode(ISD::AND, DL, OpVT, Op, getConstant(Imm, DL, OpVT));
1188 }
1189 
getPtrExtOrTrunc(SDValue Op,const SDLoc & DL,EVT VT)1190 SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
1191   // Only unsigned pointer semantics are supported right now. In the future this
1192   // might delegate to TLI to check pointer signedness.
1193   return getZExtOrTrunc(Op, DL, VT);
1194 }
1195 
getPtrExtendInReg(SDValue Op,const SDLoc & DL,EVT VT)1196 SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
1197   // Only unsigned pointer semantics are supported right now. In the future this
1198   // might delegate to TLI to check pointer signedness.
1199   return getZeroExtendInReg(Op, DL, VT);
1200 }
1201 
1202 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
getNOT(const SDLoc & DL,SDValue Val,EVT VT)1203 SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1204   EVT EltVT = VT.getScalarType();
1205   SDValue NegOne =
1206     getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
1207   return getNode(ISD::XOR, DL, VT, Val, NegOne);
1208 }
1209 
getLogicalNOT(const SDLoc & DL,SDValue Val,EVT VT)1210 SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
1211   SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
1212   return getNode(ISD::XOR, DL, VT, Val, TrueValue);
1213 }
1214 
getBoolConstant(bool V,const SDLoc & DL,EVT VT,EVT OpVT)1215 SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
1216                                       EVT OpVT) {
1217   if (!V)
1218     return getConstant(0, DL, VT);
1219 
1220   switch (TLI->getBooleanContents(OpVT)) {
1221   case TargetLowering::ZeroOrOneBooleanContent:
1222   case TargetLowering::UndefinedBooleanContent:
1223     return getConstant(1, DL, VT);
1224   case TargetLowering::ZeroOrNegativeOneBooleanContent:
1225     return getAllOnesConstant(DL, VT);
1226   }
1227   llvm_unreachable("Unexpected boolean content enum!");
1228 }
1229 
getNullCapability(const SDLoc & DL)1230 SDValue SelectionDAG::getNullCapability(const SDLoc &DL) {
1231   return getConstant(0, DL, TLI->cheriCapabilityType());
1232 }
1233 
getConstant(uint64_t Val,const SDLoc & DL,EVT VT,bool isT,bool isO)1234 SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
1235                                   bool isT, bool isO) {
1236   EVT EltVT = VT.getScalarType();
1237   assert((EltVT.getSizeInBits() >= 64 ||
1238          (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
1239          "getConstant with a uint64_t value that doesn't fit in the type!");
1240   return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
1241 }
1242 
getConstant(const APInt & Val,const SDLoc & DL,EVT VT,bool isT,bool isO)1243 SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
1244                                   bool isT, bool isO) {
1245   return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
1246 }
1247 
getConstant(const ConstantInt & Val,const SDLoc & DL,EVT VT,bool isT,bool isO)1248 SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
1249                                   EVT VT, bool isT, bool isO) {
1250   if (VT.isFatPointer()) {
1251     unsigned AddrBitWidth = getDataLayout().getPointerSizeInBits(0);
1252     APInt Int = Val.getValue();
1253     if (Int.getBitWidth() > AddrBitWidth)
1254       Int = Int.trunc(AddrBitWidth);
1255     assert(APInt::isSameValue(Int, Val.getValue()));
1256     assert(!isT && "Cannot create INTTOPTR targetconstant");
1257     MVT IntVT = MVT::getIntegerVT(AddrBitWidth);
1258     // XXXAR: If this is actually needed somewhere we should add a
1259     // DAG.getIntCapConstant() helper function.
1260     assert(Int.isNullValue() && "Should not create non-zero capability "
1261                                 "constants with SelectionDAG::getConstant()");
1262     return getNode(ISD::INTTOPTR, DL, VT, getConstant(Int, DL, IntVT));
1263   }
1264   assert(VT.isInteger() && "Cannot create FP integer constant!");
1265 
1266   EVT EltVT = VT.getScalarType();
1267   const ConstantInt *Elt = &Val;
1268 
1269   // In some cases the vector type is legal but the element type is illegal and
1270   // needs to be promoted, for example v8i8 on ARM.  In this case, promote the
1271   // inserted value (the type does not need to match the vector element type).
1272   // Any extra bits introduced will be truncated away.
1273   if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
1274       TargetLowering::TypePromoteInteger) {
1275    EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1276    APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
1277    Elt = ConstantInt::get(*getContext(), NewVal);
1278   }
1279   // In other cases the element type is illegal and needs to be expanded, for
1280   // example v2i64 on MIPS32. In this case, find the nearest legal type, split
1281   // the value into n parts and use a vector type with n-times the elements.
1282   // Then bitcast to the type requested.
1283   // Legalizing constants too early makes the DAGCombiner's job harder so we
1284   // only legalize if the DAG tells us we must produce legal types.
1285   else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
1286            TLI->getTypeAction(*getContext(), EltVT) ==
1287            TargetLowering::TypeExpandInteger) {
1288     const APInt &NewVal = Elt->getValue();
1289     EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
1290     unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
1291     unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
1292     EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
1293 
1294     // Check the temporary vector is the correct size. If this fails then
1295     // getTypeToTransformTo() probably returned a type whose size (in bits)
1296     // isn't a power-of-2 factor of the requested type size.
1297     assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
1298 
1299     SmallVector<SDValue, 2> EltParts;
1300     for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
1301       EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
1302                                            .zextOrTrunc(ViaEltSizeInBits), DL,
1303                                      ViaEltVT, isT, isO));
1304     }
1305 
1306     // EltParts is currently in little endian order. If we actually want
1307     // big-endian order then reverse it now.
1308     if (getDataLayout().isBigEndian())
1309       std::reverse(EltParts.begin(), EltParts.end());
1310 
1311     // The elements must be reversed when the element order is different
1312     // to the endianness of the elements (because the BITCAST is itself a
1313     // vector shuffle in this situation). However, we do not need any code to
1314     // perform this reversal because getConstant() is producing a vector
1315     // splat.
1316     // This situation occurs in MIPS MSA.
1317 
1318     SmallVector<SDValue, 8> Ops;
1319     for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1320       Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
1321 
1322     SDValue V = getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
1323     return V;
1324   }
1325 
1326   assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
1327          "APInt size does not match type size!");
1328   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
1329   FoldingSetNodeID ID;
1330   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1331   ID.AddPointer(Elt);
1332   ID.AddBoolean(isO);
1333   void *IP = nullptr;
1334   SDNode *N = nullptr;
1335   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1336     if (!VT.isVector())
1337       return SDValue(N, 0);
1338 
1339   if (!N) {
1340     N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
1341     CSEMap.InsertNode(N, IP);
1342     InsertNode(N);
1343     NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
1344   }
1345 
1346   SDValue Result(N, 0);
1347   if (VT.isScalableVector())
1348     Result = getSplatVector(VT, DL, Result);
1349   else if (VT.isVector())
1350     Result = getSplatBuildVector(VT, DL, Result);
1351 
1352   return Result;
1353 }
1354 
getIntPtrConstant(uint64_t Val,const SDLoc & DL,bool isTarget)1355 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
1356                                         bool isTarget) {
1357   return getConstant(Val, DL, TLI->getPointerRangeTy(getDataLayout()),
1358                      isTarget);
1359 }
1360 
getShiftAmountConstant(uint64_t Val,EVT VT,const SDLoc & DL,bool LegalTypes)1361 SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
1362                                              const SDLoc &DL, bool LegalTypes) {
1363   assert(VT.isInteger() && "Shift amount is not an integer type!");
1364   EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
1365   return getConstant(Val, DL, ShiftVT);
1366 }
1367 
getVectorIdxConstant(uint64_t Val,const SDLoc & DL,bool isTarget)1368 SDValue SelectionDAG::getVectorIdxConstant(uint64_t Val, const SDLoc &DL,
1369                                            bool isTarget) {
1370   return getConstant(Val, DL, TLI->getVectorIdxTy(getDataLayout()), isTarget);
1371 }
1372 
getConstantFP(const APFloat & V,const SDLoc & DL,EVT VT,bool isTarget)1373 SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
1374                                     bool isTarget) {
1375   return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
1376 }
1377 
getConstantFP(const ConstantFP & V,const SDLoc & DL,EVT VT,bool isTarget)1378 SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
1379                                     EVT VT, bool isTarget) {
1380   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
1381 
1382   EVT EltVT = VT.getScalarType();
1383 
1384   // Do the map lookup using the actual bit pattern for the floating point
1385   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
1386   // we don't have issues with SNANs.
1387   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
1388   FoldingSetNodeID ID;
1389   AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
1390   ID.AddPointer(&V);
1391   void *IP = nullptr;
1392   SDNode *N = nullptr;
1393   if ((N = FindNodeOrInsertPos(ID, DL, IP)))
1394     if (!VT.isVector())
1395       return SDValue(N, 0);
1396 
1397   if (!N) {
1398     N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
1399     CSEMap.InsertNode(N, IP);
1400     InsertNode(N);
1401   }
1402 
1403   SDValue Result(N, 0);
1404   if (VT.isVector())
1405     Result = getSplatBuildVector(VT, DL, Result);
1406   NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
1407   return Result;
1408 }
1409 
getConstantFP(double Val,const SDLoc & DL,EVT VT,bool isTarget)1410 SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
1411                                     bool isTarget) {
1412   EVT EltVT = VT.getScalarType();
1413   if (EltVT == MVT::f32)
1414     return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
1415   else if (EltVT == MVT::f64)
1416     return getConstantFP(APFloat(Val), DL, VT, isTarget);
1417   else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
1418            EltVT == MVT::f16 || EltVT == MVT::bf16) {
1419     bool Ignored;
1420     APFloat APF = APFloat(Val);
1421     APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
1422                 &Ignored);
1423     return getConstantFP(APF, DL, VT, isTarget);
1424   } else
1425     llvm_unreachable("Unsupported type in getConstantFP");
1426 }
1427 
getGlobalAddress(const GlobalValue * GV,const SDLoc & DL,EVT VT,int64_t Offset,bool isTargetGA,unsigned TargetFlags)1428 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
1429                                        EVT VT, int64_t Offset, bool isTargetGA,
1430                                        unsigned TargetFlags) {
1431   assert((TargetFlags == 0 || isTargetGA) &&
1432          "Cannot set target flags on target-independent globals");
1433 
1434   // Truncate (with sign-extension) the offset value to the pointer size.
1435   unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
1436   if (BitWidth < 64)
1437     Offset = SignExtend64(Offset, BitWidth);
1438 
1439   unsigned Opc;
1440   if (GV->isThreadLocal())
1441     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
1442   else
1443     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
1444 
1445   FoldingSetNodeID ID;
1446   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1447   ID.AddPointer(GV);
1448   ID.AddInteger(Offset);
1449   ID.AddInteger(TargetFlags);
1450   void *IP = nullptr;
1451   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
1452     return SDValue(E, 0);
1453 
1454   auto *N = newSDNode<GlobalAddressSDNode>(
1455       Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
1456   CSEMap.InsertNode(N, IP);
1457     InsertNode(N);
1458   return SDValue(N, 0);
1459 }
1460 
getFrameIndex(int FI,EVT VT,bool isTarget)1461 SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
1462   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
1463   FoldingSetNodeID ID;
1464   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1465   ID.AddInteger(FI);
1466   void *IP = nullptr;
1467   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1468     return SDValue(E, 0);
1469 
1470   auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
1471   CSEMap.InsertNode(N, IP);
1472   InsertNode(N);
1473   return SDValue(N, 0);
1474 }
1475 
getJumpTable(int JTI,EVT VT,bool isTarget,unsigned TargetFlags)1476 SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
1477                                    unsigned TargetFlags) {
1478   assert((TargetFlags == 0 || isTarget) &&
1479          "Cannot set target flags on target-independent jump tables");
1480   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
1481   FoldingSetNodeID ID;
1482   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1483   ID.AddInteger(JTI);
1484   ID.AddInteger(TargetFlags);
1485   void *IP = nullptr;
1486   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1487     return SDValue(E, 0);
1488 
1489   auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
1490   CSEMap.InsertNode(N, IP);
1491   InsertNode(N);
1492   return SDValue(N, 0);
1493 }
1494 
getConstantPool(const Constant * C,EVT VT,MaybeAlign Alignment,int Offset,bool isTarget,unsigned TargetFlags)1495 SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
1496                                       MaybeAlign Alignment, int Offset,
1497                                       bool isTarget, unsigned TargetFlags) {
1498   assert((TargetFlags == 0 || isTarget) &&
1499          "Cannot set target flags on target-independent globals");
1500   if (!Alignment)
1501     Alignment = shouldOptForSize()
1502                     ? getDataLayout().getABITypeAlign(C->getType())
1503                     : getDataLayout().getPrefTypeAlign(C->getType());
1504   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1505   FoldingSetNodeID ID;
1506   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1507   ID.AddInteger(Alignment->value());
1508   ID.AddInteger(Offset);
1509   ID.AddPointer(C);
1510   ID.AddInteger(TargetFlags);
1511   void *IP = nullptr;
1512   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1513     return SDValue(E, 0);
1514 
1515   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1516                                           TargetFlags);
1517   CSEMap.InsertNode(N, IP);
1518   InsertNode(N);
1519   SDValue V = SDValue(N, 0);
1520   NewSDValueDbgMsg(V, "Creating new constant pool: ", this);
1521   return V;
1522 }
1523 
getConstantPool(MachineConstantPoolValue * C,EVT VT,MaybeAlign Alignment,int Offset,bool isTarget,unsigned TargetFlags)1524 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
1525                                       MaybeAlign Alignment, int Offset,
1526                                       bool isTarget, unsigned TargetFlags) {
1527   assert((TargetFlags == 0 || isTarget) &&
1528          "Cannot set target flags on target-independent globals");
1529   if (!Alignment)
1530     Alignment = getDataLayout().getPrefTypeAlign(C->getType());
1531   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
1532   FoldingSetNodeID ID;
1533   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1534   ID.AddInteger(Alignment->value());
1535   ID.AddInteger(Offset);
1536   C->addSelectionDAGCSEId(ID);
1537   ID.AddInteger(TargetFlags);
1538   void *IP = nullptr;
1539   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1540     return SDValue(E, 0);
1541 
1542   auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, *Alignment,
1543                                           TargetFlags);
1544   CSEMap.InsertNode(N, IP);
1545   InsertNode(N);
1546   return SDValue(N, 0);
1547 }
1548 
getTargetIndex(int Index,EVT VT,int64_t Offset,unsigned TargetFlags)1549 SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
1550                                      unsigned TargetFlags) {
1551   FoldingSetNodeID ID;
1552   AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
1553   ID.AddInteger(Index);
1554   ID.AddInteger(Offset);
1555   ID.AddInteger(TargetFlags);
1556   void *IP = nullptr;
1557   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1558     return SDValue(E, 0);
1559 
1560   auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
1561   CSEMap.InsertNode(N, IP);
1562   InsertNode(N);
1563   return SDValue(N, 0);
1564 }
1565 
getBasicBlock(MachineBasicBlock * MBB)1566 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
1567   FoldingSetNodeID ID;
1568   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
1569   ID.AddPointer(MBB);
1570   void *IP = nullptr;
1571   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1572     return SDValue(E, 0);
1573 
1574   auto *N = newSDNode<BasicBlockSDNode>(MBB);
1575   CSEMap.InsertNode(N, IP);
1576   InsertNode(N);
1577   return SDValue(N, 0);
1578 }
1579 
getValueType(EVT VT)1580 SDValue SelectionDAG::getValueType(EVT VT) {
1581   if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
1582       ValueTypeNodes.size())
1583     ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
1584 
1585   SDNode *&N = VT.isExtended() ?
1586     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
1587 
1588   if (N) return SDValue(N, 0);
1589   N = newSDNode<VTSDNode>(VT);
1590   InsertNode(N);
1591   return SDValue(N, 0);
1592 }
1593 
getExternalSymbol(const char * Sym,EVT VT)1594 SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
1595   SDNode *&N = ExternalSymbols[Sym];
1596   if (N) return SDValue(N, 0);
1597   N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
1598   InsertNode(N);
1599   return SDValue(N, 0);
1600 }
1601 
getExternalFunctionSymbol(const char * Sym)1602 SDValue SelectionDAG::getExternalFunctionSymbol(const char *Sym) {
1603   auto AddrSpace = getDataLayout().getProgramAddressSpace();
1604   return getExternalSymbol(Sym, TLI->getPointerTy(getDataLayout(), AddrSpace));
1605 }
1606 
getMCSymbol(MCSymbol * Sym,EVT VT)1607 SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
1608   SDNode *&N = MCSymbols[Sym];
1609   if (N)
1610     return SDValue(N, 0);
1611   N = newSDNode<MCSymbolSDNode>(Sym, VT);
1612   InsertNode(N);
1613   return SDValue(N, 0);
1614 }
1615 
getTargetExternalSymbol(const char * Sym,EVT VT,unsigned TargetFlags)1616 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
1617                                               unsigned TargetFlags) {
1618   SDNode *&N =
1619       TargetExternalSymbols[std::pair<std::string, unsigned>(Sym, TargetFlags)];
1620   if (N) return SDValue(N, 0);
1621   N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
1622   InsertNode(N);
1623   return SDValue(N, 0);
1624 }
1625 
1626 SDValue
getTargetExternalFunctionSymbol(const char * Sym,unsigned TargetFlags)1627 SelectionDAG::getTargetExternalFunctionSymbol(const char *Sym,
1628                                               unsigned TargetFlags) {
1629   auto AddrSpace = getDataLayout().getProgramAddressSpace();
1630   return getTargetExternalSymbol(
1631       Sym, TLI->getPointerTy(getDataLayout(), AddrSpace), TargetFlags);
1632 }
1633 
getCondCode(ISD::CondCode Cond)1634 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
1635   if ((unsigned)Cond >= CondCodeNodes.size())
1636     CondCodeNodes.resize(Cond+1);
1637 
1638   if (!CondCodeNodes[Cond]) {
1639     auto *N = newSDNode<CondCodeSDNode>(Cond);
1640     CondCodeNodes[Cond] = N;
1641     InsertNode(N);
1642   }
1643 
1644   return SDValue(CondCodeNodes[Cond], 0);
1645 }
1646 
1647 /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
1648 /// point at N1 to point at N2 and indices that point at N2 to point at N1.
commuteShuffle(SDValue & N1,SDValue & N2,MutableArrayRef<int> M)1649 static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
1650   std::swap(N1, N2);
1651   ShuffleVectorSDNode::commuteMask(M);
1652 }
1653 
getVectorShuffle(EVT VT,const SDLoc & dl,SDValue N1,SDValue N2,ArrayRef<int> Mask)1654 SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
1655                                        SDValue N2, ArrayRef<int> Mask) {
1656   assert(VT.getVectorNumElements() == Mask.size() &&
1657            "Must have the same number of vector elements as mask elements!");
1658   assert(VT == N1.getValueType() && VT == N2.getValueType() &&
1659          "Invalid VECTOR_SHUFFLE");
1660 
1661   // Canonicalize shuffle undef, undef -> undef
1662   if (N1.isUndef() && N2.isUndef())
1663     return getUNDEF(VT);
1664 
1665   // Validate that all indices in Mask are within the range of the elements
1666   // input to the shuffle.
1667   int NElts = Mask.size();
1668   assert(llvm::all_of(Mask,
1669                       [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
1670          "Index out of range");
1671 
1672   // Copy the mask so we can do any needed cleanup.
1673   SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
1674 
1675   // Canonicalize shuffle v, v -> v, undef
1676   if (N1 == N2) {
1677     N2 = getUNDEF(VT);
1678     for (int i = 0; i != NElts; ++i)
1679       if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
1680   }
1681 
1682   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
1683   if (N1.isUndef())
1684     commuteShuffle(N1, N2, MaskVec);
1685 
1686   if (TLI->hasVectorBlend()) {
1687     // If shuffling a splat, try to blend the splat instead. We do this here so
1688     // that even when this arises during lowering we don't have to re-handle it.
1689     auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
1690       BitVector UndefElements;
1691       SDValue Splat = BV->getSplatValue(&UndefElements);
1692       if (!Splat)
1693         return;
1694 
1695       for (int i = 0; i < NElts; ++i) {
1696         if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
1697           continue;
1698 
1699         // If this input comes from undef, mark it as such.
1700         if (UndefElements[MaskVec[i] - Offset]) {
1701           MaskVec[i] = -1;
1702           continue;
1703         }
1704 
1705         // If we can blend a non-undef lane, use that instead.
1706         if (!UndefElements[i])
1707           MaskVec[i] = i + Offset;
1708       }
1709     };
1710     if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
1711       BlendSplat(N1BV, 0);
1712     if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
1713       BlendSplat(N2BV, NElts);
1714   }
1715 
1716   // Canonicalize all index into lhs, -> shuffle lhs, undef
1717   // Canonicalize all index into rhs, -> shuffle rhs, undef
1718   bool AllLHS = true, AllRHS = true;
1719   bool N2Undef = N2.isUndef();
1720   for (int i = 0; i != NElts; ++i) {
1721     if (MaskVec[i] >= NElts) {
1722       if (N2Undef)
1723         MaskVec[i] = -1;
1724       else
1725         AllLHS = false;
1726     } else if (MaskVec[i] >= 0) {
1727       AllRHS = false;
1728     }
1729   }
1730   if (AllLHS && AllRHS)
1731     return getUNDEF(VT);
1732   if (AllLHS && !N2Undef)
1733     N2 = getUNDEF(VT);
1734   if (AllRHS) {
1735     N1 = getUNDEF(VT);
1736     commuteShuffle(N1, N2, MaskVec);
1737   }
1738   // Reset our undef status after accounting for the mask.
1739   N2Undef = N2.isUndef();
1740   // Re-check whether both sides ended up undef.
1741   if (N1.isUndef() && N2Undef)
1742     return getUNDEF(VT);
1743 
1744   // If Identity shuffle return that node.
1745   bool Identity = true, AllSame = true;
1746   for (int i = 0; i != NElts; ++i) {
1747     if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
1748     if (MaskVec[i] != MaskVec[0]) AllSame = false;
1749   }
1750   if (Identity && NElts)
1751     return N1;
1752 
1753   // Shuffling a constant splat doesn't change the result.
1754   if (N2Undef) {
1755     SDValue V = N1;
1756 
1757     // Look through any bitcasts. We check that these don't change the number
1758     // (and size) of elements and just changes their types.
1759     while (V.getOpcode() == ISD::BITCAST)
1760       V = V->getOperand(0);
1761 
1762     // A splat should always show up as a build vector node.
1763     if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
1764       BitVector UndefElements;
1765       SDValue Splat = BV->getSplatValue(&UndefElements);
1766       // If this is a splat of an undef, shuffling it is also undef.
1767       if (Splat && Splat.isUndef())
1768         return getUNDEF(VT);
1769 
1770       bool SameNumElts =
1771           V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
1772 
1773       // We only have a splat which can skip shuffles if there is a splatted
1774       // value and no undef lanes rearranged by the shuffle.
1775       if (Splat && UndefElements.none()) {
1776         // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
1777         // number of elements match or the value splatted is a zero constant.
1778         if (SameNumElts)
1779           return N1;
1780         if (auto *C = dyn_cast<ConstantSDNode>(Splat))
1781           if (C->isNullValue())
1782             return N1;
1783       }
1784 
1785       // If the shuffle itself creates a splat, build the vector directly.
1786       if (AllSame && SameNumElts) {
1787         EVT BuildVT = BV->getValueType(0);
1788         const SDValue &Splatted = BV->getOperand(MaskVec[0]);
1789         SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
1790 
1791         // We may have jumped through bitcasts, so the type of the
1792         // BUILD_VECTOR may not match the type of the shuffle.
1793         if (BuildVT != VT)
1794           NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
1795         return NewBV;
1796       }
1797     }
1798   }
1799 
1800   FoldingSetNodeID ID;
1801   SDValue Ops[2] = { N1, N2 };
1802   AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
1803   for (int i = 0; i != NElts; ++i)
1804     ID.AddInteger(MaskVec[i]);
1805 
1806   void* IP = nullptr;
1807   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1808     return SDValue(E, 0);
1809 
1810   // Allocate the mask array for the node out of the BumpPtrAllocator, since
1811   // SDNode doesn't have access to it.  This memory will be "leaked" when
1812   // the node is deallocated, but recovered when the NodeAllocator is released.
1813   int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
1814   llvm::copy(MaskVec, MaskAlloc);
1815 
1816   auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
1817                                            dl.getDebugLoc(), MaskAlloc);
1818   createOperands(N, Ops);
1819 
1820   CSEMap.InsertNode(N, IP);
1821   InsertNode(N);
1822   SDValue V = SDValue(N, 0);
1823   NewSDValueDbgMsg(V, "Creating new node: ", this);
1824   return V;
1825 }
1826 
getCommutedVectorShuffle(const ShuffleVectorSDNode & SV)1827 SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
1828   EVT VT = SV.getValueType(0);
1829   SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
1830   ShuffleVectorSDNode::commuteMask(MaskVec);
1831 
1832   SDValue Op0 = SV.getOperand(0);
1833   SDValue Op1 = SV.getOperand(1);
1834   return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
1835 }
1836 
getRegister(unsigned RegNo,EVT VT)1837 SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
1838   FoldingSetNodeID ID;
1839   AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
1840   ID.AddInteger(RegNo);
1841   void *IP = nullptr;
1842   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1843     return SDValue(E, 0);
1844 
1845   auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
1846   N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
1847   CSEMap.InsertNode(N, IP);
1848   InsertNode(N);
1849   return SDValue(N, 0);
1850 }
1851 
getRegisterMask(const uint32_t * RegMask)1852 SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
1853   FoldingSetNodeID ID;
1854   AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
1855   ID.AddPointer(RegMask);
1856   void *IP = nullptr;
1857   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1858     return SDValue(E, 0);
1859 
1860   auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
1861   CSEMap.InsertNode(N, IP);
1862   InsertNode(N);
1863   return SDValue(N, 0);
1864 }
1865 
getEHLabel(const SDLoc & dl,SDValue Root,MCSymbol * Label)1866 SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
1867                                  MCSymbol *Label) {
1868   return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
1869 }
1870 
getLabelNode(unsigned Opcode,const SDLoc & dl,SDValue Root,MCSymbol * Label)1871 SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
1872                                    SDValue Root, MCSymbol *Label) {
1873   FoldingSetNodeID ID;
1874   SDValue Ops[] = { Root };
1875   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
1876   ID.AddPointer(Label);
1877   void *IP = nullptr;
1878   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1879     return SDValue(E, 0);
1880 
1881   auto *N =
1882       newSDNode<LabelSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(), Label);
1883   createOperands(N, Ops);
1884 
1885   CSEMap.InsertNode(N, IP);
1886   InsertNode(N);
1887   return SDValue(N, 0);
1888 }
1889 
getBlockAddress(const BlockAddress * BA,EVT VT,int64_t Offset,bool isTarget,unsigned TargetFlags)1890 SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
1891                                       int64_t Offset, bool isTarget,
1892                                       unsigned TargetFlags) {
1893   unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
1894 
1895   FoldingSetNodeID ID;
1896   AddNodeIDNode(ID, Opc, getVTList(VT), None);
1897   ID.AddPointer(BA);
1898   ID.AddInteger(Offset);
1899   ID.AddInteger(TargetFlags);
1900   void *IP = nullptr;
1901   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1902     return SDValue(E, 0);
1903 
1904   auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
1905   CSEMap.InsertNode(N, IP);
1906   InsertNode(N);
1907   return SDValue(N, 0);
1908 }
1909 
getSrcValue(const Value * V)1910 SDValue SelectionDAG::getSrcValue(const Value *V) {
1911   FoldingSetNodeID ID;
1912   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
1913   ID.AddPointer(V);
1914 
1915   void *IP = nullptr;
1916   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1917     return SDValue(E, 0);
1918 
1919   auto *N = newSDNode<SrcValueSDNode>(V);
1920   CSEMap.InsertNode(N, IP);
1921   InsertNode(N);
1922   return SDValue(N, 0);
1923 }
1924 
getMDNode(const MDNode * MD)1925 SDValue SelectionDAG::getMDNode(const MDNode *MD) {
1926   FoldingSetNodeID ID;
1927   AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
1928   ID.AddPointer(MD);
1929 
1930   void *IP = nullptr;
1931   if (SDNode *E = FindNodeOrInsertPos(ID, IP))
1932     return SDValue(E, 0);
1933 
1934   auto *N = newSDNode<MDNodeSDNode>(MD);
1935   CSEMap.InsertNode(N, IP);
1936   InsertNode(N);
1937   return SDValue(N, 0);
1938 }
1939 
getBitcast(EVT VT,SDValue V)1940 SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
1941   if (VT == V.getValueType())
1942     return V;
1943 
1944   return getNode(ISD::BITCAST, SDLoc(V), VT, V);
1945 }
1946 
getAddrSpaceCast(const SDLoc & dl,EVT VT,SDValue Ptr,unsigned SrcAS,unsigned DestAS)1947 SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
1948                                        unsigned SrcAS, unsigned DestAS) {
1949   SDValue Ops[] = {Ptr};
1950   FoldingSetNodeID ID;
1951   AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
1952   ID.AddInteger(SrcAS);
1953   ID.AddInteger(DestAS);
1954 
1955   void *IP = nullptr;
1956   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
1957     return SDValue(E, 0);
1958 
1959   auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
1960                                            VT, SrcAS, DestAS);
1961   createOperands(N, Ops);
1962 
1963   CSEMap.InsertNode(N, IP);
1964   InsertNode(N);
1965   return SDValue(N, 0);
1966 }
1967 
getFreeze(SDValue V)1968 SDValue SelectionDAG::getFreeze(SDValue V) {
1969   return getNode(ISD::FREEZE, SDLoc(V), V.getValueType(), V);
1970 }
1971 
1972 /// getShiftAmountOperand - Return the specified value casted to
1973 /// the target's desired shift amount type.
getShiftAmountOperand(EVT LHSTy,SDValue Op)1974 SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
1975   EVT OpTy = Op.getValueType();
1976   EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
1977   if (OpTy == ShTy || OpTy.isVector()) return Op;
1978 
1979   return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
1980 }
1981 
expandVAArg(SDNode * Node)1982 SDValue SelectionDAG::expandVAArg(SDNode *Node) {
1983   SDLoc dl(Node);
1984   const TargetLowering &TLI = getTargetLoweringInfo();
1985   const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1986   EVT VT = Node->getValueType(0);
1987   SDValue Tmp1 = Node->getOperand(0);
1988   SDValue Tmp2 = Node->getOperand(1);
1989   const MaybeAlign MA(Node->getConstantOperandVal(3));
1990 
1991   SDValue VAListLoad = getLoad(
1992       TLI.getPointerTy(getDataLayout(), getDataLayout().getAllocaAddrSpace()),
1993       dl, Tmp1, Tmp2, MachinePointerInfo(V));
1994   SDValue VAList = VAListLoad;
1995 
1996   if (MA && *MA > TLI.getMinStackArgumentAlignment()) {
1997     VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
1998                      getConstant(MA->value() - 1, dl, VAList.getValueType()));
1999 
2000     VAList =
2001         getNode(ISD::AND, dl, VAList.getValueType(), VAList,
2002                 getConstant(-(int64_t)MA->value(), dl, VAList.getValueType()));
2003   }
2004 
2005   // Increment the pointer, VAList, to the next vaarg
2006   Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
2007                  getConstant(getDataLayout().getTypeAllocSize(
2008                                                VT.getTypeForEVT(*getContext())),
2009                              dl, VAList.getValueType()));
2010   // Store the incremented VAList to the legalized pointer
2011   Tmp1 =
2012       getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
2013   // Load the actual argument out of the pointer VAList
2014   return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
2015 }
2016 
expandVACopy(SDNode * Node)2017 SDValue SelectionDAG::expandVACopy(SDNode *Node) {
2018   SDLoc dl(Node);
2019   const TargetLowering &TLI = getTargetLoweringInfo();
2020   // This defaults to loading a pointer from the input and storing it to the
2021   // output, returning the chain.
2022   const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2023   const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2024   SDValue Tmp1 = getLoad(
2025       TLI.getPointerTy(getDataLayout(), getDataLayout().getAllocaAddrSpace()),
2026       dl, Node->getOperand(0), Node->getOperand(2), MachinePointerInfo(VS));
2027   return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
2028                   MachinePointerInfo(VD));
2029 }
2030 
getReducedAlign(EVT VT,bool UseABI)2031 Align SelectionDAG::getReducedAlign(EVT VT, bool UseABI) {
2032   const DataLayout &DL = getDataLayout();
2033   Type *Ty = VT.getTypeForEVT(*getContext());
2034   Align RedAlign = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2035 
2036   if (TLI->isTypeLegal(VT) || !VT.isVector())
2037     return RedAlign;
2038 
2039   const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering();
2040   const Align StackAlign = TFI->getStackAlign();
2041 
2042   // See if we can choose a smaller ABI alignment in cases where it's an
2043   // illegal vector type that will get broken down.
2044   if (RedAlign > StackAlign) {
2045     EVT IntermediateVT;
2046     MVT RegisterVT;
2047     unsigned NumIntermediates;
2048     TLI->getVectorTypeBreakdown(*getContext(), VT, IntermediateVT,
2049                                 NumIntermediates, RegisterVT);
2050     Ty = IntermediateVT.getTypeForEVT(*getContext());
2051     Align RedAlign2 = UseABI ? DL.getABITypeAlign(Ty) : DL.getPrefTypeAlign(Ty);
2052     if (RedAlign2 < RedAlign)
2053       RedAlign = RedAlign2;
2054   }
2055 
2056   return RedAlign;
2057 }
2058 
CreateStackTemporary(TypeSize Bytes,Align Alignment)2059 SDValue SelectionDAG::CreateStackTemporary(TypeSize Bytes, Align Alignment) {
2060   MachineFrameInfo &MFI = MF->getFrameInfo();
2061   int FrameIdx = MFI.CreateStackObject(Bytes, Alignment, false);
2062   return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
2063 }
2064 
CreateStackTemporary(EVT VT,unsigned minAlign)2065 SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
2066   Type *Ty = VT.getTypeForEVT(*getContext());
2067   Align StackAlign =
2068       std::max(getDataLayout().getPrefTypeAlign(Ty), Align(minAlign));
2069   return CreateStackTemporary(VT.getStoreSize(), StackAlign);
2070 }
2071 
CreateStackTemporary(EVT VT1,EVT VT2)2072 SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
2073   TypeSize Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
2074   Type *Ty1 = VT1.getTypeForEVT(*getContext());
2075   Type *Ty2 = VT2.getTypeForEVT(*getContext());
2076   const DataLayout &DL = getDataLayout();
2077   Align Align = std::max(DL.getPrefTypeAlign(Ty1), DL.getPrefTypeAlign(Ty2));
2078   return CreateStackTemporary(Bytes, Align);
2079 }
2080 
FoldSetCC(EVT VT,SDValue N1,SDValue N2,ISD::CondCode Cond,const SDLoc & dl)2081 SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
2082                                 ISD::CondCode Cond, const SDLoc &dl) {
2083   EVT OpVT = N1.getValueType();
2084 
2085   // These setcc operations always fold.
2086   switch (Cond) {
2087   default: break;
2088   case ISD::SETFALSE:
2089   case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
2090   case ISD::SETTRUE:
2091   case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
2092 
2093   case ISD::SETOEQ:
2094   case ISD::SETOGT:
2095   case ISD::SETOGE:
2096   case ISD::SETOLT:
2097   case ISD::SETOLE:
2098   case ISD::SETONE:
2099   case ISD::SETO:
2100   case ISD::SETUO:
2101   case ISD::SETUEQ:
2102   case ISD::SETUNE:
2103     assert(!OpVT.isInteger() && "Illegal setcc for integer!");
2104     break;
2105   }
2106 
2107   if (OpVT.isInteger()) {
2108     // For EQ and NE, we can always pick a value for the undef to make the
2109     // predicate pass or fail, so we can return undef.
2110     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2111     // icmp eq/ne X, undef -> undef.
2112     if ((N1.isUndef() || N2.isUndef()) &&
2113         (Cond == ISD::SETEQ || Cond == ISD::SETNE))
2114       return getUNDEF(VT);
2115 
2116     // If both operands are undef, we can return undef for int comparison.
2117     // icmp undef, undef -> undef.
2118     if (N1.isUndef() && N2.isUndef())
2119       return getUNDEF(VT);
2120 
2121     // icmp X, X -> true/false
2122     // icmp X, undef -> true/false because undef could be X.
2123     if (N1 == N2)
2124       return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
2125   }
2126 
2127   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
2128     const APInt &C2 = N2C->getAPIntValue();
2129     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
2130       const APInt &C1 = N1C->getAPIntValue();
2131 
2132       switch (Cond) {
2133       default: llvm_unreachable("Unknown integer setcc!");
2134       case ISD::SETEQ:  return getBoolConstant(C1 == C2, dl, VT, OpVT);
2135       case ISD::SETNE:  return getBoolConstant(C1 != C2, dl, VT, OpVT);
2136       case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
2137       case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
2138       case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
2139       case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
2140       case ISD::SETLT:  return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
2141       case ISD::SETGT:  return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
2142       case ISD::SETLE:  return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
2143       case ISD::SETGE:  return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
2144       }
2145     }
2146   }
2147 
2148   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
2149   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
2150 
2151   if (N1CFP && N2CFP) {
2152     APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
2153     switch (Cond) {
2154     default: break;
2155     case ISD::SETEQ:  if (R==APFloat::cmpUnordered)
2156                         return getUNDEF(VT);
2157                       LLVM_FALLTHROUGH;
2158     case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
2159                                              OpVT);
2160     case ISD::SETNE:  if (R==APFloat::cmpUnordered)
2161                         return getUNDEF(VT);
2162                       LLVM_FALLTHROUGH;
2163     case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2164                                              R==APFloat::cmpLessThan, dl, VT,
2165                                              OpVT);
2166     case ISD::SETLT:  if (R==APFloat::cmpUnordered)
2167                         return getUNDEF(VT);
2168                       LLVM_FALLTHROUGH;
2169     case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
2170                                              OpVT);
2171     case ISD::SETGT:  if (R==APFloat::cmpUnordered)
2172                         return getUNDEF(VT);
2173                       LLVM_FALLTHROUGH;
2174     case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
2175                                              VT, OpVT);
2176     case ISD::SETLE:  if (R==APFloat::cmpUnordered)
2177                         return getUNDEF(VT);
2178                       LLVM_FALLTHROUGH;
2179     case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
2180                                              R==APFloat::cmpEqual, dl, VT,
2181                                              OpVT);
2182     case ISD::SETGE:  if (R==APFloat::cmpUnordered)
2183                         return getUNDEF(VT);
2184                       LLVM_FALLTHROUGH;
2185     case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2186                                          R==APFloat::cmpEqual, dl, VT, OpVT);
2187     case ISD::SETO:   return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
2188                                              OpVT);
2189     case ISD::SETUO:  return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
2190                                              OpVT);
2191     case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
2192                                              R==APFloat::cmpEqual, dl, VT,
2193                                              OpVT);
2194     case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
2195                                              OpVT);
2196     case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
2197                                              R==APFloat::cmpLessThan, dl, VT,
2198                                              OpVT);
2199     case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
2200                                              R==APFloat::cmpUnordered, dl, VT,
2201                                              OpVT);
2202     case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
2203                                              VT, OpVT);
2204     case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
2205                                              OpVT);
2206     }
2207   } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
2208     // Ensure that the constant occurs on the RHS.
2209     ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
2210     if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
2211       return SDValue();
2212     return getSetCC(dl, VT, N2, N1, SwappedCond);
2213   } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
2214              (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
2215     // If an operand is known to be a nan (or undef that could be a nan), we can
2216     // fold it.
2217     // Choosing NaN for the undef will always make unordered comparison succeed
2218     // and ordered comparison fails.
2219     // Matches behavior in llvm::ConstantFoldCompareInstruction.
2220     switch (ISD::getUnorderedFlavor(Cond)) {
2221     default:
2222       llvm_unreachable("Unknown flavor!");
2223     case 0: // Known false.
2224       return getBoolConstant(false, dl, VT, OpVT);
2225     case 1: // Known true.
2226       return getBoolConstant(true, dl, VT, OpVT);
2227     case 2: // Undefined.
2228       return getUNDEF(VT);
2229     }
2230   }
2231 
2232   // Could not fold it.
2233   return SDValue();
2234 }
2235 
2236 /// See if the specified operand can be simplified with the knowledge that only
2237 /// the bits specified by DemandedBits are used.
2238 /// TODO: really we should be making this into the DAG equivalent of
2239 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
GetDemandedBits(SDValue V,const APInt & DemandedBits)2240 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits) {
2241   EVT VT = V.getValueType();
2242   APInt DemandedElts = VT.isVector()
2243                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2244                            : APInt(1, 1);
2245   return GetDemandedBits(V, DemandedBits, DemandedElts);
2246 }
2247 
2248 /// See if the specified operand can be simplified with the knowledge that only
2249 /// the bits specified by DemandedBits are used in the elements specified by
2250 /// DemandedElts.
2251 /// TODO: really we should be making this into the DAG equivalent of
2252 /// SimplifyMultipleUseDemandedBits and not generate any new nodes.
GetDemandedBits(SDValue V,const APInt & DemandedBits,const APInt & DemandedElts)2253 SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &DemandedBits,
2254                                       const APInt &DemandedElts) {
2255   switch (V.getOpcode()) {
2256   default:
2257     return TLI->SimplifyMultipleUseDemandedBits(V, DemandedBits, DemandedElts,
2258                                                 *this, 0);
2259     break;
2260   case ISD::Constant: {
2261     const APInt &CVal = cast<ConstantSDNode>(V)->getAPIntValue();
2262     APInt NewVal = CVal & DemandedBits;
2263     if (NewVal != CVal)
2264       return getConstant(NewVal, SDLoc(V), V.getValueType());
2265     break;
2266   }
2267   case ISD::SRL:
2268     // Only look at single-use SRLs.
2269     if (!V.getNode()->hasOneUse())
2270       break;
2271     if (auto *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
2272       // See if we can recursively simplify the LHS.
2273       unsigned Amt = RHSC->getZExtValue();
2274 
2275       // Watch out for shift count overflow though.
2276       if (Amt >= DemandedBits.getBitWidth())
2277         break;
2278       APInt SrcDemandedBits = DemandedBits << Amt;
2279       if (SDValue SimplifyLHS =
2280               GetDemandedBits(V.getOperand(0), SrcDemandedBits))
2281         return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
2282                        V.getOperand(1));
2283     }
2284     break;
2285   case ISD::AND: {
2286     // X & -1 -> X (ignoring bits which aren't demanded).
2287     // Also handle the case where masked out bits in X are known to be zero.
2288     if (ConstantSDNode *RHSC = isConstOrConstSplat(V.getOperand(1))) {
2289       const APInt &AndVal = RHSC->getAPIntValue();
2290       if (DemandedBits.isSubsetOf(AndVal) ||
2291           DemandedBits.isSubsetOf(computeKnownBits(V.getOperand(0)).Zero |
2292                                   AndVal))
2293         return V.getOperand(0);
2294     }
2295     break;
2296   }
2297   }
2298   return SDValue();
2299 }
2300 
2301 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
2302 /// use this predicate to simplify operations downstream.
SignBitIsZero(SDValue Op,unsigned Depth) const2303 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
2304   unsigned BitWidth = Op.getScalarValueSizeInBits();
2305   return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
2306 }
2307 
2308 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
2309 /// this predicate to simplify operations downstream.  Mask is known to be zero
2310 /// for bits that V cannot have.
MaskedValueIsZero(SDValue V,const APInt & Mask,unsigned Depth) const2311 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2312                                      unsigned Depth) const {
2313   return Mask.isSubsetOf(computeKnownBits(V, Depth).Zero);
2314 }
2315 
2316 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero in
2317 /// DemandedElts.  We use this predicate to simplify operations downstream.
2318 /// Mask is known to be zero for bits that V cannot have.
MaskedValueIsZero(SDValue V,const APInt & Mask,const APInt & DemandedElts,unsigned Depth) const2319 bool SelectionDAG::MaskedValueIsZero(SDValue V, const APInt &Mask,
2320                                      const APInt &DemandedElts,
2321                                      unsigned Depth) const {
2322   return Mask.isSubsetOf(computeKnownBits(V, DemandedElts, Depth).Zero);
2323 }
2324 
2325 /// MaskedValueIsAllOnes - Return true if '(Op & Mask) == Mask'.
MaskedValueIsAllOnes(SDValue V,const APInt & Mask,unsigned Depth) const2326 bool SelectionDAG::MaskedValueIsAllOnes(SDValue V, const APInt &Mask,
2327                                         unsigned Depth) const {
2328   return Mask.isSubsetOf(computeKnownBits(V, Depth).One);
2329 }
2330 
2331 /// isSplatValue - Return true if the vector V has the same value
2332 /// across all DemandedElts. For scalable vectors it does not make
2333 /// sense to specify which elements are demanded or undefined, therefore
2334 /// they are simply ignored.
isSplatValue(SDValue V,const APInt & DemandedElts,APInt & UndefElts)2335 bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
2336                                 APInt &UndefElts) {
2337   EVT VT = V.getValueType();
2338   assert(VT.isVector() && "Vector type expected");
2339 
2340   if (!VT.isScalableVector() && !DemandedElts)
2341     return false; // No demanded elts, better to assume we don't know anything.
2342 
2343   // Deal with some common cases here that work for both fixed and scalable
2344   // vector types.
2345   switch (V.getOpcode()) {
2346   case ISD::SPLAT_VECTOR:
2347     return true;
2348   case ISD::ADD:
2349   case ISD::SUB:
2350   case ISD::AND: {
2351     APInt UndefLHS, UndefRHS;
2352     SDValue LHS = V.getOperand(0);
2353     SDValue RHS = V.getOperand(1);
2354     if (isSplatValue(LHS, DemandedElts, UndefLHS) &&
2355         isSplatValue(RHS, DemandedElts, UndefRHS)) {
2356       UndefElts = UndefLHS | UndefRHS;
2357       return true;
2358     }
2359     break;
2360   }
2361   }
2362 
2363   // We don't support other cases than those above for scalable vectors at
2364   // the moment.
2365   if (VT.isScalableVector())
2366     return false;
2367 
2368   unsigned NumElts = VT.getVectorNumElements();
2369   assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
2370   UndefElts = APInt::getNullValue(NumElts);
2371 
2372   switch (V.getOpcode()) {
2373   case ISD::BUILD_VECTOR: {
2374     SDValue Scl;
2375     for (unsigned i = 0; i != NumElts; ++i) {
2376       SDValue Op = V.getOperand(i);
2377       if (Op.isUndef()) {
2378         UndefElts.setBit(i);
2379         continue;
2380       }
2381       if (!DemandedElts[i])
2382         continue;
2383       if (Scl && Scl != Op)
2384         return false;
2385       Scl = Op;
2386     }
2387     return true;
2388   }
2389   case ISD::VECTOR_SHUFFLE: {
2390     // Check if this is a shuffle node doing a splat.
2391     // TODO: Do we need to handle shuffle(splat, undef, mask)?
2392     int SplatIndex = -1;
2393     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
2394     for (int i = 0; i != (int)NumElts; ++i) {
2395       int M = Mask[i];
2396       if (M < 0) {
2397         UndefElts.setBit(i);
2398         continue;
2399       }
2400       if (!DemandedElts[i])
2401         continue;
2402       if (0 <= SplatIndex && SplatIndex != M)
2403         return false;
2404       SplatIndex = M;
2405     }
2406     return true;
2407   }
2408   case ISD::EXTRACT_SUBVECTOR: {
2409     // Offset the demanded elts by the subvector index.
2410     SDValue Src = V.getOperand(0);
2411     uint64_t Idx = V.getConstantOperandVal(1);
2412     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2413     APInt UndefSrcElts;
2414     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2415     if (isSplatValue(Src, DemandedSrcElts, UndefSrcElts)) {
2416       UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
2417       return true;
2418     }
2419     break;
2420   }
2421   }
2422 
2423   return false;
2424 }
2425 
2426 /// Helper wrapper to main isSplatValue function.
isSplatValue(SDValue V,bool AllowUndefs)2427 bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
2428   EVT VT = V.getValueType();
2429   assert(VT.isVector() && "Vector type expected");
2430 
2431   APInt UndefElts;
2432   APInt DemandedElts;
2433 
2434   // For now we don't support this with scalable vectors.
2435   if (!VT.isScalableVector())
2436     DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2437   return isSplatValue(V, DemandedElts, UndefElts) &&
2438          (AllowUndefs || !UndefElts);
2439 }
2440 
getSplatSourceVector(SDValue V,int & SplatIdx)2441 SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
2442   V = peekThroughExtractSubvectors(V);
2443 
2444   EVT VT = V.getValueType();
2445   unsigned Opcode = V.getOpcode();
2446   switch (Opcode) {
2447   default: {
2448     APInt UndefElts;
2449     APInt DemandedElts;
2450 
2451     if (!VT.isScalableVector())
2452       DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
2453 
2454     if (isSplatValue(V, DemandedElts, UndefElts)) {
2455       if (VT.isScalableVector()) {
2456         // DemandedElts and UndefElts are ignored for scalable vectors, since
2457         // the only supported cases are SPLAT_VECTOR nodes.
2458         SplatIdx = 0;
2459       } else {
2460         // Handle case where all demanded elements are UNDEF.
2461         if (DemandedElts.isSubsetOf(UndefElts)) {
2462           SplatIdx = 0;
2463           return getUNDEF(VT);
2464         }
2465         SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
2466       }
2467       return V;
2468     }
2469     break;
2470   }
2471   case ISD::SPLAT_VECTOR:
2472     SplatIdx = 0;
2473     return V;
2474   case ISD::VECTOR_SHUFFLE: {
2475     if (VT.isScalableVector())
2476       return SDValue();
2477 
2478     // Check if this is a shuffle node doing a splat.
2479     // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
2480     // getTargetVShiftNode currently struggles without the splat source.
2481     auto *SVN = cast<ShuffleVectorSDNode>(V);
2482     if (!SVN->isSplat())
2483       break;
2484     int Idx = SVN->getSplatIndex();
2485     int NumElts = V.getValueType().getVectorNumElements();
2486     SplatIdx = Idx % NumElts;
2487     return V.getOperand(Idx / NumElts);
2488   }
2489   }
2490 
2491   return SDValue();
2492 }
2493 
getSplatValue(SDValue V)2494 SDValue SelectionDAG::getSplatValue(SDValue V) {
2495   int SplatIdx;
2496   if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx))
2497     return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V),
2498                    SrcVector.getValueType().getScalarType(), SrcVector,
2499                    getVectorIdxConstant(SplatIdx, SDLoc(V)));
2500   return SDValue();
2501 }
2502 
2503 const APInt *
getValidShiftAmountConstant(SDValue V,const APInt & DemandedElts) const2504 SelectionDAG::getValidShiftAmountConstant(SDValue V,
2505                                           const APInt &DemandedElts) const {
2506   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2507           V.getOpcode() == ISD::SRA) &&
2508          "Unknown shift node");
2509   unsigned BitWidth = V.getScalarValueSizeInBits();
2510   if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1), DemandedElts)) {
2511     // Shifting more than the bitwidth is not valid.
2512     const APInt &ShAmt = SA->getAPIntValue();
2513     if (ShAmt.ult(BitWidth))
2514       return &ShAmt;
2515   }
2516   return nullptr;
2517 }
2518 
getValidMinimumShiftAmountConstant(SDValue V,const APInt & DemandedElts) const2519 const APInt *SelectionDAG::getValidMinimumShiftAmountConstant(
2520     SDValue V, const APInt &DemandedElts) const {
2521   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2522           V.getOpcode() == ISD::SRA) &&
2523          "Unknown shift node");
2524   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2525     return ValidAmt;
2526   unsigned BitWidth = V.getScalarValueSizeInBits();
2527   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2528   if (!BV)
2529     return nullptr;
2530   const APInt *MinShAmt = nullptr;
2531   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2532     if (!DemandedElts[i])
2533       continue;
2534     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2535     if (!SA)
2536       return nullptr;
2537     // Shifting more than the bitwidth is not valid.
2538     const APInt &ShAmt = SA->getAPIntValue();
2539     if (ShAmt.uge(BitWidth))
2540       return nullptr;
2541     if (MinShAmt && MinShAmt->ule(ShAmt))
2542       continue;
2543     MinShAmt = &ShAmt;
2544   }
2545   return MinShAmt;
2546 }
2547 
getValidMaximumShiftAmountConstant(SDValue V,const APInt & DemandedElts) const2548 const APInt *SelectionDAG::getValidMaximumShiftAmountConstant(
2549     SDValue V, const APInt &DemandedElts) const {
2550   assert((V.getOpcode() == ISD::SHL || V.getOpcode() == ISD::SRL ||
2551           V.getOpcode() == ISD::SRA) &&
2552          "Unknown shift node");
2553   if (const APInt *ValidAmt = getValidShiftAmountConstant(V, DemandedElts))
2554     return ValidAmt;
2555   unsigned BitWidth = V.getScalarValueSizeInBits();
2556   auto *BV = dyn_cast<BuildVectorSDNode>(V.getOperand(1));
2557   if (!BV)
2558     return nullptr;
2559   const APInt *MaxShAmt = nullptr;
2560   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
2561     if (!DemandedElts[i])
2562       continue;
2563     auto *SA = dyn_cast<ConstantSDNode>(BV->getOperand(i));
2564     if (!SA)
2565       return nullptr;
2566     // Shifting more than the bitwidth is not valid.
2567     const APInt &ShAmt = SA->getAPIntValue();
2568     if (ShAmt.uge(BitWidth))
2569       return nullptr;
2570     if (MaxShAmt && MaxShAmt->uge(ShAmt))
2571       continue;
2572     MaxShAmt = &ShAmt;
2573   }
2574   return MaxShAmt;
2575 }
2576 
2577 /// Determine which bits of Op are known to be either zero or one and return
2578 /// them in Known. For vectors, the known bits are those that are shared by
2579 /// every vector element.
computeKnownBits(SDValue Op,unsigned Depth) const2580 KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
2581   EVT VT = Op.getValueType();
2582 
2583   // TOOD: Until we have a plan for how to represent demanded elements for
2584   // scalable vectors, we can just bail out for now.
2585   if (Op.getValueType().isScalableVector()) {
2586     unsigned BitWidth = Op.getScalarValueSizeInBits();
2587     return KnownBits(BitWidth);
2588   }
2589 
2590   APInt DemandedElts = VT.isVector()
2591                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
2592                            : APInt(1, 1);
2593   return computeKnownBits(Op, DemandedElts, Depth);
2594 }
2595 
2596 /// Determine which bits of Op are known to be either zero or one and return
2597 /// them in Known. The DemandedElts argument allows us to only collect the known
2598 /// bits that are shared by the requested vector elements.
computeKnownBits(SDValue Op,const APInt & DemandedElts,unsigned Depth) const2599 KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
2600                                          unsigned Depth) const {
2601   unsigned BitWidth = Op.getScalarValueSizeInBits();
2602 
2603   KnownBits Known(BitWidth);   // Don't know anything.
2604 
2605   // TOOD: Until we have a plan for how to represent demanded elements for
2606   // scalable vectors, we can just bail out for now.
2607   if (Op.getValueType().isScalableVector())
2608     return Known;
2609 
2610   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
2611     // We know all of the bits for a constant!
2612     Known.One = C->getAPIntValue();
2613     Known.Zero = ~Known.One;
2614     return Known;
2615   }
2616   if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
2617     // We know all of the bits for a constant fp!
2618     Known.One = C->getValueAPF().bitcastToAPInt();
2619     Known.Zero = ~Known.One;
2620     return Known;
2621   }
2622 
2623   if (Depth >= MaxRecursionDepth)
2624     return Known;  // Limit search depth.
2625 
2626   KnownBits Known2;
2627   unsigned NumElts = DemandedElts.getBitWidth();
2628   assert((!Op.getValueType().isVector() ||
2629           NumElts == Op.getValueType().getVectorNumElements()) &&
2630          "Unexpected vector size");
2631 
2632   if (!DemandedElts)
2633     return Known;  // No demanded elts, better to assume we don't know anything.
2634 
2635   unsigned Opcode = Op.getOpcode();
2636   switch (Opcode) {
2637   case ISD::BUILD_VECTOR:
2638     // Collect the known bits that are shared by every demanded vector element.
2639     Known.Zero.setAllBits(); Known.One.setAllBits();
2640     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
2641       if (!DemandedElts[i])
2642         continue;
2643 
2644       SDValue SrcOp = Op.getOperand(i);
2645       Known2 = computeKnownBits(SrcOp, Depth + 1);
2646 
2647       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
2648       if (SrcOp.getValueSizeInBits() != BitWidth) {
2649         assert(SrcOp.getValueSizeInBits() > BitWidth &&
2650                "Expected BUILD_VECTOR implicit truncation");
2651         Known2 = Known2.trunc(BitWidth);
2652       }
2653 
2654       // Known bits are the values that are shared by every demanded element.
2655       Known.One &= Known2.One;
2656       Known.Zero &= Known2.Zero;
2657 
2658       // If we don't know any bits, early out.
2659       if (Known.isUnknown())
2660         break;
2661     }
2662     break;
2663   case ISD::VECTOR_SHUFFLE: {
2664     // Collect the known bits that are shared by every vector element referenced
2665     // by the shuffle.
2666     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
2667     Known.Zero.setAllBits(); Known.One.setAllBits();
2668     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
2669     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
2670     for (unsigned i = 0; i != NumElts; ++i) {
2671       if (!DemandedElts[i])
2672         continue;
2673 
2674       int M = SVN->getMaskElt(i);
2675       if (M < 0) {
2676         // For UNDEF elements, we don't know anything about the common state of
2677         // the shuffle result.
2678         Known.resetAll();
2679         DemandedLHS.clearAllBits();
2680         DemandedRHS.clearAllBits();
2681         break;
2682       }
2683 
2684       if ((unsigned)M < NumElts)
2685         DemandedLHS.setBit((unsigned)M % NumElts);
2686       else
2687         DemandedRHS.setBit((unsigned)M % NumElts);
2688     }
2689     // Known bits are the values that are shared by every demanded element.
2690     if (!!DemandedLHS) {
2691       SDValue LHS = Op.getOperand(0);
2692       Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
2693       Known.One &= Known2.One;
2694       Known.Zero &= Known2.Zero;
2695     }
2696     // If we don't know any bits, early out.
2697     if (Known.isUnknown())
2698       break;
2699     if (!!DemandedRHS) {
2700       SDValue RHS = Op.getOperand(1);
2701       Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
2702       Known.One &= Known2.One;
2703       Known.Zero &= Known2.Zero;
2704     }
2705     break;
2706   }
2707   case ISD::CONCAT_VECTORS: {
2708     // Split DemandedElts and test each of the demanded subvectors.
2709     Known.Zero.setAllBits(); Known.One.setAllBits();
2710     EVT SubVectorVT = Op.getOperand(0).getValueType();
2711     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
2712     unsigned NumSubVectors = Op.getNumOperands();
2713     for (unsigned i = 0; i != NumSubVectors; ++i) {
2714       APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
2715       DemandedSub = DemandedSub.trunc(NumSubVectorElts);
2716       if (!!DemandedSub) {
2717         SDValue Sub = Op.getOperand(i);
2718         Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
2719         Known.One &= Known2.One;
2720         Known.Zero &= Known2.Zero;
2721       }
2722       // If we don't know any bits, early out.
2723       if (Known.isUnknown())
2724         break;
2725     }
2726     break;
2727   }
2728   case ISD::INSERT_SUBVECTOR: {
2729     // Demand any elements from the subvector and the remainder from the src its
2730     // inserted into.
2731     SDValue Src = Op.getOperand(0);
2732     SDValue Sub = Op.getOperand(1);
2733     uint64_t Idx = Op.getConstantOperandVal(2);
2734     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
2735     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
2736     APInt DemandedSrcElts = DemandedElts;
2737     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
2738 
2739     Known.One.setAllBits();
2740     Known.Zero.setAllBits();
2741     if (!!DemandedSubElts) {
2742       Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
2743       if (Known.isUnknown())
2744         break; // early-out.
2745     }
2746     if (!!DemandedSrcElts) {
2747       Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2748       Known.One &= Known2.One;
2749       Known.Zero &= Known2.Zero;
2750     }
2751     break;
2752   }
2753   case ISD::EXTRACT_SUBVECTOR: {
2754     // Offset the demanded elts by the subvector index.
2755     SDValue Src = Op.getOperand(0);
2756     // Bail until we can represent demanded elements for scalable vectors.
2757     if (Src.getValueType().isScalableVector())
2758       break;
2759     uint64_t Idx = Op.getConstantOperandVal(1);
2760     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
2761     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
2762     Known = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
2763     break;
2764   }
2765   case ISD::SCALAR_TO_VECTOR: {
2766     // We know about scalar_to_vector as much as we know about it source,
2767     // which becomes the first element of otherwise unknown vector.
2768     if (DemandedElts != 1)
2769       break;
2770 
2771     SDValue N0 = Op.getOperand(0);
2772     Known = computeKnownBits(N0, Depth + 1);
2773     if (N0.getValueSizeInBits() != BitWidth)
2774       Known = Known.trunc(BitWidth);
2775 
2776     break;
2777   }
2778   case ISD::BITCAST: {
2779     SDValue N0 = Op.getOperand(0);
2780     EVT SubVT = N0.getValueType();
2781     unsigned SubBitWidth = SubVT.getScalarSizeInBits();
2782 
2783     // Ignore bitcasts from unsupported types.
2784     if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
2785       break;
2786 
2787     // Fast handling of 'identity' bitcasts.
2788     if (BitWidth == SubBitWidth) {
2789       Known = computeKnownBits(N0, DemandedElts, Depth + 1);
2790       break;
2791     }
2792 
2793     bool IsLE = getDataLayout().isLittleEndian();
2794 
2795     // Bitcast 'small element' vector to 'large element' scalar/vector.
2796     if ((BitWidth % SubBitWidth) == 0) {
2797       assert(N0.getValueType().isVector() && "Expected bitcast from vector");
2798 
2799       // Collect known bits for the (larger) output by collecting the known
2800       // bits from each set of sub elements and shift these into place.
2801       // We need to separately call computeKnownBits for each set of
2802       // sub elements as the knownbits for each is likely to be different.
2803       unsigned SubScale = BitWidth / SubBitWidth;
2804       APInt SubDemandedElts(NumElts * SubScale, 0);
2805       for (unsigned i = 0; i != NumElts; ++i)
2806         if (DemandedElts[i])
2807           SubDemandedElts.setBit(i * SubScale);
2808 
2809       for (unsigned i = 0; i != SubScale; ++i) {
2810         Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
2811                          Depth + 1);
2812         unsigned Shifts = IsLE ? i : SubScale - 1 - i;
2813         Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts);
2814         Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts);
2815       }
2816     }
2817 
2818     // Bitcast 'large element' scalar/vector to 'small element' vector.
2819     if ((SubBitWidth % BitWidth) == 0) {
2820       assert(Op.getValueType().isVector() && "Expected bitcast to vector");
2821 
2822       // Collect known bits for the (smaller) output by collecting the known
2823       // bits from the overlapping larger input elements and extracting the
2824       // sub sections we actually care about.
2825       unsigned SubScale = SubBitWidth / BitWidth;
2826       APInt SubDemandedElts(NumElts / SubScale, 0);
2827       for (unsigned i = 0; i != NumElts; ++i)
2828         if (DemandedElts[i])
2829           SubDemandedElts.setBit(i / SubScale);
2830 
2831       Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
2832 
2833       Known.Zero.setAllBits(); Known.One.setAllBits();
2834       for (unsigned i = 0; i != NumElts; ++i)
2835         if (DemandedElts[i]) {
2836           unsigned Shifts = IsLE ? i : NumElts - 1 - i;
2837           unsigned Offset = (Shifts % SubScale) * BitWidth;
2838           Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
2839           Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
2840           // If we don't know any bits, early out.
2841           if (Known.isUnknown())
2842             break;
2843         }
2844     }
2845     break;
2846   }
2847   case ISD::AND:
2848     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2849     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2850 
2851     Known &= Known2;
2852     break;
2853   case ISD::OR:
2854     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2855     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2856 
2857     Known |= Known2;
2858     break;
2859   case ISD::XOR:
2860     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2861     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2862 
2863     Known ^= Known2;
2864     break;
2865   case ISD::MUL: {
2866     Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2867     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2868 
2869     // If low bits are zero in either operand, output low known-0 bits.
2870     // Also compute a conservative estimate for high known-0 bits.
2871     // More trickiness is possible, but this is sufficient for the
2872     // interesting case of alignment computation.
2873     unsigned TrailZ = Known.countMinTrailingZeros() +
2874                       Known2.countMinTrailingZeros();
2875     unsigned LeadZ =  std::max(Known.countMinLeadingZeros() +
2876                                Known2.countMinLeadingZeros(),
2877                                BitWidth) - BitWidth;
2878 
2879     Known.resetAll();
2880     Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
2881     Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
2882     break;
2883   }
2884   case ISD::UDIV: {
2885     // For the purposes of computing leading zeros we can conservatively
2886     // treat a udiv as a logical right shift by the power of 2 known to
2887     // be less than the denominator.
2888     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2889     unsigned LeadZ = Known2.countMinLeadingZeros();
2890 
2891     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
2892     unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
2893     if (RHSMaxLeadingZeros != BitWidth)
2894       LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
2895 
2896     Known.Zero.setHighBits(LeadZ);
2897     break;
2898   }
2899   case ISD::SELECT:
2900   case ISD::VSELECT:
2901     Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2902     // If we don't know any bits, early out.
2903     if (Known.isUnknown())
2904       break;
2905     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
2906 
2907     // Only known if known in both the LHS and RHS.
2908     Known.One &= Known2.One;
2909     Known.Zero &= Known2.Zero;
2910     break;
2911   case ISD::SELECT_CC:
2912     Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
2913     // If we don't know any bits, early out.
2914     if (Known.isUnknown())
2915       break;
2916     Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
2917 
2918     // Only known if known in both the LHS and RHS.
2919     Known.One &= Known2.One;
2920     Known.Zero &= Known2.Zero;
2921     break;
2922   case ISD::SMULO:
2923   case ISD::UMULO:
2924   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
2925     if (Op.getResNo() != 1)
2926       break;
2927     // The boolean result conforms to getBooleanContents.
2928     // If we know the result of a setcc has the top bits zero, use this info.
2929     // We know that we have an integer-based boolean since these operations
2930     // are only available for integer.
2931     if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
2932             TargetLowering::ZeroOrOneBooleanContent &&
2933         BitWidth > 1)
2934       Known.Zero.setBitsFrom(1);
2935     break;
2936   case ISD::SETCC:
2937   case ISD::STRICT_FSETCC:
2938   case ISD::STRICT_FSETCCS: {
2939     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
2940     // If we know the result of a setcc has the top bits zero, use this info.
2941     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
2942             TargetLowering::ZeroOrOneBooleanContent &&
2943         BitWidth > 1)
2944       Known.Zero.setBitsFrom(1);
2945     break;
2946   }
2947   case ISD::SHL:
2948     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2949 
2950     if (const APInt *ShAmt = getValidShiftAmountConstant(Op, DemandedElts)) {
2951       unsigned Shift = ShAmt->getZExtValue();
2952       Known.Zero <<= Shift;
2953       Known.One <<= Shift;
2954       // Low bits are known zero.
2955       Known.Zero.setLowBits(Shift);
2956       break;
2957     }
2958 
2959     // No matter the shift amount, the trailing zeros will stay zero.
2960     Known.Zero = APInt::getLowBitsSet(BitWidth, Known.countMinTrailingZeros());
2961     Known.One.clearAllBits();
2962 
2963     // Minimum shift low bits are known zero.
2964     if (const APInt *ShMinAmt =
2965             getValidMinimumShiftAmountConstant(Op, DemandedElts))
2966       Known.Zero.setLowBits(ShMinAmt->getZExtValue());
2967     break;
2968   case ISD::SRL:
2969     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2970 
2971     if (const APInt *ShAmt = getValidShiftAmountConstant(Op, DemandedElts)) {
2972       unsigned Shift = ShAmt->getZExtValue();
2973       Known.Zero.lshrInPlace(Shift);
2974       Known.One.lshrInPlace(Shift);
2975       // High bits are known zero.
2976       Known.Zero.setHighBits(Shift);
2977       break;
2978     }
2979 
2980     // No matter the shift amount, the leading zeros will stay zero.
2981     Known.Zero = APInt::getHighBitsSet(BitWidth, Known.countMinLeadingZeros());
2982     Known.One.clearAllBits();
2983 
2984     // Minimum shift high bits are known zero.
2985     if (const APInt *ShMinAmt =
2986             getValidMinimumShiftAmountConstant(Op, DemandedElts))
2987       Known.Zero.setHighBits(ShMinAmt->getZExtValue());
2988     break;
2989   case ISD::SRA:
2990     if (const APInt *ShAmt = getValidShiftAmountConstant(Op, DemandedElts)) {
2991       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
2992       unsigned Shift = ShAmt->getZExtValue();
2993       // Sign extend known zero/one bit (else is unknown).
2994       Known.Zero.ashrInPlace(Shift);
2995       Known.One.ashrInPlace(Shift);
2996     }
2997     break;
2998   case ISD::FSHL:
2999   case ISD::FSHR:
3000     if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
3001       unsigned Amt = C->getAPIntValue().urem(BitWidth);
3002 
3003       // For fshl, 0-shift returns the 1st arg.
3004       // For fshr, 0-shift returns the 2nd arg.
3005       if (Amt == 0) {
3006         Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
3007                                  DemandedElts, Depth + 1);
3008         break;
3009       }
3010 
3011       // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
3012       // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
3013       Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3014       Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3015       if (Opcode == ISD::FSHL) {
3016         Known.One <<= Amt;
3017         Known.Zero <<= Amt;
3018         Known2.One.lshrInPlace(BitWidth - Amt);
3019         Known2.Zero.lshrInPlace(BitWidth - Amt);
3020       } else {
3021         Known.One <<= BitWidth - Amt;
3022         Known.Zero <<= BitWidth - Amt;
3023         Known2.One.lshrInPlace(Amt);
3024         Known2.Zero.lshrInPlace(Amt);
3025       }
3026       Known.One |= Known2.One;
3027       Known.Zero |= Known2.Zero;
3028     }
3029     break;
3030   case ISD::SIGN_EXTEND_INREG: {
3031     EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3032     unsigned EBits = EVT.getScalarSizeInBits();
3033 
3034     // Sign extension.  Compute the demanded bits in the result that are not
3035     // present in the input.
3036     APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
3037 
3038     APInt InSignMask = APInt::getSignMask(EBits);
3039     APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
3040 
3041     // If the sign extended bits are demanded, we know that the sign
3042     // bit is demanded.
3043     InSignMask = InSignMask.zext(BitWidth);
3044     if (NewBits.getBoolValue())
3045       InputDemandedBits |= InSignMask;
3046 
3047     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3048     Known.One &= InputDemandedBits;
3049     Known.Zero &= InputDemandedBits;
3050 
3051     // If the sign bit of the input is known set or clear, then we know the
3052     // top bits of the result.
3053     if (Known.Zero.intersects(InSignMask)) {        // Input sign bit known clear
3054       Known.Zero |= NewBits;
3055       Known.One  &= ~NewBits;
3056     } else if (Known.One.intersects(InSignMask)) {  // Input sign bit known set
3057       Known.One  |= NewBits;
3058       Known.Zero &= ~NewBits;
3059     } else {                              // Input sign bit unknown
3060       Known.Zero &= ~NewBits;
3061       Known.One  &= ~NewBits;
3062     }
3063     break;
3064   }
3065   case ISD::CTTZ:
3066   case ISD::CTTZ_ZERO_UNDEF: {
3067     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3068     // If we have a known 1, its position is our upper bound.
3069     unsigned PossibleTZ = Known2.countMaxTrailingZeros();
3070     unsigned LowBits = Log2_32(PossibleTZ) + 1;
3071     Known.Zero.setBitsFrom(LowBits);
3072     break;
3073   }
3074   case ISD::CTLZ:
3075   case ISD::CTLZ_ZERO_UNDEF: {
3076     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3077     // If we have a known 1, its position is our upper bound.
3078     unsigned PossibleLZ = Known2.countMaxLeadingZeros();
3079     unsigned LowBits = Log2_32(PossibleLZ) + 1;
3080     Known.Zero.setBitsFrom(LowBits);
3081     break;
3082   }
3083   case ISD::CTPOP: {
3084     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3085     // If we know some of the bits are zero, they can't be one.
3086     unsigned PossibleOnes = Known2.countMaxPopulation();
3087     Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
3088     break;
3089   }
3090   case ISD::LOAD: {
3091     LoadSDNode *LD = cast<LoadSDNode>(Op);
3092     const Constant *Cst = TLI->getTargetConstantFromLoad(LD);
3093     if (ISD::isNON_EXTLoad(LD) && Cst) {
3094       // Determine any common known bits from the loaded constant pool value.
3095       Type *CstTy = Cst->getType();
3096       if ((NumElts * BitWidth) == CstTy->getPrimitiveSizeInBits()) {
3097         // If its a vector splat, then we can (quickly) reuse the scalar path.
3098         // NOTE: We assume all elements match and none are UNDEF.
3099         if (CstTy->isVectorTy()) {
3100           if (const Constant *Splat = Cst->getSplatValue()) {
3101             Cst = Splat;
3102             CstTy = Cst->getType();
3103           }
3104         }
3105         // TODO - do we need to handle different bitwidths?
3106         if (CstTy->isVectorTy() && BitWidth == CstTy->getScalarSizeInBits()) {
3107           // Iterate across all vector elements finding common known bits.
3108           Known.One.setAllBits();
3109           Known.Zero.setAllBits();
3110           for (unsigned i = 0; i != NumElts; ++i) {
3111             if (!DemandedElts[i])
3112               continue;
3113             if (Constant *Elt = Cst->getAggregateElement(i)) {
3114               if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
3115                 const APInt &Value = CInt->getValue();
3116                 Known.One &= Value;
3117                 Known.Zero &= ~Value;
3118                 continue;
3119               }
3120               if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
3121                 APInt Value = CFP->getValueAPF().bitcastToAPInt();
3122                 Known.One &= Value;
3123                 Known.Zero &= ~Value;
3124                 continue;
3125               }
3126             }
3127             Known.One.clearAllBits();
3128             Known.Zero.clearAllBits();
3129             break;
3130           }
3131         } else if (BitWidth == CstTy->getPrimitiveSizeInBits()) {
3132           if (auto *CInt = dyn_cast<ConstantInt>(Cst)) {
3133             const APInt &Value = CInt->getValue();
3134             Known.One = Value;
3135             Known.Zero = ~Value;
3136           } else if (auto *CFP = dyn_cast<ConstantFP>(Cst)) {
3137             APInt Value = CFP->getValueAPF().bitcastToAPInt();
3138             Known.One = Value;
3139             Known.Zero = ~Value;
3140           }
3141         }
3142       }
3143     } else if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
3144       // If this is a ZEXTLoad and we are looking at the loaded value.
3145       EVT VT = LD->getMemoryVT();
3146       unsigned MemBits = VT.getScalarSizeInBits();
3147       Known.Zero.setBitsFrom(MemBits);
3148     } else if (const MDNode *Ranges = LD->getRanges()) {
3149       if (LD->getExtensionType() == ISD::NON_EXTLOAD)
3150         computeKnownBitsFromRangeMetadata(*Ranges, Known);
3151     }
3152     break;
3153   }
3154   case ISD::ZERO_EXTEND_VECTOR_INREG: {
3155     EVT InVT = Op.getOperand(0).getValueType();
3156     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3157     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3158     Known = Known.zext(BitWidth);
3159     break;
3160   }
3161   case ISD::ZERO_EXTEND: {
3162     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3163     Known = Known.zext(BitWidth);
3164     break;
3165   }
3166   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3167     EVT InVT = Op.getOperand(0).getValueType();
3168     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3169     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3170     // If the sign bit is known to be zero or one, then sext will extend
3171     // it to the top bits, else it will just zext.
3172     Known = Known.sext(BitWidth);
3173     break;
3174   }
3175   case ISD::SIGN_EXTEND: {
3176     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3177     // If the sign bit is known to be zero or one, then sext will extend
3178     // it to the top bits, else it will just zext.
3179     Known = Known.sext(BitWidth);
3180     break;
3181   }
3182   case ISD::ANY_EXTEND_VECTOR_INREG: {
3183     EVT InVT = Op.getOperand(0).getValueType();
3184     APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
3185     Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
3186     Known = Known.anyext(BitWidth);
3187     break;
3188   }
3189   case ISD::ANY_EXTEND: {
3190     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3191     Known = Known.anyext(BitWidth);
3192     break;
3193   }
3194   case ISD::TRUNCATE: {
3195     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3196     Known = Known.trunc(BitWidth);
3197     break;
3198   }
3199   case ISD::AssertZext: {
3200     EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
3201     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
3202     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3203     Known.Zero |= (~InMask);
3204     Known.One  &= (~Known.Zero);
3205     break;
3206   }
3207   case ISD::AssertAlign: {
3208     unsigned LogOfAlign = Log2(cast<AssertAlignSDNode>(Op)->getAlign());
3209     assert(LogOfAlign != 0);
3210     // If a node is guaranteed to be aligned, set low zero bits accordingly as
3211     // well as clearing one bits.
3212     Known.Zero.setLowBits(LogOfAlign);
3213     Known.One.clearLowBits(LogOfAlign);
3214     break;
3215   }
3216   case ISD::FGETSIGN:
3217     // All bits are zero except the low bit.
3218     Known.Zero.setBitsFrom(1);
3219     break;
3220   case ISD::USUBO:
3221   case ISD::SSUBO:
3222     if (Op.getResNo() == 1) {
3223       // If we know the result of a setcc has the top bits zero, use this info.
3224       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3225               TargetLowering::ZeroOrOneBooleanContent &&
3226           BitWidth > 1)
3227         Known.Zero.setBitsFrom(1);
3228       break;
3229     }
3230     LLVM_FALLTHROUGH;
3231   case ISD::SUB:
3232   case ISD::SUBC: {
3233     assert(Op.getResNo() == 0 &&
3234            "We only compute knownbits for the difference here.");
3235 
3236     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3237     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3238     Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
3239                                         Known, Known2);
3240     break;
3241   }
3242   case ISD::UADDO:
3243   case ISD::SADDO:
3244   case ISD::ADDCARRY:
3245     if (Op.getResNo() == 1) {
3246       // If we know the result of a setcc has the top bits zero, use this info.
3247       if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
3248               TargetLowering::ZeroOrOneBooleanContent &&
3249           BitWidth > 1)
3250         Known.Zero.setBitsFrom(1);
3251       break;
3252     }
3253     LLVM_FALLTHROUGH;
3254   case ISD::ADD:
3255   case ISD::ADDC:
3256   case ISD::ADDE: {
3257     assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
3258 
3259     // With ADDE and ADDCARRY, a carry bit may be added in.
3260     KnownBits Carry(1);
3261     if (Opcode == ISD::ADDE)
3262       // Can't track carry from glue, set carry to unknown.
3263       Carry.resetAll();
3264     else if (Opcode == ISD::ADDCARRY)
3265       // TODO: Compute known bits for the carry operand. Not sure if it is worth
3266       // the trouble (how often will we find a known carry bit). And I haven't
3267       // tested this very much yet, but something like this might work:
3268       //   Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
3269       //   Carry = Carry.zextOrTrunc(1, false);
3270       Carry.resetAll();
3271     else
3272       Carry.setAllZero();
3273 
3274     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3275     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3276     Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
3277     break;
3278   }
3279   case ISD::SREM:
3280     if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
3281       const APInt &RA = Rem->getAPIntValue().abs();
3282       if (RA.isPowerOf2()) {
3283         APInt LowBits = RA - 1;
3284         Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3285 
3286         // The low bits of the first operand are unchanged by the srem.
3287         Known.Zero = Known2.Zero & LowBits;
3288         Known.One = Known2.One & LowBits;
3289 
3290         // If the first operand is non-negative or has all low bits zero, then
3291         // the upper bits are all zero.
3292         if (Known2.isNonNegative() || LowBits.isSubsetOf(Known2.Zero))
3293           Known.Zero |= ~LowBits;
3294 
3295         // If the first operand is negative and not all low bits are zero, then
3296         // the upper bits are all one.
3297         if (Known2.isNegative() && LowBits.intersects(Known2.One))
3298           Known.One |= ~LowBits;
3299         assert((Known.Zero & Known.One) == 0&&"Bits known to be one AND zero?");
3300       }
3301     }
3302     break;
3303   case ISD::UREM: {
3304     if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
3305       const APInt &RA = Rem->getAPIntValue();
3306       if (RA.isPowerOf2()) {
3307         APInt LowBits = (RA - 1);
3308         Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3309 
3310         // The upper bits are all zero, the lower ones are unchanged.
3311         Known.Zero = Known2.Zero | ~LowBits;
3312         Known.One = Known2.One & LowBits;
3313         break;
3314       }
3315     }
3316 
3317     // Since the result is less than or equal to either operand, any leading
3318     // zero bits in either operand must also exist in the result.
3319     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3320     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3321 
3322     uint32_t Leaders =
3323         std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
3324     Known.resetAll();
3325     Known.Zero.setHighBits(Leaders);
3326     break;
3327   }
3328   case ISD::EXTRACT_ELEMENT: {
3329     Known = computeKnownBits(Op.getOperand(0), Depth+1);
3330     const unsigned Index = Op.getConstantOperandVal(1);
3331     const unsigned EltBitWidth = Op.getValueSizeInBits();
3332 
3333     // Remove low part of known bits mask
3334     Known.Zero = Known.Zero.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3335     Known.One = Known.One.getHiBits(Known.getBitWidth() - Index * EltBitWidth);
3336 
3337     // Remove high part of known bit mask
3338     Known = Known.trunc(EltBitWidth);
3339     break;
3340   }
3341   case ISD::EXTRACT_VECTOR_ELT: {
3342     SDValue InVec = Op.getOperand(0);
3343     SDValue EltNo = Op.getOperand(1);
3344     EVT VecVT = InVec.getValueType();
3345     const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
3346     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3347 
3348     // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
3349     // anything about the extended bits.
3350     if (BitWidth > EltBitWidth)
3351       Known = Known.trunc(EltBitWidth);
3352 
3353     // If we know the element index, just demand that vector element, else for
3354     // an unknown element index, ignore DemandedElts and demand them all.
3355     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
3356     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
3357     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
3358       DemandedSrcElts =
3359           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
3360 
3361     Known = computeKnownBits(InVec, DemandedSrcElts, Depth + 1);
3362     if (BitWidth > EltBitWidth)
3363       Known = Known.anyext(BitWidth);
3364     break;
3365   }
3366   case ISD::INSERT_VECTOR_ELT: {
3367     // If we know the element index, split the demand between the
3368     // source vector and the inserted element, otherwise assume we need
3369     // the original demanded vector elements and the value.
3370     SDValue InVec = Op.getOperand(0);
3371     SDValue InVal = Op.getOperand(1);
3372     SDValue EltNo = Op.getOperand(2);
3373     bool DemandedVal = true;
3374     APInt DemandedVecElts = DemandedElts;
3375     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3376     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3377       unsigned EltIdx = CEltNo->getZExtValue();
3378       DemandedVal = !!DemandedElts[EltIdx];
3379       DemandedVecElts.clearBit(EltIdx);
3380     }
3381     Known.One.setAllBits();
3382     Known.Zero.setAllBits();
3383     if (DemandedVal) {
3384       Known2 = computeKnownBits(InVal, Depth + 1);
3385       Known.One &= Known2.One.zextOrTrunc(BitWidth);
3386       Known.Zero &= Known2.Zero.zextOrTrunc(BitWidth);
3387     }
3388     if (!!DemandedVecElts) {
3389       Known2 = computeKnownBits(InVec, DemandedVecElts, Depth + 1);
3390       Known.One &= Known2.One;
3391       Known.Zero &= Known2.Zero;
3392     }
3393     break;
3394   }
3395   case ISD::BITREVERSE: {
3396     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3397     Known.Zero = Known2.Zero.reverseBits();
3398     Known.One = Known2.One.reverseBits();
3399     break;
3400   }
3401   case ISD::BSWAP: {
3402     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3403     Known.Zero = Known2.Zero.byteSwap();
3404     Known.One = Known2.One.byteSwap();
3405     break;
3406   }
3407   case ISD::ABS: {
3408     Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3409 
3410     // If the source's MSB is zero then we know the rest of the bits already.
3411     if (Known2.isNonNegative()) {
3412       Known.Zero = Known2.Zero;
3413       Known.One = Known2.One;
3414       break;
3415     }
3416 
3417     // We only know that the absolute values's MSB will be zero iff there is
3418     // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
3419     Known2.One.clearSignBit();
3420     if (Known2.One.getBoolValue()) {
3421       Known.Zero = APInt::getSignMask(BitWidth);
3422       break;
3423     }
3424     break;
3425   }
3426   case ISD::UMIN: {
3427     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3428     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3429 
3430     // UMIN - we know that the result will have the maximum of the
3431     // known zero leading bits of the inputs.
3432     unsigned LeadZero = Known.countMinLeadingZeros();
3433     LeadZero = std::max(LeadZero, Known2.countMinLeadingZeros());
3434 
3435     Known.Zero &= Known2.Zero;
3436     Known.One &= Known2.One;
3437     Known.Zero.setHighBits(LeadZero);
3438     break;
3439   }
3440   case ISD::UMAX: {
3441     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3442     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3443 
3444     // UMAX - we know that the result will have the maximum of the
3445     // known one leading bits of the inputs.
3446     unsigned LeadOne = Known.countMinLeadingOnes();
3447     LeadOne = std::max(LeadOne, Known2.countMinLeadingOnes());
3448 
3449     Known.Zero &= Known2.Zero;
3450     Known.One &= Known2.One;
3451     Known.One.setHighBits(LeadOne);
3452     break;
3453   }
3454   case ISD::SMIN:
3455   case ISD::SMAX: {
3456     // If we have a clamp pattern, we know that the number of sign bits will be
3457     // the minimum of the clamp min/max range.
3458     bool IsMax = (Opcode == ISD::SMAX);
3459     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3460     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3461       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3462         CstHigh =
3463             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3464     if (CstLow && CstHigh) {
3465       if (!IsMax)
3466         std::swap(CstLow, CstHigh);
3467 
3468       const APInt &ValueLow = CstLow->getAPIntValue();
3469       const APInt &ValueHigh = CstHigh->getAPIntValue();
3470       if (ValueLow.sle(ValueHigh)) {
3471         unsigned LowSignBits = ValueLow.getNumSignBits();
3472         unsigned HighSignBits = ValueHigh.getNumSignBits();
3473         unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
3474         if (ValueLow.isNegative() && ValueHigh.isNegative()) {
3475           Known.One.setHighBits(MinSignBits);
3476           break;
3477         }
3478         if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
3479           Known.Zero.setHighBits(MinSignBits);
3480           break;
3481         }
3482       }
3483     }
3484 
3485     // Fallback - just get the shared known bits of the operands.
3486     Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3487     if (Known.isUnknown()) break; // Early-out
3488     Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3489     Known.Zero &= Known2.Zero;
3490     Known.One &= Known2.One;
3491     break;
3492   }
3493   case ISD::FrameIndex:
3494   case ISD::TargetFrameIndex:
3495     TLI->computeKnownBitsForFrameIndex(cast<FrameIndexSDNode>(Op)->getIndex(),
3496                                        Known, getMachineFunction());
3497     break;
3498 
3499   default:
3500     if (Opcode < ISD::BUILTIN_OP_END)
3501       break;
3502     LLVM_FALLTHROUGH;
3503   case ISD::INTRINSIC_WO_CHAIN:
3504   case ISD::INTRINSIC_W_CHAIN:
3505   case ISD::INTRINSIC_VOID:
3506     // Allow the target to implement this method for its nodes.
3507     TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
3508     break;
3509   }
3510 
3511   assert(!Known.hasConflict() && "Bits known to be one AND zero?");
3512   return Known;
3513 }
3514 
computeOverflowKind(SDValue N0,SDValue N1) const3515 SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
3516                                                              SDValue N1) const {
3517   // X + 0 never overflow
3518   if (isNullConstant(N1))
3519     return OFK_Never;
3520 
3521   KnownBits N1Known = computeKnownBits(N1);
3522   if (N1Known.Zero.getBoolValue()) {
3523     KnownBits N0Known = computeKnownBits(N0);
3524 
3525     bool overflow;
3526     (void)N0Known.getMaxValue().uadd_ov(N1Known.getMaxValue(), overflow);
3527     if (!overflow)
3528       return OFK_Never;
3529   }
3530 
3531   // mulhi + 1 never overflow
3532   if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
3533       (N1Known.getMaxValue() & 0x01) == N1Known.getMaxValue())
3534     return OFK_Never;
3535 
3536   if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
3537     KnownBits N0Known = computeKnownBits(N0);
3538 
3539     if ((N0Known.getMaxValue() & 0x01) == N0Known.getMaxValue())
3540       return OFK_Never;
3541   }
3542 
3543   return OFK_Sometime;
3544 }
3545 
isKnownToBeAPowerOfTwo(SDValue Val) const3546 bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
3547   EVT OpVT = Val.getValueType();
3548   unsigned BitWidth = OpVT.getScalarSizeInBits();
3549 
3550   // Is the constant a known power of 2?
3551   if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
3552     return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3553 
3554   // A left-shift of a constant one will have exactly one bit set because
3555   // shifting the bit off the end is undefined.
3556   if (Val.getOpcode() == ISD::SHL) {
3557     auto *C = isConstOrConstSplat(Val.getOperand(0));
3558     if (C && C->getAPIntValue() == 1)
3559       return true;
3560   }
3561 
3562   // Similarly, a logical right-shift of a constant sign-bit will have exactly
3563   // one bit set.
3564   if (Val.getOpcode() == ISD::SRL) {
3565     auto *C = isConstOrConstSplat(Val.getOperand(0));
3566     if (C && C->getAPIntValue().isSignMask())
3567       return true;
3568   }
3569 
3570   // Are all operands of a build vector constant powers of two?
3571   if (Val.getOpcode() == ISD::BUILD_VECTOR)
3572     if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
3573           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
3574             return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
3575           return false;
3576         }))
3577       return true;
3578 
3579   // More could be done here, though the above checks are enough
3580   // to handle some common cases.
3581 
3582   // Fall back to computeKnownBits to catch other known cases.
3583   KnownBits Known = computeKnownBits(Val);
3584   return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
3585 }
3586 
ComputeNumSignBits(SDValue Op,unsigned Depth) const3587 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
3588   EVT VT = Op.getValueType();
3589 
3590   // TODO: Assume we don't know anything for now.
3591   if (VT.isScalableVector())
3592     return 1;
3593 
3594   APInt DemandedElts = VT.isVector()
3595                            ? APInt::getAllOnesValue(VT.getVectorNumElements())
3596                            : APInt(1, 1);
3597   return ComputeNumSignBits(Op, DemandedElts, Depth);
3598 }
3599 
ComputeNumSignBits(SDValue Op,const APInt & DemandedElts,unsigned Depth) const3600 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
3601                                           unsigned Depth) const {
3602   EVT VT = Op.getValueType();
3603   assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
3604   unsigned VTBits = VT.getScalarSizeInBits();
3605   unsigned NumElts = DemandedElts.getBitWidth();
3606   unsigned Tmp, Tmp2;
3607   unsigned FirstAnswer = 1;
3608 
3609   if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
3610     const APInt &Val = C->getAPIntValue();
3611     return Val.getNumSignBits();
3612   }
3613 
3614   if (Depth >= MaxRecursionDepth)
3615     return 1;  // Limit search depth.
3616 
3617   if (!DemandedElts || VT.isScalableVector())
3618     return 1;  // No demanded elts, better to assume we don't know anything.
3619 
3620   unsigned Opcode = Op.getOpcode();
3621   switch (Opcode) {
3622   default: break;
3623   case ISD::AssertSext:
3624     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3625     return VTBits-Tmp+1;
3626   case ISD::AssertZext:
3627     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
3628     return VTBits-Tmp;
3629 
3630   case ISD::BUILD_VECTOR:
3631     Tmp = VTBits;
3632     for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
3633       if (!DemandedElts[i])
3634         continue;
3635 
3636       SDValue SrcOp = Op.getOperand(i);
3637       Tmp2 = ComputeNumSignBits(SrcOp, Depth + 1);
3638 
3639       // BUILD_VECTOR can implicitly truncate sources, we must handle this.
3640       if (SrcOp.getValueSizeInBits() != VTBits) {
3641         assert(SrcOp.getValueSizeInBits() > VTBits &&
3642                "Expected BUILD_VECTOR implicit truncation");
3643         unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
3644         Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
3645       }
3646       Tmp = std::min(Tmp, Tmp2);
3647     }
3648     return Tmp;
3649 
3650   case ISD::VECTOR_SHUFFLE: {
3651     // Collect the minimum number of sign bits that are shared by every vector
3652     // element referenced by the shuffle.
3653     APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
3654     const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
3655     assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
3656     for (unsigned i = 0; i != NumElts; ++i) {
3657       int M = SVN->getMaskElt(i);
3658       if (!DemandedElts[i])
3659         continue;
3660       // For UNDEF elements, we don't know anything about the common state of
3661       // the shuffle result.
3662       if (M < 0)
3663         return 1;
3664       if ((unsigned)M < NumElts)
3665         DemandedLHS.setBit((unsigned)M % NumElts);
3666       else
3667         DemandedRHS.setBit((unsigned)M % NumElts);
3668     }
3669     Tmp = std::numeric_limits<unsigned>::max();
3670     if (!!DemandedLHS)
3671       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
3672     if (!!DemandedRHS) {
3673       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
3674       Tmp = std::min(Tmp, Tmp2);
3675     }
3676     // If we don't know anything, early out and try computeKnownBits fall-back.
3677     if (Tmp == 1)
3678       break;
3679     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3680     return Tmp;
3681   }
3682 
3683   case ISD::BITCAST: {
3684     SDValue N0 = Op.getOperand(0);
3685     EVT SrcVT = N0.getValueType();
3686     unsigned SrcBits = SrcVT.getScalarSizeInBits();
3687 
3688     // Ignore bitcasts from unsupported types..
3689     if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
3690       break;
3691 
3692     // Fast handling of 'identity' bitcasts.
3693     if (VTBits == SrcBits)
3694       return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
3695 
3696     bool IsLE = getDataLayout().isLittleEndian();
3697 
3698     // Bitcast 'large element' scalar/vector to 'small element' vector.
3699     if ((SrcBits % VTBits) == 0) {
3700       assert(VT.isVector() && "Expected bitcast to vector");
3701 
3702       unsigned Scale = SrcBits / VTBits;
3703       APInt SrcDemandedElts(NumElts / Scale, 0);
3704       for (unsigned i = 0; i != NumElts; ++i)
3705         if (DemandedElts[i])
3706           SrcDemandedElts.setBit(i / Scale);
3707 
3708       // Fast case - sign splat can be simply split across the small elements.
3709       Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
3710       if (Tmp == SrcBits)
3711         return VTBits;
3712 
3713       // Slow case - determine how far the sign extends into each sub-element.
3714       Tmp2 = VTBits;
3715       for (unsigned i = 0; i != NumElts; ++i)
3716         if (DemandedElts[i]) {
3717           unsigned SubOffset = i % Scale;
3718           SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
3719           SubOffset = SubOffset * VTBits;
3720           if (Tmp <= SubOffset)
3721             return 1;
3722           Tmp2 = std::min(Tmp2, Tmp - SubOffset);
3723         }
3724       return Tmp2;
3725     }
3726     break;
3727   }
3728 
3729   case ISD::SIGN_EXTEND:
3730     Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
3731     return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
3732   case ISD::SIGN_EXTEND_INREG:
3733     // Max of the input and what this extends.
3734     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
3735     Tmp = VTBits-Tmp+1;
3736     Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3737     return std::max(Tmp, Tmp2);
3738   case ISD::SIGN_EXTEND_VECTOR_INREG: {
3739     SDValue Src = Op.getOperand(0);
3740     EVT SrcVT = Src.getValueType();
3741     APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
3742     Tmp = VTBits - SrcVT.getScalarSizeInBits();
3743     return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
3744   }
3745   case ISD::SRA:
3746     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3747     // SRA X, C -> adds C sign bits.
3748     if (const APInt *ShAmt =
3749             getValidMinimumShiftAmountConstant(Op, DemandedElts))
3750       Tmp = std::min<uint64_t>(Tmp + ShAmt->getZExtValue(), VTBits);
3751     return Tmp;
3752   case ISD::SHL:
3753     if (const APInt *ShAmt =
3754             getValidMaximumShiftAmountConstant(Op, DemandedElts)) {
3755       // shl destroys sign bits, ensure it doesn't shift out all sign bits.
3756       Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3757       if (ShAmt->ult(Tmp))
3758         return Tmp - ShAmt->getZExtValue();
3759     }
3760     break;
3761   case ISD::AND:
3762   case ISD::OR:
3763   case ISD::XOR:    // NOT is handled here.
3764     // Logical binary ops preserve the number of sign bits at the worst.
3765     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
3766     if (Tmp != 1) {
3767       Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3768       FirstAnswer = std::min(Tmp, Tmp2);
3769       // We computed what we know about the sign bits as our first
3770       // answer. Now proceed to the generic code that uses
3771       // computeKnownBits, and pick whichever answer is better.
3772     }
3773     break;
3774 
3775   case ISD::SELECT:
3776   case ISD::VSELECT:
3777     Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
3778     if (Tmp == 1) return 1;  // Early out.
3779     Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3780     return std::min(Tmp, Tmp2);
3781   case ISD::SELECT_CC:
3782     Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
3783     if (Tmp == 1) return 1;  // Early out.
3784     Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
3785     return std::min(Tmp, Tmp2);
3786 
3787   case ISD::SMIN:
3788   case ISD::SMAX: {
3789     // If we have a clamp pattern, we know that the number of sign bits will be
3790     // the minimum of the clamp min/max range.
3791     bool IsMax = (Opcode == ISD::SMAX);
3792     ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
3793     if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
3794       if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
3795         CstHigh =
3796             isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
3797     if (CstLow && CstHigh) {
3798       if (!IsMax)
3799         std::swap(CstLow, CstHigh);
3800       if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
3801         Tmp = CstLow->getAPIntValue().getNumSignBits();
3802         Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
3803         return std::min(Tmp, Tmp2);
3804       }
3805     }
3806 
3807     // Fallback - just get the minimum number of sign bits of the operands.
3808     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3809     if (Tmp == 1)
3810       return 1;  // Early out.
3811     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3812     return std::min(Tmp, Tmp2);
3813   }
3814   case ISD::UMIN:
3815   case ISD::UMAX:
3816     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3817     if (Tmp == 1)
3818       return 1;  // Early out.
3819     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3820     return std::min(Tmp, Tmp2);
3821   case ISD::SADDO:
3822   case ISD::UADDO:
3823   case ISD::SSUBO:
3824   case ISD::USUBO:
3825   case ISD::SMULO:
3826   case ISD::UMULO:
3827     if (Op.getResNo() != 1)
3828       break;
3829     // The boolean result conforms to getBooleanContents.  Fall through.
3830     // If setcc returns 0/-1, all bits are sign bits.
3831     // We know that we have an integer-based boolean since these operations
3832     // are only available for integer.
3833     if (TLI->getBooleanContents(VT.isVector(), false) ==
3834         TargetLowering::ZeroOrNegativeOneBooleanContent)
3835       return VTBits;
3836     break;
3837   case ISD::SETCC:
3838   case ISD::STRICT_FSETCC:
3839   case ISD::STRICT_FSETCCS: {
3840     unsigned OpNo = Op->isStrictFPOpcode() ? 1 : 0;
3841     // If setcc returns 0/-1, all bits are sign bits.
3842     if (TLI->getBooleanContents(Op.getOperand(OpNo).getValueType()) ==
3843         TargetLowering::ZeroOrNegativeOneBooleanContent)
3844       return VTBits;
3845     break;
3846   }
3847   case ISD::ROTL:
3848   case ISD::ROTR:
3849     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3850 
3851     // If we're rotating an 0/-1 value, then it stays an 0/-1 value.
3852     if (Tmp == VTBits)
3853       return VTBits;
3854 
3855     if (ConstantSDNode *C =
3856             isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
3857       unsigned RotAmt = C->getAPIntValue().urem(VTBits);
3858 
3859       // Handle rotate right by N like a rotate left by 32-N.
3860       if (Opcode == ISD::ROTR)
3861         RotAmt = (VTBits - RotAmt) % VTBits;
3862 
3863       // If we aren't rotating out all of the known-in sign bits, return the
3864       // number that are left.  This handles rotl(sext(x), 1) for example.
3865       if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
3866     }
3867     break;
3868   case ISD::ADD:
3869   case ISD::ADDC:
3870     // Add can have at most one carry bit.  Thus we know that the output
3871     // is, at worst, one more bit than the inputs.
3872     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3873     if (Tmp == 1) return 1; // Early out.
3874 
3875     // Special case decrementing a value (ADD X, -1):
3876     if (ConstantSDNode *CRHS =
3877             isConstOrConstSplat(Op.getOperand(1), DemandedElts))
3878       if (CRHS->isAllOnesValue()) {
3879         KnownBits Known =
3880             computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
3881 
3882         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3883         // sign bits set.
3884         if ((Known.Zero | 1).isAllOnesValue())
3885           return VTBits;
3886 
3887         // If we are subtracting one from a positive number, there is no carry
3888         // out of the result.
3889         if (Known.isNonNegative())
3890           return Tmp;
3891       }
3892 
3893     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3894     if (Tmp2 == 1) return 1; // Early out.
3895     return std::min(Tmp, Tmp2) - 1;
3896   case ISD::SUB:
3897     Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth + 1);
3898     if (Tmp2 == 1) return 1; // Early out.
3899 
3900     // Handle NEG.
3901     if (ConstantSDNode *CLHS =
3902             isConstOrConstSplat(Op.getOperand(0), DemandedElts))
3903       if (CLHS->isNullValue()) {
3904         KnownBits Known =
3905             computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
3906         // If the input is known to be 0 or 1, the output is 0/-1, which is all
3907         // sign bits set.
3908         if ((Known.Zero | 1).isAllOnesValue())
3909           return VTBits;
3910 
3911         // If the input is known to be positive (the sign bit is known clear),
3912         // the output of the NEG has the same number of sign bits as the input.
3913         if (Known.isNonNegative())
3914           return Tmp2;
3915 
3916         // Otherwise, we treat this like a SUB.
3917       }
3918 
3919     // Sub can have at most one carry bit.  Thus we know that the output
3920     // is, at worst, one more bit than the inputs.
3921     Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
3922     if (Tmp == 1) return 1; // Early out.
3923     return std::min(Tmp, Tmp2) - 1;
3924   case ISD::MUL: {
3925     // The output of the Mul can be at most twice the valid bits in the inputs.
3926     unsigned SignBitsOp0 = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3927     if (SignBitsOp0 == 1)
3928       break;
3929     unsigned SignBitsOp1 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
3930     if (SignBitsOp1 == 1)
3931       break;
3932     unsigned OutValidBits =
3933         (VTBits - SignBitsOp0 + 1) + (VTBits - SignBitsOp1 + 1);
3934     return OutValidBits > VTBits ? 1 : VTBits - OutValidBits + 1;
3935   }
3936   case ISD::TRUNCATE: {
3937     // Check if the sign bits of source go down as far as the truncated value.
3938     unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
3939     unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
3940     if (NumSrcSignBits > (NumSrcBits - VTBits))
3941       return NumSrcSignBits - (NumSrcBits - VTBits);
3942     break;
3943   }
3944   case ISD::EXTRACT_ELEMENT: {
3945     const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
3946     const int BitWidth = Op.getValueSizeInBits();
3947     const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
3948 
3949     // Get reverse index (starting from 1), Op1 value indexes elements from
3950     // little end. Sign starts at big end.
3951     const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
3952 
3953     // If the sign portion ends in our element the subtraction gives correct
3954     // result. Otherwise it gives either negative or > bitwidth result
3955     return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
3956   }
3957   case ISD::INSERT_VECTOR_ELT: {
3958     // If we know the element index, split the demand between the
3959     // source vector and the inserted element, otherwise assume we need
3960     // the original demanded vector elements and the value.
3961     SDValue InVec = Op.getOperand(0);
3962     SDValue InVal = Op.getOperand(1);
3963     SDValue EltNo = Op.getOperand(2);
3964     bool DemandedVal = true;
3965     APInt DemandedVecElts = DemandedElts;
3966     auto *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
3967     if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
3968       unsigned EltIdx = CEltNo->getZExtValue();
3969       DemandedVal = !!DemandedElts[EltIdx];
3970       DemandedVecElts.clearBit(EltIdx);
3971     }
3972     Tmp = std::numeric_limits<unsigned>::max();
3973     if (DemandedVal) {
3974       // TODO - handle implicit truncation of inserted elements.
3975       if (InVal.getScalarValueSizeInBits() != VTBits)
3976         break;
3977       Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
3978       Tmp = std::min(Tmp, Tmp2);
3979     }
3980     if (!!DemandedVecElts) {
3981       Tmp2 = ComputeNumSignBits(InVec, DemandedVecElts, Depth + 1);
3982       Tmp = std::min(Tmp, Tmp2);
3983     }
3984     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
3985     return Tmp;
3986   }
3987   case ISD::EXTRACT_VECTOR_ELT: {
3988     SDValue InVec = Op.getOperand(0);
3989     SDValue EltNo = Op.getOperand(1);
3990     EVT VecVT = InVec.getValueType();
3991     const unsigned BitWidth = Op.getValueSizeInBits();
3992     const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
3993     const unsigned NumSrcElts = VecVT.getVectorNumElements();
3994 
3995     // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
3996     // anything about sign bits. But if the sizes match we can derive knowledge
3997     // about sign bits from the vector operand.
3998     if (BitWidth != EltBitWidth)
3999       break;
4000 
4001     // If we know the element index, just demand that vector element, else for
4002     // an unknown element index, ignore DemandedElts and demand them all.
4003     APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
4004     auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
4005     if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
4006       DemandedSrcElts =
4007           APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
4008 
4009     return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
4010   }
4011   case ISD::EXTRACT_SUBVECTOR: {
4012     // Offset the demanded elts by the subvector index.
4013     SDValue Src = Op.getOperand(0);
4014     // Bail until we can represent demanded elements for scalable vectors.
4015     if (Src.getValueType().isScalableVector())
4016       break;
4017     uint64_t Idx = Op.getConstantOperandVal(1);
4018     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
4019     APInt DemandedSrcElts = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
4020     return ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4021   }
4022   case ISD::CONCAT_VECTORS: {
4023     // Determine the minimum number of sign bits across all demanded
4024     // elts of the input vectors. Early out if the result is already 1.
4025     Tmp = std::numeric_limits<unsigned>::max();
4026     EVT SubVectorVT = Op.getOperand(0).getValueType();
4027     unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
4028     unsigned NumSubVectors = Op.getNumOperands();
4029     for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
4030       APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
4031       DemandedSub = DemandedSub.trunc(NumSubVectorElts);
4032       if (!DemandedSub)
4033         continue;
4034       Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
4035       Tmp = std::min(Tmp, Tmp2);
4036     }
4037     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4038     return Tmp;
4039   }
4040   case ISD::INSERT_SUBVECTOR: {
4041     // Demand any elements from the subvector and the remainder from the src its
4042     // inserted into.
4043     SDValue Src = Op.getOperand(0);
4044     SDValue Sub = Op.getOperand(1);
4045     uint64_t Idx = Op.getConstantOperandVal(2);
4046     unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
4047     APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
4048     APInt DemandedSrcElts = DemandedElts;
4049     DemandedSrcElts.insertBits(APInt::getNullValue(NumSubElts), Idx);
4050 
4051     Tmp = std::numeric_limits<unsigned>::max();
4052     if (!!DemandedSubElts) {
4053       Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
4054       if (Tmp == 1)
4055         return 1; // early-out
4056     }
4057     if (!!DemandedSrcElts) {
4058       Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
4059       Tmp = std::min(Tmp, Tmp2);
4060     }
4061     assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
4062     return Tmp;
4063   }
4064   }
4065 
4066   // If we are looking at the loaded value of the SDNode.
4067   if (Op.getResNo() == 0) {
4068     // Handle LOADX separately here. EXTLOAD case will fallthrough.
4069     if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
4070       unsigned ExtType = LD->getExtensionType();
4071       switch (ExtType) {
4072       default: break;
4073       case ISD::SEXTLOAD: // e.g. i16->i32 = '17' bits known.
4074         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4075         return VTBits - Tmp + 1;
4076       case ISD::ZEXTLOAD: // e.g. i16->i32 = '16' bits known.
4077         Tmp = LD->getMemoryVT().getScalarSizeInBits();
4078         return VTBits - Tmp;
4079       case ISD::NON_EXTLOAD:
4080         if (const Constant *Cst = TLI->getTargetConstantFromLoad(LD)) {
4081           // We only need to handle vectors - computeKnownBits should handle
4082           // scalar cases.
4083           Type *CstTy = Cst->getType();
4084           if (CstTy->isVectorTy() &&
4085               (NumElts * VTBits) == CstTy->getPrimitiveSizeInBits()) {
4086             Tmp = VTBits;
4087             for (unsigned i = 0; i != NumElts; ++i) {
4088               if (!DemandedElts[i])
4089                 continue;
4090               if (Constant *Elt = Cst->getAggregateElement(i)) {
4091                 if (auto *CInt = dyn_cast<ConstantInt>(Elt)) {
4092                   const APInt &Value = CInt->getValue();
4093                   Tmp = std::min(Tmp, Value.getNumSignBits());
4094                   continue;
4095                 }
4096                 if (auto *CFP = dyn_cast<ConstantFP>(Elt)) {
4097                   APInt Value = CFP->getValueAPF().bitcastToAPInt();
4098                   Tmp = std::min(Tmp, Value.getNumSignBits());
4099                   continue;
4100                 }
4101               }
4102               // Unknown type. Conservatively assume no bits match sign bit.
4103               return 1;
4104             }
4105             return Tmp;
4106           }
4107         }
4108         break;
4109       }
4110     }
4111   }
4112 
4113   // Allow the target to implement this method for its nodes.
4114   if (Opcode >= ISD::BUILTIN_OP_END ||
4115       Opcode == ISD::INTRINSIC_WO_CHAIN ||
4116       Opcode == ISD::INTRINSIC_W_CHAIN ||
4117       Opcode == ISD::INTRINSIC_VOID) {
4118     unsigned NumBits =
4119         TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
4120     if (NumBits > 1)
4121       FirstAnswer = std::max(FirstAnswer, NumBits);
4122   }
4123 
4124   // Finally, if we can prove that the top bits of the result are 0's or 1's,
4125   // use this information.
4126   KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
4127 
4128   APInt Mask;
4129   if (Known.isNonNegative()) {        // sign bit is 0
4130     Mask = Known.Zero;
4131   } else if (Known.isNegative()) {  // sign bit is 1;
4132     Mask = Known.One;
4133   } else {
4134     // Nothing known.
4135     return FirstAnswer;
4136   }
4137 
4138   // Okay, we know that the sign bit in Mask is set.  Use CLO to determine
4139   // the number of identical bits in the top of the input value.
4140   Mask <<= Mask.getBitWidth()-VTBits;
4141   return std::max(FirstAnswer, Mask.countLeadingOnes());
4142 }
4143 
isBaseWithConstantOffset(SDValue Op) const4144 bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
4145   switch (Op.getOpcode()) {
4146   case ISD::ADD:
4147   case ISD::OR:
4148   case ISD::PTRADD:
4149     if (isa<ConstantSDNode>(Op.getOperand(1)))
4150       break;
4151     LLVM_FALLTHROUGH;
4152   default:
4153     return false;
4154   }
4155 
4156   if (Op.getOpcode() == ISD::OR &&
4157       !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
4158     return false;
4159 
4160   return true;
4161 }
4162 
isKnownNeverNaN(SDValue Op,bool SNaN,unsigned Depth) const4163 bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
4164   // If we're told that NaNs won't happen, assume they won't.
4165   if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
4166     return true;
4167 
4168   if (Depth >= MaxRecursionDepth)
4169     return false; // Limit search depth.
4170 
4171   // TODO: Handle vectors.
4172   // If the value is a constant, we can obviously see if it is a NaN or not.
4173   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
4174     return !C->getValueAPF().isNaN() ||
4175            (SNaN && !C->getValueAPF().isSignaling());
4176   }
4177 
4178   unsigned Opcode = Op.getOpcode();
4179   switch (Opcode) {
4180   case ISD::FADD:
4181   case ISD::FSUB:
4182   case ISD::FMUL:
4183   case ISD::FDIV:
4184   case ISD::FREM:
4185   case ISD::FSIN:
4186   case ISD::FCOS: {
4187     if (SNaN)
4188       return true;
4189     // TODO: Need isKnownNeverInfinity
4190     return false;
4191   }
4192   case ISD::FCANONICALIZE:
4193   case ISD::FEXP:
4194   case ISD::FEXP2:
4195   case ISD::FTRUNC:
4196   case ISD::FFLOOR:
4197   case ISD::FCEIL:
4198   case ISD::FROUND:
4199   case ISD::FROUNDEVEN:
4200   case ISD::FRINT:
4201   case ISD::FNEARBYINT: {
4202     if (SNaN)
4203       return true;
4204     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4205   }
4206   case ISD::FABS:
4207   case ISD::FNEG:
4208   case ISD::FCOPYSIGN: {
4209     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4210   }
4211   case ISD::SELECT:
4212     return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4213            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4214   case ISD::FP_EXTEND:
4215   case ISD::FP_ROUND: {
4216     if (SNaN)
4217       return true;
4218     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4219   }
4220   case ISD::SINT_TO_FP:
4221   case ISD::UINT_TO_FP:
4222     return true;
4223   case ISD::FMA:
4224   case ISD::FMAD: {
4225     if (SNaN)
4226       return true;
4227     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4228            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
4229            isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
4230   }
4231   case ISD::FSQRT: // Need is known positive
4232   case ISD::FLOG:
4233   case ISD::FLOG2:
4234   case ISD::FLOG10:
4235   case ISD::FPOWI:
4236   case ISD::FPOW: {
4237     if (SNaN)
4238       return true;
4239     // TODO: Refine on operand
4240     return false;
4241   }
4242   case ISD::FMINNUM:
4243   case ISD::FMAXNUM: {
4244     // Only one needs to be known not-nan, since it will be returned if the
4245     // other ends up being one.
4246     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
4247            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4248   }
4249   case ISD::FMINNUM_IEEE:
4250   case ISD::FMAXNUM_IEEE: {
4251     if (SNaN)
4252       return true;
4253     // This can return a NaN if either operand is an sNaN, or if both operands
4254     // are NaN.
4255     return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
4256             isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
4257            (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
4258             isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
4259   }
4260   case ISD::FMINIMUM:
4261   case ISD::FMAXIMUM: {
4262     // TODO: Does this quiet or return the origina NaN as-is?
4263     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
4264            isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
4265   }
4266   case ISD::EXTRACT_VECTOR_ELT: {
4267     return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
4268   }
4269   default:
4270     if (Opcode >= ISD::BUILTIN_OP_END ||
4271         Opcode == ISD::INTRINSIC_WO_CHAIN ||
4272         Opcode == ISD::INTRINSIC_W_CHAIN ||
4273         Opcode == ISD::INTRINSIC_VOID) {
4274       return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
4275     }
4276 
4277     return false;
4278   }
4279 }
4280 
isKnownNeverZeroFloat(SDValue Op) const4281 bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
4282   assert(Op.getValueType().isFloatingPoint() &&
4283          "Floating point type expected");
4284 
4285   // If the value is a constant, we can obviously see if it is a zero or not.
4286   // TODO: Add BuildVector support.
4287   if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
4288     return !C->isZero();
4289   return false;
4290 }
4291 
isKnownNeverZero(SDValue Op) const4292 bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
4293   assert(!Op.getValueType().isFloatingPoint() &&
4294          "Floating point types unsupported - use isKnownNeverZeroFloat");
4295 
4296   // If the value is a constant, we can obviously see if it is a zero or not.
4297   if (ISD::matchUnaryPredicate(
4298           Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
4299     return true;
4300 
4301   // TODO: Recognize more cases here.
4302   switch (Op.getOpcode()) {
4303   default: break;
4304   case ISD::OR:
4305     if (isKnownNeverZero(Op.getOperand(1)) ||
4306         isKnownNeverZero(Op.getOperand(0)))
4307       return true;
4308     break;
4309   }
4310 
4311   return false;
4312 }
4313 
isEqualTo(SDValue A,SDValue B) const4314 bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
4315   // Check the obvious case.
4316   if (A == B) return true;
4317 
4318   // For for negative and positive zero.
4319   if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
4320     if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
4321       if (CA->isZero() && CB->isZero()) return true;
4322 
4323   // Otherwise they may not be equal.
4324   return false;
4325 }
4326 
4327 // FIXME: unify with llvm::haveNoCommonBitsSet.
4328 // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
haveNoCommonBitsSet(SDValue A,SDValue B) const4329 bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
4330   assert(A.getValueType() == B.getValueType() &&
4331          "Values must have the same type");
4332   return (computeKnownBits(A).Zero | computeKnownBits(B).Zero).isAllOnesValue();
4333 }
4334 
FoldBUILD_VECTOR(const SDLoc & DL,EVT VT,ArrayRef<SDValue> Ops,SelectionDAG & DAG)4335 static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
4336                                 ArrayRef<SDValue> Ops,
4337                                 SelectionDAG &DAG) {
4338   int NumOps = Ops.size();
4339   assert(NumOps != 0 && "Can't build an empty vector!");
4340   assert(!VT.isScalableVector() &&
4341          "BUILD_VECTOR cannot be used with scalable types");
4342   assert(VT.getVectorNumElements() == (unsigned)NumOps &&
4343          "Incorrect element count in BUILD_VECTOR!");
4344 
4345   // BUILD_VECTOR of UNDEFs is UNDEF.
4346   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4347     return DAG.getUNDEF(VT);
4348 
4349   // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
4350   SDValue IdentitySrc;
4351   bool IsIdentity = true;
4352   for (int i = 0; i != NumOps; ++i) {
4353     if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4354         Ops[i].getOperand(0).getValueType() != VT ||
4355         (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
4356         !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
4357         cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
4358       IsIdentity = false;
4359       break;
4360     }
4361     IdentitySrc = Ops[i].getOperand(0);
4362   }
4363   if (IsIdentity)
4364     return IdentitySrc;
4365 
4366   return SDValue();
4367 }
4368 
4369 /// Try to simplify vector concatenation to an input value, undef, or build
4370 /// vector.
foldCONCAT_VECTORS(const SDLoc & DL,EVT VT,ArrayRef<SDValue> Ops,SelectionDAG & DAG)4371 static SDValue foldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
4372                                   ArrayRef<SDValue> Ops,
4373                                   SelectionDAG &DAG) {
4374   assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
4375   assert(llvm::all_of(Ops,
4376                       [Ops](SDValue Op) {
4377                         return Ops[0].getValueType() == Op.getValueType();
4378                       }) &&
4379          "Concatenation of vectors with inconsistent value types!");
4380   assert((Ops[0].getValueType().getVectorElementCount() * Ops.size()) ==
4381              VT.getVectorElementCount() &&
4382          "Incorrect element count in vector concatenation!");
4383 
4384   if (Ops.size() == 1)
4385     return Ops[0];
4386 
4387   // Concat of UNDEFs is UNDEF.
4388   if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
4389     return DAG.getUNDEF(VT);
4390 
4391   // Scan the operands and look for extract operations from a single source
4392   // that correspond to insertion at the same location via this concatenation:
4393   // concat (extract X, 0*subvec_elts), (extract X, 1*subvec_elts), ...
4394   SDValue IdentitySrc;
4395   bool IsIdentity = true;
4396   for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
4397     SDValue Op = Ops[i];
4398     unsigned IdentityIndex = i * Op.getValueType().getVectorMinNumElements();
4399     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
4400         Op.getOperand(0).getValueType() != VT ||
4401         (IdentitySrc && Op.getOperand(0) != IdentitySrc) ||
4402         Op.getConstantOperandVal(1) != IdentityIndex) {
4403       IsIdentity = false;
4404       break;
4405     }
4406     assert((!IdentitySrc || IdentitySrc == Op.getOperand(0)) &&
4407            "Unexpected identity source vector for concat of extracts");
4408     IdentitySrc = Op.getOperand(0);
4409   }
4410   if (IsIdentity) {
4411     assert(IdentitySrc && "Failed to set source vector of extracts");
4412     return IdentitySrc;
4413   }
4414 
4415   // The code below this point is only designed to work for fixed width
4416   // vectors, so we bail out for now.
4417   if (VT.isScalableVector())
4418     return SDValue();
4419 
4420   // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
4421   // simplified to one big BUILD_VECTOR.
4422   // FIXME: Add support for SCALAR_TO_VECTOR as well.
4423   EVT SVT = VT.getScalarType();
4424   SmallVector<SDValue, 16> Elts;
4425   for (SDValue Op : Ops) {
4426     EVT OpVT = Op.getValueType();
4427     if (Op.isUndef())
4428       Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
4429     else if (Op.getOpcode() == ISD::BUILD_VECTOR)
4430       Elts.append(Op->op_begin(), Op->op_end());
4431     else
4432       return SDValue();
4433   }
4434 
4435   // BUILD_VECTOR requires all inputs to be of the same type, find the
4436   // maximum type and extend them all.
4437   for (SDValue Op : Elts)
4438     SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
4439 
4440   if (SVT.bitsGT(VT.getScalarType()))
4441     for (SDValue &Op : Elts)
4442       Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
4443                ? DAG.getZExtOrTrunc(Op, DL, SVT)
4444                : DAG.getSExtOrTrunc(Op, DL, SVT);
4445 
4446   SDValue V = DAG.getBuildVector(VT, DL, Elts);
4447   NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
4448   return V;
4449 }
4450 
4451 /// Gets or creates the specified node.
getNode(unsigned Opcode,const SDLoc & DL,EVT VT)4452 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
4453   FoldingSetNodeID ID;
4454   AddNodeIDNode(ID, Opcode, getVTList(VT), None);
4455   void *IP = nullptr;
4456   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
4457     return SDValue(E, 0);
4458 
4459   auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
4460                               getVTList(VT));
4461   CSEMap.InsertNode(N, IP);
4462 
4463   InsertNode(N);
4464   SDValue V = SDValue(N, 0);
4465   NewSDValueDbgMsg(V, "Creating new node: ", this);
4466   return V;
4467 }
4468 
getNode(unsigned Opcode,const SDLoc & DL,EVT VT,SDValue Operand,const SDNodeFlags Flags)4469 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
4470                               SDValue Operand, const SDNodeFlags Flags) {
4471   // Constant fold unary operations with an integer constant operand. Even
4472   // opaque constant will be folded, because the folding of unary operations
4473   // doesn't create new constants with different values. Nevertheless, the
4474   // opaque flag is preserved during folding to prevent future folding with
4475   // other constants.
4476   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
4477     const APInt &Val = C->getAPIntValue();
4478     switch (Opcode) {
4479     default: break;
4480     case ISD::SIGN_EXTEND:
4481       return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
4482                          C->isTargetOpcode(), C->isOpaque());
4483     case ISD::TRUNCATE:
4484       if (C->isOpaque())
4485         break;
4486       LLVM_FALLTHROUGH;
4487     case ISD::ANY_EXTEND:
4488     case ISD::ZERO_EXTEND:
4489       return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
4490                          C->isTargetOpcode(), C->isOpaque());
4491     case ISD::UINT_TO_FP:
4492     case ISD::SINT_TO_FP: {
4493       APFloat apf(EVTToAPFloatSemantics(VT),
4494                   APInt::getNullValue(VT.getSizeInBits()));
4495       (void)apf.convertFromAPInt(Val,
4496                                  Opcode==ISD::SINT_TO_FP,
4497                                  APFloat::rmNearestTiesToEven);
4498       return getConstantFP(apf, DL, VT);
4499     }
4500     case ISD::BITCAST:
4501       if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
4502         return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
4503       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
4504         return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
4505       if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
4506         return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
4507       if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
4508         return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
4509       break;
4510     case ISD::ABS:
4511       return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
4512                          C->isOpaque());
4513     case ISD::BITREVERSE:
4514       return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
4515                          C->isOpaque());
4516     case ISD::BSWAP:
4517       return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
4518                          C->isOpaque());
4519     case ISD::CTPOP:
4520       return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
4521                          C->isOpaque());
4522     case ISD::CTLZ:
4523     case ISD::CTLZ_ZERO_UNDEF:
4524       return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
4525                          C->isOpaque());
4526     case ISD::CTTZ:
4527     case ISD::CTTZ_ZERO_UNDEF:
4528       return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
4529                          C->isOpaque());
4530     case ISD::FP16_TO_FP: {
4531       bool Ignored;
4532       APFloat FPV(APFloat::IEEEhalf(),
4533                   (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
4534 
4535       // This can return overflow, underflow, or inexact; we don't care.
4536       // FIXME need to be more flexible about rounding mode.
4537       (void)FPV.convert(EVTToAPFloatSemantics(VT),
4538                         APFloat::rmNearestTiesToEven, &Ignored);
4539       return getConstantFP(FPV, DL, VT);
4540     }
4541     }
4542   }
4543 
4544   // Constant fold unary operations with a floating point constant operand.
4545   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
4546     APFloat V = C->getValueAPF();    // make copy
4547     switch (Opcode) {
4548     case ISD::FNEG:
4549       V.changeSign();
4550       return getConstantFP(V, DL, VT);
4551     case ISD::FABS:
4552       V.clearSign();
4553       return getConstantFP(V, DL, VT);
4554     case ISD::FCEIL: {
4555       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
4556       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4557         return getConstantFP(V, DL, VT);
4558       break;
4559     }
4560     case ISD::FTRUNC: {
4561       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
4562       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4563         return getConstantFP(V, DL, VT);
4564       break;
4565     }
4566     case ISD::FFLOOR: {
4567       APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
4568       if (fs == APFloat::opOK || fs == APFloat::opInexact)
4569         return getConstantFP(V, DL, VT);
4570       break;
4571     }
4572     case ISD::FP_EXTEND: {
4573       bool ignored;
4574       // This can return overflow, underflow, or inexact; we don't care.
4575       // FIXME need to be more flexible about rounding mode.
4576       (void)V.convert(EVTToAPFloatSemantics(VT),
4577                       APFloat::rmNearestTiesToEven, &ignored);
4578       return getConstantFP(V, DL, VT);
4579     }
4580     case ISD::FP_TO_SINT:
4581     case ISD::FP_TO_UINT: {
4582       bool ignored;
4583       APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
4584       // FIXME need to be more flexible about rounding mode.
4585       APFloat::opStatus s =
4586           V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
4587       if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
4588         break;
4589       return getConstant(IntVal, DL, VT);
4590     }
4591     case ISD::BITCAST:
4592       if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
4593         return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4594       else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
4595         return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
4596       else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
4597         return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4598       break;
4599     case ISD::FP_TO_FP16: {
4600       bool Ignored;
4601       // This can return overflow, underflow, or inexact; we don't care.
4602       // FIXME need to be more flexible about rounding mode.
4603       (void)V.convert(APFloat::IEEEhalf(),
4604                       APFloat::rmNearestTiesToEven, &Ignored);
4605       return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
4606     }
4607     }
4608   }
4609 
4610   // Constant fold unary operations with a vector integer or float operand.
4611   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
4612     if (BV->isConstant()) {
4613       switch (Opcode) {
4614       default:
4615         // FIXME: Entirely reasonable to perform folding of other unary
4616         // operations here as the need arises.
4617         break;
4618       case ISD::FNEG:
4619       case ISD::FABS:
4620       case ISD::FCEIL:
4621       case ISD::FTRUNC:
4622       case ISD::FFLOOR:
4623       case ISD::FP_EXTEND:
4624       case ISD::FP_TO_SINT:
4625       case ISD::FP_TO_UINT:
4626       case ISD::TRUNCATE:
4627       case ISD::ANY_EXTEND:
4628       case ISD::ZERO_EXTEND:
4629       case ISD::SIGN_EXTEND:
4630       case ISD::UINT_TO_FP:
4631       case ISD::SINT_TO_FP:
4632       case ISD::ABS:
4633       case ISD::BITREVERSE:
4634       case ISD::BSWAP:
4635       case ISD::CTLZ:
4636       case ISD::CTLZ_ZERO_UNDEF:
4637       case ISD::CTTZ:
4638       case ISD::CTTZ_ZERO_UNDEF:
4639       case ISD::CTPOP: {
4640         SDValue Ops = { Operand };
4641         if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
4642           return Fold;
4643       }
4644       }
4645     }
4646   }
4647 
4648   unsigned OpOpcode = Operand.getNode()->getOpcode();
4649   switch (Opcode) {
4650   case ISD::FREEZE:
4651     assert(VT == Operand.getValueType() && "Unexpected VT!");
4652     break;
4653   case ISD::TokenFactor:
4654   case ISD::MERGE_VALUES:
4655   case ISD::CONCAT_VECTORS:
4656     return Operand;         // Factor, merge or concat of one node?  No need.
4657   case ISD::BUILD_VECTOR: {
4658     // Attempt to simplify BUILD_VECTOR.
4659     SDValue Ops[] = {Operand};
4660     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
4661       return V;
4662     break;
4663   }
4664   case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
4665   case ISD::FP_EXTEND:
4666     assert(VT.isFloatingPoint() &&
4667            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
4668     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
4669     assert((!VT.isVector() ||
4670             VT.getVectorNumElements() ==
4671             Operand.getValueType().getVectorNumElements()) &&
4672            "Vector element count mismatch!");
4673     assert(Operand.getValueType().bitsLT(VT) &&
4674            "Invalid fpext node, dst < src!");
4675     if (Operand.isUndef())
4676       return getUNDEF(VT);
4677     break;
4678   case ISD::FP_TO_SINT:
4679   case ISD::FP_TO_UINT:
4680     if (Operand.isUndef())
4681       return getUNDEF(VT);
4682     break;
4683   case ISD::SINT_TO_FP:
4684   case ISD::UINT_TO_FP:
4685     // [us]itofp(undef) = 0, because the result value is bounded.
4686     if (Operand.isUndef())
4687       return getConstantFP(0.0, DL, VT);
4688     break;
4689   case ISD::SIGN_EXTEND:
4690     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4691            "Invalid SIGN_EXTEND!");
4692     assert(VT.isVector() == Operand.getValueType().isVector() &&
4693            "SIGN_EXTEND result type type should be vector iff the operand "
4694            "type is vector!");
4695     if (Operand.getValueType() == VT) return Operand;   // noop extension
4696     assert((!VT.isVector() ||
4697             VT.getVectorElementCount() ==
4698                 Operand.getValueType().getVectorElementCount()) &&
4699            "Vector element count mismatch!");
4700     assert(Operand.getValueType().bitsLT(VT) &&
4701            "Invalid sext node, dst < src!");
4702     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
4703       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4704     else if (OpOpcode == ISD::UNDEF)
4705       // sext(undef) = 0, because the top bits will all be the same.
4706       return getConstant(0, DL, VT);
4707     break;
4708   case ISD::ZERO_EXTEND:
4709     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4710            "Invalid ZERO_EXTEND!");
4711     assert(VT.isVector() == Operand.getValueType().isVector() &&
4712            "ZERO_EXTEND result type type should be vector iff the operand "
4713            "type is vector!");
4714     if (Operand.getValueType() == VT) return Operand;   // noop extension
4715     assert((!VT.isVector() ||
4716             VT.getVectorElementCount() ==
4717                 Operand.getValueType().getVectorElementCount()) &&
4718            "Vector element count mismatch!");
4719     assert(Operand.getValueType().bitsLT(VT) &&
4720            "Invalid zext node, dst < src!");
4721     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
4722       return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
4723     else if (OpOpcode == ISD::UNDEF)
4724       // zext(undef) = 0, because the top bits will be zero.
4725       return getConstant(0, DL, VT);
4726     break;
4727   case ISD::ANY_EXTEND:
4728     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4729            "Invalid ANY_EXTEND!");
4730     assert(VT.isVector() == Operand.getValueType().isVector() &&
4731            "ANY_EXTEND result type type should be vector iff the operand "
4732            "type is vector!");
4733     if (Operand.getValueType() == VT) return Operand;   // noop extension
4734     assert((!VT.isVector() ||
4735             VT.getVectorElementCount() ==
4736                 Operand.getValueType().getVectorElementCount()) &&
4737            "Vector element count mismatch!");
4738     assert(Operand.getValueType().bitsLT(VT) &&
4739            "Invalid anyext node, dst < src!");
4740 
4741     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4742         OpOpcode == ISD::ANY_EXTEND)
4743       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
4744       return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4745     else if (OpOpcode == ISD::UNDEF)
4746       return getUNDEF(VT);
4747 
4748     // (ext (trunc x)) -> x
4749     if (OpOpcode == ISD::TRUNCATE) {
4750       SDValue OpOp = Operand.getOperand(0);
4751       if (OpOp.getValueType() == VT) {
4752         transferDbgValues(Operand, OpOp);
4753         return OpOp;
4754       }
4755     }
4756     break;
4757   case ISD::TRUNCATE:
4758     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
4759            "Invalid TRUNCATE!");
4760     assert(VT.isVector() == Operand.getValueType().isVector() &&
4761            "TRUNCATE result type type should be vector iff the operand "
4762            "type is vector!");
4763     if (Operand.getValueType() == VT) return Operand;   // noop truncate
4764     assert((!VT.isVector() ||
4765             VT.getVectorElementCount() ==
4766                 Operand.getValueType().getVectorElementCount()) &&
4767            "Vector element count mismatch!");
4768     assert(Operand.getValueType().bitsGT(VT) &&
4769            "Invalid truncate node, src < dst!");
4770     if (OpOpcode == ISD::TRUNCATE)
4771       return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4772     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
4773         OpOpcode == ISD::ANY_EXTEND) {
4774       // If the source is smaller than the dest, we still need an extend.
4775       if (Operand.getOperand(0).getValueType().getScalarType()
4776             .bitsLT(VT.getScalarType()))
4777         return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
4778       if (Operand.getOperand(0).getValueType().bitsGT(VT))
4779         return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
4780       return Operand.getOperand(0);
4781     }
4782     if (OpOpcode == ISD::UNDEF)
4783       return getUNDEF(VT);
4784     break;
4785   case ISD::ANY_EXTEND_VECTOR_INREG:
4786   case ISD::ZERO_EXTEND_VECTOR_INREG:
4787   case ISD::SIGN_EXTEND_VECTOR_INREG:
4788     assert(VT.isVector() && "This DAG node is restricted to vector types.");
4789     assert(Operand.getValueType().bitsLE(VT) &&
4790            "The input must be the same size or smaller than the result.");
4791     assert(VT.getVectorNumElements() <
4792              Operand.getValueType().getVectorNumElements() &&
4793            "The destination vector type must have fewer lanes than the input.");
4794     break;
4795   case ISD::ABS:
4796     assert(VT.isInteger() && VT == Operand.getValueType() &&
4797            "Invalid ABS!");
4798     if (OpOpcode == ISD::UNDEF)
4799       return getUNDEF(VT);
4800     break;
4801   case ISD::BSWAP:
4802     assert(VT.isInteger() && VT == Operand.getValueType() &&
4803            "Invalid BSWAP!");
4804     assert((VT.getScalarSizeInBits() % 16 == 0) &&
4805            "BSWAP types must be a multiple of 16 bits!");
4806     if (OpOpcode == ISD::UNDEF)
4807       return getUNDEF(VT);
4808     break;
4809   case ISD::BITREVERSE:
4810     assert(VT.isInteger() && VT == Operand.getValueType() &&
4811            "Invalid BITREVERSE!");
4812     if (OpOpcode == ISD::UNDEF)
4813       return getUNDEF(VT);
4814     break;
4815   case ISD::BITCAST:
4816     // Basic sanity checking.
4817     assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
4818            "Cannot BITCAST between types of different sizes!");
4819     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
4820     if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
4821       return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
4822     if (OpOpcode == ISD::UNDEF)
4823       return getUNDEF(VT);
4824     break;
4825   case ISD::SCALAR_TO_VECTOR:
4826     assert(VT.isVector() && !Operand.getValueType().isVector() &&
4827            (VT.getVectorElementType() == Operand.getValueType() ||
4828             (VT.getVectorElementType().isInteger() &&
4829              Operand.getValueType().isInteger() &&
4830              VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
4831            "Illegal SCALAR_TO_VECTOR node!");
4832     if (OpOpcode == ISD::UNDEF)
4833       return getUNDEF(VT);
4834     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
4835     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
4836         isa<ConstantSDNode>(Operand.getOperand(1)) &&
4837         Operand.getConstantOperandVal(1) == 0 &&
4838         Operand.getOperand(0).getValueType() == VT)
4839       return Operand.getOperand(0);
4840     break;
4841   case ISD::FNEG:
4842     // Negation of an unknown bag of bits is still completely undefined.
4843     if (OpOpcode == ISD::UNDEF)
4844       return getUNDEF(VT);
4845 
4846     if (OpOpcode == ISD::FNEG)  // --X -> X
4847       return Operand.getOperand(0);
4848     break;
4849   case ISD::FABS:
4850     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
4851       return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
4852     break;
4853   case ISD::VSCALE:
4854     assert(VT == Operand.getValueType() && "Unexpected VT!");
4855     break;
4856   }
4857 
4858   SDNode *N;
4859   SDVTList VTs = getVTList(VT);
4860   SDValue Ops[] = {Operand};
4861   if (VT != MVT::Glue) { // Don't CSE flag producing nodes
4862     FoldingSetNodeID ID;
4863     AddNodeIDNode(ID, Opcode, VTs, Ops);
4864     void *IP = nullptr;
4865     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
4866       E->intersectFlagsWith(Flags);
4867       return SDValue(E, 0);
4868     }
4869 
4870     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4871     N->setFlags(Flags);
4872     createOperands(N, Ops);
4873     CSEMap.InsertNode(N, IP);
4874   } else {
4875     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
4876     createOperands(N, Ops);
4877   }
4878 
4879   InsertNode(N);
4880   SDValue V = SDValue(N, 0);
4881   NewSDValueDbgMsg(V, "Creating new node: ", this);
4882   return V;
4883 }
4884 
FoldValue(unsigned Opcode,const APInt & C1,const APInt & C2)4885 static llvm::Optional<APInt> FoldValue(unsigned Opcode, const APInt &C1,
4886                                        const APInt &C2) {
4887   switch (Opcode) {
4888   case ISD::ADD:  return C1 + C2;
4889   case ISD::SUB:  return C1 - C2;
4890   case ISD::MUL:  return C1 * C2;
4891   case ISD::AND:  return C1 & C2;
4892   case ISD::OR:   return C1 | C2;
4893   case ISD::XOR:  return C1 ^ C2;
4894   case ISD::SHL:  return C1 << C2;
4895   case ISD::SRL:  return C1.lshr(C2);
4896   case ISD::SRA:  return C1.ashr(C2);
4897   case ISD::ROTL: return C1.rotl(C2);
4898   case ISD::ROTR: return C1.rotr(C2);
4899   case ISD::SMIN: return C1.sle(C2) ? C1 : C2;
4900   case ISD::SMAX: return C1.sge(C2) ? C1 : C2;
4901   case ISD::UMIN: return C1.ule(C2) ? C1 : C2;
4902   case ISD::UMAX: return C1.uge(C2) ? C1 : C2;
4903   case ISD::SADDSAT: return C1.sadd_sat(C2);
4904   case ISD::UADDSAT: return C1.uadd_sat(C2);
4905   case ISD::SSUBSAT: return C1.ssub_sat(C2);
4906   case ISD::USUBSAT: return C1.usub_sat(C2);
4907   case ISD::UDIV:
4908     if (!C2.getBoolValue())
4909       break;
4910     return C1.udiv(C2);
4911   case ISD::UREM:
4912     if (!C2.getBoolValue())
4913       break;
4914     return C1.urem(C2);
4915   case ISD::SDIV:
4916     if (!C2.getBoolValue())
4917       break;
4918     return C1.sdiv(C2);
4919   case ISD::SREM:
4920     if (!C2.getBoolValue())
4921       break;
4922     return C1.srem(C2);
4923   }
4924   return llvm::None;
4925 }
4926 
FoldSymbolOffset(unsigned Opcode,EVT VT,const GlobalAddressSDNode * GA,const SDNode * N2)4927 SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
4928                                        const GlobalAddressSDNode *GA,
4929                                        const SDNode *N2) {
4930   if (GA->getOpcode() != ISD::GlobalAddress)
4931     return SDValue();
4932   if (!TLI->isOffsetFoldingLegal(GA))
4933     return SDValue();
4934   auto *C2 = dyn_cast<ConstantSDNode>(N2);
4935   if (!C2)
4936     return SDValue();
4937   int64_t Offset = C2->getSExtValue();
4938   switch (Opcode) {
4939   case ISD::ADD: break;
4940   case ISD::SUB: Offset = -uint64_t(Offset); break;
4941   default: return SDValue();
4942   }
4943   return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
4944                           GA->getOffset() + uint64_t(Offset));
4945 }
4946 
isUndef(unsigned Opcode,ArrayRef<SDValue> Ops)4947 bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
4948   switch (Opcode) {
4949   case ISD::SDIV:
4950   case ISD::UDIV:
4951   case ISD::SREM:
4952   case ISD::UREM: {
4953     // If a divisor is zero/undef or any element of a divisor vector is
4954     // zero/undef, the whole op is undef.
4955     assert(Ops.size() == 2 && "Div/rem should have 2 operands");
4956     SDValue Divisor = Ops[1];
4957     if (Divisor.isUndef() || isNullConstant(Divisor))
4958       return true;
4959 
4960     return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
4961            llvm::any_of(Divisor->op_values(),
4962                         [](SDValue V) { return V.isUndef() ||
4963                                         isNullConstant(V); });
4964     // TODO: Handle signed overflow.
4965   }
4966   // TODO: Handle oversized shifts.
4967   default:
4968     return false;
4969   }
4970 }
4971 
FoldConstantArithmetic(unsigned Opcode,const SDLoc & DL,EVT VT,ArrayRef<SDValue> Ops)4972 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
4973                                              EVT VT, ArrayRef<SDValue> Ops) {
4974   // If the opcode is a target-specific ISD node, there's nothing we can
4975   // do here and the operand rules may not line up with the below, so
4976   // bail early.
4977   if (Opcode >= ISD::BUILTIN_OP_END)
4978     return SDValue();
4979 
4980   // For now, the array Ops should only contain two values.
4981   // This enforcement will be removed once this function is merged with
4982   // FoldConstantVectorArithmetic
4983   if (Ops.size() != 2)
4984     return SDValue();
4985 
4986   if (isUndef(Opcode, Ops))
4987     return getUNDEF(VT);
4988 
4989   SDNode *N1 = Ops[0].getNode();
4990   SDNode *N2 = Ops[1].getNode();
4991 
4992   // Handle the case of two scalars.
4993   if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
4994     if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
4995       if (C1->isOpaque() || C2->isOpaque())
4996         return SDValue();
4997 
4998       Optional<APInt> FoldAttempt =
4999           FoldValue(Opcode, C1->getAPIntValue(), C2->getAPIntValue());
5000       if (!FoldAttempt)
5001         return SDValue();
5002 
5003       SDValue Folded = getConstant(FoldAttempt.getValue(), DL, VT);
5004       assert((!Folded || !VT.isVector()) &&
5005              "Can't fold vectors ops with scalar operands");
5006       return Folded;
5007     }
5008   }
5009 
5010   // fold (add Sym, c) -> Sym+c
5011   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
5012     return FoldSymbolOffset(Opcode, VT, GA, N2);
5013   if (TLI->isCommutativeBinOp(Opcode))
5014     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
5015       return FoldSymbolOffset(Opcode, VT, GA, N1);
5016 
5017   // TODO: All the folds below are performed lane-by-lane and assume a fixed
5018   // vector width, however we should be able to do constant folds involving
5019   // splat vector nodes too.
5020   if (VT.isScalableVector())
5021     return SDValue();
5022 
5023   // For fixed width vectors, extract each constant element and fold them
5024   // individually. Either input may be an undef value.
5025   auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
5026   if (!BV1 && !N1->isUndef())
5027     return SDValue();
5028   auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
5029   if (!BV2 && !N2->isUndef())
5030     return SDValue();
5031   // If both operands are undef, that's handled the same way as scalars.
5032   if (!BV1 && !BV2)
5033     return SDValue();
5034 
5035   assert((!BV1 || !BV2 || BV1->getNumOperands() == BV2->getNumOperands()) &&
5036          "Vector binop with different number of elements in operands?");
5037 
5038   EVT SVT = VT.getScalarType();
5039   EVT LegalSVT = SVT;
5040   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5041     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5042     if (LegalSVT.bitsLT(SVT))
5043       return SDValue();
5044   }
5045   SmallVector<SDValue, 4> Outputs;
5046   unsigned NumOps = BV1 ? BV1->getNumOperands() : BV2->getNumOperands();
5047   for (unsigned I = 0; I != NumOps; ++I) {
5048     SDValue V1 = BV1 ? BV1->getOperand(I) : getUNDEF(SVT);
5049     SDValue V2 = BV2 ? BV2->getOperand(I) : getUNDEF(SVT);
5050     if (SVT.isInteger()) {
5051       if (V1->getValueType(0).bitsGT(SVT))
5052         V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
5053       if (V2->getValueType(0).bitsGT(SVT))
5054         V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
5055     }
5056 
5057     if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
5058       return SDValue();
5059 
5060     // Fold one vector element.
5061     SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
5062     if (LegalSVT != SVT)
5063       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5064 
5065     // Scalar folding only succeeded if the result is a constant or UNDEF.
5066     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5067         ScalarResult.getOpcode() != ISD::ConstantFP)
5068       return SDValue();
5069     Outputs.push_back(ScalarResult);
5070   }
5071 
5072   assert(VT.getVectorNumElements() == Outputs.size() &&
5073          "Vector size mismatch!");
5074 
5075   // We may have a vector type but a scalar result. Create a splat.
5076   Outputs.resize(VT.getVectorNumElements(), Outputs.back());
5077 
5078   // Build a big vector out of the scalar elements we generated.
5079   return getBuildVector(VT, SDLoc(), Outputs);
5080 }
5081 
5082 // TODO: Merge with FoldConstantArithmetic
FoldConstantVectorArithmetic(unsigned Opcode,const SDLoc & DL,EVT VT,ArrayRef<SDValue> Ops,const SDNodeFlags Flags)5083 SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
5084                                                    const SDLoc &DL, EVT VT,
5085                                                    ArrayRef<SDValue> Ops,
5086                                                    const SDNodeFlags Flags) {
5087   // If the opcode is a target-specific ISD node, there's nothing we can
5088   // do here and the operand rules may not line up with the below, so
5089   // bail early.
5090   if (Opcode >= ISD::BUILTIN_OP_END)
5091     return SDValue();
5092 
5093   if (isUndef(Opcode, Ops))
5094     return getUNDEF(VT);
5095 
5096   // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
5097   if (!VT.isVector())
5098     return SDValue();
5099 
5100   // TODO: All the folds below are performed lane-by-lane and assume a fixed
5101   // vector width, however we should be able to do constant folds involving
5102   // splat vector nodes too.
5103   if (VT.isScalableVector())
5104     return SDValue();
5105 
5106   // From this point onwards all vectors are assumed to be fixed width.
5107   unsigned NumElts = VT.getVectorNumElements();
5108 
5109   auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
5110     return !Op.getValueType().isVector() ||
5111            Op.getValueType().getVectorNumElements() == NumElts;
5112   };
5113 
5114   auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
5115     BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
5116     return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
5117            (BV && BV->isConstant());
5118   };
5119 
5120   // All operands must be vector types with the same number of elements as
5121   // the result type and must be either UNDEF or a build vector of constant
5122   // or UNDEF scalars.
5123   if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
5124       !llvm::all_of(Ops, IsScalarOrSameVectorSize))
5125     return SDValue();
5126 
5127   // If we are comparing vectors, then the result needs to be a i1 boolean
5128   // that is then sign-extended back to the legal result type.
5129   EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
5130 
5131   // Find legal integer scalar type for constant promotion and
5132   // ensure that its scalar size is at least as large as source.
5133   EVT LegalSVT = VT.getScalarType();
5134   if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
5135     LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
5136     if (LegalSVT.bitsLT(VT.getScalarType()))
5137       return SDValue();
5138   }
5139 
5140   // Constant fold each scalar lane separately.
5141   SmallVector<SDValue, 4> ScalarResults;
5142   for (unsigned i = 0; i != NumElts; i++) {
5143     SmallVector<SDValue, 4> ScalarOps;
5144     for (SDValue Op : Ops) {
5145       EVT InSVT = Op.getValueType().getScalarType();
5146       BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
5147       if (!InBV) {
5148         // We've checked that this is UNDEF or a constant of some kind.
5149         if (Op.isUndef())
5150           ScalarOps.push_back(getUNDEF(InSVT));
5151         else
5152           ScalarOps.push_back(Op);
5153         continue;
5154       }
5155 
5156       SDValue ScalarOp = InBV->getOperand(i);
5157       EVT ScalarVT = ScalarOp.getValueType();
5158 
5159       // Build vector (integer) scalar operands may need implicit
5160       // truncation - do this before constant folding.
5161       if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
5162         ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
5163 
5164       ScalarOps.push_back(ScalarOp);
5165     }
5166 
5167     // Constant fold the scalar operands.
5168     SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
5169 
5170     // Legalize the (integer) scalar constant if necessary.
5171     if (LegalSVT != SVT)
5172       ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
5173 
5174     // Scalar folding only succeeded if the result is a constant or UNDEF.
5175     if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
5176         ScalarResult.getOpcode() != ISD::ConstantFP)
5177       return SDValue();
5178     ScalarResults.push_back(ScalarResult);
5179   }
5180 
5181   SDValue V = getBuildVector(VT, DL, ScalarResults);
5182   NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
5183   return V;
5184 }
5185 
foldConstantFPMath(unsigned Opcode,const SDLoc & DL,EVT VT,SDValue N1,SDValue N2)5186 SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
5187                                          EVT VT, SDValue N1, SDValue N2) {
5188   // TODO: We don't do any constant folding for strict FP opcodes here, but we
5189   //       should. That will require dealing with a potentially non-default
5190   //       rounding mode, checking the "opStatus" return value from the APFloat
5191   //       math calculations, and possibly other variations.
5192   auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
5193   auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
5194   if (N1CFP && N2CFP) {
5195     APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
5196     switch (Opcode) {
5197     case ISD::FADD:
5198       C1.add(C2, APFloat::rmNearestTiesToEven);
5199       return getConstantFP(C1, DL, VT);
5200     case ISD::FSUB:
5201       C1.subtract(C2, APFloat::rmNearestTiesToEven);
5202       return getConstantFP(C1, DL, VT);
5203     case ISD::FMUL:
5204       C1.multiply(C2, APFloat::rmNearestTiesToEven);
5205       return getConstantFP(C1, DL, VT);
5206     case ISD::FDIV:
5207       C1.divide(C2, APFloat::rmNearestTiesToEven);
5208       return getConstantFP(C1, DL, VT);
5209     case ISD::FREM:
5210       C1.mod(C2);
5211       return getConstantFP(C1, DL, VT);
5212     case ISD::FCOPYSIGN:
5213       C1.copySign(C2);
5214       return getConstantFP(C1, DL, VT);
5215     default: break;
5216     }
5217   }
5218   if (N1CFP && Opcode == ISD::FP_ROUND) {
5219     APFloat C1 = N1CFP->getValueAPF();    // make copy
5220     bool Unused;
5221     // This can return overflow, underflow, or inexact; we don't care.
5222     // FIXME need to be more flexible about rounding mode.
5223     (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
5224                       &Unused);
5225     return getConstantFP(C1, DL, VT);
5226   }
5227 
5228   switch (Opcode) {
5229   case ISD::FSUB:
5230     // -0.0 - undef --> undef (consistent with "fneg undef")
5231     if (N1CFP && N1CFP->getValueAPF().isNegZero() && N2.isUndef())
5232       return getUNDEF(VT);
5233     LLVM_FALLTHROUGH;
5234 
5235   case ISD::FADD:
5236   case ISD::FMUL:
5237   case ISD::FDIV:
5238   case ISD::FREM:
5239     // If both operands are undef, the result is undef. If 1 operand is undef,
5240     // the result is NaN. This should match the behavior of the IR optimizer.
5241     if (N1.isUndef() && N2.isUndef())
5242       return getUNDEF(VT);
5243     if (N1.isUndef() || N2.isUndef())
5244       return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
5245   }
5246   return SDValue();
5247 }
5248 
getAssertAlign(const SDLoc & DL,SDValue Val,Align A)5249 SDValue SelectionDAG::getAssertAlign(const SDLoc &DL, SDValue Val, Align A) {
5250   assert(Val.getValueType().isInteger() && "Invalid AssertAlign!");
5251 
5252   // There's no need to assert on a byte-aligned pointer. All pointers are at
5253   // least byte aligned.
5254   if (A == Align(1))
5255     return Val;
5256 
5257   FoldingSetNodeID ID;
5258   AddNodeIDNode(ID, ISD::AssertAlign, getVTList(Val.getValueType()), {Val});
5259   ID.AddInteger(A.value());
5260 
5261   void *IP = nullptr;
5262   if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
5263     return SDValue(E, 0);
5264 
5265   auto *N = newSDNode<AssertAlignSDNode>(DL.getIROrder(), DL.getDebugLoc(),
5266                                          Val.getValueType(), A);
5267   createOperands(N, {Val});
5268 
5269   CSEMap.InsertNode(N, IP);
5270   InsertNode(N);
5271 
5272   SDValue V(N, 0);
5273   NewSDValueDbgMsg(V, "Creating new node: ", this);
5274   return V;
5275 }
5276 
getNode(unsigned Opcode,const SDLoc & DL,EVT VT,SDValue N1,SDValue N2,const SDNodeFlags Flags)5277 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5278                               SDValue N1, SDValue N2, const SDNodeFlags Flags) {
5279   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
5280   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
5281   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5282   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5283 
5284   // Canonicalize constant to RHS if commutative.
5285   if (TLI->isCommutativeBinOp(Opcode)) {
5286     if (N1C && !N2C) {
5287       std::swap(N1C, N2C);
5288       std::swap(N1, N2);
5289     } else if (N1CFP && !N2CFP) {
5290       std::swap(N1CFP, N2CFP);
5291       std::swap(N1, N2);
5292     }
5293   }
5294 
5295   switch (Opcode) {
5296   default: break;
5297   case ISD::TokenFactor:
5298     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
5299            N2.getValueType() == MVT::Other && "Invalid token factor!");
5300     // Fold trivial token factors.
5301     if (N1.getOpcode() == ISD::EntryToken) return N2;
5302     if (N2.getOpcode() == ISD::EntryToken) return N1;
5303     if (N1 == N2) return N1;
5304     break;
5305   case ISD::BUILD_VECTOR: {
5306     // Attempt to simplify BUILD_VECTOR.
5307     SDValue Ops[] = {N1, N2};
5308     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5309       return V;
5310     break;
5311   }
5312   case ISD::CONCAT_VECTORS: {
5313     SDValue Ops[] = {N1, N2};
5314     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5315       return V;
5316     break;
5317   }
5318   case ISD::PTRADD:
5319     assert(VT.isFatPointer() && "PTRADD result must be a capability type!");
5320     assert(N1.getValueType().isFatPointer() &&
5321            "First PTRADD argument must be a capability type!");
5322     assert(N2.getValueType().isInteger() &&
5323            "Second PTRADD argument must be an integer type!");
5324     // ptradd(X, 0) -> X.
5325     if (N2C && N2C->isNullValue())
5326       return N1;
5327     break;
5328   case ISD::AND:
5329     assert(VT.isInteger() && "This operator does not apply to FP types!");
5330     assert(N1.getValueType() == N2.getValueType() &&
5331            N1.getValueType() == VT && "Binary operator types must match!");
5332     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
5333     // worth handling here.
5334     if (N2C && N2C->isNullValue())
5335       return N2;
5336     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
5337       return N1;
5338     break;
5339   case ISD::OR:
5340   case ISD::XOR:
5341   case ISD::ADD:
5342   case ISD::SUB:
5343     assert(!VT.isFatPointer() &&
5344            "This operator does not apply to capability types!");
5345     assert(VT.isInteger() && "This operator does not apply to FP types!");
5346     assert(N1.getValueType() == N2.getValueType() &&
5347            N1.getValueType() == VT && "Binary operator types must match!");
5348     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
5349     // it's worth handling here.
5350     if (N2C && N2C->isNullValue())
5351       return N1;
5352     break;
5353   case ISD::MUL:
5354     assert(VT.isInteger() && "This operator does not apply to FP types!");
5355     assert(N1.getValueType() == N2.getValueType() &&
5356            N1.getValueType() == VT && "Binary operator types must match!");
5357     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5358       APInt MulImm = cast<ConstantSDNode>(N1->getOperand(0))->getAPIntValue();
5359       APInt N2CImm = N2C->getAPIntValue();
5360       return getVScale(DL, VT, MulImm * N2CImm);
5361     }
5362     break;
5363   case ISD::UDIV:
5364   case ISD::UREM:
5365   case ISD::MULHU:
5366   case ISD::MULHS:
5367   case ISD::SDIV:
5368   case ISD::SREM:
5369   case ISD::SMIN:
5370   case ISD::SMAX:
5371   case ISD::UMIN:
5372   case ISD::UMAX:
5373   case ISD::SADDSAT:
5374   case ISD::SSUBSAT:
5375   case ISD::UADDSAT:
5376   case ISD::USUBSAT:
5377     assert(VT.isInteger() && "This operator does not apply to FP types!");
5378     assert(N1.getValueType() == N2.getValueType() &&
5379            N1.getValueType() == VT && "Binary operator types must match!");
5380     break;
5381   case ISD::FADD:
5382   case ISD::FSUB:
5383   case ISD::FMUL:
5384   case ISD::FDIV:
5385   case ISD::FREM:
5386     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5387     assert(N1.getValueType() == N2.getValueType() &&
5388            N1.getValueType() == VT && "Binary operator types must match!");
5389     if (SDValue V = simplifyFPBinop(Opcode, N1, N2, Flags))
5390       return V;
5391     break;
5392   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
5393     assert(N1.getValueType() == VT &&
5394            N1.getValueType().isFloatingPoint() &&
5395            N2.getValueType().isFloatingPoint() &&
5396            "Invalid FCOPYSIGN!");
5397     break;
5398   case ISD::SHL:
5399     if (N2C && (N1.getOpcode() == ISD::VSCALE) && Flags.hasNoSignedWrap()) {
5400       APInt MulImm = cast<ConstantSDNode>(N1->getOperand(0))->getAPIntValue();
5401       APInt ShiftImm = N2C->getAPIntValue();
5402       return getVScale(DL, VT, MulImm << ShiftImm);
5403     }
5404     LLVM_FALLTHROUGH;
5405   case ISD::SRA:
5406   case ISD::SRL:
5407     if (SDValue V = simplifyShift(N1, N2))
5408       return V;
5409     LLVM_FALLTHROUGH;
5410   case ISD::ROTL:
5411   case ISD::ROTR:
5412     assert(VT == N1.getValueType() &&
5413            "Shift operators return type must be the same as their first arg");
5414     assert(VT.isInteger() && N2.getValueType().isInteger() &&
5415            "Shifts only work on integers");
5416     assert((!VT.isVector() || VT == N2.getValueType()) &&
5417            "Vector shift amounts must be in the same as their first arg");
5418     // Verify that the shift amount VT is big enough to hold valid shift
5419     // amounts.  This catches things like trying to shift an i1024 value by an
5420     // i8, which is easy to fall into in generic code that uses
5421     // TLI.getShiftAmount().
5422     assert(N2.getValueType().getScalarSizeInBits().getFixedSize() >=
5423                Log2_32_Ceil(VT.getScalarSizeInBits().getFixedSize()) &&
5424            "Invalid use of small shift amount with oversized value!");
5425 
5426     // Always fold shifts of i1 values so the code generator doesn't need to
5427     // handle them.  Since we know the size of the shift has to be less than the
5428     // size of the value, the shift/rotate count is guaranteed to be zero.
5429     if (VT == MVT::i1)
5430       return N1;
5431     if (N2C && N2C->isNullValue())
5432       return N1;
5433     break;
5434   case ISD::FP_ROUND:
5435     assert(VT.isFloatingPoint() &&
5436            N1.getValueType().isFloatingPoint() &&
5437            VT.bitsLE(N1.getValueType()) &&
5438            N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
5439            "Invalid FP_ROUND!");
5440     if (N1.getValueType() == VT) return N1;  // noop conversion.
5441     break;
5442   case ISD::AssertSext:
5443   case ISD::AssertZext: {
5444     EVT EVT = cast<VTSDNode>(N2)->getVT();
5445     assert(VT == N1.getValueType() && "Not an inreg extend!");
5446     assert(VT.isInteger() && EVT.isInteger() &&
5447            "Cannot *_EXTEND_INREG FP types");
5448     assert(!EVT.isVector() &&
5449            "AssertSExt/AssertZExt type should be the vector element type "
5450            "rather than the vector type!");
5451     assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
5452     if (VT.getScalarType() == EVT) return N1; // noop assertion.
5453     break;
5454   }
5455   case ISD::SIGN_EXTEND_INREG: {
5456     EVT EVT = cast<VTSDNode>(N2)->getVT();
5457     assert(VT == N1.getValueType() && "Not an inreg extend!");
5458     assert(VT.isInteger() && EVT.isInteger() &&
5459            "Cannot *_EXTEND_INREG FP types");
5460     assert(EVT.isVector() == VT.isVector() &&
5461            "SIGN_EXTEND_INREG type should be vector iff the operand "
5462            "type is vector!");
5463     assert((!EVT.isVector() ||
5464             EVT.getVectorElementCount() == VT.getVectorElementCount()) &&
5465            "Vector element counts must match in SIGN_EXTEND_INREG");
5466     assert(EVT.bitsLE(VT) && "Not extending!");
5467     if (EVT == VT) return N1;  // Not actually extending
5468 
5469     auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
5470       unsigned FromBits = EVT.getScalarSizeInBits();
5471       Val <<= Val.getBitWidth() - FromBits;
5472       Val.ashrInPlace(Val.getBitWidth() - FromBits);
5473       return getConstant(Val, DL, ConstantVT);
5474     };
5475 
5476     if (N1C) {
5477       const APInt &Val = N1C->getAPIntValue();
5478       return SignExtendInReg(Val, VT);
5479     }
5480     if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
5481       SmallVector<SDValue, 8> Ops;
5482       llvm::EVT OpVT = N1.getOperand(0).getValueType();
5483       for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
5484         SDValue Op = N1.getOperand(i);
5485         if (Op.isUndef()) {
5486           Ops.push_back(getUNDEF(OpVT));
5487           continue;
5488         }
5489         ConstantSDNode *C = cast<ConstantSDNode>(Op);
5490         APInt Val = C->getAPIntValue();
5491         Ops.push_back(SignExtendInReg(Val, OpVT));
5492       }
5493       return getBuildVector(VT, DL, Ops);
5494     }
5495     break;
5496   }
5497   case ISD::EXTRACT_VECTOR_ELT:
5498     assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
5499            "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
5500              element type of the vector.");
5501 
5502     // Extract from an undefined value or using an undefined index is undefined.
5503     if (N1.isUndef() || N2.isUndef())
5504       return getUNDEF(VT);
5505 
5506     // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF for fixed length
5507     // vectors. For scalable vectors we will provide appropriate support for
5508     // dealing with arbitrary indices.
5509     if (N2C && N1.getValueType().isFixedLengthVector() &&
5510         N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
5511       return getUNDEF(VT);
5512 
5513     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
5514     // expanding copies of large vectors from registers. This only works for
5515     // fixed length vectors, since we need to know the exact number of
5516     // elements.
5517     if (N2C && N1.getOperand(0).getValueType().isFixedLengthVector() &&
5518         N1.getOpcode() == ISD::CONCAT_VECTORS && N1.getNumOperands() > 0) {
5519       unsigned Factor =
5520         N1.getOperand(0).getValueType().getVectorNumElements();
5521       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
5522                      N1.getOperand(N2C->getZExtValue() / Factor),
5523                      getVectorIdxConstant(N2C->getZExtValue() % Factor, DL));
5524     }
5525 
5526     // EXTRACT_VECTOR_ELT of BUILD_VECTOR or SPLAT_VECTOR is often formed while
5527     // lowering is expanding large vector constants.
5528     if (N2C && (N1.getOpcode() == ISD::BUILD_VECTOR ||
5529                 N1.getOpcode() == ISD::SPLAT_VECTOR)) {
5530       assert((N1.getOpcode() != ISD::BUILD_VECTOR ||
5531               N1.getValueType().isFixedLengthVector()) &&
5532              "BUILD_VECTOR used for scalable vectors");
5533       unsigned Index =
5534           N1.getOpcode() == ISD::BUILD_VECTOR ? N2C->getZExtValue() : 0;
5535       SDValue Elt = N1.getOperand(Index);
5536 
5537       if (VT != Elt.getValueType())
5538         // If the vector element type is not legal, the BUILD_VECTOR operands
5539         // are promoted and implicitly truncated, and the result implicitly
5540         // extended. Make that explicit here.
5541         Elt = getAnyExtOrTrunc(Elt, DL, VT);
5542 
5543       return Elt;
5544     }
5545 
5546     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
5547     // operations are lowered to scalars.
5548     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
5549       // If the indices are the same, return the inserted element else
5550       // if the indices are known different, extract the element from
5551       // the original vector.
5552       SDValue N1Op2 = N1.getOperand(2);
5553       ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
5554 
5555       if (N1Op2C && N2C) {
5556         if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
5557           if (VT == N1.getOperand(1).getValueType())
5558             return N1.getOperand(1);
5559           else
5560             return getSExtOrTrunc(N1.getOperand(1), DL, VT);
5561         }
5562 
5563         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
5564       }
5565     }
5566 
5567     // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
5568     // when vector types are scalarized and v1iX is legal.
5569     // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx).
5570     // Here we are completely ignoring the extract element index (N2),
5571     // which is fine for fixed width vectors, since any index other than 0
5572     // is undefined anyway. However, this cannot be ignored for scalable
5573     // vectors - in theory we could support this, but we don't want to do this
5574     // without a profitability check.
5575     if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5576         N1.getValueType().isFixedLengthVector() &&
5577         N1.getValueType().getVectorNumElements() == 1) {
5578       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
5579                      N1.getOperand(1));
5580     }
5581     break;
5582   case ISD::EXTRACT_ELEMENT:
5583     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
5584     assert(!N1.getValueType().isVector() && !VT.isVector() &&
5585            (N1.getValueType().isInteger() == VT.isInteger()) &&
5586            N1.getValueType() != VT &&
5587            "Wrong types for EXTRACT_ELEMENT!");
5588 
5589     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
5590     // 64-bit integers into 32-bit parts.  Instead of building the extract of
5591     // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
5592     if (N1.getOpcode() == ISD::BUILD_PAIR)
5593       return N1.getOperand(N2C->getZExtValue());
5594 
5595     // EXTRACT_ELEMENT of a constant int is also very common.
5596     if (N1C) {
5597       unsigned ElementSize = VT.getSizeInBits();
5598       unsigned Shift = ElementSize * N2C->getZExtValue();
5599       APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
5600       return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
5601     }
5602     break;
5603   case ISD::EXTRACT_SUBVECTOR:
5604     EVT N1VT = N1.getValueType();
5605     assert(VT.isVector() && N1VT.isVector() &&
5606            "Extract subvector VTs must be vectors!");
5607     assert(VT.getVectorElementType() == N1VT.getVectorElementType() &&
5608            "Extract subvector VTs must have the same element type!");
5609     assert((VT.isFixedLengthVector() || N1VT.isScalableVector()) &&
5610            "Cannot extract a scalable vector from a fixed length vector!");
5611     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5612             VT.getVectorMinNumElements() <= N1VT.getVectorMinNumElements()) &&
5613            "Extract subvector must be from larger vector to smaller vector!");
5614     assert(N2C && "Extract subvector index must be a constant");
5615     assert((VT.isScalableVector() != N1VT.isScalableVector() ||
5616             (VT.getVectorMinNumElements() + N2C->getZExtValue()) <=
5617                 N1VT.getVectorMinNumElements()) &&
5618            "Extract subvector overflow!");
5619 
5620     // Trivial extraction.
5621     if (VT == N1VT)
5622       return N1;
5623 
5624     // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
5625     if (N1.isUndef())
5626       return getUNDEF(VT);
5627 
5628     // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
5629     // the concat have the same type as the extract.
5630     if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
5631         N1.getNumOperands() > 0 && VT == N1.getOperand(0).getValueType()) {
5632       unsigned Factor = VT.getVectorMinNumElements();
5633       return N1.getOperand(N2C->getZExtValue() / Factor);
5634     }
5635 
5636     // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
5637     // during shuffle legalization.
5638     if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
5639         VT == N1.getOperand(1).getValueType())
5640       return N1.getOperand(1);
5641     break;
5642   }
5643 
5644   // Perform trivial constant folding.
5645   if (SDValue SV = FoldConstantArithmetic(Opcode, DL, VT, {N1, N2}))
5646     return SV;
5647 
5648   if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
5649     return V;
5650 
5651   // Canonicalize an UNDEF to the RHS, even over a constant.
5652   if (N1.isUndef()) {
5653     if (TLI->isCommutativeBinOp(Opcode)) {
5654       std::swap(N1, N2);
5655     } else {
5656       switch (Opcode) {
5657       case ISD::SIGN_EXTEND_INREG:
5658       case ISD::SUB:
5659         return getUNDEF(VT);     // fold op(undef, arg2) -> undef
5660       case ISD::UDIV:
5661       case ISD::SDIV:
5662       case ISD::UREM:
5663       case ISD::SREM:
5664       case ISD::SSUBSAT:
5665       case ISD::USUBSAT:
5666         return getConstant(0, DL, VT);    // fold op(undef, arg2) -> 0
5667       }
5668     }
5669   }
5670 
5671   // Fold a bunch of operators when the RHS is undef.
5672   if (N2.isUndef()) {
5673     switch (Opcode) {
5674     case ISD::XOR:
5675       if (N1.isUndef())
5676         // Handle undef ^ undef -> 0 special case. This is a common
5677         // idiom (misuse).
5678         return getConstant(0, DL, VT);
5679       LLVM_FALLTHROUGH;
5680     case ISD::ADD:
5681     case ISD::SUB:
5682     case ISD::UDIV:
5683     case ISD::SDIV:
5684     case ISD::UREM:
5685     case ISD::SREM:
5686       return getUNDEF(VT);       // fold op(arg1, undef) -> undef
5687     case ISD::MUL:
5688     case ISD::AND:
5689     case ISD::SSUBSAT:
5690     case ISD::USUBSAT:
5691       return getConstant(0, DL, VT);  // fold op(arg1, undef) -> 0
5692     case ISD::OR:
5693     case ISD::SADDSAT:
5694     case ISD::UADDSAT:
5695       return getAllOnesConstant(DL, VT);
5696     }
5697   }
5698 
5699   // Memoize this node if possible.
5700   SDNode *N;
5701   SDVTList VTs = getVTList(VT);
5702   SDValue Ops[] = {N1, N2};
5703   if (VT != MVT::Glue) {
5704     FoldingSetNodeID ID;
5705     AddNodeIDNode(ID, Opcode, VTs, Ops);
5706     void *IP = nullptr;
5707     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5708       E->intersectFlagsWith(Flags);
5709       return SDValue(E, 0);
5710     }
5711 
5712     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5713     N->setFlags(Flags);
5714     createOperands(N, Ops);
5715     CSEMap.InsertNode(N, IP);
5716   } else {
5717     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5718     createOperands(N, Ops);
5719   }
5720 
5721   InsertNode(N);
5722   SDValue V = SDValue(N, 0);
5723   NewSDValueDbgMsg(V, "Creating new node: ", this);
5724   return V;
5725 }
5726 
getNode(unsigned Opcode,const SDLoc & DL,EVT VT,SDValue N1,SDValue N2,SDValue N3,const SDNodeFlags Flags)5727 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5728                               SDValue N1, SDValue N2, SDValue N3,
5729                               const SDNodeFlags Flags) {
5730   // Perform various simplifications.
5731   switch (Opcode) {
5732   case ISD::FMA: {
5733     assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
5734     assert(N1.getValueType() == VT && N2.getValueType() == VT &&
5735            N3.getValueType() == VT && "FMA types must match!");
5736     ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5737     ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
5738     ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
5739     if (N1CFP && N2CFP && N3CFP) {
5740       APFloat  V1 = N1CFP->getValueAPF();
5741       const APFloat &V2 = N2CFP->getValueAPF();
5742       const APFloat &V3 = N3CFP->getValueAPF();
5743       V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
5744       return getConstantFP(V1, DL, VT);
5745     }
5746     break;
5747   }
5748   case ISD::BUILD_VECTOR: {
5749     // Attempt to simplify BUILD_VECTOR.
5750     SDValue Ops[] = {N1, N2, N3};
5751     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
5752       return V;
5753     break;
5754   }
5755   case ISD::CONCAT_VECTORS: {
5756     SDValue Ops[] = {N1, N2, N3};
5757     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
5758       return V;
5759     break;
5760   }
5761   case ISD::SETCC: {
5762     assert(VT.isInteger() && "SETCC result type must be an integer!");
5763     assert(N1.getValueType() == N2.getValueType() &&
5764            "SETCC operands must have the same type!");
5765     assert(VT.isVector() == N1.getValueType().isVector() &&
5766            "SETCC type should be vector iff the operand type is vector!");
5767     assert((!VT.isVector() || VT.getVectorElementCount() ==
5768                                   N1.getValueType().getVectorElementCount()) &&
5769            "SETCC vector element counts must match!");
5770     // Use FoldSetCC to simplify SETCC's.
5771     if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
5772       return V;
5773     // Vector constant folding.
5774     SDValue Ops[] = {N1, N2, N3};
5775     if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
5776       NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
5777       return V;
5778     }
5779     break;
5780   }
5781   case ISD::SELECT:
5782   case ISD::VSELECT:
5783     if (SDValue V = simplifySelect(N1, N2, N3))
5784       return V;
5785     break;
5786   case ISD::VECTOR_SHUFFLE:
5787     llvm_unreachable("should use getVectorShuffle constructor!");
5788   case ISD::INSERT_VECTOR_ELT: {
5789     ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
5790     // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF, except
5791     // for scalable vectors where we will generate appropriate code to
5792     // deal with out-of-bounds cases correctly.
5793     if (N3C && N1.getValueType().isFixedLengthVector() &&
5794         N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
5795       return getUNDEF(VT);
5796 
5797     // Undefined index can be assumed out-of-bounds, so that's UNDEF too.
5798     if (N3.isUndef())
5799       return getUNDEF(VT);
5800 
5801     // If the inserted element is an UNDEF, just use the input vector.
5802     if (N2.isUndef())
5803       return N1;
5804 
5805     break;
5806   }
5807   case ISD::INSERT_SUBVECTOR: {
5808     // Inserting undef into undef is still undef.
5809     if (N1.isUndef() && N2.isUndef())
5810       return getUNDEF(VT);
5811 
5812     EVT N2VT = N2.getValueType();
5813     assert(VT == N1.getValueType() &&
5814            "Dest and insert subvector source types must match!");
5815     assert(VT.isVector() && N2VT.isVector() &&
5816            "Insert subvector VTs must be vectors!");
5817     assert((VT.isScalableVector() || N2VT.isFixedLengthVector()) &&
5818            "Cannot insert a scalable vector into a fixed length vector!");
5819     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
5820             VT.getVectorMinNumElements() >= N2VT.getVectorMinNumElements()) &&
5821            "Insert subvector must be from smaller vector to larger vector!");
5822     assert(isa<ConstantSDNode>(N3) &&
5823            "Insert subvector index must be constant");
5824     assert((VT.isScalableVector() != N2VT.isScalableVector() ||
5825             (N2VT.getVectorMinNumElements() +
5826              cast<ConstantSDNode>(N3)->getZExtValue()) <=
5827                 VT.getVectorMinNumElements()) &&
5828            "Insert subvector overflow!");
5829 
5830     // Trivial insertion.
5831     if (VT == N2VT)
5832       return N2;
5833 
5834     // If this is an insert of an extracted vector into an undef vector, we
5835     // can just use the input to the extract.
5836     if (N1.isUndef() && N2.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
5837         N2.getOperand(1) == N3 && N2.getOperand(0).getValueType() == VT)
5838       return N2.getOperand(0);
5839     break;
5840   }
5841   case ISD::BITCAST:
5842     // Fold bit_convert nodes from a type to themselves.
5843     if (N1.getValueType() == VT)
5844       return N1;
5845     break;
5846   }
5847 
5848   // Memoize node if it doesn't produce a flag.
5849   SDNode *N;
5850   SDVTList VTs = getVTList(VT);
5851   SDValue Ops[] = {N1, N2, N3};
5852   if (VT != MVT::Glue) {
5853     FoldingSetNodeID ID;
5854     AddNodeIDNode(ID, Opcode, VTs, Ops);
5855     void *IP = nullptr;
5856     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
5857       E->intersectFlagsWith(Flags);
5858       return SDValue(E, 0);
5859     }
5860 
5861     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5862     N->setFlags(Flags);
5863     createOperands(N, Ops);
5864     CSEMap.InsertNode(N, IP);
5865   } else {
5866     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
5867     createOperands(N, Ops);
5868   }
5869 
5870   InsertNode(N);
5871   SDValue V = SDValue(N, 0);
5872   NewSDValueDbgMsg(V, "Creating new node: ", this);
5873   return V;
5874 }
5875 
getNode(unsigned Opcode,const SDLoc & DL,EVT VT,SDValue N1,SDValue N2,SDValue N3,SDValue N4)5876 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5877                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
5878   SDValue Ops[] = { N1, N2, N3, N4 };
5879   return getNode(Opcode, DL, VT, Ops);
5880 }
5881 
getNode(unsigned Opcode,const SDLoc & DL,EVT VT,SDValue N1,SDValue N2,SDValue N3,SDValue N4,SDValue N5)5882 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
5883                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
5884                               SDValue N5) {
5885   SDValue Ops[] = { N1, N2, N3, N4, N5 };
5886   return getNode(Opcode, DL, VT, Ops);
5887 }
5888 
5889 /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
5890 /// the incoming stack arguments to be loaded from the stack.
getStackArgumentTokenFactor(SDValue Chain)5891 SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
5892   SmallVector<SDValue, 8> ArgChains;
5893 
5894   // Include the original chain at the beginning of the list. When this is
5895   // used by target LowerCall hooks, this helps legalize find the
5896   // CALLSEQ_BEGIN node.
5897   ArgChains.push_back(Chain);
5898 
5899   // Add a chain value for each stack argument.
5900   for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
5901        UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
5902     if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
5903       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
5904         if (FI->getIndex() < 0)
5905           ArgChains.push_back(SDValue(L, 1));
5906 
5907   // Build a tokenfactor for all the chains.
5908   return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
5909 }
5910 
5911 /// getMemsetValue - Vectorized representation of the memset value
5912 /// operand.
getMemsetValue(SDValue Value,EVT VT,SelectionDAG & DAG,const SDLoc & dl)5913 static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
5914                               const SDLoc &dl) {
5915   assert(!Value.isUndef());
5916 
5917   unsigned NumBits = VT.getScalarSizeInBits();
5918   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
5919     assert(C->getAPIntValue().getBitWidth() == 8);
5920     APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
5921     if (VT.isInteger() || VT.isFatPointer()) {
5922       bool IsOpaque = VT.getSizeInBits() > 64 ||
5923           !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
5924       return DAG.getConstant(Val, dl, VT, false, IsOpaque);
5925     }
5926     return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
5927                              VT);
5928   }
5929 
5930   assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
5931   EVT IntVT = VT.getScalarType();
5932   if (!IntVT.isInteger())
5933     IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
5934 
5935   Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
5936   if (NumBits > 8) {
5937     // Use a multiplication with 0x010101... to extend the input to the
5938     // required length.
5939     APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
5940     Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
5941                         DAG.getConstant(Magic, dl, IntVT));
5942   }
5943 
5944   if (VT != Value.getValueType() && !VT.isInteger())
5945     Value = DAG.getBitcast(VT.getScalarType(), Value);
5946   if (VT != Value.getValueType())
5947     Value = DAG.getSplatBuildVector(VT, dl, Value);
5948 
5949   return Value;
5950 }
5951 
5952 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
5953 /// used when a memcpy is turned into a memset when the source is a constant
5954 /// string ptr.
getMemsetStringVal(EVT VT,const SDLoc & dl,SelectionDAG & DAG,const TargetLowering & TLI,const ConstantDataArraySlice & Slice)5955 static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
5956                                   const TargetLowering &TLI,
5957                                   const ConstantDataArraySlice &Slice) {
5958   // Handle vector with all elements zero.
5959   if (Slice.Array == nullptr) {
5960     if (VT.isFatPointer())
5961       return DAG.getNullCapability(dl);
5962     if (VT.isInteger())
5963       return DAG.getConstant(0, dl, VT);
5964     else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
5965       return DAG.getConstantFP(0.0, dl, VT);
5966     else if (VT.isVector()) {
5967       unsigned NumElts = VT.getVectorNumElements();
5968       MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5969       return DAG.getNode(ISD::BITCAST, dl, VT,
5970                          DAG.getConstant(0, dl,
5971                                          EVT::getVectorVT(*DAG.getContext(),
5972                                                           EltVT, NumElts)));
5973     } else
5974       llvm_unreachable("Expected type!");
5975   }
5976 
5977   assert(!VT.isVector() && "Can't handle vector type here!");
5978   unsigned NumVTBits = VT.getSizeInBits();
5979   unsigned NumVTBytes = NumVTBits / 8;
5980   unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
5981 
5982   APInt Val(NumVTBits, 0);
5983   if (DAG.getDataLayout().isLittleEndian()) {
5984     for (unsigned i = 0; i != NumBytes; ++i)
5985       Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
5986   } else {
5987     for (unsigned i = 0; i != NumBytes; ++i)
5988       Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
5989   }
5990 
5991   // If the "cost" of materializing the integer immediate is less than the cost
5992   // of a load, then it is cost effective to turn the load into the immediate.
5993   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
5994   if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
5995     return DAG.getConstant(Val, dl, VT);
5996   return SDValue(nullptr, 0);
5997 }
5998 
getMemBasePlusOffset(SDValue Base,int64_t Offset,const SDLoc & DL,const SDNodeFlags Flags)5999 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, int64_t Offset,
6000                                            const SDLoc &DL,
6001                                            const SDNodeFlags Flags) {
6002   if (Offset == 0)
6003     return Base;
6004 
6005   // For integer pointers the offset and pointer type must be identical
6006   // (otherwise we assert later). For CHERI capabilities we use the the pointer
6007   // range type as the offset type.
6008   EVT OffsetVT = Base.getValueType();
6009   if (Base.getValueType().isFatPointer()) {
6010     OffsetVT = TLI->getPointerRangeTy(getDataLayout());
6011   }
6012   return getMemBasePlusOffset(Base, getConstant(Offset, DL, OffsetVT), DL,
6013                               Flags);
6014 }
6015 
getMemBasePlusOffset(SDValue Ptr,SDValue Offset,const SDLoc & DL,const SDNodeFlags Flags)6016 SDValue SelectionDAG::getMemBasePlusOffset(SDValue Ptr, SDValue Offset,
6017                                            const SDLoc &DL,
6018                                            const SDNodeFlags Flags) {
6019   assert(Offset.getValueType().isInteger());
6020   if (auto *Constant = dyn_cast<ConstantSDNode>(Offset.getNode())) {
6021     if (Constant->isNullValue())
6022       return Ptr;
6023   }
6024   EVT BasePtrVT = Ptr.getValueType();
6025   if (BasePtrVT.isFatPointer()) {
6026     return getNode(ISD::PTRADD, DL, BasePtrVT, Ptr, Offset, Flags);
6027   }
6028   return getNode(ISD::ADD, DL, BasePtrVT, Ptr, Offset, Flags);
6029 }
6030 
6031 /// Returns true if memcpy source is constant data.
isMemSrcFromConstant(SDValue Src,ConstantDataArraySlice & Slice)6032 static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
6033   uint64_t SrcDelta = 0;
6034   GlobalAddressSDNode *G = nullptr;
6035   if (Src.getOpcode() == ISD::GlobalAddress)
6036     G = cast<GlobalAddressSDNode>(Src);
6037   else if (Src.getOpcode() == ISD::ADD &&
6038            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
6039            Src.getOperand(1).getOpcode() == ISD::Constant) {
6040     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
6041     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
6042   }
6043   if (!G)
6044     return false;
6045 
6046   return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
6047                                   SrcDelta + G->getOffset());
6048 }
6049 
shouldLowerMemFuncForSize(const MachineFunction & MF,SelectionDAG & DAG)6050 static bool shouldLowerMemFuncForSize(const MachineFunction &MF,
6051                                       SelectionDAG &DAG) {
6052   // On Darwin, -Os means optimize for size without hurting performance, so
6053   // only really optimize for size when -Oz (MinSize) is used.
6054   if (MF.getTarget().getTargetTriple().isOSDarwin())
6055     return MF.getFunction().hasMinSize();
6056   return DAG.shouldOptForSize();
6057 }
6058 
chainLoadsAndStoresForMemcpy(SelectionDAG & DAG,const SDLoc & dl,SmallVector<SDValue,32> & OutChains,unsigned From,unsigned To,SmallVector<SDValue,16> & OutLoadChains,SmallVector<SDValue,16> & OutStoreChains)6059 static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
6060                           SmallVector<SDValue, 32> &OutChains, unsigned From,
6061                           unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
6062                           SmallVector<SDValue, 16> &OutStoreChains) {
6063   assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
6064   assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
6065   SmallVector<SDValue, 16> GluedLoadChains;
6066   for (unsigned i = From; i < To; ++i) {
6067     OutChains.push_back(OutLoadChains[i]);
6068     GluedLoadChains.push_back(OutLoadChains[i]);
6069   }
6070 
6071   // Chain for all loads.
6072   SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
6073                                   GluedLoadChains);
6074 
6075   for (unsigned i = From; i < To; ++i) {
6076     StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
6077     SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
6078                                   ST->getBasePtr(), ST->getMemoryVT(),
6079                                   ST->getMemOperand());
6080     OutChains.push_back(NewStore);
6081   }
6082 }
6083 
6084 static void
diagnoseInefficientCheriMemOp(SelectionDAG & DAG,const DiagnosticLocation & Loc,const Twine & MemOp,CodeGenOpt::Level OptLevel,StringRef Type,unsigned Align,uint64_t Size,uint64_t CapSize)6085 diagnoseInefficientCheriMemOp(SelectionDAG &DAG, const DiagnosticLocation &Loc,
6086                               const Twine &MemOp, CodeGenOpt::Level OptLevel,
6087                               StringRef Type, unsigned Align, uint64_t Size,
6088                               uint64_t CapSize) {
6089   assert(Align < CapSize);
6090   assert(Size >= CapSize);
6091   if (OptLevel == CodeGenOpt::None)
6092     return; // Don't bother warning about inefficient code at -O0
6093   // Skip the memcpy/memmove diag if we have already diagnosed something else
6094   if (Type == "!!<CHERI-NODIAG>!!")
6095     return;
6096 
6097   DiagnosticInfoCheriInefficient Warning(
6098       DAG.getMachineFunction().getFunction(), Loc,
6099       MemOp + " operation with capability argument " + Type +
6100           " and underaligned destination (aligned to " + Twine(Align) +
6101           " bytes) may be inefficient or result in CHERI tags bits being "
6102           "stripped");
6103   DAG.getContext()->diagnose(Warning);
6104 }
6105 
getMemcpyLoadsAndStores(SelectionDAG & DAG,const SDLoc & dl,SDValue Chain,SDValue Dst,SDValue Src,uint64_t Size,Align Alignment,bool isVol,bool AlwaysInline,bool MustPreserveCheriCapabilities,MachinePointerInfo DstPtrInfo,MachinePointerInfo SrcPtrInfo,StringRef CopyTy,CodeGenOpt::Level OptLevel)6106 static SDValue getMemcpyLoadsAndStores(
6107     SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
6108     uint64_t Size, Align Alignment, bool isVol, bool AlwaysInline,
6109     bool MustPreserveCheriCapabilities, MachinePointerInfo DstPtrInfo,
6110     MachinePointerInfo SrcPtrInfo, StringRef CopyTy,
6111     CodeGenOpt::Level OptLevel) {
6112   // Turn a memcpy of undef to nop.
6113   // FIXME: We need to honor volatile even is Src is undef.
6114   if (Src.isUndef())
6115     return Chain;
6116 
6117   // Expand memcpy to a series of load and store ops if the size operand falls
6118   // below a certain threshold.
6119   // TODO: In the AlwaysInline case, if the size is big then generate a loop
6120   // rather than maybe a humongous number of loads and stores.
6121   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6122   const DataLayout &DL = DAG.getDataLayout();
6123   LLVMContext &C = *DAG.getContext();
6124   std::vector<EVT> MemOps;
6125   bool DstAlignCanChange = false;
6126   MachineFunction &MF = DAG.getMachineFunction();
6127   MachineFrameInfo &MFI = MF.getFrameInfo();
6128   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6129   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6130   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6131     DstAlignCanChange = true;
6132   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6133   if (!SrcAlign || Alignment > *SrcAlign)
6134     SrcAlign = Alignment;
6135   assert(SrcAlign && "SrcAlign must be set");
6136   ConstantDataArraySlice Slice;
6137   bool CopyFromConstant = isMemSrcFromConstant(Src, Slice);
6138   bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
6139   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
6140   const MemOp Op =
6141       isZeroConstant
6142           ? MemOp::Set(Size, DstAlignCanChange, Alignment,
6143                        /*IsZeroMemset*/ true, isVol)
6144           : MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign, isVol,
6145                         MustPreserveCheriCapabilities, CopyFromConstant);
6146   const bool FoundLowering = TLI.findOptimalMemOpLowering(
6147       MemOps, Limit, Op, DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6148       MF.getFunction().getAttributes());
6149   // Don't warn about inefficient memcpy if we reached the inline memcpy limit
6150   // Also don't warn about copies of less than CapSize
6151   // TODO: the frontend probably shouldn't emit must-preserve-tags for such
6152   // small memcpys
6153   auto CapTy = TLI.cheriCapabilityType();
6154   if (CapTy.isValid()) {
6155     const uint64_t CapSize = CapTy.getStoreSize();
6156     bool ReachedLimit = (CapSize * Limit) < Size;
6157     if (MustPreserveCheriCapabilities && !ReachedLimit && Size >= CapSize &&
6158         (!FoundLowering || !MemOps[0].isFatPointer())) {
6159       LLVM_DEBUG(
6160           dbgs()
6161           << " memcpy must preserve tags but value is not statically "
6162              "known to be sufficiently aligned -> using memcpy() call\n");
6163       if (AlwaysInline) {
6164         report_fatal_error("MustPreserveCheriCapabilities and AlwaysInline set "
6165                            "but operation cannot be lowered to loads+stores!");
6166       }
6167       diagnoseInefficientCheriMemOp(
6168           DAG, dl.getDebugLoc(), "memcpy", OptLevel,
6169           CopyTy.empty() ? "<unknown type>" : CopyTy,
6170           std::max((uint64_t)1, std::min(Alignment, *SrcAlign).value()), Size,
6171           CapSize);
6172       return SDValue();
6173     }
6174   }
6175   if (!FoundLowering)
6176     return SDValue();
6177 
6178   if (DstAlignCanChange) {
6179     Type *Ty = MemOps[0].getTypeForEVT(C);
6180     LLVM_DEBUG(dbgs() << " DstAlignCanChange -> using type "; Ty->dump());
6181     Align NewAlign = DL.getABITypeAlign(Ty);
6182     LLVM_DEBUG(dbgs() << "\t->NewAlign = " << NewAlign.value() << ", stack alignment="
6183                       << DL.getStackAlignment().value() << "\n");
6184     if (MemOps[0].isFatPointer()) {
6185       assert(!DL.exceedsNaturalStackAlignment(NewAlign) &&
6186              "Stack not capability-aligned?");
6187     }
6188 
6189     // Don't promote to an alignment that would require dynamic stack
6190     // realignment.
6191     const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
6192     if (!TRI->needsStackRealignment(MF))
6193       while (NewAlign > Alignment && DL.exceedsNaturalStackAlignment(NewAlign))
6194         NewAlign = NewAlign / 2;
6195 
6196     if (MemOps[0].isFatPointer()) {
6197       assert(NewAlign == DL.getABITypeAlignment(Ty) &&
6198              "Stack not capability-aligned?");
6199     }
6200     if (NewAlign > Alignment) {
6201       // Give the stack frame object a larger alignment if needed.
6202       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6203         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6204       Alignment = NewAlign;
6205     }
6206   }
6207 
6208   MachineMemOperand::Flags MMOFlags =
6209       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6210   SmallVector<SDValue, 16> OutLoadChains;
6211   SmallVector<SDValue, 16> OutStoreChains;
6212   SmallVector<SDValue, 32> OutChains;
6213   unsigned NumMemOps = MemOps.size();
6214   uint64_t SrcOff = 0, DstOff = 0;
6215   for (unsigned i = 0; i != NumMemOps; ++i) {
6216     EVT VT = MemOps[i];
6217     unsigned VTSize = VT.getSizeInBits() / 8;
6218     SDValue Value, Store;
6219 
6220     if (VTSize > Size) {
6221       // Issuing an unaligned load / store pair  that overlaps with the previous
6222       // pair. Adjust the offset accordingly.
6223       assert(i == NumMemOps-1 && i != 0);
6224       SrcOff -= VTSize - Size;
6225       DstOff -= VTSize - Size;
6226     }
6227 
6228     if (CopyFromConstant &&
6229         (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
6230       // It's unlikely a store of a vector immediate can be done in a single
6231       // instruction. It would require a load from a constantpool first.
6232       // We only handle zero vectors here.
6233       // FIXME: Handle other cases where store of vector immediate is done in
6234       // a single instruction.
6235       ConstantDataArraySlice SubSlice;
6236       if (SrcOff < Slice.Length) {
6237         SubSlice = Slice;
6238         SubSlice.move(SrcOff);
6239       } else {
6240         // This is an out-of-bounds access and hence UB. Pretend we read zero.
6241         SubSlice.Array = nullptr;
6242         SubSlice.Offset = 0;
6243         SubSlice.Length = VTSize;
6244       }
6245       Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
6246       if (Value.getNode()) {
6247         Store = DAG.getStore(
6248             Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
6249             DstPtrInfo.getWithOffset(DstOff), Alignment.value(), MMOFlags);
6250         OutChains.push_back(Store);
6251       }
6252     }
6253 
6254     if (!Store.getNode()) {
6255       // The type might not be legal for the target.  This should only happen
6256       // if the type is smaller than a legal type, as on PPC, so the right
6257       // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
6258       // to Load/Store if NVT==VT.
6259       // FIXME does the case above also need this?
6260       EVT NVT = TLI.getTypeToTransformTo(C, VT);
6261       assert(NVT.bitsGE(VT));
6262 
6263       bool isDereferenceable =
6264         SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6265       MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6266       if (isDereferenceable)
6267         SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6268 
6269       Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
6270                              DAG.getMemBasePlusOffset(Src, SrcOff, dl),
6271                              SrcPtrInfo.getWithOffset(SrcOff), VT,
6272                              commonAlignment(*SrcAlign, SrcOff).value(),
6273                              SrcMMOFlags);
6274       OutLoadChains.push_back(Value.getValue(1));
6275 
6276       Store = DAG.getTruncStore(
6277           Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
6278           DstPtrInfo.getWithOffset(DstOff), VT, Alignment.value(), MMOFlags);
6279       OutStoreChains.push_back(Store);
6280     }
6281     SrcOff += VTSize;
6282     DstOff += VTSize;
6283     Size -= VTSize;
6284   }
6285 
6286   unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
6287                                 TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
6288   unsigned NumLdStInMemcpy = OutStoreChains.size();
6289 
6290   if (NumLdStInMemcpy) {
6291     // It may be that memcpy might be converted to memset if it's memcpy
6292     // of constants. In such a case, we won't have loads and stores, but
6293     // just stores. In the absence of loads, there is nothing to gang up.
6294     if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
6295       // If target does not care, just leave as it.
6296       for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
6297         OutChains.push_back(OutLoadChains[i]);
6298         OutChains.push_back(OutStoreChains[i]);
6299       }
6300     } else {
6301       // Ld/St less than/equal limit set by target.
6302       if (NumLdStInMemcpy <= GluedLdStLimit) {
6303           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6304                                         NumLdStInMemcpy, OutLoadChains,
6305                                         OutStoreChains);
6306       } else {
6307         unsigned NumberLdChain =  NumLdStInMemcpy / GluedLdStLimit;
6308         unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
6309         unsigned GlueIter = 0;
6310 
6311         for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
6312           unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
6313           unsigned IndexTo   = NumLdStInMemcpy - GlueIter;
6314 
6315           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
6316                                        OutLoadChains, OutStoreChains);
6317           GlueIter += GluedLdStLimit;
6318         }
6319 
6320         // Residual ld/st.
6321         if (RemainingLdStInMemcpy) {
6322           chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
6323                                         RemainingLdStInMemcpy, OutLoadChains,
6324                                         OutStoreChains);
6325         }
6326       }
6327     }
6328   }
6329   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6330 }
6331 
getMemmoveLoadsAndStores(SelectionDAG & DAG,const SDLoc & dl,SDValue Chain,SDValue Dst,SDValue Src,uint64_t Size,Align Alignment,bool isVol,bool AlwaysInline,bool MustPreserveCheriCapabilities,MachinePointerInfo DstPtrInfo,MachinePointerInfo SrcPtrInfo,StringRef MoveTy,CodeGenOpt::Level OptLevel)6332 static SDValue getMemmoveLoadsAndStores(
6333     SelectionDAG &DAG, const SDLoc &dl, SDValue Chain, SDValue Dst, SDValue Src,
6334     uint64_t Size, Align Alignment, bool isVol, bool AlwaysInline,
6335     bool MustPreserveCheriCapabilities, MachinePointerInfo DstPtrInfo,
6336     MachinePointerInfo SrcPtrInfo, StringRef MoveTy,
6337     CodeGenOpt::Level OptLevel) {
6338   // Turn a memmove of undef to nop.
6339   // FIXME: We need to honor volatile even is Src is undef.
6340   if (Src.isUndef())
6341     return Chain;
6342 
6343   // Expand memmove to a series of load and store ops if the size operand falls
6344   // below a certain threshold.
6345   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6346   const DataLayout &DL = DAG.getDataLayout();
6347   LLVMContext &C = *DAG.getContext();
6348   std::vector<EVT> MemOps;
6349   bool DstAlignCanChange = false;
6350   MachineFunction &MF = DAG.getMachineFunction();
6351   MachineFrameInfo &MFI = MF.getFrameInfo();
6352   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6353   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6354   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6355     DstAlignCanChange = true;
6356   MaybeAlign SrcAlign = DAG.InferPtrAlign(Src);
6357   if (!SrcAlign || Alignment > *SrcAlign)
6358     SrcAlign = Alignment;
6359   assert(SrcAlign && "SrcAlign must be set");
6360   unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
6361   const bool FoundLowering = TLI.findOptimalMemOpLowering(
6362       MemOps, Limit,
6363       MemOp::Copy(Size, DstAlignCanChange, Alignment, *SrcAlign,
6364                   /*IsVolatile*/ true, MustPreserveCheriCapabilities),
6365       DstPtrInfo.getAddrSpace(), SrcPtrInfo.getAddrSpace(),
6366       MF.getFunction().getAttributes());
6367 
6368   // Don't warn about inefficient memcpy if we reached the inline memmove limit
6369   // Also don't warn about copies of less than CapSize
6370   // TODO: the frontend probably shouldn't emit must-preserve-tags for such
6371   // small memcpys
6372   auto CapTy = TLI.cheriCapabilityType();
6373   if (CapTy.isValid()) {
6374     const uint64_t CapSize = CapTy.getStoreSize();
6375     bool ReachedLimit = (CapSize * Limit) < Size;
6376     if (MustPreserveCheriCapabilities && !ReachedLimit && Size >= CapSize &&
6377         (!FoundLowering || !MemOps[0].isFatPointer())) {
6378       LLVM_DEBUG(
6379           dbgs()
6380           << __func__
6381           << " memmove must preserve tags but value is not statically "
6382              "known to be sufficiently aligned -> using memmove() call\n");
6383       if (AlwaysInline) {
6384         report_fatal_error("MustPreserveCheriCapabilities and AlwaysInline set "
6385                            "but operation cannot be lowered to loads+stores!");
6386       }
6387       diagnoseInefficientCheriMemOp(
6388           DAG, dl.getDebugLoc(), "memmove", OptLevel,
6389           MoveTy.empty() ? "<unknown type>" : MoveTy,
6390           std::max(Align(1), std::min(Alignment, *SrcAlign)).value(), Size,
6391           CapSize);
6392       return SDValue();
6393     }
6394   }
6395   if (!FoundLowering)
6396     return SDValue();
6397 
6398   if (DstAlignCanChange) {
6399     Type *Ty = MemOps[0].getTypeForEVT(C);
6400     Align NewAlign = DL.getABITypeAlign(Ty);
6401     if (MemOps[0].isFatPointer()) {
6402       assert(!DL.exceedsNaturalStackAlignment(NewAlign) &&
6403              "Stack not capability-aligned?");
6404     }
6405     if (NewAlign > Alignment) {
6406       // Give the stack frame object a larger alignment if needed.
6407       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6408         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6409       Alignment = NewAlign;
6410     }
6411   }
6412 
6413   MachineMemOperand::Flags MMOFlags =
6414       isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
6415   uint64_t SrcOff = 0, DstOff = 0;
6416   SmallVector<SDValue, 8> LoadValues;
6417   SmallVector<SDValue, 8> LoadChains;
6418   SmallVector<SDValue, 8> OutChains;
6419   unsigned NumMemOps = MemOps.size();
6420   for (unsigned i = 0; i < NumMemOps; i++) {
6421     EVT VT = MemOps[i];
6422     unsigned VTSize = VT.getSizeInBits() / 8;
6423     SDValue Value;
6424 
6425     bool isDereferenceable =
6426       SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
6427     MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
6428     if (isDereferenceable)
6429       SrcMMOFlags |= MachineMemOperand::MODereferenceable;
6430 
6431     Value = DAG.getLoad(
6432         VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
6433         SrcPtrInfo.getWithOffset(SrcOff), SrcAlign->value(), SrcMMOFlags);
6434     LoadValues.push_back(Value);
6435     LoadChains.push_back(Value.getValue(1));
6436     SrcOff += VTSize;
6437   }
6438   Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
6439   OutChains.clear();
6440   for (unsigned i = 0; i < NumMemOps; i++) {
6441     EVT VT = MemOps[i];
6442     unsigned VTSize = VT.getSizeInBits() / 8;
6443     SDValue Store;
6444 
6445     Store = DAG.getStore(
6446         Chain, dl, LoadValues[i], DAG.getMemBasePlusOffset(Dst, DstOff, dl),
6447         DstPtrInfo.getWithOffset(DstOff), Alignment.value(), MMOFlags);
6448     OutChains.push_back(Store);
6449     DstOff += VTSize;
6450   }
6451 
6452   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6453 }
6454 
6455 /// Lower the call to 'memset' intrinsic function into a series of store
6456 /// operations.
6457 ///
6458 /// \param DAG Selection DAG where lowered code is placed.
6459 /// \param dl Link to corresponding IR location.
6460 /// \param Chain Control flow dependency.
6461 /// \param Dst Pointer to destination memory location.
6462 /// \param Src Value of byte to write into the memory.
6463 /// \param Size Number of bytes to write.
6464 /// \param Alignment Alignment of the destination in bytes.
6465 /// \param isVol True if destination is volatile.
6466 /// \param DstPtrInfo IR information on the memory pointer.
6467 /// \returns New head in the control flow, if lowering was successful, empty
6468 /// SDValue otherwise.
6469 ///
6470 /// The function tries to replace 'llvm.memset' intrinsic with several store
6471 /// operations and value calculation code. This is usually profitable for small
6472 /// memory size.
getMemsetStores(SelectionDAG & DAG,const SDLoc & dl,SDValue Chain,SDValue Dst,SDValue Src,uint64_t Size,Align Alignment,bool isVol,MachinePointerInfo DstPtrInfo)6473 static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
6474                                SDValue Chain, SDValue Dst, SDValue Src,
6475                                uint64_t Size, Align Alignment, bool isVol,
6476                                MachinePointerInfo DstPtrInfo) {
6477   // Turn a memset of undef to nop.
6478   // FIXME: We need to honor volatile even is Src is undef.
6479   if (Src.isUndef())
6480     return Chain;
6481 
6482   // Expand memset to a series of load/store ops if the size operand
6483   // falls below a certain threshold.
6484   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6485   std::vector<EVT> MemOps;
6486   bool DstAlignCanChange = false;
6487   MachineFunction &MF = DAG.getMachineFunction();
6488   MachineFrameInfo &MFI = MF.getFrameInfo();
6489   bool OptSize = shouldLowerMemFuncForSize(MF, DAG);
6490   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
6491   if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
6492     DstAlignCanChange = true;
6493   bool IsZeroVal =
6494     isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
6495   if (!TLI.findOptimalMemOpLowering(
6496           MemOps, TLI.getMaxStoresPerMemset(OptSize),
6497           MemOp::Set(Size, DstAlignCanChange, Alignment, IsZeroVal, isVol),
6498           DstPtrInfo.getAddrSpace(), ~0u, MF.getFunction().getAttributes()))
6499     return SDValue();
6500 
6501   if (DstAlignCanChange) {
6502     Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
6503     Align NewAlign = DAG.getDataLayout().getABITypeAlign(Ty);
6504     if (MemOps[0].isFatPointer()) {
6505       assert(!DAG.getDataLayout().exceedsNaturalStackAlignment(NewAlign) &&
6506              "Stack not capability-aligned?");
6507     }
6508     if (NewAlign > Alignment) {
6509       // Give the stack frame object a larger alignment if needed.
6510       if (MFI.getObjectAlign(FI->getIndex()) < NewAlign)
6511         MFI.setObjectAlignment(FI->getIndex(), NewAlign);
6512       Alignment = NewAlign;
6513     }
6514   }
6515 
6516   SmallVector<SDValue, 8> OutChains;
6517   uint64_t DstOff = 0;
6518   unsigned NumMemOps = MemOps.size();
6519 
6520   // Find the largest store and generate the bit pattern for it.
6521   EVT LargestVT = MemOps[0];
6522   for (unsigned i = 1; i < NumMemOps; i++)
6523     if (MemOps[i].bitsGT(LargestVT))
6524       LargestVT = MemOps[i];
6525   SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
6526 
6527   for (unsigned i = 0; i < NumMemOps; i++) {
6528     EVT VT = MemOps[i];
6529     unsigned VTSize = VT.getSizeInBits() / 8;
6530     if (VTSize > Size) {
6531       // Issuing an unaligned load / store pair  that overlaps with the previous
6532       // pair. Adjust the offset accordingly.
6533       assert(i == NumMemOps-1 && i != 0);
6534       DstOff -= VTSize - Size;
6535     }
6536 
6537     // If this store is smaller than the largest store see whether we can get
6538     // the smaller value for free with a truncate.
6539     SDValue Value = MemSetValue;
6540     if (VT.bitsLT(LargestVT)) {
6541       if (!LargestVT.isVector() && !VT.isVector() &&
6542           TLI.isTruncateFree(LargestVT, VT))
6543         Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
6544       else
6545         Value = getMemsetValue(Src, VT, DAG, dl);
6546     }
6547     assert(Value.getValueType() == VT && "Value with wrong type.");
6548     SDValue Store = DAG.getStore(
6549         Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
6550         DstPtrInfo.getWithOffset(DstOff), Alignment.value(),
6551         isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
6552     OutChains.push_back(Store);
6553     DstOff += VT.getSizeInBits() / 8;
6554     Size -= VTSize;
6555   }
6556 
6557   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
6558 }
6559 
getCSetBounds(SDValue Val,const SDLoc & DL,SDValue Length,Align Alignment,StringRef Pass,cheri::SetBoundsPointerSource Kind,const Twine & Details,std::string SrcLoc)6560 SDValue SelectionDAG::getCSetBounds(SDValue Val, const SDLoc &DL,
6561                                     SDValue Length, Align Alignment,
6562                                     StringRef Pass,
6563                                     cheri::SetBoundsPointerSource Kind,
6564                                     const Twine &Details, std::string SrcLoc) {
6565   if (cheri::ShouldCollectCSetBoundsStats) {
6566     Optional<uint64_t> SizeConst;
6567     if (ConstantSDNode *Constant = dyn_cast<ConstantSDNode>(Length.getNode())) {
6568       SizeConst = Constant->getZExtValue();
6569     }
6570     if (SrcLoc.empty()) {
6571       SrcLoc = cheri::inferSourceLocation(DL.getDebugLoc(),
6572                                           getMachineFunction().getName());
6573     }
6574     cheri::CSetBoundsStats->add(Alignment, SizeConst, Pass, Kind, Details,
6575                                 SrcLoc);
6576   }
6577   Intrinsic::ID SetBounds = Intrinsic::cheri_cap_bounds_set;
6578   // Using the bounded stack cap intrinisic allows reuse of the same register:
6579   if (isa<FrameIndexSDNode>(Val.getNode()))
6580     SetBounds = Intrinsic::cheri_bounded_stack_cap;
6581   MVT SizeVT = MVT::getIntegerVT(getDataLayout().getPointerSizeInBits(0));
6582   return getNode(ISD::INTRINSIC_WO_CHAIN, DL, Val.getValueType(),
6583                  getConstant(SetBounds, DL, SizeVT), Val, Length);
6584 }
6585 
checkAddrSpaceIsValidForLibcall(const TargetLowering * TLI,unsigned AS)6586 static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
6587                                             unsigned AS) {
6588   // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
6589   // pointer operands can be losslessly bitcasted to pointers of address space 0
6590   if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
6591     report_fatal_error("cannot lower memory intrinsic in address space " +
6592                        Twine(AS));
6593   }
6594 }
6595 
getMemcpy(SDValue Chain,const SDLoc & dl,SDValue Dst,SDValue Src,SDValue Size,Align Alignment,bool isVol,bool AlwaysInline,bool isTailCall,bool MustPreserveCheriCapabilities,MachinePointerInfo DstPtrInfo,MachinePointerInfo SrcPtrInfo,StringRef CopyType)6596 SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
6597                                 SDValue Src, SDValue Size, Align Alignment,
6598                                 bool isVol, bool AlwaysInline, bool isTailCall,
6599                                 bool MustPreserveCheriCapabilities,
6600                                 MachinePointerInfo DstPtrInfo,
6601                                 MachinePointerInfo SrcPtrInfo,
6602                                 StringRef CopyType) {
6603   LLVM_DEBUG(dbgs() << "DAG.getMemcpy() align=" << Alignment.value()
6604                     << " size=";
6605              Size.dump(););
6606   // Check to see if we should lower the memcpy to loads and stores first.
6607   // For cases within the target-specified limits, this is the best choice.
6608   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6609   if (MustPreserveCheriCapabilities)
6610     assert(TLI->cheriCapabilityType().isValid());
6611   if (ConstantSize) {
6612     // Memcpy with size zero? Just return the original chain.
6613     if (ConstantSize->isNullValue())
6614       return Chain;
6615 
6616     SDValue Result = getMemcpyLoadsAndStores(
6617         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
6618         Alignment, isVol, false, MustPreserveCheriCapabilities,
6619         DstPtrInfo, SrcPtrInfo, CopyType, OptLevel);
6620     if (Result.getNode())
6621       return Result;
6622   }
6623 
6624   // Then check to see if we should lower the memcpy with target-specific
6625   // code. If the target chooses to do this, this is the next best.
6626   if (TSI) {
6627     SDValue Result = TSI->EmitTargetCodeForMemcpy(
6628         *this, dl, Chain, Dst, Src, Size, Alignment, isVol,
6629         AlwaysInline, MustPreserveCheriCapabilities, DstPtrInfo, SrcPtrInfo);
6630     if (Result.getNode())
6631       return Result;
6632   }
6633 
6634   // If we really need inline code and the target declined to provide it,
6635   // use a (potentially long) sequence of loads and stores.
6636   if (AlwaysInline) {
6637     assert(ConstantSize && "AlwaysInline requires a constant size!");
6638     return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
6639                                    ConstantSize->getZExtValue(), Alignment,
6640                                    isVol, true, MustPreserveCheriCapabilities,
6641                                    DstPtrInfo, SrcPtrInfo, CopyType, OptLevel);
6642   }
6643 
6644   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6645   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6646 
6647   // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
6648   // memcpy is not guaranteed to be safe. libc memcpys aren't required to
6649   // respect volatile, so they may do things like read or write memory
6650   // beyond the given memory regions. But fixing this isn't easy, and most
6651   // people don't care.
6652 
6653   // Emit a library call.
6654   TargetLowering::ArgListTy Args;
6655   TargetLowering::ArgListEntry Entry;
6656   Entry.Ty = Dst.getValueType().getTypeForEVT(*getContext());
6657   Entry.Node = Dst; Args.push_back(Entry);
6658   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
6659   Entry.Node = Src; Args.push_back(Entry);
6660 
6661   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6662   Entry.Node = Size; Args.push_back(Entry);
6663   // FIXME: pass in SDLoc
6664   TargetLowering::CallLoweringInfo CLI(*this);
6665   CLI.setDebugLoc(dl)
6666       .setChain(Chain)
6667       .setLibCallee(
6668           TLI->getLibcallCallingConv(RTLIB::MEMCPY),
6669           Dst.getValueType().getTypeForEVT(*getContext()),
6670           getExternalFunctionSymbol(TLI->getLibcallName(RTLIB::MEMCPY)),
6671           std::move(Args))
6672       .setDiscardResult()
6673       .setTailCall(isTailCall);
6674 
6675   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6676   return CallResult.second;
6677 }
6678 
getAtomicMemcpy(SDValue Chain,const SDLoc & dl,SDValue Dst,unsigned DstAlign,SDValue Src,unsigned SrcAlign,SDValue Size,Type * SizeTy,unsigned ElemSz,bool isTailCall,MachinePointerInfo DstPtrInfo,MachinePointerInfo SrcPtrInfo)6679 SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
6680                                       SDValue Dst, unsigned DstAlign,
6681                                       SDValue Src, unsigned SrcAlign,
6682                                       SDValue Size, Type *SizeTy,
6683                                       unsigned ElemSz, bool isTailCall,
6684                                       MachinePointerInfo DstPtrInfo,
6685                                       MachinePointerInfo SrcPtrInfo) {
6686   // Emit a library call.
6687   TargetLowering::ArgListTy Args;
6688   TargetLowering::ArgListEntry Entry;
6689   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6690   Entry.Node = Dst;
6691   Args.push_back(Entry);
6692 
6693   Entry.Node = Src;
6694   Args.push_back(Entry);
6695 
6696   Entry.Ty = SizeTy;
6697   Entry.Node = Size;
6698   Args.push_back(Entry);
6699 
6700   RTLIB::Libcall LibraryCall =
6701       RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6702   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6703     report_fatal_error("Unsupported element size");
6704 
6705   TargetLowering::CallLoweringInfo CLI(*this);
6706   CLI.setDebugLoc(dl)
6707       .setChain(Chain)
6708       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6709                     Type::getVoidTy(*getContext()),
6710                     getExternalFunctionSymbol(TLI->getLibcallName(LibraryCall)),
6711                     std::move(Args))
6712       .setDiscardResult()
6713       .setTailCall(isTailCall);
6714 
6715   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6716   return CallResult.second;
6717 }
6718 
getMemmove(SDValue Chain,const SDLoc & dl,SDValue Dst,SDValue Src,SDValue Size,Align Alignment,bool isVol,bool isTailCall,bool MustPreserveCheriCapabilities,MachinePointerInfo DstPtrInfo,MachinePointerInfo SrcPtrInfo,StringRef MoveType)6719 SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
6720                                  SDValue Src, SDValue Size, Align Alignment,
6721                                  bool isVol, bool isTailCall,
6722                                  bool MustPreserveCheriCapabilities,
6723                                  MachinePointerInfo DstPtrInfo,
6724                                  MachinePointerInfo SrcPtrInfo,
6725                                  StringRef MoveType) {
6726 
6727   // Check to see if we should lower the memmove to loads and stores first.
6728   // For cases within the target-specified limits, this is the best choice.
6729   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6730   if (ConstantSize) {
6731     // Memmove with size zero? Just return the original chain.
6732     if (ConstantSize->isNullValue())
6733       return Chain;
6734 
6735     SDValue Result = getMemmoveLoadsAndStores(
6736         *this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(), Alignment,
6737         isVol, false, MustPreserveCheriCapabilities, DstPtrInfo, SrcPtrInfo,
6738         MoveType, OptLevel);
6739     if (Result.getNode())
6740       return Result;
6741   }
6742 
6743   // Then check to see if we should lower the memmove with target-specific
6744   // code. If the target chooses to do this, this is the next best.
6745   if (TSI) {
6746     SDValue Result = TSI->EmitTargetCodeForMemmove(
6747         *this, dl, Chain, Dst, Src, Size, Alignment, isVol,
6748         MustPreserveCheriCapabilities, DstPtrInfo, SrcPtrInfo);
6749     if (Result.getNode())
6750       return Result;
6751   }
6752 
6753   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6754   checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
6755 
6756   // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
6757   // not be safe.  See memcpy above for more details.
6758 
6759   // Emit a library call.
6760   TargetLowering::ArgListTy Args;
6761   TargetLowering::ArgListEntry Entry;
6762   Entry.Ty = Dst.getValueType().getTypeForEVT(*getContext());
6763   Entry.Node = Dst; Args.push_back(Entry);
6764   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
6765   Entry.Node = Src; Args.push_back(Entry);
6766 
6767   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6768   Entry.Node = Size; Args.push_back(Entry);
6769   // FIXME:  pass in SDLoc
6770   TargetLowering::CallLoweringInfo CLI(*this);
6771   CLI.setDebugLoc(dl)
6772       .setChain(Chain)
6773       .setLibCallee(
6774           TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
6775           Dst.getValueType().getTypeForEVT(*getContext()),
6776           getExternalFunctionSymbol(TLI->getLibcallName(RTLIB::MEMMOVE)),
6777           std::move(Args))
6778       .setDiscardResult()
6779       .setTailCall(isTailCall);
6780 
6781   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6782   return CallResult.second;
6783 }
6784 
getAtomicMemmove(SDValue Chain,const SDLoc & dl,SDValue Dst,unsigned DstAlign,SDValue Src,unsigned SrcAlign,SDValue Size,Type * SizeTy,unsigned ElemSz,bool isTailCall,MachinePointerInfo DstPtrInfo,MachinePointerInfo SrcPtrInfo)6785 SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
6786                                        SDValue Dst, unsigned DstAlign,
6787                                        SDValue Src, unsigned SrcAlign,
6788                                        SDValue Size, Type *SizeTy,
6789                                        unsigned ElemSz, bool isTailCall,
6790                                        MachinePointerInfo DstPtrInfo,
6791                                        MachinePointerInfo SrcPtrInfo) {
6792   // Emit a library call.
6793   TargetLowering::ArgListTy Args;
6794   TargetLowering::ArgListEntry Entry;
6795   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6796   Entry.Node = Dst;
6797   Args.push_back(Entry);
6798 
6799   Entry.Node = Src;
6800   Args.push_back(Entry);
6801 
6802   Entry.Ty = SizeTy;
6803   Entry.Node = Size;
6804   Args.push_back(Entry);
6805 
6806   RTLIB::Libcall LibraryCall =
6807       RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6808   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6809     report_fatal_error("Unsupported element size");
6810 
6811   TargetLowering::CallLoweringInfo CLI(*this);
6812   CLI.setDebugLoc(dl)
6813       .setChain(Chain)
6814       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6815                     Type::getVoidTy(*getContext()),
6816                     getExternalFunctionSymbol(TLI->getLibcallName(LibraryCall)),
6817                     std::move(Args))
6818       .setDiscardResult()
6819       .setTailCall(isTailCall);
6820 
6821   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6822   return CallResult.second;
6823 }
6824 
getMemset(SDValue Chain,const SDLoc & dl,SDValue Dst,SDValue Src,SDValue Size,Align Alignment,bool isVol,bool isTailCall,MachinePointerInfo DstPtrInfo)6825 SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
6826                                 SDValue Src, SDValue Size, Align Alignment,
6827                                 bool isVol, bool isTailCall,
6828                                 MachinePointerInfo DstPtrInfo) {
6829   // Check to see if we should lower the memset to stores first.
6830   // For cases within the target-specified limits, this is the best choice.
6831   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
6832   if (ConstantSize) {
6833     // Memset with size zero? Just return the original chain.
6834     if (ConstantSize->isNullValue())
6835       return Chain;
6836 
6837     SDValue Result = getMemsetStores(*this, dl, Chain, Dst, Src,
6838                                      ConstantSize->getZExtValue(), Alignment,
6839                                      isVol, DstPtrInfo);
6840 
6841     if (Result.getNode())
6842       return Result;
6843   }
6844 
6845   // Then check to see if we should lower the memset with target-specific
6846   // code. If the target chooses to do this, this is the next best.
6847   if (TSI) {
6848     SDValue Result = TSI->EmitTargetCodeForMemset(
6849         *this, dl, Chain, Dst, Src, Size, Alignment, isVol, DstPtrInfo);
6850     if (Result.getNode())
6851       return Result;
6852   }
6853 
6854   checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
6855 
6856   // Emit a library call.
6857   TargetLowering::ArgListTy Args;
6858   TargetLowering::ArgListEntry Entry;
6859   Entry.Node = Dst; Entry.Ty = Dst.getValueType().getTypeForEVT(*getContext());
6860   Args.push_back(Entry);
6861   Entry.Node = Src;
6862   Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
6863   Args.push_back(Entry);
6864   Entry.Node = Size;
6865   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6866   Args.push_back(Entry);
6867 
6868   // FIXME: pass in SDLoc
6869   TargetLowering::CallLoweringInfo CLI(*this);
6870   CLI.setDebugLoc(dl)
6871       .setChain(Chain)
6872       .setLibCallee(
6873           TLI->getLibcallCallingConv(RTLIB::MEMSET),
6874           Dst.getValueType().getTypeForEVT(*getContext()),
6875           getExternalFunctionSymbol(TLI->getLibcallName(RTLIB::MEMSET)),
6876           std::move(Args))
6877       .setDiscardResult()
6878       .setTailCall(isTailCall);
6879 
6880   std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
6881   return CallResult.second;
6882 }
6883 
getAtomicMemset(SDValue Chain,const SDLoc & dl,SDValue Dst,unsigned DstAlign,SDValue Value,SDValue Size,Type * SizeTy,unsigned ElemSz,bool isTailCall,MachinePointerInfo DstPtrInfo)6884 SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
6885                                       SDValue Dst, unsigned DstAlign,
6886                                       SDValue Value, SDValue Size, Type *SizeTy,
6887                                       unsigned ElemSz, bool isTailCall,
6888                                       MachinePointerInfo DstPtrInfo) {
6889   // Emit a library call.
6890   TargetLowering::ArgListTy Args;
6891   TargetLowering::ArgListEntry Entry;
6892   Entry.Ty = getDataLayout().getIntPtrType(*getContext());
6893   Entry.Node = Dst;
6894   Args.push_back(Entry);
6895 
6896   Entry.Ty = Type::getInt8Ty(*getContext());
6897   Entry.Node = Value;
6898   Args.push_back(Entry);
6899 
6900   Entry.Ty = SizeTy;
6901   Entry.Node = Size;
6902   Args.push_back(Entry);
6903 
6904   RTLIB::Libcall LibraryCall =
6905       RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
6906   if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
6907     report_fatal_error("Unsupported element size");
6908 
6909   TargetLowering::CallLoweringInfo CLI(*this);
6910   CLI.setDebugLoc(dl)
6911       .setChain(Chain)
6912       .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
6913                     Type::getVoidTy(*getContext()),
6914                     getExternalFunctionSymbol(TLI->getLibcallName(LibraryCall)),
6915                     std::move(Args))
6916       .setDiscardResult()
6917       .setTailCall(isTailCall);
6918 
6919   std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
6920   return CallResult.second;
6921 }
6922 
getAtomic(unsigned Opcode,const SDLoc & dl,EVT MemVT,SDVTList VTList,ArrayRef<SDValue> Ops,MachineMemOperand * MMO)6923 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6924                                 SDVTList VTList, ArrayRef<SDValue> Ops,
6925                                 MachineMemOperand *MMO) {
6926   FoldingSetNodeID ID;
6927   ID.AddInteger(MemVT.getRawBits());
6928   AddNodeIDNode(ID, Opcode, VTList, Ops);
6929   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
6930   void* IP = nullptr;
6931   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
6932     cast<AtomicSDNode>(E)->refineAlignment(MMO);
6933     return SDValue(E, 0);
6934   }
6935 
6936   auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
6937                                     VTList, MemVT, MMO);
6938   createOperands(N, Ops);
6939 
6940   CSEMap.InsertNode(N, IP);
6941   InsertNode(N);
6942   return SDValue(N, 0);
6943 }
6944 
getAtomicCmpSwap(unsigned Opcode,const SDLoc & dl,EVT MemVT,SDVTList VTs,SDValue Chain,SDValue Ptr,SDValue Cmp,SDValue Swp,MachineMemOperand * MMO)6945 SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
6946                                        EVT MemVT, SDVTList VTs, SDValue Chain,
6947                                        SDValue Ptr, SDValue Cmp, SDValue Swp,
6948                                        MachineMemOperand *MMO) {
6949   assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
6950          Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
6951   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
6952 
6953   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
6954   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6955 }
6956 
getAtomic(unsigned Opcode,const SDLoc & dl,EVT MemVT,SDValue Chain,SDValue Ptr,SDValue Val,MachineMemOperand * MMO)6957 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6958                                 SDValue Chain, SDValue Ptr, SDValue Val,
6959                                 MachineMemOperand *MMO) {
6960   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
6961           Opcode == ISD::ATOMIC_LOAD_SUB ||
6962           Opcode == ISD::ATOMIC_LOAD_AND ||
6963           Opcode == ISD::ATOMIC_LOAD_CLR ||
6964           Opcode == ISD::ATOMIC_LOAD_OR ||
6965           Opcode == ISD::ATOMIC_LOAD_XOR ||
6966           Opcode == ISD::ATOMIC_LOAD_NAND ||
6967           Opcode == ISD::ATOMIC_LOAD_MIN ||
6968           Opcode == ISD::ATOMIC_LOAD_MAX ||
6969           Opcode == ISD::ATOMIC_LOAD_UMIN ||
6970           Opcode == ISD::ATOMIC_LOAD_UMAX ||
6971           Opcode == ISD::ATOMIC_LOAD_FADD ||
6972           Opcode == ISD::ATOMIC_LOAD_FSUB ||
6973           Opcode == ISD::ATOMIC_SWAP ||
6974           Opcode == ISD::ATOMIC_STORE) &&
6975          "Invalid Atomic Op");
6976 
6977   EVT VT = Val.getValueType();
6978 
6979   SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
6980                                                getVTList(VT, MVT::Other);
6981   SDValue Ops[] = {Chain, Ptr, Val};
6982   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6983 }
6984 
getAtomic(unsigned Opcode,const SDLoc & dl,EVT MemVT,EVT VT,SDValue Chain,SDValue Ptr,MachineMemOperand * MMO)6985 SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
6986                                 EVT VT, SDValue Chain, SDValue Ptr,
6987                                 MachineMemOperand *MMO) {
6988   assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
6989 
6990   SDVTList VTs = getVTList(VT, MVT::Other);
6991   SDValue Ops[] = {Chain, Ptr};
6992   return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
6993 }
6994 
6995 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
getMergeValues(ArrayRef<SDValue> Ops,const SDLoc & dl)6996 SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
6997   if (Ops.size() == 1)
6998     return Ops[0];
6999 
7000   SmallVector<EVT, 4> VTs;
7001   VTs.reserve(Ops.size());
7002   for (unsigned i = 0; i < Ops.size(); ++i)
7003     VTs.push_back(Ops[i].getValueType());
7004   return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
7005 }
7006 
getMemIntrinsicNode(unsigned Opcode,const SDLoc & dl,SDVTList VTList,ArrayRef<SDValue> Ops,EVT MemVT,MachinePointerInfo PtrInfo,Align Alignment,MachineMemOperand::Flags Flags,uint64_t Size,const AAMDNodes & AAInfo)7007 SDValue SelectionDAG::getMemIntrinsicNode(
7008     unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
7009     EVT MemVT, MachinePointerInfo PtrInfo, Align Alignment,
7010     MachineMemOperand::Flags Flags, uint64_t Size, const AAMDNodes &AAInfo) {
7011   if (!Size && MemVT.isScalableVector())
7012     Size = MemoryLocation::UnknownSize;
7013   else if (!Size)
7014     Size = MemVT.getStoreSize();
7015 
7016   MachineFunction &MF = getMachineFunction();
7017   MachineMemOperand *MMO =
7018       MF.getMachineMemOperand(PtrInfo, Flags, Size, Alignment, AAInfo);
7019 
7020   return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
7021 }
7022 
getMemIntrinsicNode(unsigned Opcode,const SDLoc & dl,SDVTList VTList,ArrayRef<SDValue> Ops,EVT MemVT,MachineMemOperand * MMO)7023 SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
7024                                           SDVTList VTList,
7025                                           ArrayRef<SDValue> Ops, EVT MemVT,
7026                                           MachineMemOperand *MMO) {
7027   assert((Opcode == ISD::INTRINSIC_VOID ||
7028           Opcode == ISD::INTRINSIC_W_CHAIN ||
7029           Opcode == ISD::PREFETCH ||
7030           ((int)Opcode <= std::numeric_limits<int>::max() &&
7031            (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
7032          "Opcode is not a memory-accessing opcode!");
7033 
7034   // Memoize the node unless it returns a flag.
7035   MemIntrinsicSDNode *N;
7036   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7037     FoldingSetNodeID ID;
7038     AddNodeIDNode(ID, Opcode, VTList, Ops);
7039     ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
7040         Opcode, dl.getIROrder(), VTList, MemVT, MMO));
7041     ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7042     void *IP = nullptr;
7043     if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7044       cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
7045       return SDValue(E, 0);
7046     }
7047 
7048     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7049                                       VTList, MemVT, MMO);
7050     createOperands(N, Ops);
7051 
7052   CSEMap.InsertNode(N, IP);
7053   } else {
7054     N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
7055                                       VTList, MemVT, MMO);
7056     createOperands(N, Ops);
7057   }
7058   InsertNode(N);
7059   SDValue V(N, 0);
7060   NewSDValueDbgMsg(V, "Creating new node: ", this);
7061   return V;
7062 }
7063 
getLifetimeNode(bool IsStart,const SDLoc & dl,SDValue Chain,int FrameIndex,int64_t Size,int64_t Offset)7064 SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
7065                                       SDValue Chain, int FrameIndex,
7066                                       int64_t Size, int64_t Offset) {
7067   const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
7068   const auto VTs = getVTList(MVT::Other);
7069   SDValue Ops[2] = {
7070       Chain,
7071       getFrameIndex(FrameIndex,
7072                     getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
7073                     true)};
7074 
7075   FoldingSetNodeID ID;
7076   AddNodeIDNode(ID, Opcode, VTs, Ops);
7077   ID.AddInteger(FrameIndex);
7078   ID.AddInteger(Size);
7079   ID.AddInteger(Offset);
7080   void *IP = nullptr;
7081   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7082     return SDValue(E, 0);
7083 
7084   LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
7085       Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
7086   createOperands(N, Ops);
7087   CSEMap.InsertNode(N, IP);
7088   InsertNode(N);
7089   SDValue V(N, 0);
7090   NewSDValueDbgMsg(V, "Creating new node: ", this);
7091   return V;
7092 }
7093 
7094 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7095 /// MachinePointerInfo record from it.  This is particularly useful because the
7096 /// code generator has many cases where it doesn't bother passing in a
7097 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
InferPointerInfo(const MachinePointerInfo & Info,SelectionDAG & DAG,SDValue Ptr,int64_t Offset=0)7098 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7099                                            SelectionDAG &DAG, SDValue Ptr,
7100                                            int64_t Offset = 0) {
7101   // If this is FI+Offset, we can model it.
7102   if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
7103     return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
7104                                              FI->getIndex(), Offset);
7105 
7106   // If this is (FI+Offset1)+Offset2, we can model it.
7107   if (Ptr.getOpcode() != ISD::ADD ||
7108       !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
7109       !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
7110     return Info;
7111 
7112   int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
7113   return MachinePointerInfo::getFixedStack(
7114       DAG.getMachineFunction(), FI,
7115       Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
7116 }
7117 
7118 /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
7119 /// MachinePointerInfo record from it.  This is particularly useful because the
7120 /// code generator has many cases where it doesn't bother passing in a
7121 /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
InferPointerInfo(const MachinePointerInfo & Info,SelectionDAG & DAG,SDValue Ptr,SDValue OffsetOp)7122 static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
7123                                            SelectionDAG &DAG, SDValue Ptr,
7124                                            SDValue OffsetOp) {
7125   // If the 'Offset' value isn't a constant, we can't handle this.
7126   if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
7127     return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
7128   if (OffsetOp.isUndef())
7129     return InferPointerInfo(Info, DAG, Ptr);
7130   return Info;
7131 }
7132 
getLoad(ISD::MemIndexedMode AM,ISD::LoadExtType ExtType,EVT VT,const SDLoc & dl,SDValue Chain,SDValue Ptr,SDValue Offset,MachinePointerInfo PtrInfo,EVT MemVT,Align Alignment,MachineMemOperand::Flags MMOFlags,const AAMDNodes & AAInfo,const MDNode * Ranges)7133 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7134                               EVT VT, const SDLoc &dl, SDValue Chain,
7135                               SDValue Ptr, SDValue Offset,
7136                               MachinePointerInfo PtrInfo, EVT MemVT,
7137                               Align Alignment,
7138                               MachineMemOperand::Flags MMOFlags,
7139                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7140   assert(Chain.getValueType() == MVT::Other &&
7141         "Invalid chain type");
7142 
7143   MMOFlags |= MachineMemOperand::MOLoad;
7144   assert((MMOFlags & MachineMemOperand::MOStore) == 0);
7145   // If we don't have a PtrInfo, infer the trivial frame index case to simplify
7146   // clients.
7147   if (PtrInfo.V.isNull())
7148     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
7149 
7150   uint64_t Size = MemoryLocation::getSizeOrUnknown(MemVT.getStoreSize());
7151   MachineFunction &MF = getMachineFunction();
7152   MachineMemOperand *MMO = MF.getMachineMemOperand(PtrInfo, MMOFlags, Size,
7153                                                    Alignment, AAInfo, Ranges);
7154   return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
7155 }
7156 
getLoad(ISD::MemIndexedMode AM,ISD::LoadExtType ExtType,EVT VT,const SDLoc & dl,SDValue Chain,SDValue Ptr,SDValue Offset,EVT MemVT,MachineMemOperand * MMO)7157 SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
7158                               EVT VT, const SDLoc &dl, SDValue Chain,
7159                               SDValue Ptr, SDValue Offset, EVT MemVT,
7160                               MachineMemOperand *MMO) {
7161   if (VT == MemVT) {
7162     ExtType = ISD::NON_EXTLOAD;
7163   } else if (ExtType == ISD::NON_EXTLOAD) {
7164     assert(VT == MemVT && "Non-extending load from different memory type!");
7165   } else {
7166     // Extending load.
7167     assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
7168            "Should only be an extending load, not truncating!");
7169     assert(VT.isInteger() == MemVT.isInteger() &&
7170            "Cannot convert from FP to Int or Int -> FP!");
7171     assert(VT.isVector() == MemVT.isVector() &&
7172            "Cannot use an ext load to convert to or from a vector!");
7173     assert((!VT.isVector() ||
7174             VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
7175            "Cannot use an ext load to change the number of vector elements!");
7176   }
7177 
7178   bool Indexed = AM != ISD::UNINDEXED;
7179   assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
7180 
7181   SDVTList VTs = Indexed ?
7182     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
7183   SDValue Ops[] = { Chain, Ptr, Offset };
7184   FoldingSetNodeID ID;
7185   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
7186   ID.AddInteger(MemVT.getRawBits());
7187   ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
7188       dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
7189   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7190   void *IP = nullptr;
7191   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7192     cast<LoadSDNode>(E)->refineAlignment(MMO);
7193     return SDValue(E, 0);
7194   }
7195   auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7196                                   ExtType, MemVT, MMO);
7197   createOperands(N, Ops);
7198 
7199   CSEMap.InsertNode(N, IP);
7200   InsertNode(N);
7201   SDValue V(N, 0);
7202   NewSDValueDbgMsg(V, "Creating new node: ", this);
7203   return V;
7204 }
7205 
getLoad(EVT VT,const SDLoc & dl,SDValue Chain,SDValue Ptr,MachinePointerInfo PtrInfo,MaybeAlign Alignment,MachineMemOperand::Flags MMOFlags,const AAMDNodes & AAInfo,const MDNode * Ranges)7206 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7207                               SDValue Ptr, MachinePointerInfo PtrInfo,
7208                               MaybeAlign Alignment,
7209                               MachineMemOperand::Flags MMOFlags,
7210                               const AAMDNodes &AAInfo, const MDNode *Ranges) {
7211   SDValue Undef = getUNDEF(Ptr.getValueType());
7212   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7213                  PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
7214 }
7215 
getLoad(EVT VT,const SDLoc & dl,SDValue Chain,SDValue Ptr,MachineMemOperand * MMO)7216 SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7217                               SDValue Ptr, MachineMemOperand *MMO) {
7218   SDValue Undef = getUNDEF(Ptr.getValueType());
7219   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
7220                  VT, MMO);
7221 }
7222 
getExtLoad(ISD::LoadExtType ExtType,const SDLoc & dl,EVT VT,SDValue Chain,SDValue Ptr,MachinePointerInfo PtrInfo,EVT MemVT,MaybeAlign Alignment,MachineMemOperand::Flags MMOFlags,const AAMDNodes & AAInfo)7223 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7224                                  EVT VT, SDValue Chain, SDValue Ptr,
7225                                  MachinePointerInfo PtrInfo, EVT MemVT,
7226                                  MaybeAlign Alignment,
7227                                  MachineMemOperand::Flags MMOFlags,
7228                                  const AAMDNodes &AAInfo) {
7229   SDValue Undef = getUNDEF(Ptr.getValueType());
7230   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
7231                  MemVT, Alignment, MMOFlags, AAInfo);
7232 }
7233 
getExtLoad(ISD::LoadExtType ExtType,const SDLoc & dl,EVT VT,SDValue Chain,SDValue Ptr,EVT MemVT,MachineMemOperand * MMO)7234 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
7235                                  EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
7236                                  MachineMemOperand *MMO) {
7237   SDValue Undef = getUNDEF(Ptr.getValueType());
7238   return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
7239                  MemVT, MMO);
7240 }
7241 
getIndexedLoad(SDValue OrigLoad,const SDLoc & dl,SDValue Base,SDValue Offset,ISD::MemIndexedMode AM)7242 SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
7243                                      SDValue Base, SDValue Offset,
7244                                      ISD::MemIndexedMode AM) {
7245   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
7246   assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
7247   // Don't propagate the invariant or dereferenceable flags.
7248   auto MMOFlags =
7249       LD->getMemOperand()->getFlags() &
7250       ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
7251   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
7252                  LD->getChain(), Base, Offset, LD->getPointerInfo(),
7253                  LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
7254                  LD->getAAInfo());
7255 }
7256 
getStore(SDValue Chain,const SDLoc & dl,SDValue Val,SDValue Ptr,MachinePointerInfo PtrInfo,Align Alignment,MachineMemOperand::Flags MMOFlags,const AAMDNodes & AAInfo)7257 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7258                                SDValue Ptr, MachinePointerInfo PtrInfo,
7259                                Align Alignment,
7260                                MachineMemOperand::Flags MMOFlags,
7261                                const AAMDNodes &AAInfo) {
7262   assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
7263 
7264   MMOFlags |= MachineMemOperand::MOStore;
7265   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7266 
7267   if (PtrInfo.V.isNull())
7268     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7269 
7270   MachineFunction &MF = getMachineFunction();
7271   uint64_t Size =
7272       MemoryLocation::getSizeOrUnknown(Val.getValueType().getStoreSize());
7273   MachineMemOperand *MMO =
7274       MF.getMachineMemOperand(PtrInfo, MMOFlags, Size, Alignment, AAInfo);
7275   return getStore(Chain, dl, Val, Ptr, MMO);
7276 }
7277 
getStore(SDValue Chain,const SDLoc & dl,SDValue Val,SDValue Ptr,MachineMemOperand * MMO)7278 SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7279                                SDValue Ptr, MachineMemOperand *MMO) {
7280   assert(Chain.getValueType() == MVT::Other &&
7281         "Invalid chain type");
7282   EVT VT = Val.getValueType();
7283   SDVTList VTs = getVTList(MVT::Other);
7284   SDValue Undef = getUNDEF(Ptr.getValueType());
7285   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7286   FoldingSetNodeID ID;
7287   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7288   ID.AddInteger(VT.getRawBits());
7289   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7290       dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
7291   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7292   void *IP = nullptr;
7293   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7294     cast<StoreSDNode>(E)->refineAlignment(MMO);
7295     return SDValue(E, 0);
7296   }
7297   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7298                                    ISD::UNINDEXED, false, VT, MMO);
7299   createOperands(N, Ops);
7300 
7301   CSEMap.InsertNode(N, IP);
7302   InsertNode(N);
7303   SDValue V(N, 0);
7304   NewSDValueDbgMsg(V, "Creating new node: ", this);
7305   return V;
7306 }
7307 
getTruncStore(SDValue Chain,const SDLoc & dl,SDValue Val,SDValue Ptr,MachinePointerInfo PtrInfo,EVT SVT,Align Alignment,MachineMemOperand::Flags MMOFlags,const AAMDNodes & AAInfo)7308 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7309                                     SDValue Ptr, MachinePointerInfo PtrInfo,
7310                                     EVT SVT, Align Alignment,
7311                                     MachineMemOperand::Flags MMOFlags,
7312                                     const AAMDNodes &AAInfo) {
7313   assert(Chain.getValueType() == MVT::Other &&
7314         "Invalid chain type");
7315 
7316   MMOFlags |= MachineMemOperand::MOStore;
7317   assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
7318 
7319   if (PtrInfo.V.isNull())
7320     PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
7321 
7322   MachineFunction &MF = getMachineFunction();
7323   MachineMemOperand *MMO = MF.getMachineMemOperand(
7324       PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
7325   return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
7326 }
7327 
getTruncStore(SDValue Chain,const SDLoc & dl,SDValue Val,SDValue Ptr,EVT SVT,MachineMemOperand * MMO)7328 SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
7329                                     SDValue Ptr, EVT SVT,
7330                                     MachineMemOperand *MMO) {
7331   EVT VT = Val.getValueType();
7332 
7333   assert(Chain.getValueType() == MVT::Other &&
7334         "Invalid chain type");
7335   if (VT == SVT)
7336     return getStore(Chain, dl, Val, Ptr, MMO);
7337 
7338   assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
7339          "Should only be a truncating store, not extending!");
7340   assert(VT.isInteger() == SVT.isInteger() &&
7341          "Can't do FP-INT conversion!");
7342   assert(VT.isVector() == SVT.isVector() &&
7343          "Cannot use trunc store to convert to or from a vector!");
7344   assert((!VT.isVector() ||
7345           VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
7346          "Cannot use trunc store to change the number of vector elements!");
7347 
7348   SDVTList VTs = getVTList(MVT::Other);
7349   SDValue Undef = getUNDEF(Ptr.getValueType());
7350   SDValue Ops[] = { Chain, Val, Ptr, Undef };
7351   FoldingSetNodeID ID;
7352   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7353   ID.AddInteger(SVT.getRawBits());
7354   ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
7355       dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
7356   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7357   void *IP = nullptr;
7358   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7359     cast<StoreSDNode>(E)->refineAlignment(MMO);
7360     return SDValue(E, 0);
7361   }
7362   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7363                                    ISD::UNINDEXED, true, SVT, MMO);
7364   createOperands(N, Ops);
7365 
7366   CSEMap.InsertNode(N, IP);
7367   InsertNode(N);
7368   SDValue V(N, 0);
7369   NewSDValueDbgMsg(V, "Creating new node: ", this);
7370   return V;
7371 }
7372 
getIndexedStore(SDValue OrigStore,const SDLoc & dl,SDValue Base,SDValue Offset,ISD::MemIndexedMode AM)7373 SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
7374                                       SDValue Base, SDValue Offset,
7375                                       ISD::MemIndexedMode AM) {
7376   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
7377   assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
7378   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
7379   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
7380   FoldingSetNodeID ID;
7381   AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
7382   ID.AddInteger(ST->getMemoryVT().getRawBits());
7383   ID.AddInteger(ST->getRawSubclassData());
7384   ID.AddInteger(ST->getPointerInfo().getAddrSpace());
7385   void *IP = nullptr;
7386   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
7387     return SDValue(E, 0);
7388 
7389   auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7390                                    ST->isTruncatingStore(), ST->getMemoryVT(),
7391                                    ST->getMemOperand());
7392   createOperands(N, Ops);
7393 
7394   CSEMap.InsertNode(N, IP);
7395   InsertNode(N);
7396   SDValue V(N, 0);
7397   NewSDValueDbgMsg(V, "Creating new node: ", this);
7398   return V;
7399 }
7400 
getMaskedLoad(EVT VT,const SDLoc & dl,SDValue Chain,SDValue Base,SDValue Offset,SDValue Mask,SDValue PassThru,EVT MemVT,MachineMemOperand * MMO,ISD::MemIndexedMode AM,ISD::LoadExtType ExtTy,bool isExpanding)7401 SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
7402                                     SDValue Base, SDValue Offset, SDValue Mask,
7403                                     SDValue PassThru, EVT MemVT,
7404                                     MachineMemOperand *MMO,
7405                                     ISD::MemIndexedMode AM,
7406                                     ISD::LoadExtType ExtTy, bool isExpanding) {
7407   bool Indexed = AM != ISD::UNINDEXED;
7408   assert((Indexed || Offset.isUndef()) &&
7409          "Unindexed masked load with an offset!");
7410   SDVTList VTs = Indexed ? getVTList(VT, Base.getValueType(), MVT::Other)
7411                          : getVTList(VT, MVT::Other);
7412   SDValue Ops[] = {Chain, Base, Offset, Mask, PassThru};
7413   FoldingSetNodeID ID;
7414   AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
7415   ID.AddInteger(MemVT.getRawBits());
7416   ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
7417       dl.getIROrder(), VTs, AM, ExtTy, isExpanding, MemVT, MMO));
7418   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7419   void *IP = nullptr;
7420   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7421     cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
7422     return SDValue(E, 0);
7423   }
7424   auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
7425                                         AM, ExtTy, isExpanding, MemVT, MMO);
7426   createOperands(N, Ops);
7427 
7428   CSEMap.InsertNode(N, IP);
7429   InsertNode(N);
7430   SDValue V(N, 0);
7431   NewSDValueDbgMsg(V, "Creating new node: ", this);
7432   return V;
7433 }
7434 
getIndexedMaskedLoad(SDValue OrigLoad,const SDLoc & dl,SDValue Base,SDValue Offset,ISD::MemIndexedMode AM)7435 SDValue SelectionDAG::getIndexedMaskedLoad(SDValue OrigLoad, const SDLoc &dl,
7436                                            SDValue Base, SDValue Offset,
7437                                            ISD::MemIndexedMode AM) {
7438   MaskedLoadSDNode *LD = cast<MaskedLoadSDNode>(OrigLoad);
7439   assert(LD->getOffset().isUndef() && "Masked load is already a indexed load!");
7440   return getMaskedLoad(OrigLoad.getValueType(), dl, LD->getChain(), Base,
7441                        Offset, LD->getMask(), LD->getPassThru(),
7442                        LD->getMemoryVT(), LD->getMemOperand(), AM,
7443                        LD->getExtensionType(), LD->isExpandingLoad());
7444 }
7445 
getMaskedStore(SDValue Chain,const SDLoc & dl,SDValue Val,SDValue Base,SDValue Offset,SDValue Mask,EVT MemVT,MachineMemOperand * MMO,ISD::MemIndexedMode AM,bool IsTruncating,bool IsCompressing)7446 SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
7447                                      SDValue Val, SDValue Base, SDValue Offset,
7448                                      SDValue Mask, EVT MemVT,
7449                                      MachineMemOperand *MMO,
7450                                      ISD::MemIndexedMode AM, bool IsTruncating,
7451                                      bool IsCompressing) {
7452   assert(Chain.getValueType() == MVT::Other &&
7453         "Invalid chain type");
7454   bool Indexed = AM != ISD::UNINDEXED;
7455   assert((Indexed || Offset.isUndef()) &&
7456          "Unindexed masked store with an offset!");
7457   SDVTList VTs = Indexed ? getVTList(Base.getValueType(), MVT::Other)
7458                          : getVTList(MVT::Other);
7459   SDValue Ops[] = {Chain, Val, Base, Offset, Mask};
7460   FoldingSetNodeID ID;
7461   AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
7462   ID.AddInteger(MemVT.getRawBits());
7463   ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
7464       dl.getIROrder(), VTs, AM, IsTruncating, IsCompressing, MemVT, MMO));
7465   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7466   void *IP = nullptr;
7467   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7468     cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
7469     return SDValue(E, 0);
7470   }
7471   auto *N =
7472       newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
7473                                    IsTruncating, IsCompressing, MemVT, MMO);
7474   createOperands(N, Ops);
7475 
7476   CSEMap.InsertNode(N, IP);
7477   InsertNode(N);
7478   SDValue V(N, 0);
7479   NewSDValueDbgMsg(V, "Creating new node: ", this);
7480   return V;
7481 }
7482 
getIndexedMaskedStore(SDValue OrigStore,const SDLoc & dl,SDValue Base,SDValue Offset,ISD::MemIndexedMode AM)7483 SDValue SelectionDAG::getIndexedMaskedStore(SDValue OrigStore, const SDLoc &dl,
7484                                             SDValue Base, SDValue Offset,
7485                                             ISD::MemIndexedMode AM) {
7486   MaskedStoreSDNode *ST = cast<MaskedStoreSDNode>(OrigStore);
7487   assert(ST->getOffset().isUndef() &&
7488          "Masked store is already a indexed store!");
7489   return getMaskedStore(ST->getChain(), dl, ST->getValue(), Base, Offset,
7490                         ST->getMask(), ST->getMemoryVT(), ST->getMemOperand(),
7491                         AM, ST->isTruncatingStore(), ST->isCompressingStore());
7492 }
7493 
getMaskedGather(SDVTList VTs,EVT VT,const SDLoc & dl,ArrayRef<SDValue> Ops,MachineMemOperand * MMO,ISD::MemIndexType IndexType)7494 SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
7495                                       ArrayRef<SDValue> Ops,
7496                                       MachineMemOperand *MMO,
7497                                       ISD::MemIndexType IndexType) {
7498   assert(Ops.size() == 6 && "Incompatible number of operands");
7499 
7500   FoldingSetNodeID ID;
7501   AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
7502   ID.AddInteger(VT.getRawBits());
7503   ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
7504       dl.getIROrder(), VTs, VT, MMO, IndexType));
7505   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7506   void *IP = nullptr;
7507   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7508     cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
7509     return SDValue(E, 0);
7510   }
7511 
7512   auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7513                                           VTs, VT, MMO, IndexType);
7514   createOperands(N, Ops);
7515 
7516   assert(N->getPassThru().getValueType() == N->getValueType(0) &&
7517          "Incompatible type of the PassThru value in MaskedGatherSDNode");
7518   assert(N->getMask().getValueType().getVectorNumElements() ==
7519              N->getValueType(0).getVectorNumElements() &&
7520          "Vector width mismatch between mask and data");
7521   assert(N->getIndex().getValueType().getVectorNumElements() >=
7522              N->getValueType(0).getVectorNumElements() &&
7523          "Vector width mismatch between index and data");
7524   assert(isa<ConstantSDNode>(N->getScale()) &&
7525          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7526          "Scale should be a constant power of 2");
7527 
7528   CSEMap.InsertNode(N, IP);
7529   InsertNode(N);
7530   SDValue V(N, 0);
7531   NewSDValueDbgMsg(V, "Creating new node: ", this);
7532   return V;
7533 }
7534 
getMaskedScatter(SDVTList VTs,EVT VT,const SDLoc & dl,ArrayRef<SDValue> Ops,MachineMemOperand * MMO,ISD::MemIndexType IndexType)7535 SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
7536                                        ArrayRef<SDValue> Ops,
7537                                        MachineMemOperand *MMO,
7538                                        ISD::MemIndexType IndexType) {
7539   assert(Ops.size() == 6 && "Incompatible number of operands");
7540 
7541   FoldingSetNodeID ID;
7542   AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
7543   ID.AddInteger(VT.getRawBits());
7544   ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
7545       dl.getIROrder(), VTs, VT, MMO, IndexType));
7546   ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
7547   void *IP = nullptr;
7548   if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
7549     cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
7550     return SDValue(E, 0);
7551   }
7552   auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
7553                                            VTs, VT, MMO, IndexType);
7554   createOperands(N, Ops);
7555 
7556   assert(N->getMask().getValueType().getVectorNumElements() ==
7557              N->getValue().getValueType().getVectorNumElements() &&
7558          "Vector width mismatch between mask and data");
7559   assert(N->getIndex().getValueType().getVectorNumElements() >=
7560              N->getValue().getValueType().getVectorNumElements() &&
7561          "Vector width mismatch between index and data");
7562   assert(isa<ConstantSDNode>(N->getScale()) &&
7563          cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
7564          "Scale should be a constant power of 2");
7565 
7566   CSEMap.InsertNode(N, IP);
7567   InsertNode(N);
7568   SDValue V(N, 0);
7569   NewSDValueDbgMsg(V, "Creating new node: ", this);
7570   return V;
7571 }
7572 
simplifySelect(SDValue Cond,SDValue T,SDValue F)7573 SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
7574   // select undef, T, F --> T (if T is a constant), otherwise F
7575   // select, ?, undef, F --> F
7576   // select, ?, T, undef --> T
7577   if (Cond.isUndef())
7578     return isConstantValueOfAnyType(T) ? T : F;
7579   if (T.isUndef())
7580     return F;
7581   if (F.isUndef())
7582     return T;
7583 
7584   // select true, T, F --> T
7585   // select false, T, F --> F
7586   if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
7587     return CondC->isNullValue() ? F : T;
7588 
7589   // TODO: This should simplify VSELECT with constant condition using something
7590   // like this (but check boolean contents to be complete?):
7591   //  if (ISD::isBuildVectorAllOnes(Cond.getNode()))
7592   //    return T;
7593   //  if (ISD::isBuildVectorAllZeros(Cond.getNode()))
7594   //    return F;
7595 
7596   // select ?, T, T --> T
7597   if (T == F)
7598     return T;
7599 
7600   return SDValue();
7601 }
7602 
simplifyShift(SDValue X,SDValue Y)7603 SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
7604   // shift undef, Y --> 0 (can always assume that the undef value is 0)
7605   if (X.isUndef())
7606     return getConstant(0, SDLoc(X.getNode()), X.getValueType());
7607   // shift X, undef --> undef (because it may shift by the bitwidth)
7608   if (Y.isUndef())
7609     return getUNDEF(X.getValueType());
7610 
7611   // shift 0, Y --> 0
7612   // shift X, 0 --> X
7613   if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
7614     return X;
7615 
7616   // shift X, C >= bitwidth(X) --> undef
7617   // All vector elements must be too big (or undef) to avoid partial undefs.
7618   auto isShiftTooBig = [X](ConstantSDNode *Val) {
7619     return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
7620   };
7621   if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
7622     return getUNDEF(X.getValueType());
7623 
7624   return SDValue();
7625 }
7626 
simplifyFPBinop(unsigned Opcode,SDValue X,SDValue Y,SDNodeFlags Flags)7627 SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y,
7628                                       SDNodeFlags Flags) {
7629   // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
7630   // (an undef operand can be chosen to be Nan/Inf), then the result of this
7631   // operation is poison. That result can be relaxed to undef.
7632   ConstantFPSDNode *XC = isConstOrConstSplatFP(X, /* AllowUndefs */ true);
7633   ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
7634   bool HasNan = (XC && XC->getValueAPF().isNaN()) ||
7635                 (YC && YC->getValueAPF().isNaN());
7636   bool HasInf = (XC && XC->getValueAPF().isInfinity()) ||
7637                 (YC && YC->getValueAPF().isInfinity());
7638 
7639   if (Flags.hasNoNaNs() && (HasNan || X.isUndef() || Y.isUndef()))
7640     return getUNDEF(X.getValueType());
7641 
7642   if (Flags.hasNoInfs() && (HasInf || X.isUndef() || Y.isUndef()))
7643     return getUNDEF(X.getValueType());
7644 
7645   if (!YC)
7646     return SDValue();
7647 
7648   // X + -0.0 --> X
7649   if (Opcode == ISD::FADD)
7650     if (YC->getValueAPF().isNegZero())
7651       return X;
7652 
7653   // X - +0.0 --> X
7654   if (Opcode == ISD::FSUB)
7655     if (YC->getValueAPF().isPosZero())
7656       return X;
7657 
7658   // X * 1.0 --> X
7659   // X / 1.0 --> X
7660   if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
7661     if (YC->getValueAPF().isExactlyValue(1.0))
7662       return X;
7663 
7664   return SDValue();
7665 }
7666 
getVAArg(EVT VT,const SDLoc & dl,SDValue Chain,SDValue Ptr,SDValue SV,unsigned Align)7667 SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
7668                                SDValue Ptr, SDValue SV, unsigned Align) {
7669   SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
7670   return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
7671 }
7672 
getNode(unsigned Opcode,const SDLoc & DL,EVT VT,ArrayRef<SDUse> Ops)7673 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7674                               ArrayRef<SDUse> Ops) {
7675   switch (Ops.size()) {
7676   case 0: return getNode(Opcode, DL, VT);
7677   case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
7678   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
7679   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
7680   default: break;
7681   }
7682 
7683   // Copy from an SDUse array into an SDValue array for use with
7684   // the regular getNode logic.
7685   SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
7686   return getNode(Opcode, DL, VT, NewOps);
7687 }
7688 
getNode(unsigned Opcode,const SDLoc & DL,EVT VT,ArrayRef<SDValue> Ops,const SDNodeFlags Flags)7689 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
7690                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7691   unsigned NumOps = Ops.size();
7692   switch (NumOps) {
7693   case 0: return getNode(Opcode, DL, VT);
7694   case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
7695   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
7696   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
7697   default: break;
7698   }
7699 
7700   switch (Opcode) {
7701   default: break;
7702   case ISD::BUILD_VECTOR:
7703     // Attempt to simplify BUILD_VECTOR.
7704     if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
7705       return V;
7706     break;
7707   case ISD::CONCAT_VECTORS:
7708     if (SDValue V = foldCONCAT_VECTORS(DL, VT, Ops, *this))
7709       return V;
7710     break;
7711   case ISD::SELECT_CC:
7712     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
7713     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
7714            "LHS and RHS of condition must have same type!");
7715     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7716            "True and False arms of SelectCC must have same type!");
7717     assert(Ops[2].getValueType() == VT &&
7718            "select_cc node must be of same type as true and false value!");
7719     break;
7720   case ISD::BR_CC:
7721     assert(NumOps == 5 && "BR_CC takes 5 operands!");
7722     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
7723            "LHS/RHS of comparison should match types!");
7724     break;
7725   }
7726 
7727   // Memoize nodes.
7728   SDNode *N;
7729   SDVTList VTs = getVTList(VT);
7730 
7731   if (VT != MVT::Glue) {
7732     FoldingSetNodeID ID;
7733     AddNodeIDNode(ID, Opcode, VTs, Ops);
7734     void *IP = nullptr;
7735 
7736     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7737       return SDValue(E, 0);
7738 
7739     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7740     createOperands(N, Ops);
7741 
7742     CSEMap.InsertNode(N, IP);
7743   } else {
7744     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
7745     createOperands(N, Ops);
7746   }
7747 
7748   N->setFlags(Flags);
7749   InsertNode(N);
7750   SDValue V(N, 0);
7751   NewSDValueDbgMsg(V, "Creating new node: ", this);
7752   return V;
7753 }
7754 
getNode(unsigned Opcode,const SDLoc & DL,ArrayRef<EVT> ResultTys,ArrayRef<SDValue> Ops)7755 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7756                               ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
7757   return getNode(Opcode, DL, getVTList(ResultTys), Ops);
7758 }
7759 
getNode(unsigned Opcode,const SDLoc & DL,SDVTList VTList,ArrayRef<SDValue> Ops,const SDNodeFlags Flags)7760 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7761                               ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
7762   if (VTList.NumVTs == 1)
7763     return getNode(Opcode, DL, VTList.VTs[0], Ops);
7764 
7765   switch (Opcode) {
7766   case ISD::STRICT_FP_EXTEND:
7767     assert(VTList.NumVTs == 2 && Ops.size() == 2 &&
7768            "Invalid STRICT_FP_EXTEND!");
7769     assert(VTList.VTs[0].isFloatingPoint() &&
7770            Ops[1].getValueType().isFloatingPoint() && "Invalid FP cast!");
7771     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
7772            "STRICT_FP_EXTEND result type should be vector iff the operand "
7773            "type is vector!");
7774     assert((!VTList.VTs[0].isVector() ||
7775             VTList.VTs[0].getVectorNumElements() ==
7776             Ops[1].getValueType().getVectorNumElements()) &&
7777            "Vector element count mismatch!");
7778     assert(Ops[1].getValueType().bitsLT(VTList.VTs[0]) &&
7779            "Invalid fpext node, dst <= src!");
7780     break;
7781   case ISD::STRICT_FP_ROUND:
7782     assert(VTList.NumVTs == 2 && Ops.size() == 3 && "Invalid STRICT_FP_ROUND!");
7783     assert(VTList.VTs[0].isVector() == Ops[1].getValueType().isVector() &&
7784            "STRICT_FP_ROUND result type should be vector iff the operand "
7785            "type is vector!");
7786     assert((!VTList.VTs[0].isVector() ||
7787             VTList.VTs[0].getVectorNumElements() ==
7788             Ops[1].getValueType().getVectorNumElements()) &&
7789            "Vector element count mismatch!");
7790     assert(VTList.VTs[0].isFloatingPoint() &&
7791            Ops[1].getValueType().isFloatingPoint() &&
7792            VTList.VTs[0].bitsLT(Ops[1].getValueType()) &&
7793            isa<ConstantSDNode>(Ops[2]) &&
7794            (cast<ConstantSDNode>(Ops[2])->getZExtValue() == 0 ||
7795             cast<ConstantSDNode>(Ops[2])->getZExtValue() == 1) &&
7796            "Invalid STRICT_FP_ROUND!");
7797     break;
7798 #if 0
7799   // FIXME: figure out how to safely handle things like
7800   // int foo(int x) { return 1 << (x & 255); }
7801   // int bar() { return foo(256); }
7802   case ISD::SRA_PARTS:
7803   case ISD::SRL_PARTS:
7804   case ISD::SHL_PARTS:
7805     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
7806         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
7807       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7808     else if (N3.getOpcode() == ISD::AND)
7809       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
7810         // If the and is only masking out bits that cannot effect the shift,
7811         // eliminate the and.
7812         unsigned NumBits = VT.getScalarSizeInBits()*2;
7813         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
7814           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
7815       }
7816     break;
7817 #endif
7818   }
7819 
7820   // Memoize the node unless it returns a flag.
7821   SDNode *N;
7822   if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
7823     FoldingSetNodeID ID;
7824     AddNodeIDNode(ID, Opcode, VTList, Ops);
7825     void *IP = nullptr;
7826     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
7827       return SDValue(E, 0);
7828 
7829     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7830     createOperands(N, Ops);
7831     CSEMap.InsertNode(N, IP);
7832   } else {
7833     N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
7834     createOperands(N, Ops);
7835   }
7836 
7837   N->setFlags(Flags);
7838   InsertNode(N);
7839   SDValue V(N, 0);
7840   NewSDValueDbgMsg(V, "Creating new node: ", this);
7841   return V;
7842 }
7843 
getNode(unsigned Opcode,const SDLoc & DL,SDVTList VTList)7844 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
7845                               SDVTList VTList) {
7846   return getNode(Opcode, DL, VTList, None);
7847 }
7848 
getNode(unsigned Opcode,const SDLoc & DL,SDVTList VTList,SDValue N1)7849 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7850                               SDValue N1) {
7851   SDValue Ops[] = { N1 };
7852   return getNode(Opcode, DL, VTList, Ops);
7853 }
7854 
getNode(unsigned Opcode,const SDLoc & DL,SDVTList VTList,SDValue N1,SDValue N2)7855 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7856                               SDValue N1, SDValue N2) {
7857   SDValue Ops[] = { N1, N2 };
7858   return getNode(Opcode, DL, VTList, Ops);
7859 }
7860 
getNode(unsigned Opcode,const SDLoc & DL,SDVTList VTList,SDValue N1,SDValue N2,SDValue N3)7861 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7862                               SDValue N1, SDValue N2, SDValue N3) {
7863   SDValue Ops[] = { N1, N2, N3 };
7864   return getNode(Opcode, DL, VTList, Ops);
7865 }
7866 
getNode(unsigned Opcode,const SDLoc & DL,SDVTList VTList,SDValue N1,SDValue N2,SDValue N3,SDValue N4)7867 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7868                               SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
7869   SDValue Ops[] = { N1, N2, N3, N4 };
7870   return getNode(Opcode, DL, VTList, Ops);
7871 }
7872 
getNode(unsigned Opcode,const SDLoc & DL,SDVTList VTList,SDValue N1,SDValue N2,SDValue N3,SDValue N4,SDValue N5)7873 SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
7874                               SDValue N1, SDValue N2, SDValue N3, SDValue N4,
7875                               SDValue N5) {
7876   SDValue Ops[] = { N1, N2, N3, N4, N5 };
7877   return getNode(Opcode, DL, VTList, Ops);
7878 }
7879 
getVTList(EVT VT)7880 SDVTList SelectionDAG::getVTList(EVT VT) {
7881   return makeVTList(SDNode::getValueTypeList(VT), 1);
7882 }
7883 
getVTList(EVT VT1,EVT VT2)7884 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
7885   FoldingSetNodeID ID;
7886   ID.AddInteger(2U);
7887   ID.AddInteger(VT1.getRawBits());
7888   ID.AddInteger(VT2.getRawBits());
7889 
7890   void *IP = nullptr;
7891   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7892   if (!Result) {
7893     EVT *Array = Allocator.Allocate<EVT>(2);
7894     Array[0] = VT1;
7895     Array[1] = VT2;
7896     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
7897     VTListMap.InsertNode(Result, IP);
7898   }
7899   return Result->getSDVTList();
7900 }
7901 
getVTList(EVT VT1,EVT VT2,EVT VT3)7902 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
7903   FoldingSetNodeID ID;
7904   ID.AddInteger(3U);
7905   ID.AddInteger(VT1.getRawBits());
7906   ID.AddInteger(VT2.getRawBits());
7907   ID.AddInteger(VT3.getRawBits());
7908 
7909   void *IP = nullptr;
7910   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7911   if (!Result) {
7912     EVT *Array = Allocator.Allocate<EVT>(3);
7913     Array[0] = VT1;
7914     Array[1] = VT2;
7915     Array[2] = VT3;
7916     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
7917     VTListMap.InsertNode(Result, IP);
7918   }
7919   return Result->getSDVTList();
7920 }
7921 
getVTList(EVT VT1,EVT VT2,EVT VT3,EVT VT4)7922 SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
7923   FoldingSetNodeID ID;
7924   ID.AddInteger(4U);
7925   ID.AddInteger(VT1.getRawBits());
7926   ID.AddInteger(VT2.getRawBits());
7927   ID.AddInteger(VT3.getRawBits());
7928   ID.AddInteger(VT4.getRawBits());
7929 
7930   void *IP = nullptr;
7931   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7932   if (!Result) {
7933     EVT *Array = Allocator.Allocate<EVT>(4);
7934     Array[0] = VT1;
7935     Array[1] = VT2;
7936     Array[2] = VT3;
7937     Array[3] = VT4;
7938     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
7939     VTListMap.InsertNode(Result, IP);
7940   }
7941   return Result->getSDVTList();
7942 }
7943 
getVTList(ArrayRef<EVT> VTs)7944 SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
7945   unsigned NumVTs = VTs.size();
7946   FoldingSetNodeID ID;
7947   ID.AddInteger(NumVTs);
7948   for (unsigned index = 0; index < NumVTs; index++) {
7949     ID.AddInteger(VTs[index].getRawBits());
7950   }
7951 
7952   void *IP = nullptr;
7953   SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
7954   if (!Result) {
7955     EVT *Array = Allocator.Allocate<EVT>(NumVTs);
7956     llvm::copy(VTs, Array);
7957     Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
7958     VTListMap.InsertNode(Result, IP);
7959   }
7960   return Result->getSDVTList();
7961 }
7962 
7963 
7964 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
7965 /// specified operands.  If the resultant node already exists in the DAG,
7966 /// this does not modify the specified node, instead it returns the node that
7967 /// already exists.  If the resultant node does not exist in the DAG, the
7968 /// input node is returned.  As a degenerate case, if you specify the same
7969 /// input operands as the node already has, the input node is returned.
UpdateNodeOperands(SDNode * N,SDValue Op)7970 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
7971   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
7972 
7973   // Check to see if there is no change.
7974   if (Op == N->getOperand(0)) return N;
7975 
7976   // See if the modified node already exists.
7977   void *InsertPos = nullptr;
7978   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
7979     return Existing;
7980 
7981   // Nope it doesn't.  Remove the node from its current place in the maps.
7982   if (InsertPos)
7983     if (!RemoveNodeFromCSEMaps(N))
7984       InsertPos = nullptr;
7985 
7986   // Now we update the operands.
7987   N->OperandList[0].set(Op);
7988 
7989   updateDivergence(N);
7990   // If this gets put into a CSE map, add it.
7991   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
7992   return N;
7993 }
7994 
UpdateNodeOperands(SDNode * N,SDValue Op1,SDValue Op2)7995 SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
7996   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
7997 
7998   // Check to see if there is no change.
7999   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
8000     return N;   // No operands changed, just return the input node.
8001 
8002   // See if the modified node already exists.
8003   void *InsertPos = nullptr;
8004   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
8005     return Existing;
8006 
8007   // Nope it doesn't.  Remove the node from its current place in the maps.
8008   if (InsertPos)
8009     if (!RemoveNodeFromCSEMaps(N))
8010       InsertPos = nullptr;
8011 
8012   // Now we update the operands.
8013   if (N->OperandList[0] != Op1)
8014     N->OperandList[0].set(Op1);
8015   if (N->OperandList[1] != Op2)
8016     N->OperandList[1].set(Op2);
8017 
8018   updateDivergence(N);
8019   // If this gets put into a CSE map, add it.
8020   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8021   return N;
8022 }
8023 
8024 SDNode *SelectionDAG::
UpdateNodeOperands(SDNode * N,SDValue Op1,SDValue Op2,SDValue Op3)8025 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
8026   SDValue Ops[] = { Op1, Op2, Op3 };
8027   return UpdateNodeOperands(N, Ops);
8028 }
8029 
8030 SDNode *SelectionDAG::
UpdateNodeOperands(SDNode * N,SDValue Op1,SDValue Op2,SDValue Op3,SDValue Op4)8031 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8032                    SDValue Op3, SDValue Op4) {
8033   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
8034   return UpdateNodeOperands(N, Ops);
8035 }
8036 
8037 SDNode *SelectionDAG::
UpdateNodeOperands(SDNode * N,SDValue Op1,SDValue Op2,SDValue Op3,SDValue Op4,SDValue Op5)8038 UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
8039                    SDValue Op3, SDValue Op4, SDValue Op5) {
8040   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
8041   return UpdateNodeOperands(N, Ops);
8042 }
8043 
8044 SDNode *SelectionDAG::
UpdateNodeOperands(SDNode * N,ArrayRef<SDValue> Ops)8045 UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
8046   unsigned NumOps = Ops.size();
8047   assert(N->getNumOperands() == NumOps &&
8048          "Update with wrong number of operands");
8049 
8050   // If no operands changed just return the input node.
8051   if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
8052     return N;
8053 
8054   // See if the modified node already exists.
8055   void *InsertPos = nullptr;
8056   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
8057     return Existing;
8058 
8059   // Nope it doesn't.  Remove the node from its current place in the maps.
8060   if (InsertPos)
8061     if (!RemoveNodeFromCSEMaps(N))
8062       InsertPos = nullptr;
8063 
8064   // Now we update the operands.
8065   for (unsigned i = 0; i != NumOps; ++i)
8066     if (N->OperandList[i] != Ops[i])
8067       N->OperandList[i].set(Ops[i]);
8068 
8069   updateDivergence(N);
8070   // If this gets put into a CSE map, add it.
8071   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
8072   return N;
8073 }
8074 
8075 /// DropOperands - Release the operands and set this node to have
8076 /// zero operands.
DropOperands()8077 void SDNode::DropOperands() {
8078   // Unlike the code in MorphNodeTo that does this, we don't need to
8079   // watch for dead nodes here.
8080   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
8081     SDUse &Use = *I++;
8082     Use.set(SDValue());
8083   }
8084 }
8085 
setNodeMemRefs(MachineSDNode * N,ArrayRef<MachineMemOperand * > NewMemRefs)8086 void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
8087                                   ArrayRef<MachineMemOperand *> NewMemRefs) {
8088   if (NewMemRefs.empty()) {
8089     N->clearMemRefs();
8090     return;
8091   }
8092 
8093   // Check if we can avoid allocating by storing a single reference directly.
8094   if (NewMemRefs.size() == 1) {
8095     N->MemRefs = NewMemRefs[0];
8096     N->NumMemRefs = 1;
8097     return;
8098   }
8099 
8100   MachineMemOperand **MemRefsBuffer =
8101       Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
8102   llvm::copy(NewMemRefs, MemRefsBuffer);
8103   N->MemRefs = MemRefsBuffer;
8104   N->NumMemRefs = static_cast<int>(NewMemRefs.size());
8105 }
8106 
8107 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
8108 /// machine opcode.
8109 ///
SelectNodeTo(SDNode * N,unsigned MachineOpc,EVT VT)8110 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8111                                    EVT VT) {
8112   SDVTList VTs = getVTList(VT);
8113   return SelectNodeTo(N, MachineOpc, VTs, None);
8114 }
8115 
SelectNodeTo(SDNode * N,unsigned MachineOpc,EVT VT,SDValue Op1)8116 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8117                                    EVT VT, SDValue Op1) {
8118   SDVTList VTs = getVTList(VT);
8119   SDValue Ops[] = { Op1 };
8120   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8121 }
8122 
SelectNodeTo(SDNode * N,unsigned MachineOpc,EVT VT,SDValue Op1,SDValue Op2)8123 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8124                                    EVT VT, SDValue Op1,
8125                                    SDValue Op2) {
8126   SDVTList VTs = getVTList(VT);
8127   SDValue Ops[] = { Op1, Op2 };
8128   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8129 }
8130 
SelectNodeTo(SDNode * N,unsigned MachineOpc,EVT VT,SDValue Op1,SDValue Op2,SDValue Op3)8131 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8132                                    EVT VT, SDValue Op1,
8133                                    SDValue Op2, SDValue Op3) {
8134   SDVTList VTs = getVTList(VT);
8135   SDValue Ops[] = { Op1, Op2, Op3 };
8136   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8137 }
8138 
SelectNodeTo(SDNode * N,unsigned MachineOpc,EVT VT,ArrayRef<SDValue> Ops)8139 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8140                                    EVT VT, ArrayRef<SDValue> Ops) {
8141   SDVTList VTs = getVTList(VT);
8142   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8143 }
8144 
SelectNodeTo(SDNode * N,unsigned MachineOpc,EVT VT1,EVT VT2,ArrayRef<SDValue> Ops)8145 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8146                                    EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
8147   SDVTList VTs = getVTList(VT1, VT2);
8148   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8149 }
8150 
SelectNodeTo(SDNode * N,unsigned MachineOpc,EVT VT1,EVT VT2)8151 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8152                                    EVT VT1, EVT VT2) {
8153   SDVTList VTs = getVTList(VT1, VT2);
8154   return SelectNodeTo(N, MachineOpc, VTs, None);
8155 }
8156 
SelectNodeTo(SDNode * N,unsigned MachineOpc,EVT VT1,EVT VT2,EVT VT3,ArrayRef<SDValue> Ops)8157 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8158                                    EVT VT1, EVT VT2, EVT VT3,
8159                                    ArrayRef<SDValue> Ops) {
8160   SDVTList VTs = getVTList(VT1, VT2, VT3);
8161   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8162 }
8163 
SelectNodeTo(SDNode * N,unsigned MachineOpc,EVT VT1,EVT VT2,SDValue Op1,SDValue Op2)8164 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8165                                    EVT VT1, EVT VT2,
8166                                    SDValue Op1, SDValue Op2) {
8167   SDVTList VTs = getVTList(VT1, VT2);
8168   SDValue Ops[] = { Op1, Op2 };
8169   return SelectNodeTo(N, MachineOpc, VTs, Ops);
8170 }
8171 
SelectNodeTo(SDNode * N,unsigned MachineOpc,SDVTList VTs,ArrayRef<SDValue> Ops)8172 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
8173                                    SDVTList VTs,ArrayRef<SDValue> Ops) {
8174   SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
8175   // Reset the NodeID to -1.
8176   New->setNodeId(-1);
8177   if (New != N) {
8178     ReplaceAllUsesWith(N, New);
8179     RemoveDeadNode(N);
8180   }
8181   return New;
8182 }
8183 
8184 /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
8185 /// the line number information on the merged node since it is not possible to
8186 /// preserve the information that operation is associated with multiple lines.
8187 /// This will make the debugger working better at -O0, were there is a higher
8188 /// probability having other instructions associated with that line.
8189 ///
8190 /// For IROrder, we keep the smaller of the two
UpdateSDLocOnMergeSDNode(SDNode * N,const SDLoc & OLoc)8191 SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
8192   DebugLoc NLoc = N->getDebugLoc();
8193   if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
8194     N->setDebugLoc(DebugLoc());
8195   }
8196   unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
8197   N->setIROrder(Order);
8198   return N;
8199 }
8200 
8201 /// MorphNodeTo - This *mutates* the specified node to have the specified
8202 /// return type, opcode, and operands.
8203 ///
8204 /// Note that MorphNodeTo returns the resultant node.  If there is already a
8205 /// node of the specified opcode and operands, it returns that node instead of
8206 /// the current one.  Note that the SDLoc need not be the same.
8207 ///
8208 /// Using MorphNodeTo is faster than creating a new node and swapping it in
8209 /// with ReplaceAllUsesWith both because it often avoids allocating a new
8210 /// node, and because it doesn't require CSE recalculation for any of
8211 /// the node's users.
8212 ///
8213 /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
8214 /// As a consequence it isn't appropriate to use from within the DAG combiner or
8215 /// the legalizer which maintain worklists that would need to be updated when
8216 /// deleting things.
MorphNodeTo(SDNode * N,unsigned Opc,SDVTList VTs,ArrayRef<SDValue> Ops)8217 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
8218                                   SDVTList VTs, ArrayRef<SDValue> Ops) {
8219   // If an identical node already exists, use it.
8220   void *IP = nullptr;
8221   if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
8222     FoldingSetNodeID ID;
8223     AddNodeIDNode(ID, Opc, VTs, Ops);
8224     if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
8225       return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
8226   }
8227 
8228   if (!RemoveNodeFromCSEMaps(N))
8229     IP = nullptr;
8230 
8231   // Start the morphing.
8232   N->NodeType = Opc;
8233   N->ValueList = VTs.VTs;
8234   N->NumValues = VTs.NumVTs;
8235 
8236   // Clear the operands list, updating used nodes to remove this from their
8237   // use list.  Keep track of any operands that become dead as a result.
8238   SmallPtrSet<SDNode*, 16> DeadNodeSet;
8239   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
8240     SDUse &Use = *I++;
8241     SDNode *Used = Use.getNode();
8242     Use.set(SDValue());
8243     if (Used->use_empty())
8244       DeadNodeSet.insert(Used);
8245   }
8246 
8247   // For MachineNode, initialize the memory references information.
8248   if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
8249     MN->clearMemRefs();
8250 
8251   // Swap for an appropriately sized array from the recycler.
8252   removeOperands(N);
8253   createOperands(N, Ops);
8254 
8255   // Delete any nodes that are still dead after adding the uses for the
8256   // new operands.
8257   if (!DeadNodeSet.empty()) {
8258     SmallVector<SDNode *, 16> DeadNodes;
8259     for (SDNode *N : DeadNodeSet)
8260       if (N->use_empty())
8261         DeadNodes.push_back(N);
8262     RemoveDeadNodes(DeadNodes);
8263   }
8264 
8265   if (IP)
8266     CSEMap.InsertNode(N, IP);   // Memoize the new node.
8267   return N;
8268 }
8269 
mutateStrictFPToFP(SDNode * Node)8270 SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
8271   unsigned OrigOpc = Node->getOpcode();
8272   unsigned NewOpc;
8273   switch (OrigOpc) {
8274   default:
8275     llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
8276 #define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8277   case ISD::STRICT_##DAGN: NewOpc = ISD::DAGN; break;
8278 #define CMP_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN)               \
8279   case ISD::STRICT_##DAGN: NewOpc = ISD::SETCC; break;
8280 #include "llvm/IR/ConstrainedOps.def"
8281   }
8282 
8283   assert(Node->getNumValues() == 2 && "Unexpected number of results!");
8284 
8285   // We're taking this node out of the chain, so we need to re-link things.
8286   SDValue InputChain = Node->getOperand(0);
8287   SDValue OutputChain = SDValue(Node, 1);
8288   ReplaceAllUsesOfValueWith(OutputChain, InputChain);
8289 
8290   SmallVector<SDValue, 3> Ops;
8291   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
8292     Ops.push_back(Node->getOperand(i));
8293 
8294   SDVTList VTs = getVTList(Node->getValueType(0));
8295   SDNode *Res = MorphNodeTo(Node, NewOpc, VTs, Ops);
8296 
8297   // MorphNodeTo can operate in two ways: if an existing node with the
8298   // specified operands exists, it can just return it.  Otherwise, it
8299   // updates the node in place to have the requested operands.
8300   if (Res == Node) {
8301     // If we updated the node in place, reset the node ID.  To the isel,
8302     // this should be just like a newly allocated machine node.
8303     Res->setNodeId(-1);
8304   } else {
8305     ReplaceAllUsesWith(Node, Res);
8306     RemoveDeadNode(Node);
8307   }
8308 
8309   return Res;
8310 }
8311 
8312 /// getMachineNode - These are used for target selectors to create a new node
8313 /// with specified return type(s), MachineInstr opcode, and operands.
8314 ///
8315 /// Note that getMachineNode returns the resultant node.  If there is already a
8316 /// node of the specified opcode and operands, it returns that node instead of
8317 /// the current one.
getMachineNode(unsigned Opcode,const SDLoc & dl,EVT VT)8318 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8319                                             EVT VT) {
8320   SDVTList VTs = getVTList(VT);
8321   return getMachineNode(Opcode, dl, VTs, None);
8322 }
8323 
getMachineNode(unsigned Opcode,const SDLoc & dl,EVT VT,SDValue Op1)8324 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8325                                             EVT VT, SDValue Op1) {
8326   SDVTList VTs = getVTList(VT);
8327   SDValue Ops[] = { Op1 };
8328   return getMachineNode(Opcode, dl, VTs, Ops);
8329 }
8330 
getMachineNode(unsigned Opcode,const SDLoc & dl,EVT VT,SDValue Op1,SDValue Op2)8331 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8332                                             EVT VT, SDValue Op1, SDValue Op2) {
8333   SDVTList VTs = getVTList(VT);
8334   SDValue Ops[] = { Op1, Op2 };
8335   return getMachineNode(Opcode, dl, VTs, Ops);
8336 }
8337 
getMachineNode(unsigned Opcode,const SDLoc & dl,EVT VT,SDValue Op1,SDValue Op2,SDValue Op3)8338 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8339                                             EVT VT, SDValue Op1, SDValue Op2,
8340                                             SDValue Op3) {
8341   SDVTList VTs = getVTList(VT);
8342   SDValue Ops[] = { Op1, Op2, Op3 };
8343   return getMachineNode(Opcode, dl, VTs, Ops);
8344 }
8345 
getMachineNode(unsigned Opcode,const SDLoc & dl,EVT VT,ArrayRef<SDValue> Ops)8346 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8347                                             EVT VT, ArrayRef<SDValue> Ops) {
8348   SDVTList VTs = getVTList(VT);
8349   return getMachineNode(Opcode, dl, VTs, Ops);
8350 }
8351 
getMachineNode(unsigned Opcode,const SDLoc & dl,EVT VT1,EVT VT2,SDValue Op1,SDValue Op2)8352 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8353                                             EVT VT1, EVT VT2, SDValue Op1,
8354                                             SDValue Op2) {
8355   SDVTList VTs = getVTList(VT1, VT2);
8356   SDValue Ops[] = { Op1, Op2 };
8357   return getMachineNode(Opcode, dl, VTs, Ops);
8358 }
8359 
getMachineNode(unsigned Opcode,const SDLoc & dl,EVT VT1,EVT VT2,SDValue Op1,SDValue Op2,SDValue Op3)8360 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8361                                             EVT VT1, EVT VT2, SDValue Op1,
8362                                             SDValue Op2, SDValue Op3) {
8363   SDVTList VTs = getVTList(VT1, VT2);
8364   SDValue Ops[] = { Op1, Op2, Op3 };
8365   return getMachineNode(Opcode, dl, VTs, Ops);
8366 }
8367 
getMachineNode(unsigned Opcode,const SDLoc & dl,EVT VT1,EVT VT2,ArrayRef<SDValue> Ops)8368 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8369                                             EVT VT1, EVT VT2,
8370                                             ArrayRef<SDValue> Ops) {
8371   SDVTList VTs = getVTList(VT1, VT2);
8372   return getMachineNode(Opcode, dl, VTs, Ops);
8373 }
8374 
getMachineNode(unsigned Opcode,const SDLoc & dl,EVT VT1,EVT VT2,EVT VT3,SDValue Op1,SDValue Op2)8375 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8376                                             EVT VT1, EVT VT2, EVT VT3,
8377                                             SDValue Op1, SDValue Op2) {
8378   SDVTList VTs = getVTList(VT1, VT2, VT3);
8379   SDValue Ops[] = { Op1, Op2 };
8380   return getMachineNode(Opcode, dl, VTs, Ops);
8381 }
8382 
getMachineNode(unsigned Opcode,const SDLoc & dl,EVT VT1,EVT VT2,EVT VT3,SDValue Op1,SDValue Op2,SDValue Op3)8383 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8384                                             EVT VT1, EVT VT2, EVT VT3,
8385                                             SDValue Op1, SDValue Op2,
8386                                             SDValue Op3) {
8387   SDVTList VTs = getVTList(VT1, VT2, VT3);
8388   SDValue Ops[] = { Op1, Op2, Op3 };
8389   return getMachineNode(Opcode, dl, VTs, Ops);
8390 }
8391 
getMachineNode(unsigned Opcode,const SDLoc & dl,EVT VT1,EVT VT2,EVT VT3,ArrayRef<SDValue> Ops)8392 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8393                                             EVT VT1, EVT VT2, EVT VT3,
8394                                             ArrayRef<SDValue> Ops) {
8395   SDVTList VTs = getVTList(VT1, VT2, VT3);
8396   return getMachineNode(Opcode, dl, VTs, Ops);
8397 }
8398 
getMachineNode(unsigned Opcode,const SDLoc & dl,ArrayRef<EVT> ResultTys,ArrayRef<SDValue> Ops)8399 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
8400                                             ArrayRef<EVT> ResultTys,
8401                                             ArrayRef<SDValue> Ops) {
8402   SDVTList VTs = getVTList(ResultTys);
8403   return getMachineNode(Opcode, dl, VTs, Ops);
8404 }
8405 
getMachineNode(unsigned Opcode,const SDLoc & DL,SDVTList VTs,ArrayRef<SDValue> Ops)8406 MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
8407                                             SDVTList VTs,
8408                                             ArrayRef<SDValue> Ops) {
8409   bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
8410   MachineSDNode *N;
8411   void *IP = nullptr;
8412 
8413   if (DoCSE) {
8414     FoldingSetNodeID ID;
8415     AddNodeIDNode(ID, ~Opcode, VTs, Ops);
8416     IP = nullptr;
8417     if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
8418       return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
8419     }
8420   }
8421 
8422   // Allocate a new MachineSDNode.
8423   N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
8424   createOperands(N, Ops);
8425 
8426   if (DoCSE)
8427     CSEMap.InsertNode(N, IP);
8428 
8429   InsertNode(N);
8430   NewSDValueDbgMsg(SDValue(N, 0), "Creating new machine node: ", this);
8431   return N;
8432 }
8433 
8434 /// getTargetExtractSubreg - A convenience function for creating
8435 /// TargetOpcode::EXTRACT_SUBREG nodes.
getTargetExtractSubreg(int SRIdx,const SDLoc & DL,EVT VT,SDValue Operand)8436 SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8437                                              SDValue Operand) {
8438   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8439   SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
8440                                   VT, Operand, SRIdxVal);
8441   return SDValue(Subreg, 0);
8442 }
8443 
8444 /// getTargetInsertSubreg - A convenience function for creating
8445 /// TargetOpcode::INSERT_SUBREG nodes.
getTargetInsertSubreg(int SRIdx,const SDLoc & DL,EVT VT,SDValue Operand,SDValue Subreg)8446 SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
8447                                             SDValue Operand, SDValue Subreg) {
8448   SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
8449   SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
8450                                   VT, Operand, Subreg, SRIdxVal);
8451   return SDValue(Result, 0);
8452 }
8453 
8454 /// getNodeIfExists - Get the specified node if it's already available, or
8455 /// else return NULL.
getNodeIfExists(unsigned Opcode,SDVTList VTList,ArrayRef<SDValue> Ops,const SDNodeFlags Flags)8456 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
8457                                       ArrayRef<SDValue> Ops,
8458                                       const SDNodeFlags Flags) {
8459   if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
8460     FoldingSetNodeID ID;
8461     AddNodeIDNode(ID, Opcode, VTList, Ops);
8462     void *IP = nullptr;
8463     if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
8464       E->intersectFlagsWith(Flags);
8465       return E;
8466     }
8467   }
8468   return nullptr;
8469 }
8470 
8471 /// getDbgValue - Creates a SDDbgValue node.
8472 ///
8473 /// SDNode
getDbgValue(DIVariable * Var,DIExpression * Expr,SDNode * N,unsigned R,bool IsIndirect,const DebugLoc & DL,unsigned O)8474 SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
8475                                       SDNode *N, unsigned R, bool IsIndirect,
8476                                       const DebugLoc &DL, unsigned O) {
8477   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8478          "Expected inlined-at fields to agree");
8479   return new (DbgInfo->getAlloc())
8480       SDDbgValue(Var, Expr, N, R, IsIndirect, DL, O);
8481 }
8482 
8483 /// Constant
getConstantDbgValue(DIVariable * Var,DIExpression * Expr,const Value * C,const DebugLoc & DL,unsigned O)8484 SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
8485                                               DIExpression *Expr,
8486                                               const Value *C,
8487                                               const DebugLoc &DL, unsigned O) {
8488   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8489          "Expected inlined-at fields to agree");
8490   return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, DL, O);
8491 }
8492 
8493 /// FrameIndex
getFrameIndexDbgValue(DIVariable * Var,DIExpression * Expr,unsigned FI,bool IsIndirect,const DebugLoc & DL,unsigned O)8494 SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
8495                                                 DIExpression *Expr, unsigned FI,
8496                                                 bool IsIndirect,
8497                                                 const DebugLoc &DL,
8498                                                 unsigned O) {
8499   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8500          "Expected inlined-at fields to agree");
8501   return new (DbgInfo->getAlloc())
8502       SDDbgValue(Var, Expr, FI, IsIndirect, DL, O, SDDbgValue::FRAMEIX);
8503 }
8504 
8505 /// VReg
getVRegDbgValue(DIVariable * Var,DIExpression * Expr,unsigned VReg,bool IsIndirect,const DebugLoc & DL,unsigned O)8506 SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var,
8507                                           DIExpression *Expr,
8508                                           unsigned VReg, bool IsIndirect,
8509                                           const DebugLoc &DL, unsigned O) {
8510   assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
8511          "Expected inlined-at fields to agree");
8512   return new (DbgInfo->getAlloc())
8513       SDDbgValue(Var, Expr, VReg, IsIndirect, DL, O, SDDbgValue::VREG);
8514 }
8515 
transferDbgValues(SDValue From,SDValue To,unsigned OffsetInBits,unsigned SizeInBits,bool InvalidateDbg)8516 void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
8517                                      unsigned OffsetInBits, unsigned SizeInBits,
8518                                      bool InvalidateDbg) {
8519   SDNode *FromNode = From.getNode();
8520   SDNode *ToNode = To.getNode();
8521   assert(FromNode && ToNode && "Can't modify dbg values");
8522 
8523   // PR35338
8524   // TODO: assert(From != To && "Redundant dbg value transfer");
8525   // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
8526   if (From == To || FromNode == ToNode)
8527     return;
8528 
8529   if (!FromNode->getHasDebugValue())
8530     return;
8531 
8532   SmallVector<SDDbgValue *, 2> ClonedDVs;
8533   for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
8534     if (Dbg->getKind() != SDDbgValue::SDNODE || Dbg->isInvalidated())
8535       continue;
8536 
8537     // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
8538 
8539     // Just transfer the dbg value attached to From.
8540     if (Dbg->getResNo() != From.getResNo())
8541       continue;
8542 
8543     DIVariable *Var = Dbg->getVariable();
8544     auto *Expr = Dbg->getExpression();
8545     // If a fragment is requested, update the expression.
8546     if (SizeInBits) {
8547       // When splitting a larger (e.g., sign-extended) value whose
8548       // lower bits are described with an SDDbgValue, do not attempt
8549       // to transfer the SDDbgValue to the upper bits.
8550       if (auto FI = Expr->getFragmentInfo())
8551         if (OffsetInBits + SizeInBits > FI->SizeInBits)
8552           continue;
8553       auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
8554                                                              SizeInBits);
8555       if (!Fragment)
8556         continue;
8557       Expr = *Fragment;
8558     }
8559     // Clone the SDDbgValue and move it to To.
8560     SDDbgValue *Clone = getDbgValue(
8561         Var, Expr, ToNode, To.getResNo(), Dbg->isIndirect(), Dbg->getDebugLoc(),
8562         std::max(ToNode->getIROrder(), Dbg->getOrder()));
8563     ClonedDVs.push_back(Clone);
8564 
8565     if (InvalidateDbg) {
8566       // Invalidate value and indicate the SDDbgValue should not be emitted.
8567       Dbg->setIsInvalidated();
8568       Dbg->setIsEmitted();
8569     }
8570   }
8571 
8572   for (SDDbgValue *Dbg : ClonedDVs)
8573     AddDbgValue(Dbg, ToNode, false);
8574 }
8575 
salvageDebugInfo(SDNode & N)8576 void SelectionDAG::salvageDebugInfo(SDNode &N) {
8577   if (!N.getHasDebugValue())
8578     return;
8579 
8580   SmallVector<SDDbgValue *, 2> ClonedDVs;
8581   for (auto DV : GetDbgValues(&N)) {
8582     if (DV->isInvalidated())
8583       continue;
8584     switch (N.getOpcode()) {
8585     default:
8586       break;
8587     case ISD::ADD:
8588       SDValue N0 = N.getOperand(0);
8589       SDValue N1 = N.getOperand(1);
8590       if (!isConstantIntBuildVectorOrConstantInt(N0) &&
8591           isConstantIntBuildVectorOrConstantInt(N1)) {
8592         uint64_t Offset = N.getConstantOperandVal(1);
8593         // Rewrite an ADD constant node into a DIExpression. Since we are
8594         // performing arithmetic to compute the variable's *value* in the
8595         // DIExpression, we need to mark the expression with a
8596         // DW_OP_stack_value.
8597         auto *DIExpr = DV->getExpression();
8598         DIExpr =
8599             DIExpression::prepend(DIExpr, DIExpression::StackValue, Offset);
8600         SDDbgValue *Clone =
8601             getDbgValue(DV->getVariable(), DIExpr, N0.getNode(), N0.getResNo(),
8602                         DV->isIndirect(), DV->getDebugLoc(), DV->getOrder());
8603         ClonedDVs.push_back(Clone);
8604         DV->setIsInvalidated();
8605         DV->setIsEmitted();
8606         LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
8607                    N0.getNode()->dumprFull(this);
8608                    dbgs() << " into " << *DIExpr << '\n');
8609       }
8610     }
8611   }
8612 
8613   for (SDDbgValue *Dbg : ClonedDVs)
8614     AddDbgValue(Dbg, Dbg->getSDNode(), false);
8615 }
8616 
8617 /// Creates a SDDbgLabel node.
getDbgLabel(DILabel * Label,const DebugLoc & DL,unsigned O)8618 SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
8619                                       const DebugLoc &DL, unsigned O) {
8620   assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
8621          "Expected inlined-at fields to agree");
8622   return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
8623 }
8624 
8625 namespace {
8626 
8627 /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
8628 /// pointed to by a use iterator is deleted, increment the use iterator
8629 /// so that it doesn't dangle.
8630 ///
8631 class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
8632   SDNode::use_iterator &UI;
8633   SDNode::use_iterator &UE;
8634 
NodeDeleted(SDNode * N,SDNode * E)8635   void NodeDeleted(SDNode *N, SDNode *E) override {
8636     // Increment the iterator as needed.
8637     while (UI != UE && N == *UI)
8638       ++UI;
8639   }
8640 
8641 public:
RAUWUpdateListener(SelectionDAG & d,SDNode::use_iterator & ui,SDNode::use_iterator & ue)8642   RAUWUpdateListener(SelectionDAG &d,
8643                      SDNode::use_iterator &ui,
8644                      SDNode::use_iterator &ue)
8645     : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
8646 };
8647 
8648 } // end anonymous namespace
8649 
8650 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8651 /// This can cause recursive merging of nodes in the DAG.
8652 ///
8653 /// This version assumes From has a single result value.
8654 ///
ReplaceAllUsesWith(SDValue FromN,SDValue To)8655 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
8656   SDNode *From = FromN.getNode();
8657   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
8658          "Cannot replace with this method!");
8659   assert(From != To.getNode() && "Cannot replace uses of with self");
8660 
8661   // Preserve Debug Values
8662   transferDbgValues(FromN, To);
8663 
8664   // Iterate over all the existing uses of From. New uses will be added
8665   // to the beginning of the use list, which we avoid visiting.
8666   // This specifically avoids visiting uses of From that arise while the
8667   // replacement is happening, because any such uses would be the result
8668   // of CSE: If an existing node looks like From after one of its operands
8669   // is replaced by To, we don't want to replace of all its users with To
8670   // too. See PR3018 for more info.
8671   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8672   RAUWUpdateListener Listener(*this, UI, UE);
8673   while (UI != UE) {
8674     SDNode *User = *UI;
8675 
8676     // This node is about to morph, remove its old self from the CSE maps.
8677     RemoveNodeFromCSEMaps(User);
8678 
8679     // A user can appear in a use list multiple times, and when this
8680     // happens the uses are usually next to each other in the list.
8681     // To help reduce the number of CSE recomputations, process all
8682     // the uses of this user that we can find this way.
8683     do {
8684       SDUse &Use = UI.getUse();
8685       ++UI;
8686       Use.set(To);
8687       if (To->isDivergent() != From->isDivergent())
8688         updateDivergence(User);
8689     } while (UI != UE && *UI == User);
8690     // Now that we have modified User, add it back to the CSE maps.  If it
8691     // already exists there, recursively merge the results together.
8692     AddModifiedNodeToCSEMaps(User);
8693   }
8694 
8695   // If we just RAUW'd the root, take note.
8696   if (FromN == getRoot())
8697     setRoot(To);
8698 }
8699 
8700 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8701 /// This can cause recursive merging of nodes in the DAG.
8702 ///
8703 /// This version assumes that for each value of From, there is a
8704 /// corresponding value in To in the same position with the same type.
8705 ///
ReplaceAllUsesWith(SDNode * From,SDNode * To)8706 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
8707 #ifndef NDEBUG
8708   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8709     assert((!From->hasAnyUseOfValue(i) ||
8710             From->getValueType(i) == To->getValueType(i)) &&
8711            "Cannot use this version of ReplaceAllUsesWith!");
8712 #endif
8713 
8714   // Handle the trivial case.
8715   if (From == To)
8716     return;
8717 
8718   // Preserve Debug Info. Only do this if there's a use.
8719   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8720     if (From->hasAnyUseOfValue(i)) {
8721       assert((i < To->getNumValues()) && "Invalid To location");
8722       transferDbgValues(SDValue(From, i), SDValue(To, i));
8723     }
8724 
8725   // Iterate over just the existing users of From. See the comments in
8726   // the ReplaceAllUsesWith above.
8727   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8728   RAUWUpdateListener Listener(*this, UI, UE);
8729   while (UI != UE) {
8730     SDNode *User = *UI;
8731 
8732     // This node is about to morph, remove its old self from the CSE maps.
8733     RemoveNodeFromCSEMaps(User);
8734 
8735     // A user can appear in a use list multiple times, and when this
8736     // happens the uses are usually next to each other in the list.
8737     // To help reduce the number of CSE recomputations, process all
8738     // the uses of this user that we can find this way.
8739     do {
8740       SDUse &Use = UI.getUse();
8741       ++UI;
8742       Use.setNode(To);
8743       if (To->isDivergent() != From->isDivergent())
8744         updateDivergence(User);
8745     } while (UI != UE && *UI == User);
8746 
8747     // Now that we have modified User, add it back to the CSE maps.  If it
8748     // already exists there, recursively merge the results together.
8749     AddModifiedNodeToCSEMaps(User);
8750   }
8751 
8752   // If we just RAUW'd the root, take note.
8753   if (From == getRoot().getNode())
8754     setRoot(SDValue(To, getRoot().getResNo()));
8755 }
8756 
8757 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
8758 /// This can cause recursive merging of nodes in the DAG.
8759 ///
8760 /// This version can replace From with any result values.  To must match the
8761 /// number and types of values returned by From.
ReplaceAllUsesWith(SDNode * From,const SDValue * To)8762 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
8763   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
8764     return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
8765 
8766   // Preserve Debug Info.
8767   for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
8768     transferDbgValues(SDValue(From, i), To[i]);
8769 
8770   // Iterate over just the existing users of From. See the comments in
8771   // the ReplaceAllUsesWith above.
8772   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
8773   RAUWUpdateListener Listener(*this, UI, UE);
8774   while (UI != UE) {
8775     SDNode *User = *UI;
8776 
8777     // This node is about to morph, remove its old self from the CSE maps.
8778     RemoveNodeFromCSEMaps(User);
8779 
8780     // A user can appear in a use list multiple times, and when this happens the
8781     // uses are usually next to each other in the list.  To help reduce the
8782     // number of CSE and divergence recomputations, process all the uses of this
8783     // user that we can find this way.
8784     bool To_IsDivergent = false;
8785     do {
8786       SDUse &Use = UI.getUse();
8787       const SDValue &ToOp = To[Use.getResNo()];
8788       ++UI;
8789       Use.set(ToOp);
8790       To_IsDivergent |= ToOp->isDivergent();
8791     } while (UI != UE && *UI == User);
8792 
8793     if (To_IsDivergent != From->isDivergent())
8794       updateDivergence(User);
8795 
8796     // Now that we have modified User, add it back to the CSE maps.  If it
8797     // already exists there, recursively merge the results together.
8798     AddModifiedNodeToCSEMaps(User);
8799   }
8800 
8801   // If we just RAUW'd the root, take note.
8802   if (From == getRoot().getNode())
8803     setRoot(SDValue(To[getRoot().getResNo()]));
8804 }
8805 
8806 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
8807 /// uses of other values produced by From.getNode() alone.  The Deleted
8808 /// vector is handled the same way as for ReplaceAllUsesWith.
ReplaceAllUsesOfValueWith(SDValue From,SDValue To)8809 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
8810   // Handle the really simple, really trivial case efficiently.
8811   if (From == To) return;
8812 
8813   // Handle the simple, trivial, case efficiently.
8814   if (From.getNode()->getNumValues() == 1) {
8815     ReplaceAllUsesWith(From, To);
8816     return;
8817   }
8818 
8819   // Preserve Debug Info.
8820   transferDbgValues(From, To);
8821 
8822   // Iterate over just the existing users of From. See the comments in
8823   // the ReplaceAllUsesWith above.
8824   SDNode::use_iterator UI = From.getNode()->use_begin(),
8825                        UE = From.getNode()->use_end();
8826   RAUWUpdateListener Listener(*this, UI, UE);
8827   while (UI != UE) {
8828     SDNode *User = *UI;
8829     bool UserRemovedFromCSEMaps = false;
8830 
8831     // A user can appear in a use list multiple times, and when this
8832     // happens the uses are usually next to each other in the list.
8833     // To help reduce the number of CSE recomputations, process all
8834     // the uses of this user that we can find this way.
8835     do {
8836       SDUse &Use = UI.getUse();
8837 
8838       // Skip uses of different values from the same node.
8839       if (Use.getResNo() != From.getResNo()) {
8840         ++UI;
8841         continue;
8842       }
8843 
8844       // If this node hasn't been modified yet, it's still in the CSE maps,
8845       // so remove its old self from the CSE maps.
8846       if (!UserRemovedFromCSEMaps) {
8847         RemoveNodeFromCSEMaps(User);
8848         UserRemovedFromCSEMaps = true;
8849       }
8850 
8851       ++UI;
8852       Use.set(To);
8853       if (To->isDivergent() != From->isDivergent())
8854         updateDivergence(User);
8855     } while (UI != UE && *UI == User);
8856     // We are iterating over all uses of the From node, so if a use
8857     // doesn't use the specific value, no changes are made.
8858     if (!UserRemovedFromCSEMaps)
8859       continue;
8860 
8861     // Now that we have modified User, add it back to the CSE maps.  If it
8862     // already exists there, recursively merge the results together.
8863     AddModifiedNodeToCSEMaps(User);
8864   }
8865 
8866   // If we just RAUW'd the root, take note.
8867   if (From == getRoot())
8868     setRoot(To);
8869 }
8870 
8871 namespace {
8872 
8873   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
8874   /// to record information about a use.
8875   struct UseMemo {
8876     SDNode *User;
8877     unsigned Index;
8878     SDUse *Use;
8879   };
8880 
8881   /// operator< - Sort Memos by User.
operator <(const UseMemo & L,const UseMemo & R)8882   bool operator<(const UseMemo &L, const UseMemo &R) {
8883     return (intptr_t)L.User < (intptr_t)R.User;
8884   }
8885 
8886 } // end anonymous namespace
8887 
updateDivergence(SDNode * N)8888 void SelectionDAG::updateDivergence(SDNode * N)
8889 {
8890   if (TLI->isSDNodeAlwaysUniform(N))
8891     return;
8892   bool IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
8893   for (auto &Op : N->ops()) {
8894     if (Op.Val.getValueType() != MVT::Other)
8895       IsDivergent |= Op.getNode()->isDivergent();
8896   }
8897   if (N->SDNodeBits.IsDivergent != IsDivergent) {
8898     N->SDNodeBits.IsDivergent = IsDivergent;
8899     for (auto U : N->uses()) {
8900       updateDivergence(U);
8901     }
8902   }
8903 }
8904 
CreateTopologicalOrder(std::vector<SDNode * > & Order)8905 void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode *> &Order) {
8906   DenseMap<SDNode *, unsigned> Degree;
8907   Order.reserve(AllNodes.size());
8908   for (auto &N : allnodes()) {
8909     unsigned NOps = N.getNumOperands();
8910     Degree[&N] = NOps;
8911     if (0 == NOps)
8912       Order.push_back(&N);
8913   }
8914   for (size_t I = 0; I != Order.size(); ++I) {
8915     SDNode *N = Order[I];
8916     for (auto U : N->uses()) {
8917       unsigned &UnsortedOps = Degree[U];
8918       if (0 == --UnsortedOps)
8919         Order.push_back(U);
8920     }
8921   }
8922 }
8923 
8924 #ifndef NDEBUG
VerifyDAGDiverence()8925 void SelectionDAG::VerifyDAGDiverence() {
8926   std::vector<SDNode *> TopoOrder;
8927   CreateTopologicalOrder(TopoOrder);
8928   const TargetLowering &TLI = getTargetLoweringInfo();
8929   DenseMap<const SDNode *, bool> DivergenceMap;
8930   for (auto &N : allnodes()) {
8931     DivergenceMap[&N] = false;
8932   }
8933   for (auto N : TopoOrder) {
8934     bool IsDivergent = DivergenceMap[N];
8935     bool IsSDNodeDivergent = TLI.isSDNodeSourceOfDivergence(N, FLI, DA);
8936     for (auto &Op : N->ops()) {
8937       if (Op.Val.getValueType() != MVT::Other)
8938         IsSDNodeDivergent |= DivergenceMap[Op.getNode()];
8939     }
8940     if (!IsDivergent && IsSDNodeDivergent && !TLI.isSDNodeAlwaysUniform(N)) {
8941       DivergenceMap[N] = true;
8942     }
8943   }
8944   for (auto &N : allnodes()) {
8945     (void)N;
8946     assert(DivergenceMap[&N] == N.isDivergent() &&
8947            "Divergence bit inconsistency detected\n");
8948   }
8949 }
8950 #endif
8951 
8952 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
8953 /// uses of other values produced by From.getNode() alone.  The same value
8954 /// may appear in both the From and To list.  The Deleted vector is
8955 /// handled the same way as for ReplaceAllUsesWith.
ReplaceAllUsesOfValuesWith(const SDValue * From,const SDValue * To,unsigned Num)8956 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
8957                                               const SDValue *To,
8958                                               unsigned Num){
8959   // Handle the simple, trivial case efficiently.
8960   if (Num == 1)
8961     return ReplaceAllUsesOfValueWith(*From, *To);
8962 
8963   transferDbgValues(*From, *To);
8964 
8965   // Read up all the uses and make records of them. This helps
8966   // processing new uses that are introduced during the
8967   // replacement process.
8968   SmallVector<UseMemo, 4> Uses;
8969   for (unsigned i = 0; i != Num; ++i) {
8970     unsigned FromResNo = From[i].getResNo();
8971     SDNode *FromNode = From[i].getNode();
8972     for (SDNode::use_iterator UI = FromNode->use_begin(),
8973          E = FromNode->use_end(); UI != E; ++UI) {
8974       SDUse &Use = UI.getUse();
8975       if (Use.getResNo() == FromResNo) {
8976         UseMemo Memo = { *UI, i, &Use };
8977         Uses.push_back(Memo);
8978       }
8979     }
8980   }
8981 
8982   // Sort the uses, so that all the uses from a given User are together.
8983   llvm::sort(Uses);
8984 
8985   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
8986        UseIndex != UseIndexEnd; ) {
8987     // We know that this user uses some value of From.  If it is the right
8988     // value, update it.
8989     SDNode *User = Uses[UseIndex].User;
8990 
8991     // This node is about to morph, remove its old self from the CSE maps.
8992     RemoveNodeFromCSEMaps(User);
8993 
8994     // The Uses array is sorted, so all the uses for a given User
8995     // are next to each other in the list.
8996     // To help reduce the number of CSE recomputations, process all
8997     // the uses of this user that we can find this way.
8998     do {
8999       unsigned i = Uses[UseIndex].Index;
9000       SDUse &Use = *Uses[UseIndex].Use;
9001       ++UseIndex;
9002 
9003       Use.set(To[i]);
9004     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
9005 
9006     // Now that we have modified User, add it back to the CSE maps.  If it
9007     // already exists there, recursively merge the results together.
9008     AddModifiedNodeToCSEMaps(User);
9009   }
9010 }
9011 
9012 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
9013 /// based on their topological order. It returns the maximum id and a vector
9014 /// of the SDNodes* in assigned order by reference.
AssignTopologicalOrder()9015 unsigned SelectionDAG::AssignTopologicalOrder() {
9016   unsigned DAGSize = 0;
9017 
9018   // SortedPos tracks the progress of the algorithm. Nodes before it are
9019   // sorted, nodes after it are unsorted. When the algorithm completes
9020   // it is at the end of the list.
9021   allnodes_iterator SortedPos = allnodes_begin();
9022 
9023   // Visit all the nodes. Move nodes with no operands to the front of
9024   // the list immediately. Annotate nodes that do have operands with their
9025   // operand count. Before we do this, the Node Id fields of the nodes
9026   // may contain arbitrary values. After, the Node Id fields for nodes
9027   // before SortedPos will contain the topological sort index, and the
9028   // Node Id fields for nodes At SortedPos and after will contain the
9029   // count of outstanding operands.
9030   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
9031     SDNode *N = &*I++;
9032     checkForCycles(N, this);
9033     unsigned Degree = N->getNumOperands();
9034     if (Degree == 0) {
9035       // A node with no uses, add it to the result array immediately.
9036       N->setNodeId(DAGSize++);
9037       allnodes_iterator Q(N);
9038       if (Q != SortedPos)
9039         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
9040       assert(SortedPos != AllNodes.end() && "Overran node list");
9041       ++SortedPos;
9042     } else {
9043       // Temporarily use the Node Id as scratch space for the degree count.
9044       N->setNodeId(Degree);
9045     }
9046   }
9047 
9048   // Visit all the nodes. As we iterate, move nodes into sorted order,
9049   // such that by the time the end is reached all nodes will be sorted.
9050   for (SDNode &Node : allnodes()) {
9051     SDNode *N = &Node;
9052     checkForCycles(N, this);
9053     // N is in sorted position, so all its uses have one less operand
9054     // that needs to be sorted.
9055     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
9056          UI != UE; ++UI) {
9057       SDNode *P = *UI;
9058       unsigned Degree = P->getNodeId();
9059       assert(Degree != 0 && "Invalid node degree");
9060       --Degree;
9061       if (Degree == 0) {
9062         // All of P's operands are sorted, so P may sorted now.
9063         P->setNodeId(DAGSize++);
9064         if (P->getIterator() != SortedPos)
9065           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
9066         assert(SortedPos != AllNodes.end() && "Overran node list");
9067         ++SortedPos;
9068       } else {
9069         // Update P's outstanding operand count.
9070         P->setNodeId(Degree);
9071       }
9072     }
9073     if (Node.getIterator() == SortedPos) {
9074 #ifndef NDEBUG
9075       allnodes_iterator I(N);
9076       SDNode *S = &*++I;
9077       dbgs() << "Overran sorted position:\n";
9078       S->dumprFull(this); dbgs() << "\n";
9079       dbgs() << "Checking if this is due to cycles\n";
9080       checkForCycles(this, true);
9081 #endif
9082       llvm_unreachable(nullptr);
9083     }
9084   }
9085 
9086   assert(SortedPos == AllNodes.end() &&
9087          "Topological sort incomplete!");
9088   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
9089          "First node in topological sort is not the entry token!");
9090   assert(AllNodes.front().getNodeId() == 0 &&
9091          "First node in topological sort has non-zero id!");
9092   assert(AllNodes.front().getNumOperands() == 0 &&
9093          "First node in topological sort has operands!");
9094   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
9095          "Last node in topologic sort has unexpected id!");
9096   assert(AllNodes.back().use_empty() &&
9097          "Last node in topologic sort has users!");
9098   assert(DAGSize == allnodes_size() && "Node count mismatch!");
9099   return DAGSize;
9100 }
9101 
9102 /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
9103 /// value is produced by SD.
AddDbgValue(SDDbgValue * DB,SDNode * SD,bool isParameter)9104 void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
9105   if (SD) {
9106     assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
9107     SD->setHasDebugValue(true);
9108   }
9109   DbgInfo->add(DB, SD, isParameter);
9110 }
9111 
AddDbgLabel(SDDbgLabel * DB)9112 void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) {
9113   DbgInfo->add(DB);
9114 }
9115 
makeEquivalentMemoryOrdering(LoadSDNode * OldLoad,SDValue NewMemOp)9116 SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
9117                                                    SDValue NewMemOp) {
9118   assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
9119   // The new memory operation must have the same position as the old load in
9120   // terms of memory dependency. Create a TokenFactor for the old load and new
9121   // memory operation and update uses of the old load's output chain to use that
9122   // TokenFactor.
9123   SDValue OldChain = SDValue(OldLoad, 1);
9124   SDValue NewChain = SDValue(NewMemOp.getNode(), 1);
9125   if (OldChain == NewChain || !OldLoad->hasAnyUseOfValue(1))
9126     return NewChain;
9127 
9128   SDValue TokenFactor =
9129       getNode(ISD::TokenFactor, SDLoc(OldLoad), MVT::Other, OldChain, NewChain);
9130   ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
9131   UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain);
9132   return TokenFactor;
9133 }
9134 
getSymbolFunctionGlobalAddress(SDValue Op,Function ** OutFunction)9135 SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
9136                                                      Function **OutFunction) {
9137   assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
9138 
9139   auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9140   auto *Module = MF->getFunction().getParent();
9141   auto *Function = Module->getFunction(Symbol);
9142 
9143   if (OutFunction != nullptr)
9144       *OutFunction = Function;
9145 
9146   if (Function != nullptr) {
9147     auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
9148     return getGlobalAddress(Function, SDLoc(Op), PtrTy);
9149   }
9150 
9151   std::string ErrorStr;
9152   raw_string_ostream ErrorFormatter(ErrorStr);
9153 
9154   ErrorFormatter << "Undefined external symbol ";
9155   ErrorFormatter << '"' << Symbol << '"';
9156   ErrorFormatter.flush();
9157 
9158   report_fatal_error(ErrorStr);
9159 }
9160 
9161 //===----------------------------------------------------------------------===//
9162 //                              SDNode Class
9163 //===----------------------------------------------------------------------===//
9164 
isNullConstant(SDValue V)9165 bool llvm::isNullConstant(SDValue V) {
9166   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9167   return Const != nullptr && Const->isNullValue();
9168 }
9169 
isNullFPConstant(SDValue V)9170 bool llvm::isNullFPConstant(SDValue V) {
9171   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
9172   return Const != nullptr && Const->isZero() && !Const->isNegative();
9173 }
9174 
isAllOnesConstant(SDValue V)9175 bool llvm::isAllOnesConstant(SDValue V) {
9176   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9177   return Const != nullptr && Const->isAllOnesValue();
9178 }
9179 
isOneConstant(SDValue V)9180 bool llvm::isOneConstant(SDValue V) {
9181   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
9182   return Const != nullptr && Const->isOne();
9183 }
9184 
peekThroughBitcasts(SDValue V)9185 SDValue llvm::peekThroughBitcasts(SDValue V) {
9186   while (V.getOpcode() == ISD::BITCAST)
9187     V = V.getOperand(0);
9188   return V;
9189 }
9190 
peekThroughOneUseBitcasts(SDValue V)9191 SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
9192   while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
9193     V = V.getOperand(0);
9194   return V;
9195 }
9196 
peekThroughExtractSubvectors(SDValue V)9197 SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
9198   while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
9199     V = V.getOperand(0);
9200   return V;
9201 }
9202 
isBitwiseNot(SDValue V,bool AllowUndefs)9203 bool llvm::isBitwiseNot(SDValue V, bool AllowUndefs) {
9204   if (V.getOpcode() != ISD::XOR)
9205     return false;
9206   V = peekThroughBitcasts(V.getOperand(1));
9207   unsigned NumBits = V.getScalarValueSizeInBits();
9208   ConstantSDNode *C =
9209       isConstOrConstSplat(V, AllowUndefs, /*AllowTruncation*/ true);
9210   return C && (C->getAPIntValue().countTrailingOnes() >= NumBits);
9211 }
9212 
isConstOrConstSplat(SDValue N,bool AllowUndefs,bool AllowTruncation)9213 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs,
9214                                           bool AllowTruncation) {
9215   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9216     return CN;
9217 
9218   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9219     BitVector UndefElements;
9220     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
9221 
9222     // BuildVectors can truncate their operands. Ignore that case here unless
9223     // AllowTruncation is set.
9224     if (CN && (UndefElements.none() || AllowUndefs)) {
9225       EVT CVT = CN->getValueType(0);
9226       EVT NSVT = N.getValueType().getScalarType();
9227       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9228       if (AllowTruncation || (CVT == NSVT))
9229         return CN;
9230     }
9231   }
9232 
9233   return nullptr;
9234 }
9235 
isConstOrConstSplat(SDValue N,const APInt & DemandedElts,bool AllowUndefs,bool AllowTruncation)9236 ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
9237                                           bool AllowUndefs,
9238                                           bool AllowTruncation) {
9239   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
9240     return CN;
9241 
9242   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9243     BitVector UndefElements;
9244     ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
9245 
9246     // BuildVectors can truncate their operands. Ignore that case here unless
9247     // AllowTruncation is set.
9248     if (CN && (UndefElements.none() || AllowUndefs)) {
9249       EVT CVT = CN->getValueType(0);
9250       EVT NSVT = N.getValueType().getScalarType();
9251       assert(CVT.bitsGE(NSVT) && "Illegal build vector element extension");
9252       if (AllowTruncation || (CVT == NSVT))
9253         return CN;
9254     }
9255   }
9256 
9257   return nullptr;
9258 }
9259 
isConstOrConstSplatFP(SDValue N,bool AllowUndefs)9260 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
9261   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9262     return CN;
9263 
9264   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9265     BitVector UndefElements;
9266     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
9267     if (CN && (UndefElements.none() || AllowUndefs))
9268       return CN;
9269   }
9270 
9271   return nullptr;
9272 }
9273 
isConstOrConstSplatFP(SDValue N,const APInt & DemandedElts,bool AllowUndefs)9274 ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
9275                                               const APInt &DemandedElts,
9276                                               bool AllowUndefs) {
9277   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
9278     return CN;
9279 
9280   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
9281     BitVector UndefElements;
9282     ConstantFPSDNode *CN =
9283         BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
9284     if (CN && (UndefElements.none() || AllowUndefs))
9285       return CN;
9286   }
9287 
9288   return nullptr;
9289 }
9290 
isNullOrNullSplat(SDValue N,bool AllowUndefs)9291 bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
9292   // TODO: may want to use peekThroughBitcast() here.
9293   ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
9294   return C && C->isNullValue();
9295 }
9296 
isOneOrOneSplat(SDValue N)9297 bool llvm::isOneOrOneSplat(SDValue N) {
9298   // TODO: may want to use peekThroughBitcast() here.
9299   unsigned BitWidth = N.getScalarValueSizeInBits();
9300   ConstantSDNode *C = isConstOrConstSplat(N);
9301   return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
9302 }
9303 
isAllOnesOrAllOnesSplat(SDValue N)9304 bool llvm::isAllOnesOrAllOnesSplat(SDValue N) {
9305   N = peekThroughBitcasts(N);
9306   unsigned BitWidth = N.getScalarValueSizeInBits();
9307   ConstantSDNode *C = isConstOrConstSplat(N);
9308   return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
9309 }
9310 
~HandleSDNode()9311 HandleSDNode::~HandleSDNode() {
9312   DropOperands();
9313 }
9314 
GlobalAddressSDNode(unsigned Opc,unsigned Order,const DebugLoc & DL,const GlobalValue * GA,EVT VT,int64_t o,unsigned TF)9315 GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
9316                                          const DebugLoc &DL,
9317                                          const GlobalValue *GA, EVT VT,
9318                                          int64_t o, unsigned TF)
9319     : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
9320   TheGlobal = GA;
9321 }
9322 
AddrSpaceCastSDNode(unsigned Order,const DebugLoc & dl,EVT VT,unsigned SrcAS,unsigned DestAS)9323 AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
9324                                          EVT VT, unsigned SrcAS,
9325                                          unsigned DestAS)
9326     : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
9327       SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
9328 
MemSDNode(unsigned Opc,unsigned Order,const DebugLoc & dl,SDVTList VTs,EVT memvt,MachineMemOperand * mmo)9329 MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
9330                      SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
9331     : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
9332   MemSDNodeBits.IsVolatile = MMO->isVolatile();
9333   MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
9334   MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
9335   MemSDNodeBits.IsInvariant = MMO->isInvariant();
9336 
9337   // We check here that the size of the memory operand fits within the size of
9338   // the MMO. This is because the MMO might indicate only a possible address
9339   // range instead of specifying the affected memory addresses precisely.
9340   // TODO: Make MachineMemOperands aware of scalable vectors.
9341   assert(memvt.getStoreSize().getKnownMinSize() <= MMO->getSize() &&
9342          "Size mismatch!");
9343 }
9344 
9345 /// Profile - Gather unique data for the node.
9346 ///
Profile(FoldingSetNodeID & ID) const9347 void SDNode::Profile(FoldingSetNodeID &ID) const {
9348   AddNodeIDNode(ID, this);
9349 }
9350 
9351 namespace {
9352 
9353   struct EVTArray {
9354     std::vector<EVT> VTs;
9355 
EVTArray__anon8b1174b51011::EVTArray9356     EVTArray() {
9357       VTs.reserve(MVT::LAST_VALUETYPE);
9358       for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
9359         VTs.push_back(MVT((MVT::SimpleValueType)i));
9360     }
9361   };
9362 
9363 } // end anonymous namespace
9364 
9365 static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
9366 static ManagedStatic<EVTArray> SimpleVTArray;
9367 static ManagedStatic<sys::SmartMutex<true>> VTMutex;
9368 
9369 /// getValueTypeList - Return a pointer to the specified value type.
9370 ///
getValueTypeList(EVT VT)9371 const EVT *SDNode::getValueTypeList(EVT VT) {
9372   if (VT.isExtended()) {
9373     sys::SmartScopedLock<true> Lock(*VTMutex);
9374     return &(*EVTs->insert(VT).first);
9375   } else {
9376     assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
9377            "Value type out of range!");
9378     return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
9379   }
9380 }
9381 
9382 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
9383 /// indicated value.  This method ignores uses of other values defined by this
9384 /// operation.
hasNUsesOfValue(unsigned NUses,unsigned Value) const9385 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
9386   assert(Value < getNumValues() && "Bad value!");
9387 
9388   // TODO: Only iterate over uses of a given value of the node
9389   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
9390     if (UI.getUse().getResNo() == Value) {
9391       if (NUses == 0)
9392         return false;
9393       --NUses;
9394     }
9395   }
9396 
9397   // Found exactly the right number of uses?
9398   return NUses == 0;
9399 }
9400 
9401 /// hasAnyUseOfValue - Return true if there are any use of the indicated
9402 /// value. This method ignores uses of other values defined by this operation.
hasAnyUseOfValue(unsigned Value) const9403 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
9404   assert(Value < getNumValues() && "Bad value!");
9405 
9406   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
9407     if (UI.getUse().getResNo() == Value)
9408       return true;
9409 
9410   return false;
9411 }
9412 
9413 /// isOnlyUserOf - Return true if this node is the only use of N.
isOnlyUserOf(const SDNode * N) const9414 bool SDNode::isOnlyUserOf(const SDNode *N) const {
9415   bool Seen = false;
9416   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9417     SDNode *User = *I;
9418     if (User == this)
9419       Seen = true;
9420     else
9421       return false;
9422   }
9423 
9424   return Seen;
9425 }
9426 
9427 /// Return true if the only users of N are contained in Nodes.
areOnlyUsersOf(ArrayRef<const SDNode * > Nodes,const SDNode * N)9428 bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
9429   bool Seen = false;
9430   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
9431     SDNode *User = *I;
9432     if (llvm::any_of(Nodes,
9433                      [&User](const SDNode *Node) { return User == Node; }))
9434       Seen = true;
9435     else
9436       return false;
9437   }
9438 
9439   return Seen;
9440 }
9441 
9442 /// isOperand - Return true if this node is an operand of N.
isOperandOf(const SDNode * N) const9443 bool SDValue::isOperandOf(const SDNode *N) const {
9444   return any_of(N->op_values(), [this](SDValue Op) { return *this == Op; });
9445 }
9446 
isOperandOf(const SDNode * N) const9447 bool SDNode::isOperandOf(const SDNode *N) const {
9448   return any_of(N->op_values(),
9449                 [this](SDValue Op) { return this == Op.getNode(); });
9450 }
9451 
9452 /// reachesChainWithoutSideEffects - Return true if this operand (which must
9453 /// be a chain) reaches the specified operand without crossing any
9454 /// side-effecting instructions on any chain path.  In practice, this looks
9455 /// through token factors and non-volatile loads.  In order to remain efficient,
9456 /// this only looks a couple of nodes in, it does not do an exhaustive search.
9457 ///
9458 /// Note that we only need to examine chains when we're searching for
9459 /// side-effects; SelectionDAG requires that all side-effects are represented
9460 /// by chains, even if another operand would force a specific ordering. This
9461 /// constraint is necessary to allow transformations like splitting loads.
reachesChainWithoutSideEffects(SDValue Dest,unsigned Depth) const9462 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
9463                                              unsigned Depth) const {
9464   if (*this == Dest) return true;
9465 
9466   // Don't search too deeply, we just want to be able to see through
9467   // TokenFactor's etc.
9468   if (Depth == 0) return false;
9469 
9470   // If this is a token factor, all inputs to the TF happen in parallel.
9471   if (getOpcode() == ISD::TokenFactor) {
9472     // First, try a shallow search.
9473     if (is_contained((*this)->ops(), Dest)) {
9474       // We found the chain we want as an operand of this TokenFactor.
9475       // Essentially, we reach the chain without side-effects if we could
9476       // serialize the TokenFactor into a simple chain of operations with
9477       // Dest as the last operation. This is automatically true if the
9478       // chain has one use: there are no other ordering constraints.
9479       // If the chain has more than one use, we give up: some other
9480       // use of Dest might force a side-effect between Dest and the current
9481       // node.
9482       if (Dest.hasOneUse())
9483         return true;
9484     }
9485     // Next, try a deep search: check whether every operand of the TokenFactor
9486     // reaches Dest.
9487     return llvm::all_of((*this)->ops(), [=](SDValue Op) {
9488       return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
9489     });
9490   }
9491 
9492   // Loads don't have side effects, look through them.
9493   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
9494     if (Ld->isUnordered())
9495       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
9496   }
9497   return false;
9498 }
9499 
hasPredecessor(const SDNode * N) const9500 bool SDNode::hasPredecessor(const SDNode *N) const {
9501   SmallPtrSet<const SDNode *, 32> Visited;
9502   SmallVector<const SDNode *, 16> Worklist;
9503   Worklist.push_back(this);
9504   return hasPredecessorHelper(N, Visited, Worklist);
9505 }
9506 
intersectFlagsWith(const SDNodeFlags Flags)9507 void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
9508   this->Flags.intersectWith(Flags);
9509 }
9510 
9511 SDValue
matchBinOpReduction(SDNode * Extract,ISD::NodeType & BinOp,ArrayRef<ISD::NodeType> CandidateBinOps,bool AllowPartials)9512 SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
9513                                   ArrayRef<ISD::NodeType> CandidateBinOps,
9514                                   bool AllowPartials) {
9515   // The pattern must end in an extract from index 0.
9516   if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9517       !isNullConstant(Extract->getOperand(1)))
9518     return SDValue();
9519 
9520   // Match against one of the candidate binary ops.
9521   SDValue Op = Extract->getOperand(0);
9522   if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
9523         return Op.getOpcode() == unsigned(BinOp);
9524       }))
9525     return SDValue();
9526 
9527   // Floating-point reductions may require relaxed constraints on the final step
9528   // of the reduction because they may reorder intermediate operations.
9529   unsigned CandidateBinOp = Op.getOpcode();
9530   if (Op.getValueType().isFloatingPoint()) {
9531     SDNodeFlags Flags = Op->getFlags();
9532     switch (CandidateBinOp) {
9533     case ISD::FADD:
9534       if (!Flags.hasNoSignedZeros() || !Flags.hasAllowReassociation())
9535         return SDValue();
9536       break;
9537     default:
9538       llvm_unreachable("Unhandled FP opcode for binop reduction");
9539     }
9540   }
9541 
9542   // Matching failed - attempt to see if we did enough stages that a partial
9543   // reduction from a subvector is possible.
9544   auto PartialReduction = [&](SDValue Op, unsigned NumSubElts) {
9545     if (!AllowPartials || !Op)
9546       return SDValue();
9547     EVT OpVT = Op.getValueType();
9548     EVT OpSVT = OpVT.getScalarType();
9549     EVT SubVT = EVT::getVectorVT(*getContext(), OpSVT, NumSubElts);
9550     if (!TLI->isExtractSubvectorCheap(SubVT, OpVT, 0))
9551       return SDValue();
9552     BinOp = (ISD::NodeType)CandidateBinOp;
9553     return getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Op), SubVT, Op,
9554                    getVectorIdxConstant(0, SDLoc(Op)));
9555   };
9556 
9557   // At each stage, we're looking for something that looks like:
9558   // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
9559   //                    <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
9560   //                               i32 undef, i32 undef, i32 undef, i32 undef>
9561   // %a = binop <8 x i32> %op, %s
9562   // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
9563   // we expect something like:
9564   // <4,5,6,7,u,u,u,u>
9565   // <2,3,u,u,u,u,u,u>
9566   // <1,u,u,u,u,u,u,u>
9567   // While a partial reduction match would be:
9568   // <2,3,u,u,u,u,u,u>
9569   // <1,u,u,u,u,u,u,u>
9570   unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
9571   SDValue PrevOp;
9572   for (unsigned i = 0; i < Stages; ++i) {
9573     unsigned MaskEnd = (1 << i);
9574 
9575     if (Op.getOpcode() != CandidateBinOp)
9576       return PartialReduction(PrevOp, MaskEnd);
9577 
9578     SDValue Op0 = Op.getOperand(0);
9579     SDValue Op1 = Op.getOperand(1);
9580 
9581     ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
9582     if (Shuffle) {
9583       Op = Op1;
9584     } else {
9585       Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
9586       Op = Op0;
9587     }
9588 
9589     // The first operand of the shuffle should be the same as the other operand
9590     // of the binop.
9591     if (!Shuffle || Shuffle->getOperand(0) != Op)
9592       return PartialReduction(PrevOp, MaskEnd);
9593 
9594     // Verify the shuffle has the expected (at this stage of the pyramid) mask.
9595     for (int Index = 0; Index < (int)MaskEnd; ++Index)
9596       if (Shuffle->getMaskElt(Index) != (int)(MaskEnd + Index))
9597         return PartialReduction(PrevOp, MaskEnd);
9598 
9599     PrevOp = Op;
9600   }
9601 
9602   // Handle subvector reductions, which tend to appear after the shuffle
9603   // reduction stages.
9604   while (Op.getOpcode() == CandidateBinOp) {
9605     unsigned NumElts = Op.getValueType().getVectorNumElements();
9606     SDValue Op0 = Op.getOperand(0);
9607     SDValue Op1 = Op.getOperand(1);
9608     if (Op0.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9609         Op1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
9610         Op0.getOperand(0) != Op1.getOperand(0))
9611       break;
9612     SDValue Src = Op0.getOperand(0);
9613     unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
9614     if (NumSrcElts != (2 * NumElts))
9615       break;
9616     if (!(Op0.getConstantOperandAPInt(1) == 0 &&
9617           Op1.getConstantOperandAPInt(1) == NumElts) &&
9618         !(Op1.getConstantOperandAPInt(1) == 0 &&
9619           Op0.getConstantOperandAPInt(1) == NumElts))
9620       break;
9621     Op = Src;
9622   }
9623 
9624   BinOp = (ISD::NodeType)CandidateBinOp;
9625   return Op;
9626 }
9627 
UnrollVectorOp(SDNode * N,unsigned ResNE)9628 SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
9629   assert(N->getNumValues() == 1 &&
9630          "Can't unroll a vector with multiple results!");
9631 
9632   EVT VT = N->getValueType(0);
9633   unsigned NE = VT.getVectorNumElements();
9634   EVT EltVT = VT.getVectorElementType();
9635   SDLoc dl(N);
9636 
9637   SmallVector<SDValue, 8> Scalars;
9638   SmallVector<SDValue, 4> Operands(N->getNumOperands());
9639 
9640   // If ResNE is 0, fully unroll the vector op.
9641   if (ResNE == 0)
9642     ResNE = NE;
9643   else if (NE > ResNE)
9644     NE = ResNE;
9645 
9646   unsigned i;
9647   for (i= 0; i != NE; ++i) {
9648     for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
9649       SDValue Operand = N->getOperand(j);
9650       EVT OperandVT = Operand.getValueType();
9651       if (OperandVT.isVector()) {
9652         // A vector operand; extract a single element.
9653         EVT OperandEltVT = OperandVT.getVectorElementType();
9654         Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT,
9655                               Operand, getVectorIdxConstant(i, dl));
9656       } else {
9657         // A scalar operand; just use it as is.
9658         Operands[j] = Operand;
9659       }
9660     }
9661 
9662     switch (N->getOpcode()) {
9663     default: {
9664       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
9665                                 N->getFlags()));
9666       break;
9667     }
9668     case ISD::VSELECT:
9669       Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
9670       break;
9671     case ISD::SHL:
9672     case ISD::SRA:
9673     case ISD::SRL:
9674     case ISD::ROTL:
9675     case ISD::ROTR:
9676       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
9677                                getShiftAmountOperand(Operands[0].getValueType(),
9678                                                      Operands[1])));
9679       break;
9680     case ISD::SIGN_EXTEND_INREG: {
9681       EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
9682       Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
9683                                 Operands[0],
9684                                 getValueType(ExtVT)));
9685     }
9686     }
9687   }
9688 
9689   for (; i < ResNE; ++i)
9690     Scalars.push_back(getUNDEF(EltVT));
9691 
9692   EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
9693   return getBuildVector(VecVT, dl, Scalars);
9694 }
9695 
UnrollVectorOverflowOp(SDNode * N,unsigned ResNE)9696 std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
9697     SDNode *N, unsigned ResNE) {
9698   unsigned Opcode = N->getOpcode();
9699   assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
9700           Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
9701           Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
9702          "Expected an overflow opcode");
9703 
9704   EVT ResVT = N->getValueType(0);
9705   EVT OvVT = N->getValueType(1);
9706   EVT ResEltVT = ResVT.getVectorElementType();
9707   EVT OvEltVT = OvVT.getVectorElementType();
9708   SDLoc dl(N);
9709 
9710   // If ResNE is 0, fully unroll the vector op.
9711   unsigned NE = ResVT.getVectorNumElements();
9712   if (ResNE == 0)
9713     ResNE = NE;
9714   else if (NE > ResNE)
9715     NE = ResNE;
9716 
9717   SmallVector<SDValue, 8> LHSScalars;
9718   SmallVector<SDValue, 8> RHSScalars;
9719   ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
9720   ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
9721 
9722   EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
9723   SDVTList VTs = getVTList(ResEltVT, SVT);
9724   SmallVector<SDValue, 8> ResScalars;
9725   SmallVector<SDValue, 8> OvScalars;
9726   for (unsigned i = 0; i < NE; ++i) {
9727     SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
9728     SDValue Ov =
9729         getSelect(dl, OvEltVT, Res.getValue(1),
9730                   getBoolConstant(true, dl, OvEltVT, ResVT),
9731                   getConstant(0, dl, OvEltVT));
9732 
9733     ResScalars.push_back(Res);
9734     OvScalars.push_back(Ov);
9735   }
9736 
9737   ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
9738   OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
9739 
9740   EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
9741   EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
9742   return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
9743                         getBuildVector(NewOvVT, dl, OvScalars));
9744 }
9745 
areNonVolatileConsecutiveLoads(LoadSDNode * LD,LoadSDNode * Base,unsigned Bytes,int Dist) const9746 bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
9747                                                   LoadSDNode *Base,
9748                                                   unsigned Bytes,
9749                                                   int Dist) const {
9750   if (LD->isVolatile() || Base->isVolatile())
9751     return false;
9752   // TODO: probably too restrictive for atomics, revisit
9753   if (!LD->isSimple())
9754     return false;
9755   if (LD->isIndexed() || Base->isIndexed())
9756     return false;
9757   if (LD->getChain() != Base->getChain())
9758     return false;
9759   EVT VT = LD->getValueType(0);
9760   if (VT.getSizeInBits() / 8 != Bytes)
9761     return false;
9762 
9763   auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
9764   auto LocDecomp = BaseIndexOffset::match(LD, *this);
9765 
9766   int64_t Offset = 0;
9767   if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
9768     return (Dist * Bytes == Offset);
9769   return false;
9770 }
9771 
9772 /// InferPtrAlignment - Infer alignment of a load / store address. Return None
9773 /// if it cannot be inferred.
InferPtrAlign(SDValue Ptr) const9774 MaybeAlign SelectionDAG::InferPtrAlign(SDValue Ptr) const {
9775   // If this is a GlobalAddress + cst, return the alignment.
9776   const GlobalValue *GV = nullptr;
9777   int64_t GVOffset = 0;
9778   if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
9779     unsigned PtrWidth = getDataLayout().getIndexTypeSizeInBits(GV->getType());
9780     KnownBits Known(PtrWidth);
9781     llvm::computeKnownBits(GV, Known, getDataLayout());
9782     unsigned AlignBits = Known.countMinTrailingZeros();
9783     if (AlignBits)
9784       return commonAlignment(Align(1ull << std::min(31U, AlignBits)), GVOffset);
9785   }
9786 
9787   // If this is a direct reference to a stack slot, use information about the
9788   // stack slot's alignment.
9789   int FrameIdx = INT_MIN;
9790   int64_t FrameOffset = 0;
9791   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
9792     FrameIdx = FI->getIndex();
9793   } else if (isBaseWithConstantOffset(Ptr) &&
9794              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
9795     // Handle FI+Cst
9796     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
9797     FrameOffset = Ptr.getConstantOperandVal(1);
9798   }
9799 
9800   if (FrameIdx != INT_MIN) {
9801     const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
9802     return commonAlignment(MFI.getObjectAlign(FrameIdx), FrameOffset);
9803   }
9804 
9805   return None;
9806 }
9807 
9808 /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
9809 /// which is split (or expanded) into two not necessarily identical pieces.
GetSplitDestVTs(const EVT & VT) const9810 std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
9811   // Currently all types are split in half.
9812   EVT LoVT, HiVT;
9813   if (!VT.isVector())
9814     LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
9815   else
9816     LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
9817 
9818   return std::make_pair(LoVT, HiVT);
9819 }
9820 
9821 /// GetDependentSplitDestVTs - Compute the VTs needed for the low/hi parts of a
9822 /// type, dependent on an enveloping VT that has been split into two identical
9823 /// pieces. Sets the HiIsEmpty flag when hi type has zero storage size.
9824 std::pair<EVT, EVT>
GetDependentSplitDestVTs(const EVT & VT,const EVT & EnvVT,bool * HiIsEmpty) const9825 SelectionDAG::GetDependentSplitDestVTs(const EVT &VT, const EVT &EnvVT,
9826                                        bool *HiIsEmpty) const {
9827   EVT EltTp = VT.getVectorElementType();
9828   bool IsScalable = VT.isScalableVector();
9829   // Examples:
9830   //   custom VL=8  with enveloping VL=8/8 yields 8/0 (hi empty)
9831   //   custom VL=9  with enveloping VL=8/8 yields 8/1
9832   //   custom VL=10 with enveloping VL=8/8 yields 8/2
9833   //   etc.
9834   unsigned VTNumElts = VT.getVectorNumElements();
9835   unsigned EnvNumElts = EnvVT.getVectorNumElements();
9836   EVT LoVT, HiVT;
9837   if (VTNumElts > EnvNumElts) {
9838     LoVT = EnvVT;
9839     HiVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts - EnvNumElts,
9840                             IsScalable);
9841     *HiIsEmpty = false;
9842   } else {
9843     // Flag that hi type has zero storage size, but return split envelop type
9844     // (this would be easier if vector types with zero elements were allowed).
9845     LoVT = EVT::getVectorVT(*getContext(), EltTp, VTNumElts, IsScalable);
9846     HiVT = EnvVT;
9847     *HiIsEmpty = true;
9848   }
9849   return std::make_pair(LoVT, HiVT);
9850 }
9851 
9852 /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
9853 /// low/high part.
9854 std::pair<SDValue, SDValue>
SplitVector(const SDValue & N,const SDLoc & DL,const EVT & LoVT,const EVT & HiVT)9855 SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
9856                           const EVT &HiVT) {
9857   assert(LoVT.isScalableVector() == HiVT.isScalableVector() &&
9858          LoVT.isScalableVector() == N.getValueType().isScalableVector() &&
9859          "Splitting vector with an invalid mixture of fixed and scalable "
9860          "vector types");
9861   assert(LoVT.getVectorMinNumElements() + HiVT.getVectorMinNumElements() <=
9862              N.getValueType().getVectorMinNumElements() &&
9863          "More vector elements requested than available!");
9864   SDValue Lo, Hi;
9865   Lo =
9866       getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N, getVectorIdxConstant(0, DL));
9867   // For scalable vectors it is safe to use LoVT.getVectorMinNumElements()
9868   // (rather than having to use ElementCount), because EXTRACT_SUBVECTOR scales
9869   // IDX with the runtime scaling factor of the result vector type. For
9870   // fixed-width result vectors, that runtime scaling factor is 1.
9871   Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
9872                getVectorIdxConstant(LoVT.getVectorMinNumElements(), DL));
9873   return std::make_pair(Lo, Hi);
9874 }
9875 
9876 /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
WidenVector(const SDValue & N,const SDLoc & DL)9877 SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
9878   EVT VT = N.getValueType();
9879   EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
9880                                 NextPowerOf2(VT.getVectorNumElements()));
9881   return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
9882                  getVectorIdxConstant(0, DL));
9883 }
9884 
ExtractVectorElements(SDValue Op,SmallVectorImpl<SDValue> & Args,unsigned Start,unsigned Count,EVT EltVT)9885 void SelectionDAG::ExtractVectorElements(SDValue Op,
9886                                          SmallVectorImpl<SDValue> &Args,
9887                                          unsigned Start, unsigned Count,
9888                                          EVT EltVT) {
9889   EVT VT = Op.getValueType();
9890   if (Count == 0)
9891     Count = VT.getVectorNumElements();
9892   if (EltVT == EVT())
9893     EltVT = VT.getVectorElementType();
9894   SDLoc SL(Op);
9895   for (unsigned i = Start, e = Start + Count; i != e; ++i) {
9896     Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Op,
9897                            getVectorIdxConstant(i, SL)));
9898   }
9899 }
9900 
9901 // getAddressSpace - Return the address space this GlobalAddress belongs to.
getAddressSpace() const9902 unsigned GlobalAddressSDNode::getAddressSpace() const {
9903   return getGlobal()->getType()->getAddressSpace();
9904 }
9905 
getType() const9906 Type *ConstantPoolSDNode::getType() const {
9907   if (isMachineConstantPoolEntry())
9908     return Val.MachineCPVal->getType();
9909   return Val.ConstVal->getType();
9910 }
9911 
isConstantSplat(APInt & SplatValue,APInt & SplatUndef,unsigned & SplatBitSize,bool & HasAnyUndefs,unsigned MinSplatBits,bool IsBigEndian) const9912 bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
9913                                         unsigned &SplatBitSize,
9914                                         bool &HasAnyUndefs,
9915                                         unsigned MinSplatBits,
9916                                         bool IsBigEndian) const {
9917   EVT VT = getValueType(0);
9918   assert(VT.isVector() && "Expected a vector type");
9919   unsigned VecWidth = VT.getSizeInBits();
9920   if (MinSplatBits > VecWidth)
9921     return false;
9922 
9923   // FIXME: The widths are based on this node's type, but build vectors can
9924   // truncate their operands.
9925   SplatValue = APInt(VecWidth, 0);
9926   SplatUndef = APInt(VecWidth, 0);
9927 
9928   // Get the bits. Bits with undefined values (when the corresponding element
9929   // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
9930   // in SplatValue. If any of the values are not constant, give up and return
9931   // false.
9932   unsigned int NumOps = getNumOperands();
9933   assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
9934   unsigned EltWidth = VT.getScalarSizeInBits();
9935 
9936   for (unsigned j = 0; j < NumOps; ++j) {
9937     unsigned i = IsBigEndian ? NumOps - 1 - j : j;
9938     SDValue OpVal = getOperand(i);
9939     unsigned BitPos = j * EltWidth;
9940 
9941     if (OpVal.isUndef())
9942       SplatUndef.setBits(BitPos, BitPos + EltWidth);
9943     else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
9944       SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
9945     else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
9946       SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
9947     else
9948       return false;
9949   }
9950 
9951   // The build_vector is all constants or undefs. Find the smallest element
9952   // size that splats the vector.
9953   HasAnyUndefs = (SplatUndef != 0);
9954 
9955   // FIXME: This does not work for vectors with elements less than 8 bits.
9956   while (VecWidth > 8) {
9957     unsigned HalfSize = VecWidth / 2;
9958     APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
9959     APInt LowValue = SplatValue.trunc(HalfSize);
9960     APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
9961     APInt LowUndef = SplatUndef.trunc(HalfSize);
9962 
9963     // If the two halves do not match (ignoring undef bits), stop here.
9964     if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
9965         MinSplatBits > HalfSize)
9966       break;
9967 
9968     SplatValue = HighValue | LowValue;
9969     SplatUndef = HighUndef & LowUndef;
9970 
9971     VecWidth = HalfSize;
9972   }
9973 
9974   SplatBitSize = VecWidth;
9975   return true;
9976 }
9977 
getSplatValue(const APInt & DemandedElts,BitVector * UndefElements) const9978 SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
9979                                          BitVector *UndefElements) const {
9980   if (UndefElements) {
9981     UndefElements->clear();
9982     UndefElements->resize(getNumOperands());
9983   }
9984   assert(getNumOperands() == DemandedElts.getBitWidth() &&
9985          "Unexpected vector size");
9986   if (!DemandedElts)
9987     return SDValue();
9988   SDValue Splatted;
9989   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
9990     if (!DemandedElts[i])
9991       continue;
9992     SDValue Op = getOperand(i);
9993     if (Op.isUndef()) {
9994       if (UndefElements)
9995         (*UndefElements)[i] = true;
9996     } else if (!Splatted) {
9997       Splatted = Op;
9998     } else if (Splatted != Op) {
9999       return SDValue();
10000     }
10001   }
10002 
10003   if (!Splatted) {
10004     unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
10005     assert(getOperand(FirstDemandedIdx).isUndef() &&
10006            "Can only have a splat without a constant for all undefs.");
10007     return getOperand(FirstDemandedIdx);
10008   }
10009 
10010   return Splatted;
10011 }
10012 
getSplatValue(BitVector * UndefElements) const10013 SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
10014   APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
10015   return getSplatValue(DemandedElts, UndefElements);
10016 }
10017 
10018 ConstantSDNode *
getConstantSplatNode(const APInt & DemandedElts,BitVector * UndefElements) const10019 BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
10020                                         BitVector *UndefElements) const {
10021   return dyn_cast_or_null<ConstantSDNode>(
10022       getSplatValue(DemandedElts, UndefElements));
10023 }
10024 
10025 ConstantSDNode *
getConstantSplatNode(BitVector * UndefElements) const10026 BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
10027   return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
10028 }
10029 
10030 ConstantFPSDNode *
getConstantFPSplatNode(const APInt & DemandedElts,BitVector * UndefElements) const10031 BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
10032                                           BitVector *UndefElements) const {
10033   return dyn_cast_or_null<ConstantFPSDNode>(
10034       getSplatValue(DemandedElts, UndefElements));
10035 }
10036 
10037 ConstantFPSDNode *
getConstantFPSplatNode(BitVector * UndefElements) const10038 BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
10039   return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
10040 }
10041 
10042 int32_t
getConstantFPSplatPow2ToLog2Int(BitVector * UndefElements,uint32_t BitWidth) const10043 BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
10044                                                    uint32_t BitWidth) const {
10045   if (ConstantFPSDNode *CN =
10046           dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
10047     bool IsExact;
10048     APSInt IntVal(BitWidth);
10049     const APFloat &APF = CN->getValueAPF();
10050     if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
10051             APFloat::opOK ||
10052         !IsExact)
10053       return -1;
10054 
10055     return IntVal.exactLogBase2();
10056   }
10057   return -1;
10058 }
10059 
isConstant() const10060 bool BuildVectorSDNode::isConstant() const {
10061   for (const SDValue &Op : op_values()) {
10062     unsigned Opc = Op.getOpcode();
10063     if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
10064       return false;
10065   }
10066   return true;
10067 }
10068 
isSplatMask(const int * Mask,EVT VT)10069 bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
10070   // Find the first non-undef value in the shuffle mask.
10071   unsigned i, e;
10072   for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
10073     /* search */;
10074 
10075   // If all elements are undefined, this shuffle can be considered a splat
10076   // (although it should eventually get simplified away completely).
10077   if (i == e)
10078     return true;
10079 
10080   // Make sure all remaining elements are either undef or the same as the first
10081   // non-undef value.
10082   for (int Idx = Mask[i]; i != e; ++i)
10083     if (Mask[i] >= 0 && Mask[i] != Idx)
10084       return false;
10085   return true;
10086 }
10087 
10088 // Returns the SDNode if it is a constant integer BuildVector
10089 // or constant integer.
isConstantIntBuildVectorOrConstantInt(SDValue N)10090 SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
10091   if (isa<ConstantSDNode>(N))
10092     return N.getNode();
10093   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
10094     return N.getNode();
10095   // Treat a GlobalAddress supporting constant offset folding as a
10096   // constant integer.
10097   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
10098     if (GA->getOpcode() == ISD::GlobalAddress &&
10099         TLI->isOffsetFoldingLegal(GA))
10100       return GA;
10101   return nullptr;
10102 }
10103 
isConstantFPBuildVectorOrConstantFP(SDValue N)10104 SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
10105   if (isa<ConstantFPSDNode>(N))
10106     return N.getNode();
10107 
10108   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
10109     return N.getNode();
10110 
10111   return nullptr;
10112 }
10113 
createOperands(SDNode * Node,ArrayRef<SDValue> Vals)10114 void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
10115   assert(!Node->OperandList && "Node already has operands");
10116   assert(SDNode::getMaxNumOperands() >= Vals.size() &&
10117          "too many operands to fit into SDNode");
10118   SDUse *Ops = OperandRecycler.allocate(
10119       ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
10120 
10121   bool IsDivergent = false;
10122   for (unsigned I = 0; I != Vals.size(); ++I) {
10123     Ops[I].setUser(Node);
10124     Ops[I].setInitial(Vals[I]);
10125     if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
10126       IsDivergent = IsDivergent || Ops[I].getNode()->isDivergent();
10127   }
10128   Node->NumOperands = Vals.size();
10129   Node->OperandList = Ops;
10130   IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
10131   if (!TLI->isSDNodeAlwaysUniform(Node))
10132     Node->SDNodeBits.IsDivergent = IsDivergent;
10133   checkForCycles(Node);
10134 }
10135 
getTokenFactor(const SDLoc & DL,SmallVectorImpl<SDValue> & Vals)10136 SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
10137                                      SmallVectorImpl<SDValue> &Vals) {
10138   size_t Limit = SDNode::getMaxNumOperands();
10139   while (Vals.size() > Limit) {
10140     unsigned SliceIdx = Vals.size() - Limit;
10141     auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
10142     SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
10143     Vals.erase(Vals.begin() + SliceIdx, Vals.end());
10144     Vals.emplace_back(NewTF);
10145   }
10146   return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
10147 }
10148 
10149 #ifndef NDEBUG
checkForCyclesHelper(const SDNode * N,SmallPtrSetImpl<const SDNode * > & Visited,SmallPtrSetImpl<const SDNode * > & Checked,const llvm::SelectionDAG * DAG)10150 static void checkForCyclesHelper(const SDNode *N,
10151                                  SmallPtrSetImpl<const SDNode*> &Visited,
10152                                  SmallPtrSetImpl<const SDNode*> &Checked,
10153                                  const llvm::SelectionDAG *DAG) {
10154   // If this node has already been checked, don't check it again.
10155   if (Checked.count(N))
10156     return;
10157 
10158   // If a node has already been visited on this depth-first walk, reject it as
10159   // a cycle.
10160   if (!Visited.insert(N).second) {
10161     errs() << "Detected cycle in SelectionDAG\n";
10162     dbgs() << "Offending node:\n";
10163     N->dumprFull(DAG); dbgs() << "\n";
10164     abort();
10165   }
10166 
10167   for (const SDValue &Op : N->op_values())
10168     checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
10169 
10170   Checked.insert(N);
10171   Visited.erase(N);
10172 }
10173 #endif
10174 
checkForCycles(const llvm::SDNode * N,const llvm::SelectionDAG * DAG,bool force)10175 void llvm::checkForCycles(const llvm::SDNode *N,
10176                           const llvm::SelectionDAG *DAG,
10177                           bool force) {
10178 #ifndef NDEBUG
10179   bool check = force;
10180 #ifdef EXPENSIVE_CHECKS
10181   check = true;
10182 #endif  // EXPENSIVE_CHECKS
10183   if (check) {
10184     assert(N && "Checking nonexistent SDNode");
10185     SmallPtrSet<const SDNode*, 32> visited;
10186     SmallPtrSet<const SDNode*, 32> checked;
10187     checkForCyclesHelper(N, visited, checked, DAG);
10188   }
10189 #endif  // !NDEBUG
10190 }
10191 
checkForCycles(const llvm::SelectionDAG * DAG,bool force)10192 void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
10193   checkForCycles(DAG->getRoot().getNode(), DAG, force);
10194 }
10195