LLVM  14.0.0git
SelectionDAGAddressAnalysis.cpp
Go to the documentation of this file.
1 //==- llvm/CodeGen/SelectionDAGAddressAnalysis.cpp - DAG Address Analysis --==//
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 
17 #include "llvm/Support/Casting.h"
18 #include "llvm/Support/Debug.h"
19 #include <cstdint>
20 
21 using namespace llvm;
22 
24  const SelectionDAG &DAG,
25  int64_t &Off) const {
26  // Conservatively fail if we a match failed..
27  if (!Base.getNode() || !Other.Base.getNode())
28  return false;
29  if (!hasValidOffset() || !Other.hasValidOffset())
30  return false;
31  // Initial Offset difference.
32  Off = *Other.Offset - *Offset;
33 
34  if ((Other.Index == Index) && (Other.IsIndexSignExt == IsIndexSignExt)) {
35  // Trivial match.
36  if (Other.Base == Base)
37  return true;
38 
39  // Match GlobalAddresses
40  if (auto *A = dyn_cast<GlobalAddressSDNode>(Base))
41  if (auto *B = dyn_cast<GlobalAddressSDNode>(Other.Base))
42  if (A->getGlobal() == B->getGlobal()) {
43  Off += B->getOffset() - A->getOffset();
44  return true;
45  }
46 
47  // Match Constants
48  if (auto *A = dyn_cast<ConstantPoolSDNode>(Base))
49  if (auto *B = dyn_cast<ConstantPoolSDNode>(Other.Base)) {
50  bool IsMatch =
51  A->isMachineConstantPoolEntry() == B->isMachineConstantPoolEntry();
52  if (IsMatch) {
53  if (A->isMachineConstantPoolEntry())
54  IsMatch = A->getMachineCPVal() == B->getMachineCPVal();
55  else
56  IsMatch = A->getConstVal() == B->getConstVal();
57  }
58  if (IsMatch) {
59  Off += B->getOffset() - A->getOffset();
60  return true;
61  }
62  }
63 
65 
66  // Match FrameIndexes.
67  if (auto *A = dyn_cast<FrameIndexSDNode>(Base))
68  if (auto *B = dyn_cast<FrameIndexSDNode>(Other.Base)) {
69  // Equal FrameIndexes - offsets are directly comparable.
70  if (A->getIndex() == B->getIndex())
71  return true;
72  // Non-equal FrameIndexes - If both frame indices are fixed
73  // we know their relative offsets and can compare them. Otherwise
74  // we must be conservative.
75  if (MFI.isFixedObjectIndex(A->getIndex()) &&
76  MFI.isFixedObjectIndex(B->getIndex())) {
77  Off += MFI.getObjectOffset(B->getIndex()) -
78  MFI.getObjectOffset(A->getIndex());
79  return true;
80  }
81  }
82  }
83  return false;
84 }
85 
87  const Optional<int64_t> NumBytes0,
88  const SDNode *Op1,
89  const Optional<int64_t> NumBytes1,
90  const SelectionDAG &DAG, bool &IsAlias) {
91 
92  BaseIndexOffset BasePtr0 = match(Op0, DAG);
93  BaseIndexOffset BasePtr1 = match(Op1, DAG);
94 
95  if (!(BasePtr0.getBase().getNode() && BasePtr1.getBase().getNode()))
96  return false;
97  int64_t PtrDiff;
98  if (NumBytes0.hasValue() && NumBytes1.hasValue() &&
99  BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff)) {
100  // If the size of memory access is unknown, do not use it to analysis.
101  // One example of unknown size memory access is to load/store scalable
102  // vector objects on the stack.
103  // BasePtr1 is PtrDiff away from BasePtr0. They alias if none of the
104  // following situations arise:
105  if (PtrDiff >= 0 &&
106  *NumBytes0 != static_cast<int64_t>(MemoryLocation::UnknownSize)) {
107  // [----BasePtr0----]
108  // [---BasePtr1--]
109  // ========PtrDiff========>
110  IsAlias = !(*NumBytes0 <= PtrDiff);
111  return true;
112  }
113  if (PtrDiff < 0 &&
114  *NumBytes1 != static_cast<int64_t>(MemoryLocation::UnknownSize)) {
115  // [----BasePtr0----]
116  // [---BasePtr1--]
117  // =====(-PtrDiff)====>
118  IsAlias = !((PtrDiff + *NumBytes1) <= 0);
119  return true;
120  }
121  return false;
122  }
123  // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
124  // able to calculate their relative offset if at least one arises
125  // from an alloca. However, these allocas cannot overlap and we
126  // can infer there is no alias.
127  if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase()))
128  if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) {
130  // If the base are the same frame index but the we couldn't find a
131  // constant offset, (indices are different) be conservative.
132  if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) ||
133  !MFI.isFixedObjectIndex(B->getIndex()))) {
134  IsAlias = false;
135  return true;
136  }
137  }
138 
139  bool IsFI0 = isa<FrameIndexSDNode>(BasePtr0.getBase());
140  bool IsFI1 = isa<FrameIndexSDNode>(BasePtr1.getBase());
141  bool IsGV0 = isa<GlobalAddressSDNode>(BasePtr0.getBase());
142  bool IsGV1 = isa<GlobalAddressSDNode>(BasePtr1.getBase());
143  bool IsCV0 = isa<ConstantPoolSDNode>(BasePtr0.getBase());
144  bool IsCV1 = isa<ConstantPoolSDNode>(BasePtr1.getBase());
145 
146  // If of mismatched base types or checkable indices we can check
147  // they do not alias.
148  if ((BasePtr0.getIndex() == BasePtr1.getIndex() || (IsFI0 != IsFI1) ||
149  (IsGV0 != IsGV1) || (IsCV0 != IsCV1)) &&
150  (IsFI0 || IsGV0 || IsCV0) && (IsFI1 || IsGV1 || IsCV1)) {
151  IsAlias = false;
152  return true;
153  }
154  return false; // Cannot determine whether the pointers alias.
155 }
156 
157 bool BaseIndexOffset::contains(const SelectionDAG &DAG, int64_t BitSize,
158  const BaseIndexOffset &Other,
159  int64_t OtherBitSize, int64_t &BitOffset) const {
160  int64_t Offset;
161  if (!equalBaseIndex(Other, DAG, Offset))
162  return false;
163  if (Offset >= 0) {
164  // Other is after *this:
165  // [-------*this---------]
166  // [---Other--]
167  // ==Offset==>
168  BitOffset = 8 * Offset;
169  return BitOffset + OtherBitSize <= BitSize;
170  }
171  // Other starts strictly before *this, it cannot be fully contained.
172  // [-------*this---------]
173  // [--Other--]
174  return false;
175 }
176 
177 /// Parses tree in Ptr for base, index, offset addresses.
179  const SelectionDAG &DAG) {
180  SDValue Ptr = N->getBasePtr();
181 
182  // (((B + I*M) + c)) + c ...
184  SDValue Index = SDValue();
185  int64_t Offset = 0;
186  bool IsIndexSignExt = false;
187 
188  // pre-inc/pre-dec ops are components of EA.
189  if (N->getAddressingMode() == ISD::PRE_INC) {
190  if (auto *C = dyn_cast<ConstantSDNode>(N->getOffset()))
191  Offset += C->getSExtValue();
192  else // If unknown, give up now.
193  return BaseIndexOffset(SDValue(), SDValue(), 0, false);
194  } else if (N->getAddressingMode() == ISD::PRE_DEC) {
195  if (auto *C = dyn_cast<ConstantSDNode>(N->getOffset()))
196  Offset -= C->getSExtValue();
197  else // If unknown, give up now.
198  return BaseIndexOffset(SDValue(), SDValue(), 0, false);
199  }
200 
201  // Consume constant adds & ors with appropriate masking.
202  while (true) {
203  switch (Base->getOpcode()) {
204  case ISD::OR:
205  // Only consider ORs which act as adds.
206  if (auto *C = dyn_cast<ConstantSDNode>(Base->getOperand(1)))
207  if (DAG.MaskedValueIsZero(Base->getOperand(0), C->getAPIntValue())) {
208  Offset += C->getSExtValue();
209  Base = DAG.getTargetLoweringInfo().unwrapAddress(Base->getOperand(0));
210  continue;
211  }
212  break;
213  case ISD::ADD:
214  if (auto *C = dyn_cast<ConstantSDNode>(Base->getOperand(1))) {
215  Offset += C->getSExtValue();
216  Base = DAG.getTargetLoweringInfo().unwrapAddress(Base->getOperand(0));
217  continue;
218  }
219  break;
220  case ISD::LOAD:
221  case ISD::STORE: {
222  auto *LSBase = cast<LSBaseSDNode>(Base.getNode());
223  unsigned int IndexResNo = (Base->getOpcode() == ISD::LOAD) ? 1 : 0;
224  if (LSBase->isIndexed() && Base.getResNo() == IndexResNo)
225  if (auto *C = dyn_cast<ConstantSDNode>(LSBase->getOffset())) {
226  auto Off = C->getSExtValue();
227  if (LSBase->getAddressingMode() == ISD::PRE_DEC ||
228  LSBase->getAddressingMode() == ISD::POST_DEC)
229  Offset -= Off;
230  else
231  Offset += Off;
232  Base = DAG.getTargetLoweringInfo().unwrapAddress(LSBase->getBasePtr());
233  continue;
234  }
235  break;
236  }
237  }
238  // If we get here break out of the loop.
239  break;
240  }
241 
242  if (Base->getOpcode() == ISD::ADD) {
243  // TODO: The following code appears to be needless as it just
244  // bails on some Ptrs early, reducing the cases where we
245  // find equivalence. We should be able to remove this.
246  // Inside a loop the current BASE pointer is calculated using an ADD and a
247  // MUL instruction. In this case Base is the actual BASE pointer.
248  // (i64 add (i64 %array_ptr)
249  // (i64 mul (i64 %induction_var)
250  // (i64 %element_size)))
251  if (Base->getOperand(1)->getOpcode() == ISD::MUL)
252  return BaseIndexOffset(Base, Index, Offset, IsIndexSignExt);
253 
254  // Look at Base + Index + Offset cases.
255  Index = Base->getOperand(1);
256  SDValue PotentialBase = Base->getOperand(0);
257 
258  // Skip signextends.
259  if (Index->getOpcode() == ISD::SIGN_EXTEND) {
260  Index = Index->getOperand(0);
261  IsIndexSignExt = true;
262  }
263 
264  // Check if Index Offset pattern
265  if (Index->getOpcode() != ISD::ADD ||
266  !isa<ConstantSDNode>(Index->getOperand(1)))
267  return BaseIndexOffset(PotentialBase, Index, Offset, IsIndexSignExt);
268 
269  Offset += cast<ConstantSDNode>(Index->getOperand(1))->getSExtValue();
270  Index = Index->getOperand(0);
271  if (Index->getOpcode() == ISD::SIGN_EXTEND) {
272  Index = Index->getOperand(0);
273  IsIndexSignExt = true;
274  } else
275  IsIndexSignExt = false;
276  Base = PotentialBase;
277  }
278  return BaseIndexOffset(Base, Index, Offset, IsIndexSignExt);
279 }
280 
282  const SelectionDAG &DAG) {
283  if (const auto *LS0 = dyn_cast<LSBaseSDNode>(N))
284  return matchLSNode(LS0, DAG);
285  if (const auto *LN = dyn_cast<LifetimeSDNode>(N)) {
286  if (LN->hasOffset())
287  return BaseIndexOffset(LN->getOperand(1), SDValue(), LN->getOffset(),
288  false);
289  return BaseIndexOffset(LN->getOperand(1), SDValue(), false);
290  }
291  return BaseIndexOffset();
292 }
293 
294 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
295 
297  print(dbgs());
298 }
299 
301  OS << "BaseIndexOffset base=[";
302  Base->print(OS);
303  OS << "] index=[";
304  if (Index)
305  Index->print(OS);
306  OS << "] offset=" << Offset;
307 }
308 
309 #endif
llvm::BaseIndexOffset::print
void print(raw_ostream &OS) const
Definition: SelectionDAGAddressAnalysis.cpp:300
LLVM_DUMP_METHOD
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition: Compiler.h:491
llvm
---------------------— PointerInfo ------------------------------------—
Definition: AllocatorList.h:23
llvm::ISD::OR
@ OR
Definition: ISDOpcodes.h:633
llvm::SDValue::getNode
SDNode * getNode() const
get the SDNode which holds the desired result
Definition: SelectionDAGNodes.h:152
llvm::ISD::PRE_DEC
@ PRE_DEC
Definition: ISDOpcodes.h:1304
llvm::SDNode
Represents one node in the SelectionDAG.
Definition: SelectionDAGNodes.h:455
llvm::BaseIndexOffset::getBase
SDValue getBase()
Definition: SelectionDAGAddressAnalysis.h:48
SelectionDAGAddressAnalysis.h
llvm::Optional< int64_t >
Offset
uint64_t Offset
Definition: ELFObjHandler.cpp:81
llvm::BaseIndexOffset::contains
bool contains(const SelectionDAG &DAG, int64_t BitSize, const BaseIndexOffset &Other, int64_t OtherBitSize, int64_t &BitOffset) const
Definition: SelectionDAGAddressAnalysis.cpp:157
SelectionDAG.h
llvm::BaseIndexOffset::dump
void dump() const
Definition: SelectionDAGAddressAnalysis.cpp:296
llvm::Optional::hasValue
constexpr bool hasValue() const
Definition: Optional.h:288
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
TargetLowering.h
llvm::SelectionDAG
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
Definition: SelectionDAG.h:216
SelectionDAGNodes.h
llvm::SelectionDAG::getTargetLoweringInfo
const TargetLowering & getTargetLoweringInfo() const
Definition: SelectionDAG.h:443
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::SelectionDAG::MaskedValueIsZero
bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
Definition: SelectionDAG.cpp:2463
B
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
llvm::raw_ostream
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:53
llvm::MemoryLocation::UnknownSize
@ UnknownSize
Definition: MemoryLocation.h:214
llvm::MachineFrameInfo::getObjectOffset
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
Definition: MachineFrameInfo.h:494
llvm::MachineFrameInfo::isFixedObjectIndex
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
Definition: MachineFrameInfo.h:656
llvm::BaseIndexOffset::match
static BaseIndexOffset match(const SDNode *N, const SelectionDAG &DAG)
Parses tree in N for base, index, offset addresses.
Definition: SelectionDAGAddressAnalysis.cpp:281
Index
uint32_t Index
Definition: ELFObjHandler.cpp:84
llvm::ISD::LOAD
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
Definition: ISDOpcodes.h:921
MemoryLocation.h
llvm::MachineFunction::getFrameInfo
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Definition: MachineFunction.h:642
llvm::SDNode::print
void print(raw_ostream &OS, const SelectionDAG *G=nullptr) const
Definition: SelectionDAGDumper.cpp:1048
llvm::ISD::POST_DEC
@ POST_DEC
Definition: ISDOpcodes.h:1304
llvm::BaseIndexOffset::computeAliasing
static bool computeAliasing(const SDNode *Op0, const Optional< int64_t > NumBytes0, const SDNode *Op1, const Optional< int64_t > NumBytes1, const SelectionDAG &DAG, bool &IsAlias)
Definition: SelectionDAGAddressAnalysis.cpp:86
llvm::ISD::PRE_INC
@ PRE_INC
Definition: ISDOpcodes.h:1304
llvm::BaseIndexOffset::equalBaseIndex
bool equalBaseIndex(const BaseIndexOffset &Other, const SelectionDAG &DAG, int64_t &Off) const
Definition: SelectionDAGAddressAnalysis.cpp:23
llvm::BaseIndexOffset::getIndex
SDValue getIndex()
Definition: SelectionDAGAddressAnalysis.h:50
MachineFrameInfo.h
ISDOpcodes.h
Casting.h
llvm::SDValue
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
Definition: SelectionDAGNodes.h:138
llvm::BaseIndexOffset::hasValidOffset
bool hasValidOffset() const
Definition: SelectionDAGAddressAnalysis.h:52
llvm::BaseIndexOffset
Helper struct to parse and store a memory address as base + index + offset.
Definition: SelectionDAGAddressAnalysis.h:32
llvm::ISD::STORE
@ STORE
Definition: ISDOpcodes.h:922
llvm::ISD::ADD
@ ADD
Simple integer binary arithmetic operators.
Definition: ISDOpcodes.h:239
llvm::MachineFrameInfo
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
Definition: MachineFrameInfo.h:107
llvm::LSBaseSDNode
Base class for LoadSDNode and StoreSDNode.
Definition: SelectionDAGNodes.h:2248
matchLSNode
static BaseIndexOffset matchLSNode(const LSBaseSDNode *N, const SelectionDAG &DAG)
Parses tree in Ptr for base, index, offset addresses.
Definition: SelectionDAGAddressAnalysis.cpp:178
llvm::BaseIndexOffset::BaseIndexOffset
BaseIndexOffset()=default
llvm::ISD::MUL
@ MUL
Definition: ISDOpcodes.h:241
N
#define N
llvm::SelectionDAG::getMachineFunction
MachineFunction & getMachineFunction() const
Definition: SelectionDAG.h:437
llvm::ISD::SIGN_EXTEND
@ SIGN_EXTEND
Conversion operators.
Definition: ISDOpcodes.h:726
MachineFunction.h
Debug.h
llvm::sampleprof::Base
@ Base
Definition: Discriminator.h:58
Other
Optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1172
llvm::TargetLowering::unwrapAddress
virtual SDValue unwrapAddress(SDValue N) const
Definition: TargetLowering.h:3589