Debian Codegraph @

flang/lib/Optimizer/Analysis/AliasAnalysis.cpp

raw
1 //===- AliasAnalysis.cpp - Alias Analysis for FIR ------------------------===//
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 #include "flang/Optimizer/Analysis/AliasAnalysis.h"
10 #include "flang/Optimizer/Dialect/FIROps.h"
11 #include "flang/Optimizer/Dialect/FIROpsSupport.h"
12 #include "flang/Optimizer/Dialect/FIRType.h"
13 #include "flang/Optimizer/Dialect/FortranVariableInterface.h"
14 #include "flang/Optimizer/HLFIR/HLFIROps.h"
15 #include "mlir/Analysis/AliasAnalysis.h"
16 #include "mlir/IR/BuiltinOps.h"
17 #include "mlir/IR/Value.h"
18 #include "mlir/Interfaces/SideEffectInterfaces.h"
19 #include "llvm/ADT/TypeSwitch.h"
20 #include "llvm/Support/Casting.h"
21 #include "llvm/Support/Debug.h"
22
23 using namespace mlir;
24
25 #define DEBUG_TYPE "fir-alias-analysis"
26
27 //===----------------------------------------------------------------------===//
28 // AliasAnalysis: alias
29 //===----------------------------------------------------------------------===//
30
31 /// Temporary function to skip through all the no op operations
32 /// TODO: Generalize support of fir.load
33 static mlir::Value getOriginalDef(mlir::Value v) {
34 mlir::Operation *defOp;
35 bool breakFromLoop = false;
36 while (!breakFromLoop && (defOp = v.getDefiningOp())) {
37 llvm::TypeSwitch<Operation *>(defOp)
38 .Case<fir::ConvertOp>([&](fir::ConvertOp op) { v = op.getValue(); })
39 .Case<fir::DeclareOp, hlfir::DeclareOp>(
40 [&](auto op) { v = op.getMemref(); })
41 .Default([&](auto op) { breakFromLoop = true; });
42 }
43 return v;
44 }
45
46 namespace fir {
47
48 void AliasAnalysis::Source::print(llvm::raw_ostream &os) const {
49 if (auto v = llvm::dyn_cast<mlir::Value>(origin.u))
50 os << v;
51 else if (auto gbl = llvm::dyn_cast<mlir::SymbolRefAttr>(origin.u))
52 os << gbl;
53 os << " SourceKind: " << EnumToString(kind);
54 os << " Type: " << valueType << " ";
55 if (origin.isData) {
56 os << " following data ";
57 } else {
58 os << " following box reference ";
59 }
60 attributes.Dump(os, EnumToString);
61 }
62
63 bool AliasAnalysis::Source::isPointerReference(mlir::Type ty) {
64 auto eleTy = fir::dyn_cast_ptrEleTy(ty);
65 if (!eleTy)
66 return false;
67
68 return fir::isPointerType(eleTy) || mlir::isa<fir::PointerType>(eleTy);
69 }
70
71 bool AliasAnalysis::Source::isTargetOrPointer() const {
72 return attributes.test(Attribute::Pointer) ||
73 attributes.test(Attribute::Target);
74 }
75
76 bool AliasAnalysis::Source::isDummyArgument() const {
77 if (auto v = origin.u.dyn_cast<mlir::Value>()) {
78 return fir::isDummyArgument(v);
79 }
80 return false;
81 }
82
83 bool AliasAnalysis::Source::isData() const { return origin.isData; }
84 bool AliasAnalysis::Source::isBoxData() const {
85 return mlir::isa<fir::BaseBoxType>(fir::unwrapRefType(valueType)) &&
86 origin.isData;
87 }
88
89 bool AliasAnalysis::Source::isRecordWithPointerComponent() const {
90 auto eleTy = fir::dyn_cast_ptrEleTy(valueType);
91 if (!eleTy)
92 return false;
93 // TO DO: Look for pointer components
94 return mlir::isa<fir::RecordType>(eleTy);
95 }
96
97 AliasResult AliasAnalysis::alias(Value lhs, Value rhs) {
98 // TODO: alias() has to be aware of the function scopes.
99 // After MLIR inlining, the current implementation may
100 // not recognize non-aliasing entities.
101 auto lhsSrc = getSource(lhs);
102 auto rhsSrc = getSource(rhs);
103 bool approximateSource = lhsSrc.approximateSource || rhsSrc.approximateSource;
104 LLVM_DEBUG(llvm::dbgs() << "\nAliasAnalysis::alias\n";
105 llvm::dbgs() << " lhs: " << lhs << "\n";
106 llvm::dbgs() << " lhsSrc: " << lhsSrc << "\n";
107 llvm::dbgs() << " rhs: " << rhs << "\n";
108 llvm::dbgs() << " rhsSrc: " << rhsSrc << "\n";);
109
110 // Indirect case currently not handled. Conservatively assume
111 // it aliases with everything
112 if (lhsSrc.kind >= SourceKind::Indirect ||
113 rhsSrc.kind >= SourceKind::Indirect) {
114 return AliasResult::MayAlias;
115 }
116
117 if (lhsSrc.kind == rhsSrc.kind) {
118 if (lhsSrc.origin == rhsSrc.origin) {
119 LLVM_DEBUG(llvm::dbgs()
120 << " aliasing because same source kind and origin\n");
121 if (approximateSource)
122 return AliasResult::MayAlias;
123 return AliasResult::MustAlias;
124 }
125
126 // Two host associated accesses may overlap due to an equivalence.
127 if (lhsSrc.kind == SourceKind::HostAssoc) {
128 LLVM_DEBUG(llvm::dbgs() << " aliasing because of host association\n");
129 return AliasResult::MayAlias;
130 }
131 }
132
133 Source *src1, *src2;
134 if (lhsSrc.kind < rhsSrc.kind) {
135 src1 = &lhsSrc;
136 src2 = &rhsSrc;
137 } else {
138 src1 = &rhsSrc;
139 src2 = &lhsSrc;
140 }
141
142 if (src1->kind == SourceKind::Argument &&
143 src2->kind == SourceKind::HostAssoc) {
144 // Treat the host entity as TARGET for the purpose of disambiguating
145 // it with a dummy access. It is required for this particular case:
146 // subroutine test
147 // integer :: x(10)
148 // call inner(x)
149 // contains
150 // subroutine inner(y)
151 // integer, target :: y(:)
152 // x(1) = y(1)
153 // end subroutine inner
154 // end subroutine test
155 //
156 // F18 15.5.2.13 (4) (b) allows 'x' and 'y' to address the same object.
157 // 'y' has an explicit TARGET attribute, but 'x' has neither TARGET
158 // nor POINTER.
159 src2->attributes.set(Attribute::Target);
160 }
161
162 // Dummy TARGET/POINTER argument may alias with a global TARGET/POINTER.
163 if (src1->isTargetOrPointer() && src2->isTargetOrPointer() &&
164 src1->isData() == src2->isData()) {
165 LLVM_DEBUG(llvm::dbgs() << " aliasing because of target or pointer\n");
166 return AliasResult::MayAlias;
167 }
168
169 // Box for POINTER component inside an object of a derived type
170 // may alias box of a POINTER object, as well as boxes for POINTER
171 // components inside two objects of derived types may alias.
172 if ((src1->isRecordWithPointerComponent() && src2->isTargetOrPointer()) ||
173 (src2->isRecordWithPointerComponent() && src1->isTargetOrPointer()) ||
174 (src1->isRecordWithPointerComponent() &&
175 src2->isRecordWithPointerComponent())) {
176 LLVM_DEBUG(llvm::dbgs() << " aliasing because of pointer components\n");
177 return AliasResult::MayAlias;
178 }
179
180 return AliasResult::NoAlias;
181 }
182
183 //===----------------------------------------------------------------------===//
184 // AliasAnalysis: getModRef
185 //===----------------------------------------------------------------------===//
186
187 /// This is mostly inspired by MLIR::LocalAliasAnalysis with 2 notable
188 /// differences 1) Regions are not handled here but will be handled by a data
189 /// flow analysis to come 2) Allocate and Free effects are considered
190 /// modifying
191 ModRefResult AliasAnalysis::getModRef(Operation *op, Value location) {
192 MemoryEffectOpInterface interface = dyn_cast<MemoryEffectOpInterface>(op);
193 if (!interface)
194 return ModRefResult::getModAndRef();
195
196 // Build a ModRefResult by merging the behavior of the effects of this
197 // operation.
198 SmallVector<MemoryEffects::EffectInstance> effects;
199 interface.getEffects(effects);
200
201 ModRefResult result = ModRefResult::getNoModRef();
202 for (const MemoryEffects::EffectInstance &effect : effects) {
203
204 // Check for an alias between the effect and our memory location.
205 AliasResult aliasResult = AliasResult::MayAlias;
206 if (Value effectValue = effect.getValue())
207 aliasResult = alias(effectValue, location);
208
209 // If we don't alias, ignore this effect.
210 if (aliasResult.isNo())
211 continue;
212
213 // Merge in the corresponding mod or ref for this effect.
214 if (isa<MemoryEffects::Read>(effect.getEffect()))
215 result = result.merge(ModRefResult::getRef());
216 else
217 result = result.merge(ModRefResult::getMod());
218
219 if (result.isModAndRef())
220 break;
221 }
222 return result;
223 }
224
225 AliasAnalysis::Source::Attributes
226 getAttrsFromVariable(fir::FortranVariableOpInterface var) {
227 AliasAnalysis::Source::Attributes attrs;
228 if (var.isTarget())
229 attrs.set(AliasAnalysis::Attribute::Target);
230 if (var.isPointer())
231 attrs.set(AliasAnalysis::Attribute::Pointer);
232 if (var.isIntentIn())
233 attrs.set(AliasAnalysis::Attribute::IntentIn);
234
235 return attrs;
236 }
237
238 AliasAnalysis::Source AliasAnalysis::getSource(mlir::Value v,
239 bool getInstantiationPoint) {
240 auto *defOp = v.getDefiningOp();
241 SourceKind type{SourceKind::Unknown};
242 mlir::Type ty;
243 bool breakFromLoop{false};
244 bool approximateSource{false};
245 bool followBoxData{mlir::isa<fir::BaseBoxType>(v.getType())};
246 bool isBoxRef{fir::isa_ref_type(v.getType()) &&
247 mlir::isa<fir::BaseBoxType>(fir::unwrapRefType(v.getType()))};
248 bool followingData = !isBoxRef;
249 mlir::SymbolRefAttr global;
250 Source::Attributes attributes;
251 mlir::Value instantiationPoint;
252 while (defOp && !breakFromLoop) {
253 ty = defOp->getResultTypes()[0];
254 llvm::TypeSwitch<Operation *>(defOp)
255 .Case<fir::AllocaOp, fir::AllocMemOp>([&](auto op) {
256 // Unique memory allocation.
257 type = SourceKind::Allocate;
258 breakFromLoop = true;
259 })
260 .Case<fir::ConvertOp>([&](auto op) {
261 // Skip ConvertOp's and track further through the operand.
262 v = op->getOperand(0);
263 defOp = v.getDefiningOp();
264 })
265 .Case<fir::BoxAddrOp>([&](auto op) {
266 v = op->getOperand(0);
267 defOp = v.getDefiningOp();
268 if (mlir::isa<fir::BaseBoxType>(v.getType()))
269 followBoxData = true;
270 })
271 .Case<fir::ArrayCoorOp, fir::CoordinateOp>([&](auto op) {
272 v = op->getOperand(0);
273 defOp = v.getDefiningOp();
274 if (mlir::isa<fir::BaseBoxType>(v.getType()))
275 followBoxData = true;
276 approximateSource = true;
277 })
278 .Case<fir::EmboxOp, fir::ReboxOp>([&](auto op) {
279 if (followBoxData) {
280 v = op->getOperand(0);
281 defOp = v.getDefiningOp();
282 } else
283 breakFromLoop = true;
284 })
285 .Case<fir::LoadOp>([&](auto op) {
286 // If the load is from a leaf source, return the leaf. Do not track
287 // through indirections otherwise.
288 // TODO: Add support to fir.alloca and fir.allocmem
289 auto def = getOriginalDef(op.getMemref());
290 if (isDummyArgument(def) ||
291 def.template getDefiningOp<fir::AddrOfOp>()) {
292 v = def;
293 defOp = v.getDefiningOp();
294 return;
295 }
296 // No further tracking for addresses loaded from memory for now.
297 type = SourceKind::Indirect;
298 breakFromLoop = true;
299 })
300 .Case<fir::AddrOfOp>([&](auto op) {
301 // Address of a global scope object.
302 ty = v.getType();
303 type = SourceKind::Global;
304
305 auto globalOpName = mlir::OperationName(
306 fir::GlobalOp::getOperationName(), defOp->getContext());
307 if (fir::valueHasFirAttribute(
308 v, fir::GlobalOp::getTargetAttrName(globalOpName)))
309 attributes.set(Attribute::Target);
310
311 // TODO: Take followBoxData into account when setting the pointer
312 // attribute
313 if (Source::isPointerReference(ty))
314 attributes.set(Attribute::Pointer);
315 global = llvm::cast<fir::AddrOfOp>(op).getSymbol();
316 breakFromLoop = true;
317 })
318 .Case<hlfir::DeclareOp, fir::DeclareOp>([&](auto op) {
319 auto varIf = llvm::cast<fir::FortranVariableOpInterface>(defOp);
320 // While going through a declare operation collect
321 // the variable attributes from it. Right now, some
322 // of the attributes are duplicated, e.g. a TARGET dummy
323 // argument has the target attribute both on its declare
324 // operation and on the entry block argument.
325 // In case of host associated use, the declare operation
326 // is the only carrier of the variable attributes,
327 // so we have to collect them here.
328 attributes |= getAttrsFromVariable(varIf);
329 if (varIf.isHostAssoc()) {
330 // Do not track past such DeclareOp, because it does not
331 // currently provide any useful information. The host associated
332 // access will end up dereferencing the host association tuple,
333 // so we may as well stop right now.
334 v = defOp->getResult(0);
335 // TODO: if the host associated variable is a dummy argument
336 // of the host, I think, we can treat it as SourceKind::Argument
337 // for the purpose of alias analysis inside the internal procedure.
338 type = SourceKind::HostAssoc;
339 breakFromLoop = true;
340 return;
341 }
342 if (getInstantiationPoint) {
343 // Fetch only the innermost instantiation point.
344 if (!instantiationPoint)
345 instantiationPoint = op->getResult(0);
346
347 if (op.getDummyScope()) {
348 // Do not track past DeclareOp that has the dummy_scope
349 // operand. This DeclareOp is known to represent
350 // a dummy argument for some runtime instantiation
351 // of a procedure.
352 type = SourceKind::Argument;
353 breakFromLoop = true;
354 return;
355 }
356 }
357 // TODO: Look for the fortran attributes present on the operation
358 // Track further through the operand
359 v = op.getMemref();
360 defOp = v.getDefiningOp();
361 })
362 .Case<hlfir::DesignateOp>([&](auto op) {
363 // Track further through the memory indexed into
364 // => if the source arrays/structures don't alias then nor do the
365 // results of hlfir.designate
366 v = op.getMemref();
367 defOp = v.getDefiningOp();
368 // TODO: there will be some cases which provably don't alias if one
369 // takes into account the component or indices, which are currently
370 // ignored here - leading to false positives
371 // because of this limitation, we need to make sure we never return
372 // MustAlias after going through a designate operation
373 approximateSource = true;
374 if (mlir::isa<fir::BaseBoxType>(v.getType()))
375 followBoxData = true;
376 })
377 .Default([&](auto op) {
378 defOp = nullptr;
379 breakFromLoop = true;
380 });
381 }
382 if (!defOp && type == SourceKind::Unknown)
383 // Check if the memory source is coming through a dummy argument.
384 if (isDummyArgument(v)) {
385 type = SourceKind::Argument;
386 ty = v.getType();
387 if (fir::valueHasFirAttribute(v, fir::getTargetAttrName()))
388 attributes.set(Attribute::Target);
389
390 if (Source::isPointerReference(ty))
391 attributes.set(Attribute::Pointer);
392 }
393
394 if (type == SourceKind::Global) {
395 return {{global, instantiationPoint, followingData},
396 type,
397 ty,
398 attributes,
399 approximateSource};
400 }
401 return {{v, instantiationPoint, followingData},
402 type,
403 ty,
404 attributes,
405 approximateSource};
406 }
407
408 } // namespace fir