LLVM 24.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"
19#include "llvm/Support/Debug.h"
20#include <cstdint>
21
22using namespace llvm;
23
25 const SelectionDAG &DAG,
26 int64_t &Off) const {
27 StackOffset Diff;
28 if (!equalBaseIndex(Other, DAG, Diff) || Diff.getScalable() != 0)
29 return false;
30 Off = Diff.getFixed();
31 return true;
32}
33
35 const SelectionDAG &DAG,
36 StackOffset &Off) const {
37 // Conservatively fail if we a match failed..
38 if (!Base.getNode() || !Other.Base.getNode())
39 return false;
40 if (!hasValidStackOffset() || !Other.hasValidStackOffset())
41 return false;
42 // Initial Offset difference.
43 Off = *Other.Offset - *Offset;
44
45 if ((Other.Index == Index) && (Other.IsIndexSignExt == IsIndexSignExt)) {
46 // Trivial match.
47 if (Other.Base == Base)
48 return true;
49
50 // Match GlobalAddresses
51 if (auto *A = dyn_cast<GlobalAddressSDNode>(Base)) {
52 if (auto *B = dyn_cast<GlobalAddressSDNode>(Other.Base))
53 if (A->getGlobal() == B->getGlobal()) {
54 Off += StackOffset::getFixed(B->getOffset() - A->getOffset());
55 return true;
56 }
57
58 return false;
59 }
60
61 // Match Constants
62 if (auto *A = dyn_cast<ConstantPoolSDNode>(Base)) {
63 if (auto *B = dyn_cast<ConstantPoolSDNode>(Other.Base)) {
64 bool IsMatch =
65 A->isMachineConstantPoolEntry() == B->isMachineConstantPoolEntry();
66 if (IsMatch) {
67 if (A->isMachineConstantPoolEntry())
68 IsMatch = A->getMachineCPVal() == B->getMachineCPVal();
69 else
70 IsMatch = A->getConstVal() == B->getConstVal();
71 }
72 if (IsMatch) {
73 Off += StackOffset::getFixed(B->getOffset() - A->getOffset());
74 return true;
75 }
76 }
77
78 return false;
79 }
80
81 // Match FrameIndexes.
82 if (auto *A = dyn_cast<FrameIndexSDNode>(Base))
83 if (auto *B = dyn_cast<FrameIndexSDNode>(Other.Base)) {
84 // Equal FrameIndexes - offsets are directly comparable.
85 if (A->getIndex() == B->getIndex())
86 return true;
87 // Non-equal FrameIndexes - If both frame indices are fixed
88 // we know their relative offsets and can compare them. Otherwise
89 // we must be conservative.
91 if (MFI.isFixedObjectIndex(A->getIndex()) &&
92 MFI.isFixedObjectIndex(B->getIndex())) {
93 Off += StackOffset::getFixed(MFI.getObjectOffset(B->getIndex()) -
94 MFI.getObjectOffset(A->getIndex()));
95 return true;
96 }
97 }
98 }
99
100 return false;
101}
102
104 const LocationSize NumBytes0,
105 const SDNode *Op1,
106 const LocationSize NumBytes1,
107 const SelectionDAG &DAG, bool &IsAlias) {
108 BaseIndexOffset BasePtr0 = match(Op0, DAG);
109 if (!BasePtr0.getBase().getNode())
110 return false;
111
112 BaseIndexOffset BasePtr1 = match(Op1, DAG);
113 if (!BasePtr1.getBase().getNode())
114 return false;
115
116 int64_t PtrDiff;
117 if (BasePtr0.equalBaseIndex(BasePtr1, DAG, PtrDiff)) {
118 // If the size of memory access is unknown, do not use it to analysis.
119 // BasePtr1 is PtrDiff away from BasePtr0. They alias if none of the
120 // following situations arise:
121 if (PtrDiff >= 0 && NumBytes0.hasValue() && !NumBytes0.isScalable()) {
122 // [----BasePtr0----]
123 // [---BasePtr1--]
124 // ========PtrDiff========>
125 IsAlias = !(static_cast<int64_t>(NumBytes0.getValue().getFixedValue()) <=
126 PtrDiff);
127 return true;
128 }
129 if (PtrDiff < 0 && NumBytes1.hasValue() && !NumBytes1.isScalable()) {
130 // [----BasePtr0----]
131 // [---BasePtr1--]
132 // =====(-PtrDiff)====>
133 IsAlias = !((PtrDiff + static_cast<int64_t>(
134 NumBytes1.getValue().getFixedValue())) <= 0);
135 return true;
136 }
137 return false;
138 }
139 // If both BasePtr0 and BasePtr1 are FrameIndexes, we will not be
140 // able to calculate their relative offset if at least one arises
141 // from an alloca. However, these allocas cannot overlap and we
142 // can infer there is no alias.
143 if (auto *A = dyn_cast<FrameIndexSDNode>(BasePtr0.getBase()))
144 if (auto *B = dyn_cast<FrameIndexSDNode>(BasePtr1.getBase())) {
146 // If the base are the same frame index but the we couldn't find a
147 // constant offset, (indices are different) be conservative.
148 if (A->getIndex() != B->getIndex() && (!MFI.isFixedObjectIndex(A->getIndex()) ||
149 !MFI.isFixedObjectIndex(B->getIndex()))) {
150 IsAlias = false;
151 return true;
152 }
153 }
154
155 bool IsFI0 = isa<FrameIndexSDNode>(BasePtr0.getBase());
156 bool IsFI1 = isa<FrameIndexSDNode>(BasePtr1.getBase());
157 bool IsGV0 = isa<GlobalAddressSDNode>(BasePtr0.getBase());
158 bool IsGV1 = isa<GlobalAddressSDNode>(BasePtr1.getBase());
159 bool IsCV0 = isa<ConstantPoolSDNode>(BasePtr0.getBase());
160 bool IsCV1 = isa<ConstantPoolSDNode>(BasePtr1.getBase());
161
162 if ((IsFI0 || IsGV0 || IsCV0) && (IsFI1 || IsGV1 || IsCV1)) {
163 // We can derive NoAlias In case of mismatched base types.
164 if (IsFI0 != IsFI1 || IsGV0 != IsGV1 || IsCV0 != IsCV1) {
165 IsAlias = false;
166 return true;
167 }
168 if (IsGV0 && IsGV1) {
169 auto *GV0 = cast<GlobalAddressSDNode>(BasePtr0.getBase())->getGlobal();
170 auto *GV1 = cast<GlobalAddressSDNode>(BasePtr1.getBase())->getGlobal();
171 // It doesn't make sense to access one global value using another globals
172 // values address, so we can assume that there is no aliasing in case of
173 // two different globals (unless we have symbols that may indirectly point
174 // to each other).
175 // FIXME: This is perhaps a bit too defensive. We could try to follow the
176 // chain with aliasee information for GlobalAlias variables to find out if
177 // we indirect symbols may alias or not.
178 if (GV0 != GV1 && !isa<GlobalAlias>(GV0) && !isa<GlobalAlias>(GV1)) {
179 IsAlias = false;
180 return true;
181 }
182 }
183 }
184 return false; // Cannot determine whether the pointers alias.
185}
186
187bool BaseIndexOffset::contains(const SelectionDAG &DAG, int64_t BitSize,
188 const BaseIndexOffset &Other,
189 int64_t OtherBitSize, int64_t &BitOffset) const {
190 int64_t Offset;
191 if (!equalBaseIndex(Other, DAG, Offset))
192 return false;
193 if (Offset >= 0) {
194 // Other is after *this:
195 // [-------*this---------]
196 // [---Other--]
197 // ==Offset==>
198 BitOffset = 8 * Offset;
199 return BitOffset + OtherBitSize <= BitSize;
200 }
201 // Other starts strictly before *this, it cannot be fully contained.
202 // [-------*this---------]
203 // [--Other--]
204 return false;
205}
206
207/// Parses tree in Ptr for base, index, offset addresses.
209 const SelectionDAG &DAG) {
210 SDValue Ptr = N->getBasePtr();
211
212 // (((B + I*M) + c)) + c ...
214 SDValue Index = SDValue();
216 bool IsIndexSignExt = false;
217
218 // pre-inc/pre-dec ops are components of EA.
219 if (N->getAddressingMode() == ISD::PRE_INC) {
220 if (auto *C = dyn_cast<ConstantSDNode>(N->getOffset()))
221 Offset += StackOffset::getFixed(C->getSExtValue());
222 else // If unknown, give up now.
223 return BaseIndexOffset(SDValue(), SDValue(), 0, false);
224 } else if (N->getAddressingMode() == ISD::PRE_DEC) {
225 if (auto *C = dyn_cast<ConstantSDNode>(N->getOffset()))
226 Offset -= StackOffset::getFixed(C->getSExtValue());
227 else // If unknown, give up now.
228 return BaseIndexOffset(SDValue(), SDValue(), 0, false);
229 }
230
231 // Consume fixed and scalable offsets, including ORs that act as adds.
232 while (true) {
233 switch (Base->getOpcode()) {
234 case ISD::OR:
235 // Only consider ORs which act as adds.
236 if (auto *C = dyn_cast<ConstantSDNode>(Base->getOperand(1)))
237 if (DAG.MaskedValueIsZero(Base->getOperand(0), C->getAPIntValue())) {
238 Offset += StackOffset::getFixed(C->getSExtValue());
239 Base = DAG.getTargetLoweringInfo().unwrapAddress(Base->getOperand(0));
240 continue;
241 }
242 break;
243 case ISD::ADD:
244 case ISD::PTRADD:
245 if (auto *C = dyn_cast<ConstantSDNode>(Base->getOperand(1)))
246 Offset += StackOffset::getFixed(C->getSExtValue());
247 else if (Base->getOperand(1).getOpcode() == ISD::VSCALE)
249 Base->getOperand(1).getConstantOperandAPInt(0).getSExtValue());
250 else
251 break;
252 Base = DAG.getTargetLoweringInfo().unwrapAddress(Base->getOperand(0));
253 continue;
254 case ISD::LOAD:
255 case ISD::STORE: {
256 auto *LSBase = cast<LSBaseSDNode>(Base.getNode());
257 unsigned int IndexResNo = (Base->getOpcode() == ISD::LOAD) ? 1 : 0;
258 if (LSBase->isIndexed() && Base.getResNo() == IndexResNo)
259 if (auto *C = dyn_cast<ConstantSDNode>(LSBase->getOffset())) {
260 auto Off = C->getSExtValue();
261 if (LSBase->getAddressingMode() == ISD::PRE_DEC ||
262 LSBase->getAddressingMode() == ISD::POST_DEC)
264 else
266 Base = DAG.getTargetLoweringInfo().unwrapAddress(LSBase->getBasePtr());
267 continue;
268 }
269 break;
270 }
271 }
272 // If we get here break out of the loop.
273 break;
274 }
275
276 if (Base->isAnyAdd()) {
277 // TODO: The following code appears to be needless as it just
278 // bails on some Ptrs early, reducing the cases where we
279 // find equivalence. We should be able to remove this.
280 // Inside a loop the current BASE pointer is calculated using an ADD and a
281 // MUL instruction. In this case Base is the actual BASE pointer.
282 // (i64 add (i64 %array_ptr)
283 // (i64 mul (i64 %induction_var)
284 // (i64 %element_size)))
285 if (Base->getOperand(1)->getOpcode() == ISD::MUL)
286 return BaseIndexOffset(Base, Index, Offset, IsIndexSignExt);
287
288 // Look at Base + Index + Offset cases.
289 Index = Base->getOperand(1);
290 SDValue PotentialBase = Base->getOperand(0);
291
292 // Skip signextends.
293 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
294 Index = Index->getOperand(0);
295 IsIndexSignExt = true;
296 }
297
298 // Check if Index Offset pattern
299 if (!Index->isAnyAdd() || !isa<ConstantSDNode>(Index->getOperand(1)))
300 return BaseIndexOffset(PotentialBase, Index, Offset, IsIndexSignExt);
301
303 cast<ConstantSDNode>(Index->getOperand(1))->getSExtValue());
304 Index = Index->getOperand(0);
305 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
306 Index = Index->getOperand(0);
307 IsIndexSignExt = true;
308 } else
309 IsIndexSignExt = false;
310 Base = PotentialBase;
311 }
312 return BaseIndexOffset(Base, Index, Offset, IsIndexSignExt);
313}
314
316 const SelectionDAG &DAG) {
317 if (const auto *LS0 = dyn_cast<LSBaseSDNode>(N))
318 return matchLSNode(LS0, DAG);
319 if (const auto *LN = dyn_cast<LifetimeSDNode>(N)) {
320 return BaseIndexOffset(LN->getOperand(1), SDValue(), 0, false);
321 }
322 return BaseIndexOffset();
323}
324
325#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
326
330
332 OS << "BaseIndexOffset base=[";
333 Base->print(OS);
334 OS << "] index=[";
335 if (Index)
336 Index->print(OS);
337 OS << "] offset=" << Offset->getFixed();
338 if (Offset->getScalable() != 0)
339 OS << " + " << Offset->getScalable() << " * vscale";
340}
341
342#endif
return SDValue()
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds.
Definition Compiler.h:690
This file provides utility analysis objects describing memory locations.
static BaseIndexOffset matchLSNode(const LSBaseSDNode *N, const SelectionDAG &DAG)
Parses tree in Ptr for base, index, offset addresses.
This file describes how to lower LLVM code to machine code.
Helper struct to parse and store a memory address as base + index + offset.
LLVM_ABI bool equalBaseIndex(const BaseIndexOffset &Other, const SelectionDAG &DAG, StackOffset &Off) const
LLVM_ABI bool contains(const SelectionDAG &DAG, int64_t BitSize, const BaseIndexOffset &Other, int64_t OtherBitSize, int64_t &BitOffset) const
LLVM_ABI void print(raw_ostream &OS) const
static LLVM_ABI BaseIndexOffset match(const SDNode *N, const SelectionDAG &DAG)
Parses tree in N for base, index, and fixed/scalable offsets.
static LLVM_ABI bool computeAliasing(const SDNode *Op0, const LocationSize NumBytes0, const SDNode *Op1, const LocationSize NumBytes1, const SelectionDAG &DAG, bool &IsAlias)
Base class for LoadSDNode and StoreSDNode.
bool hasValue() const
bool isScalable() const
TypeSize getValue() const
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
bool isFixedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a fixed stack object.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Represents one node in the SelectionDAG.
Unlike LLVM values, Selection DAG nodes may return multiple values as the result of a computation.
SDNode * getNode() const
get the SDNode which holds the desired result
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
const TargetLowering & getTargetLoweringInfo() const
MachineFunction & getMachineFunction() const
LLVM_ABI bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
StackOffset holds a fixed and a scalable offset in bytes.
Definition TypeSize.h:31
int64_t getFixed() const
Returns the fixed component of the stack.
Definition TypeSize.h:47
int64_t getScalable() const
Returns the scalable component of the stack.
Definition TypeSize.h:50
static StackOffset getScalable(int64_t Scalable)
Definition TypeSize.h:41
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:40
virtual SDValue unwrapAddress(SDValue N) const
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
@ PTRADD
PTRADD represents pointer arithmetic semantics, for targets that opt in using shouldPreservePtrArith(...
@ ADD
Simple integer binary arithmetic operators.
Definition ISDOpcodes.h:266
@ LOAD
LOAD and STORE have token chains as their first operand, then the same operands as an LLVM load/store...
@ SIGN_EXTEND
Conversion operators.
Definition ISDOpcodes.h:876
@ VSCALE
VSCALE(IMM) - Returns the runtime scaling factor used to calculate the number of elements within a sc...
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
@ Other
Any other memory.
Definition ModRef.h:68
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
#define N