MLIR 24.0.0git
OpenACCSupport.h
Go to the documentation of this file.
1//===- OpenACCSupport.h - OpenACC Support Interface -------------*- C++ -*-===//
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 file defines the OpenACCSupport analysis interface, which provides
10// extensible support for OpenACC passes. Custom implementations
11// can be registered to provide pipeline and dialect-specific information
12// that cannot be adequately expressed through type or operation interfaces
13// alone.
14//
15// Usage Pattern:
16// ==============
17//
18// A pass that needs this functionality should call
19// getAnalysis<OpenACCSupport>(), which will provide either:
20// - A cached version if previously initialized, OR
21// - A default implementation if not previously initialized
22//
23// This analysis is never invalidated (isInvalidated returns false), so it only
24// needs to be initialized once and will persist throughout the pass pipeline.
25//
26// Registering a Custom Implementation:
27// =====================================
28//
29// If a custom implementation is needed, create a pass that runs BEFORE the pass
30// that needs the analysis. In this setup pass, use
31// getAnalysis<OpenACCSupport>() followed by setImplementation() to register
32// your custom implementation. The custom implementation will need to provide
33// implementation for all methods defined in the `OpenACCSupportTraits::Concept`
34// class.
35//
36// Example:
37// void MySetupPass::runOnOperation() {
38// OpenACCSupport &support = getAnalysis<OpenACCSupport>();
39// support.setImplementation(MyCustomImpl());
40// }
41//
42// void MyAnalysisConsumerPass::runOnOperation() {
43// OpenACCSupport &support = getAnalysis<OpenACCSupport>();
44// std::string name = support.getVariableName(someValue);
45// // ... use the analysis results
46// }
47//
48//===----------------------------------------------------------------------===//
49
50#ifndef MLIR_DIALECT_OPENACC_ANALYSIS_OPENACCSUPPORT_H
51#define MLIR_DIALECT_OPENACC_ANALYSIS_OPENACCSUPPORT_H
52
57#include "mlir/IR/BuiltinOps.h"
58#include "mlir/IR/Remarks.h"
59#include "mlir/IR/Value.h"
61#include "llvm/ADT/StringRef.h"
62#include <functional>
63#include <memory>
64#include <optional>
65#include <string>
66
67namespace mlir {
68namespace acc {
69
70/// How the name of a variable is to be rendered.
72 /// Render the name the source language spells, which is the name a message
73 /// to the user states. When false, the name the variable is emitted under is
74 /// rendered instead - for a global the symbol it is addressed through -
75 /// which is the name it is resolved against the symbols of a binary by. Only
76 /// a language that uniques or mangles the names of its variables spells the
77 /// two differently.
79};
80
81namespace detail {
82/// This class contains internal trait classes used by OpenACCSupport.
83/// It follows the Concept-Model pattern used throughout MLIR (e.g., in
84/// AliasAnalysis and interface definitions).
86 class Concept {
87 public:
88 virtual ~Concept() = default;
89
90 /// Get the variable name for a given MLIR value.
91 virtual std::string getVariableName(Value v, VariableNameConfig config) = 0;
92
93 /// Get the recipe name for a given kind, type and value.
94 virtual std::string getRecipeName(RecipeKind kind, Type type,
95 Value var) = 0;
96
97 // Used to report a case that is not supported by the implementation.
98 virtual InFlightDiagnostic emitNYI(Location loc, const Twine &message) = 0;
99
100 // Used to emit an OpenACC remark. The category is optional and is used to
101 // either capture the pass name or pipeline phase when the remark is
102 // emitted. When not provided, in the default implementation, the category
103 // is "openacc".
105 emitRemark(Operation *op, std::function<std::string()> messageFn,
106 llvm::StringRef category) = 0;
107
108 /// Check if a symbol use is valid for use in an OpenACC region.
109 virtual bool isValidSymbolUse(Operation *user, SymbolRefAttr symbol,
110 Operation **definingOpPtr) = 0;
111
112 /// Check if a value use is legal in an OpenACC region.
113 virtual bool isValidValueUse(Value v, mlir::Region &region,
114 SymbolTableCollection *symbolTables) = 0;
115
116 /// Get or optionally create a GPU module in the given module.
117 virtual std::optional<gpu::GPUModuleOp>
118 getOrCreateGPUModule(ModuleOp mod, bool create, llvm::StringRef name) = 0;
119
120 /// Returns the size and ABI alignment in bytes for \p ty.
121 virtual std::optional<TypeSizeAndAlignment>
122 getTypeSizeAndAlignment(Type ty, ModuleOp module,
123 OpenACCSupport &support) = 0;
124
125 /// Returns true when a call that receives \p v cannot use that address
126 /// after it returns. The default is false: the address may be kept.
128 };
129
130 /// SFINAE helpers to detect if implementation has optional methods
131 template <typename ImplT, typename... Args>
133 decltype(std::declval<ImplT>().isValidSymbolUse(std::declval<Args>()...));
134
135 template <typename ImplT>
137 llvm::is_detected<isValidSymbolUse_t, ImplT, Operation *, SymbolRefAttr,
138 Operation **>;
139
140 template <typename ImplT, typename... Args>
141
143 decltype(std::declval<ImplT>().isValidValueUse(std::declval<Args>()...));
144
145 /// An implementation may take the symbol table cache or, for compatibility,
146 /// only the value and the region.
147 template <typename ImplT>
149 llvm::is_detected<isValidValueUse_t, ImplT, Value, Region &,
151
152 template <typename ImplT>
154 llvm::is_detected<isValidValueUse_t, ImplT, Value, Region &>;
155
156 template <typename ImplT, typename... Args>
158 decltype(std::declval<ImplT>().emitRemark(std::declval<Args>()...));
159
160 template <typename ImplT>
162 llvm::is_detected<emitRemark_t, ImplT, Operation *,
163 std::function<std::string()>, llvm::StringRef>;
164
165 template <typename ImplT, typename... Args>
167 decltype(std::declval<ImplT>().getOrCreateGPUModule(
168 std::declval<Args>()...));
169
170 template <typename ImplT>
172 llvm::is_detected<getOrCreateGPUModule_t, ImplT, ModuleOp, bool,
173 llvm::StringRef>;
174
175 template <typename ImplT, typename... Args>
177 decltype(std::declval<ImplT>().getTypeSizeAndAlignment(
178 std::declval<Args>()...));
179
180 template <typename ImplT>
182 llvm::is_detected<getTypeSizeAndAlignment_t, ImplT, Type, ModuleOp,
184
185 template <typename ImplT, typename... Args>
187 decltype(std::declval<ImplT>().isAddressNotCapturedByCalls(
188 std::declval<Args>()...));
189
190 template <typename ImplT>
192 llvm::is_detected<isAddressNotCapturedByCalls_t, ImplT, Value>;
193
194 /// This class wraps a concrete OpenACCSupport implementation and forwards
195 /// interface calls to it. This provides type erasure, allowing different
196 /// implementation types to be used interchangeably without inheritance.
197 /// Methods can be optionally implemented; if not present, default behavior
198 /// is used.
199 template <typename ImplT>
200 class Model final : public Concept {
201 public:
202 explicit Model(ImplT &&impl) : impl(std::forward<ImplT>(impl)) {}
203 ~Model() override = default;
204
205 std::string getVariableName(Value v, VariableNameConfig config) final {
206 return impl.getVariableName(v, config);
207 }
208
209 std::string getRecipeName(RecipeKind kind, Type type, Value var) final {
210 return impl.getRecipeName(kind, type, var);
211 }
212
213 InFlightDiagnostic emitNYI(Location loc, const Twine &message) final {
214 return impl.emitNYI(loc, message);
215 }
216
218 emitRemark(Operation *op, std::function<std::string()> messageFn,
219 llvm::StringRef category) final {
220 if constexpr (has_emitRemark<ImplT>::value)
221 return impl.emitRemark(op, std::move(messageFn), category);
222 else
223 return acc::emitRemark(op, messageFn(), category);
224 }
225
226 bool isValidSymbolUse(Operation *user, SymbolRefAttr symbol,
227 Operation **definingOpPtr) final {
229 return impl.isValidSymbolUse(user, symbol, definingOpPtr);
230 else
231 return acc::isValidSymbolUse(user, symbol, definingOpPtr);
232 }
233
234 bool isValidValueUse(Value v, Region &region,
235 SymbolTableCollection *symbolTables) final {
237 return impl.isValidValueUse(v, region, symbolTables);
239 return impl.isValidValueUse(v, region);
240 else
241 return acc::isValidValueUse(v, region, symbolTables);
242 }
243
244 std::optional<gpu::GPUModuleOp>
245 getOrCreateGPUModule(ModuleOp mod, bool create,
246 llvm::StringRef name) final {
248 return impl.getOrCreateGPUModule(mod, create, name);
249 else
250 return acc::getOrCreateGPUModule(mod, create, name);
251 }
252
253 std::optional<TypeSizeAndAlignment>
254 getTypeSizeAndAlignment(Type ty, ModuleOp module,
255 OpenACCSupport &support) final {
257 return impl.getTypeSizeAndAlignment(ty, module, support);
258 else
259 return acc::getTypeSizeAndAlignment(ty, module, &support);
260 }
261
264 return impl.isAddressNotCapturedByCalls(v);
265 else
266 return false;
267 }
268
269 private:
270 ImplT impl;
271 };
272};
273} // namespace detail
274
275//===----------------------------------------------------------------------===//
276// OpenACCSupport
277//===----------------------------------------------------------------------===//
278
281 template <typename ImplT>
283
284public:
285 OpenACCSupport() = default;
287
288 /// Register a custom OpenACCSupport implementation. Only one implementation
289 /// can be registered at a time; calling this replaces any existing
290 /// implementation.
291 template <typename AnalysisT>
292 void setImplementation(AnalysisT &&analysis) {
293 impl =
294 std::make_unique<Model<AnalysisT>>(std::forward<AnalysisT>(analysis));
295 }
296
297 /// Get the variable name for a given value. Which of the names a variable
298 /// goes by is a question only an implementation that knows the source
299 /// language can answer, so the default implementation returns the one name
300 /// the IR states regardless of \p config.
301 ///
302 /// \param v The MLIR value to get the variable name for.
303 /// \param config Which of the names of the variable to return.
304 /// \return The variable name, or an empty string if unavailable.
305 std::string getVariableName(Value v, VariableNameConfig config = {});
306
307 /// Get the recipe name for a given type and value.
308 ///
309 /// \param kind The kind of recipe to get the name for.
310 /// \param type The type to get the recipe name for. Can be null if the
311 /// var is provided instead.
312 /// \param var The MLIR value to get the recipe name for. Can be null if
313 /// the type is provided instead.
314 /// \return The recipe name, or an empty string if not available.
315 std::string getRecipeName(RecipeKind kind, Type type, Value var);
316
317 /// Report a case that is not yet supported by the implementation.
318 ///
319 /// \param loc The location to report the unsupported case at.
320 /// \param message The message to report.
321 /// \return An in-flight diagnostic object that can be used to report the
322 /// unsupported case.
323 InFlightDiagnostic emitNYI(Location loc, const Twine &message) {
324 if (impl)
325 return impl->emitNYI(loc, message);
326 return mlir::emitError(loc, "not yet implemented: " + message);
327 }
328
329 /// Emit an OpenACC remark with lazy message generation.
330 ///
331 /// The messageFn is only invoked if remarks are enabled for the given
332 /// operation, allowing callers to avoid constructing expensive messages
333 /// when remarks are disabled.
334 ///
335 /// \param op The operation to emit the remark for.
336 /// \param messageFn A callable that returns the remark message.
337 /// \param category Optional category for the remark. Defaults to "openacc".
338 /// \return An in-flight remark object that can be used to append
339 /// additional information to the remark.
341 emitRemark(Operation *op, std::function<std::string()> messageFn,
342 llvm::StringRef category = "openacc");
343
344 /// Emit an OpenACC remark.
345 ///
346 /// \param op The operation to emit the remark for.
347 /// \param message The remark message.
348 /// \param category Optional category for the remark. Defaults to "openacc".
349 /// \return An in-flight remark object that can be used to append
350 /// additional information to the remark.
352 emitRemark(Operation *op, const Twine &message,
353 llvm::StringRef category = "openacc") {
354 return emitRemark(op, std::function<std::string()>([msg = message.str()]() {
355 return msg;
356 }),
357 category);
358 }
359
360 /// Check if a symbol use is valid for use in an OpenACC region.
361 ///
362 /// \param user The operation using the symbol.
363 /// \param symbol The symbol reference being used.
364 /// \param definingOpPtr Optional output parameter to receive the defining op.
365 /// \return true if the symbol use is valid, false otherwise.
366 bool isValidSymbolUse(Operation *user, SymbolRefAttr symbol,
367 Operation **definingOpPtr = nullptr);
368
369 /// Check if a value use is legal in an OpenACC region.
370 ///
371 /// \param v The MLIR value to check for legality.
372 /// \param region The MLIR region in which the legality is checked.
373 /// \param symbolTables Optional cache of symbol tables used to resolve
374 /// symbols. Pass one when checking many values of the same module:
375 /// without it each symbol lookup scans the whole module.
376 bool isValidValueUse(Value v, Region &region,
377 SymbolTableCollection *symbolTables = nullptr);
378
379 /// Get or optionally create a GPU module in the given module.
380 ///
381 /// \param mod The module to search or create the GPU module in.
382 /// \param create If true (default), create the GPU module if it doesn't
383 /// exist.
384 /// \param name The name for the GPU module. If empty, implementation uses its
385 /// default name.
386 /// \return The GPU module if found or created, std::nullopt otherwise.
387 std::optional<gpu::GPUModuleOp>
388 getOrCreateGPUModule(ModuleOp mod, bool create = true,
389 llvm::StringRef name = "");
390
391 /// Returns the size and ABI alignment in bytes for \p ty.
392 std::optional<TypeSizeAndAlignment> getTypeSizeAndAlignment(Type ty,
393 ModuleOp module) {
394 if (impl)
395 if (auto result = impl->getTypeSizeAndAlignment(ty, module, *this))
396 return result;
397 return acc::getTypeSizeAndAlignment(ty, module, this);
398 }
399
400 /// Returns true when a call that receives \p v cannot use that address
401 /// after it returns. The default is false: the address may be kept, so a
402 /// caller that tracks the address treats the call as an escape. Only an
403 /// implementation that knows the source language of \p v can return true.
405 if (impl)
406 return impl->isAddressNotCapturedByCalls(v);
407 return false;
408 }
409
410 /// Signal that this analysis should always be preserved so that
411 /// underlying implementation registration is not lost.
413 return false;
414 }
415
416private:
417 /// The registered custom implementation (if any).
418 std::unique_ptr<Concept> impl;
419};
420
421} // namespace acc
422} // namespace mlir
423
424#endif // MLIR_DIALECT_OPENACC_ANALYSIS_OPENACCSUPPORT_H
detail::PreservedAnalyses PreservedAnalyses
This class represents a diagnostic that is inflight and set to be reported.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
This class represents a collection of SymbolTables.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
remark::detail::InFlightRemark emitRemark(Operation *op, std::function< std::string()> messageFn, llvm::StringRef category="openacc")
Emit an OpenACC remark with lazy message generation.
std::string getVariableName(Value v, VariableNameConfig config={})
Get the variable name for a given value.
remark::detail::InFlightRemark emitRemark(Operation *op, const Twine &message, llvm::StringRef category="openacc")
Emit an OpenACC remark.
void setImplementation(AnalysisT &&analysis)
Register a custom OpenACCSupport implementation.
InFlightDiagnostic emitNYI(Location loc, const Twine &message)
Report a case that is not yet supported by the implementation.
bool isValidSymbolUse(Operation *user, SymbolRefAttr symbol, Operation **definingOpPtr=nullptr)
Check if a symbol use is valid for use in an OpenACC region.
bool isInvalidated(const AnalysisManager::PreservedAnalyses &pa)
Signal that this analysis should always be preserved so that underlying implementation registration i...
std::optional< gpu::GPUModuleOp > getOrCreateGPUModule(ModuleOp mod, bool create=true, llvm::StringRef name="")
Get or optionally create a GPU module in the given module.
bool isAddressNotCapturedByCalls(Value v)
Returns true when a call that receives v cannot use that address after it returns.
std::optional< TypeSizeAndAlignment > getTypeSizeAndAlignment(Type ty, ModuleOp module)
Returns the size and ABI alignment in bytes for ty.
std::string getRecipeName(RecipeKind kind, Type type, Value var)
Get the recipe name for a given type and value.
bool isValidValueUse(Value v, Region &region, SymbolTableCollection *symbolTables=nullptr)
Check if a value use is legal in an OpenACC region.
virtual std::string getRecipeName(RecipeKind kind, Type type, Value var)=0
Get the recipe name for a given kind, type and value.
virtual std::optional< TypeSizeAndAlignment > getTypeSizeAndAlignment(Type ty, ModuleOp module, OpenACCSupport &support)=0
Returns the size and ABI alignment in bytes for ty.
virtual std::string getVariableName(Value v, VariableNameConfig config)=0
Get the variable name for a given MLIR value.
virtual bool isAddressNotCapturedByCalls(Value v)=0
Returns true when a call that receives v cannot use that address after it returns.
virtual bool isValidValueUse(Value v, mlir::Region &region, SymbolTableCollection *symbolTables)=0
Check if a value use is legal in an OpenACC region.
virtual InFlightDiagnostic emitNYI(Location loc, const Twine &message)=0
virtual bool isValidSymbolUse(Operation *user, SymbolRefAttr symbol, Operation **definingOpPtr)=0
Check if a symbol use is valid for use in an OpenACC region.
virtual remark::detail::InFlightRemark emitRemark(Operation *op, std::function< std::string()> messageFn, llvm::StringRef category)=0
virtual std::optional< gpu::GPUModuleOp > getOrCreateGPUModule(ModuleOp mod, bool create, llvm::StringRef name)=0
Get or optionally create a GPU module in the given module.
This class wraps a concrete OpenACCSupport implementation and forwards interface calls to it.
bool isValidValueUse(Value v, Region &region, SymbolTableCollection *symbolTables) final
Check if a value use is legal in an OpenACC region.
std::string getVariableName(Value v, VariableNameConfig config) final
Get the variable name for a given MLIR value.
remark::detail::InFlightRemark emitRemark(Operation *op, std::function< std::string()> messageFn, llvm::StringRef category) final
std::optional< gpu::GPUModuleOp > getOrCreateGPUModule(ModuleOp mod, bool create, llvm::StringRef name) final
Get or optionally create a GPU module in the given module.
InFlightDiagnostic emitNYI(Location loc, const Twine &message) final
std::string getRecipeName(RecipeKind kind, Type type, Value var) final
Get the recipe name for a given kind, type and value.
bool isValidSymbolUse(Operation *user, SymbolRefAttr symbol, Operation **definingOpPtr) final
Check if a symbol use is valid for use in an OpenACC region.
std::optional< TypeSizeAndAlignment > getTypeSizeAndAlignment(Type ty, ModuleOp module, OpenACCSupport &support) final
Returns the size and ABI alignment in bytes for ty.
bool isAddressNotCapturedByCalls(Value v) final
Returns true when a call that receives v cannot use that address after it returns.
InFlightRemark is a RAII class that holds a reference to a Remark instance and allows to build the re...
Definition Remarks.h:488
bool isValidSymbolUse(mlir::Operation *user, mlir::SymbolRefAttr symbol, mlir::Operation **definingOpPtr=nullptr)
Check if a symbol use is valid for use in an OpenACC region.
std::optional< gpu::GPUModuleOp > getOrCreateGPUModule(ModuleOp mod, bool create=true, llvm::StringRef name=kDefaultGPUModuleName)
Get or create a GPU module in the given module.
bool isValidValueUse(mlir::Value val, mlir::Region &region, mlir::SymbolTableCollection *symbolTables=nullptr)
Check if a value use is valid in an OpenACC region.
remark::detail::InFlightRemark emitRemark(mlir::Operation *op, const std::function< std::string()> &messageFn, llvm::StringRef category="openacc")
Emit an OpenACC remark with lazy message generation.
std::optional< TypeSizeAndAlignment > getTypeSizeAndAlignment(Type ty, ModuleOp module, const DataLayout &dl, OpenACCSupport *support=nullptr, Value var={})
Returns the size and ABI alignment in bytes.
Include the generated interface declarations.
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
How the name of a variable is to be rendered.
bool preferDemangledName
Render the name the source language spells, which is the name a message to the user states.
This class contains internal trait classes used by OpenACCSupport.
llvm::is_detected< getOrCreateGPUModule_t, ImplT, ModuleOp, bool, llvm::StringRef > has_getOrCreateGPUModule
llvm::is_detected< isValidValueUse_t, ImplT, Value, Region & > has_isValidValueUseNoSymbolTables
decltype(std::declval< ImplT >().getTypeSizeAndAlignment( std::declval< Args >()...)) getTypeSizeAndAlignment_t
llvm::is_detected< emitRemark_t, ImplT, Operation *, std::function< std::string()>, llvm::StringRef > has_emitRemark
decltype(std::declval< ImplT >().isValidValueUse(std::declval< Args >()...)) isValidValueUse_t
llvm::is_detected< isValidValueUse_t, ImplT, Value, Region &, SymbolTableCollection * > has_isValidValueUse
An implementation may take the symbol table cache or, for compatibility, only the value and the regio...
llvm::is_detected< isAddressNotCapturedByCalls_t, ImplT, Value > has_isAddressNotCapturedByCalls
llvm::is_detected< isValidSymbolUse_t, ImplT, Operation *, SymbolRefAttr, Operation ** > has_isValidSymbolUse
decltype(std::declval< ImplT >().emitRemark(std::declval< Args >()...)) emitRemark_t
decltype(std::declval< ImplT >().isAddressNotCapturedByCalls( std::declval< Args >()...)) isAddressNotCapturedByCalls_t
decltype(std::declval< ImplT >().getOrCreateGPUModule( std::declval< Args >()...)) getOrCreateGPUModule_t
decltype(std::declval< ImplT >().isValidSymbolUse(std::declval< Args >()...)) isValidSymbolUse_t
SFINAE helpers to detect if implementation has optional methods.
llvm::is_detected< getTypeSizeAndAlignment_t, ImplT, Type, ModuleOp, OpenACCSupport & > has_getTypeSizeAndAlignment