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/IR/GlobalAlias.h"
18 #include "llvm/Support/Casting.h"
19 #include "llvm/Support/Debug.h"
20 #include <cstdint>
21 
22 using namespace llvm;
23 
25  const SelectionDAG &DAG,
26  int64_t &Off) const {
27  // Conservatively fail if we a match failed..
28  if (!Base.getNode() || !Other.Base.getNode())
29  return false;
30  if (!hasValidOffset() || !Other.hasValidOffset())
31  return false;
32  // Initial Offset difference.
33  Off = *Other.Offset - *Offset;
34 
35  if ((Other.Index == Index) && (Other.IsIndexSignExt == IsIndexSignExt)) {
36  // Trivial match.
37  if (Other.Base == Base)
38  return true;
39 
40  // Match GlobalAddresses
41  if (auto *A = dyn_cast<GlobalAddressSDNode>(Base))
42  if (auto *B = dyn_cast<GlobalAddressSDNode>(Other.Base))
43  if (A->getGlobal() == B->getGlobal()) {
44  Off += B->getOffset() - A->getOffset();
45  return true;
46  }
47 
48  // Match Constants
49  if (auto *A = dyn_cast<ConstantPoolSDNode>(Base))
50  if (auto *B = dyn_cast<ConstantPoolSDNode>(Other.Base)) {
51  bool IsMatch =
52  A->isMachineConstantPoolEntry() == B->isMachineConstantPoolEntry();
53  if (IsMatch) {
54  if (A->isMachineConstantPoolEntry())
55  IsMatch = A->getMachineCPVal() == B->getMachineCPVal();
56  else
57  IsMatch = A->getConstVal() == B->getConstVal();
58  }
59  if (IsMatch) {
60  Off += B->getOffset() - A->getOffset();
61  return true;
62  }
63  }
64 
66 
67  // Match FrameIndexes.
68  if (auto *A = dyn_cast<FrameIndexSDNode>(Base))
69  if (auto *B = dyn_cast<FrameIndexSDNode>(Other.Base)) {
70  // Equal FrameIndexes - offsets are directly comparable.
71  if (A->getIndex() == B->getIndex())
72  return true;
73  // Non-equal FrameIndexes - If both frame indices are fixed
74  // we know their relative offsets and can compare them. Otherwise
75  // we must be conservative.
76  if (MFI.isFixedObjectIndex(A->getIndex()) &&
77  MFI.isFixedObjectIndex(B->getIndex())) {
78  Off += MFI.getObjectOffset(B->getIndex()) -
79  MFI.getObjectOffset(A->getIndex());
80  return true;
81  }
82  }
83  }
84  return false;
85 }
86 
88  const Optional<int64_t> NumBytes0,
89  const SDNode *Op1,
90  const Optional<int64_t> NumBytes1,
91  const SelectionDAG &DAG, bool &IsAlias) {
92 
93  BaseIndexOffset BasePtr0 = match(Op0, DAG);
94  BaseIndexOffset BasePtr1 = match(Op1, DAG);
95 
96  if (!(BasePtr0.getBase().getNode() && BasePtr1.getBase().getNode()))
97  return false;
98  int64_t PtrDiff;
99  if (NumBytes0.hasValue() && NumBytes1.hasValue() &&
100  BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff)) {
101  // If the size of memory access is unknown, do not use it to analysis.
102  // One example of unknown size memory access is to load/store scalable
103  // vector objects on the stack.
104  // BasePtr1 is PtrDiff away from BasePtr0. They alias if none of the
105  // following situations arise:
106  if (PtrDiff >= 0 &&
107  *NumBytes0 != static_cast<int64_t>(MemoryLocation::UnknownSize)) {
108  // [----BasePtr0----]
109  // [---BasePtr1--]
110  // ========PtrDiff========>
111  IsAlias = !(*NumBytes0 <= PtrDiff);
112  return true;
113  }
114  if (PtrDiff < 0 &&
115  *NumBytes1 != static_cast<int64_t>(MemoryLocation::UnknownSize)) {
116  // [----BasePtr0----]
117  // [---BasePtr1--]
118  // =====(-PtrDiff)====>
119  IsAlias = !((PtrDiff + *NumBytes1) <= 0);
120  return true;
121  }
122  return false;
123  }
124  // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
125  // able to calculate their relative offset if at least one arises
126  // from an alloca. However, these allocas cannot overlap and we
127  // can infer there is no alias.
128  if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase()))
129  if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) {
131  // If the base are the same frame index but the we couldn't find a
132  // constant offset, (indices are different) be conservative.
133  if (A != B && (!MFI.isFixedObjectIndex(A->getIndex()) ||
134  !MFI.isFixedObjectIndex(B->getIndex()))) {
135  IsAlias = false;
136  return true;
137  }
138  }
139 
140  bool IsFI0 = isa<FrameIndexSDNode>(BasePtr0.getBase());
141  bool IsFI1 = isa<FrameIndexSDNode>(BasePtr1.getBase());
142  bool IsGV0 = isa<GlobalAddressSDNode>(BasePtr0.getBase());
143  bool IsGV1 = isa<GlobalAddressSDNode>(BasePtr1.getBase());
144  bool IsCV0 = isa<ConstantPoolSDNode>(BasePtr0.getBase());
145  bool IsCV1 = isa<ConstantPoolSDNode>(BasePtr1.getBase());
146 
147  if ((IsFI0 || IsGV0 || IsCV0) && (IsFI1 || IsGV1 || IsCV1)) {
148  // We can derive NoAlias In case of mismatched base types.
149  if (IsFI0 != IsFI1 || IsGV0 != IsGV1 || IsCV0 != IsCV1) {
150  IsAlias = false;
151  return true;
152  }
153  if (IsGV0 && IsGV1) {
154  auto *GV0 = cast<GlobalAddressSDNode>(BasePtr0.getBase())->getGlobal();
155  auto *GV1 = cast<GlobalAddressSDNode>(BasePtr1.getBase())->getGlobal();
156  // It doesn't make sense to access one global value using another globals
157  // values address, so we can assume that there is no aliasing in case of
158  // two different globals (unless we have symbols that may indirectly point
159  // to each other).
160  // FIXME: This is perhaps a bit too defensive. We could try to follow the
161  // chain with aliasee information for GlobalAlias variables to find out if
162  // we indirect symbols may alias or not.
163  if (GV0 != GV1 && !isa<GlobalAlias>(GV0) && !isa<GlobalAlias>(GV1)) {
164  IsAlias = false;
165  return true;
166  }
167  }
168  }
169  return false; // Cannot determine whether the pointers alias.
170 }
171 
172 bool BaseIndexOffset::contains(const SelectionDAG &DAG, int64_t BitSize,
173  const BaseIndexOffset &Other,
174  int64_t OtherBitSize, int64_t &BitOffset) const {
175  int64_t Offset;
176  if (!equalBaseIndex(Other, DAG, Offset))
177  return false;
178  if (Offset >= 0) {
179  // Other is after *this:
180  // [-------*this---------]
181  // [---Other--]
182  // ==Offset==>
183  BitOffset = 8 * Offset;
184  return BitOffset + OtherBitSize <= BitSize;
185  }
186  // Other starts strictly before *this, it cannot be fully contained.
187  // [-------*this---------]
188  // [--Other--]
189  return false;
190 }
191 
192 /// Parses tree in Ptr for base, index, offset addresses.
194  const SelectionDAG &DAG) {
195  SDValue Ptr = N->getBasePtr();
196 
197  // (((B + I*M) + c)) + c ...
199  SDValue Index = SDValue();
200  int64_t Offset = 0;
201  bool IsIndexSignExt = false;
202 
203  // pre-inc/pre-dec ops are components of EA.
204  if (N->getAddressingMode() == ISD::PRE_INC) {
205  if (auto *C = dyn_cast<ConstantSDNode>(N->getOffset()))
206  Offset += C->getSExtValue();
207  else // If unknown, give up now.
208  return BaseIndexOffset(SDValue(), SDValue(), 0, false);
209  } else if (N->getAddressingMode() == ISD::PRE_DEC) {
210  if (auto *C = dyn_cast<ConstantSDNode>(N->getOffset()))
211  Offset -= C->getSExtValue();
212  else // If unknown, give up now.
213  return BaseIndexOffset(SDValue(), SDValue(), 0, false);
214  }
215 
216  // Consume constant adds & ors with appropriate masking.
217  while (true) {
218  switch (Base->getOpcode()) {
219  case ISD::OR:
220  // Only consider ORs which act as adds.
221  if (auto *C = dyn_cast<ConstantSDNode>(Base->getOperand(1)))
222  if (DAG.MaskedValueIsZero(Base->getOperand(0), C->getAPIntValue())) {
223  Offset += C->getSExtValue();
224  Base = DAG.getTargetLoweringInfo().unwrapAddress(Base->getOperand(0));
225  continue;
226  }
227  break;
228  case ISD::ADD:
229  if (auto *C = dyn_cast<ConstantSDNode>(Base->getOperand(1))) {
230  Offset += C->getSExtValue();
231  Base = DAG.getTargetLoweringInfo().unwrapAddress(Base->getOperand(0));
232  continue;
233  }
234  break;
235  case ISD::LOAD:
236  case ISD::STORE: {
237  auto *LSBase = cast<LSBaseSDNode>(Base.getNode());
238  unsigned int IndexResNo = (Base->getOpcode() == ISD::LOAD) ? 1 : 0;
239  if (LSBase->isIndexed() && Base.getResNo() == IndexResNo)
240  if (auto *C = dyn_cast<ConstantSDNode>(LSBase->getOffset())) {
241  auto Off = C->getSExtValue();
242  if (LSBase->getAddressingMode() == ISD::PRE_DEC ||
243  LSBase->getAddressingMode() == ISD::POST_DEC)
244  Offset -= Off;
245  else
246  Offset += Off;
247  Base = DAG.getTargetLoweringInfo().unwrapAddress(LSBase->getBasePtr());
248  continue;
249  }
250  break;
251  }
252  }
253  // If we get here break out of the loop.
254  break;
255  }
256 
257  if (Base->getOpcode() == ISD::ADD) {
258  // TODO: The following code appears to be needless as it just
259  // bails on some Ptrs early, reducing the cases where we
260  // find equivalence. We should be able to remove this.
261  // Inside a loop the current BASE pointer is calculated using an ADD and a
262  // MUL instruction. In this case Base is the actual BASE pointer.
263  // (i64 add (i64 %array_ptr)
264  // (i64 mul (i64 %induction_var)
265  // (i64 %element_size)))
266  if (Base->getOperand(1)->getOpcode() == ISD::MUL)
267  return BaseIndexOffset(Base, Index, Offset, IsIndexSignExt);
268 
269  // Look at Base + Index + Offset cases.
270  Index = Base->getOperand(1);
271  SDValue PotentialBase = Base->getOperand(0);
272 
273  // Skip signextends.
274  if (Index->getOpcode() == ISD::SIGN_EXTEND) {
275  Index = Index->getOperand(0);
276  IsIndexSignExt = true;
277  }
278 
279  // Check if Index Offset pattern
280  if (Index->getOpcode() != ISD::ADD ||
281  !isa<ConstantSDNode>(Index->getOperand(1)))
282  return BaseIndexOffset(PotentialBase, Index, Offset, IsIndexSignExt);
283 
284  Offset += cast<ConstantSDNode>(Index->getOperand(1))->getSExtValue();
285  Index = Index->getOperand(0);
286  if (Index->getOpcode() == ISD::SIGN_EXTEND) {
287  Index = Index->getOperand(0);
288  IsIndexSignExt = true;
289  } else
290  IsIndexSignExt = false;
291  Base = PotentialBase;
292  }
293  return BaseIndexOffset(Base, Index, Offset, IsIndexSignExt);
294 }
295 
297  const SelectionDAG &DAG) {
298  if (const auto *LS0 = dyn_cast<LSBaseSDNode>(N))
299  return matchLSNode(LS0, DAG);
300  if (const auto *LN = dyn_cast<LifetimeSDNode>(N)) {
301  if (LN->hasOffset())
302  return BaseIndexOffset(LN->getOperand(1), SDValue(), LN->getOffset(),
303  false);
304  return BaseIndexOffset(LN->getOperand(1), SDValue(), false);
305  }
306  return BaseIndexOffset();
307 }
308 
309 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
310 
312  print(dbgs());
313 }
314 
316  OS << "BaseIndexOffset base=[";
317  Base->print(OS);
318  OS << "] index=[";
319  if (Index)
320  Index->print(OS);
321  OS << "] offset=" << Offset;
322 }
323 
324 #endif
llvm::BaseIndexOffset::print
void print(raw_ostream &OS) const
Definition: SelectionDAGAddressAnalysis.cpp:315
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:506
llvm
This file implements support for optimizing divisions by a constant.
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:1310
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:172
SelectionDAG.h
llvm::BaseIndexOffset::dump
void dump() const
Definition: SelectionDAGAddressAnalysis.cpp:311
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:2485
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:296
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:1310
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:87
llvm::ISD::PRE_INC
@ PRE_INC
Definition: ISDOpcodes.h:1310
llvm::BaseIndexOffset::equalBaseIndex
bool equalBaseIndex(const BaseIndexOffset &Other, const SelectionDAG &DAG, int64_t &Off) const
Definition: SelectionDAGAddressAnalysis.cpp:24
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
GlobalAlias.h
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:193
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:1184
llvm::TargetLowering::unwrapAddress
virtual SDValue unwrapAddress(SDValue N) const
Definition: TargetLowering.h:3589