21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/TypeSwitch.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/Support/Casting.h"
33 auto barg = mlir::dyn_cast<mlir::BlockArgument>(v);
39 mlir::dyn_cast<mlir::acc::ComputeRegionOp>(block->
getParentOp());
42 assert(block == computeReg.getBody() &&
43 "block must be the body of acc.compute_region");
44 return computeReg.getOperand(barg);
50 mlir::dyn_cast<mlir::acc::ComputeRegionOp>(operand.
getOwner());
57 computeReg.getLaunchArgs().size() + computeReg.getInputArgs().size())
59 return computeReg.getBody()->getArgument(idx);
67 return mlir::isa_and_nonnull<ACC_DATA_ENTRY_OPS>(def) ? def :
nullptr;
70template <
typename OpTy>
75 if (!region.
isAncestor(user->getParentRegion()))
77 return mlir::isa<OpTy>(user);
80 return llvm::all_of(val.
getUsers(), checkIfUsedOnlyByOpInside);
93std::optional<mlir::acc::ClauseDefaultValue>
95 std::optional<mlir::acc::ClauseDefaultValue> defaultAttr;
102 while (!defaultAttr.has_value() && currOp) {
105 std::optional<mlir::acc::ClauseDefaultValue>>(currOp)
106 .Case<ACC_COMPUTE_CONSTRUCT_OPS, mlir::acc::DataOp>(
107 [&](
auto op) {
return op.getDefaultAttr(); })
108 .Default([&](
Operation *) {
return std::nullopt; });
116 mlir::acc::VariableTypeCategory typeCategory =
117 mlir::acc::VariableTypeCategory::uncategorized;
118 if (
auto mappableTy = dyn_cast<mlir::acc::MappableType>(var.
getType()))
119 typeCategory = mappableTy.getTypeCategory(var);
120 else if (
auto pointerLikeTy =
121 dyn_cast<mlir::acc::PointerLikeType>(var.
getType()))
122 typeCategory = pointerLikeTy.getPointeeTypeCategory(
124 pointerLikeTy.getElementType());
129 return llvm::StringLiteral(
"<acc.varname.placeholder>");
139 return std::to_string(*constVal);
142 if (
auto varNameAttr = definingOp->getDiscardableAttrOfType<VarNameAttr>(
144 return varNameAttr.getName().str();
147 if (isa<ACC_DATA_ENTRY_OPS, MapInfoOp>(definingOp))
152 if (
auto addressOf = dyn_cast<AddressOfGlobalOpInterface>(definingOp))
153 return addressOf.getSymbol().getLeafReference().str();
156 if (
auto viewOp = dyn_cast<ViewLikeOpInterface>(definingOp)) {
157 current = viewOp.getViewSource();
169 assert(kind == mlir::acc::RecipeKind::private_recipe ||
170 kind == mlir::acc::RecipeKind::firstprivate_recipe ||
171 kind == mlir::acc::RecipeKind::reduction_recipe);
172 if (!llvm::isa<mlir::acc::PointerLikeType, mlir::acc::MappableType>(type))
175 std::string recipeName;
176 llvm::raw_string_ostream ss(recipeName);
177 ss << (kind == mlir::acc::RecipeKind::private_recipe ?
"privatization_"
178 : kind == mlir::acc::RecipeKind::firstprivate_recipe
179 ?
"firstprivatization_"
188 for (
char &c : recipeName) {
189 if (!std::isalnum(
static_cast<unsigned char>(c)) && c !=
'.' && c !=
'_') {
194 else if (c ==
'(' || c ==
')' || c ==
'[' || c ==
']' || c ==
'{' ||
195 c ==
'}' || c ==
'<' || c ==
'>')
206 if (
auto partialEntityAccessOp =
208 if (!partialEntityAccessOp.isCompleteView())
209 return partialEntityAccessOp.getBaseEntity();
219 mlir::SymbolRefAttr symbol) {
223 for (
auto gpuModule : moduleOp.getOps<mlir::gpu::GPUModuleOp>()) {
225 gpuModule, symbol.getRootReference()))
232 mlir::SymbolRefAttr symbol,
239 *definingOpPtr = gpuOp;
252 *definingOpPtr = definingOp;
257 if (mlir::isa<mlir::accomp::RecipeInterface>(definingOp))
263 mlir::dyn_cast<mlir::acc::GlobalVariableOpInterface>(definingOp))
264 if (globalVar.isDeviceAccessible())
269 mlir::dyn_cast_if_present<mlir::FunctionOpInterface>(definingOp)) {
283 func.getFunctionBody().empty() &&
func.getName().starts_with(
"llvm.") &&
284 llvm::Intrinsic::lookupIntrinsicID(
func.getName()) !=
285 llvm::Intrinsic::not_intrinsic)
298static mlir::acc::GlobalVariableOpInterface
306 mlir::acc::GlobalVariableOpInterface>(addrOf, symbol);
313 if (
auto mappableTy = dyn_cast<mlir::acc::MappableType>(val.
getType()))
314 if (mappableTy.isDeviceAccessible(val, symbolTables))
317 if (
auto pointerLikeTy = dyn_cast<mlir::acc::PointerLikeType>(val.
getType()))
318 if (pointerLikeTy.isDeviceAccessible(val, symbolTables))
327 if (
auto declareAttr =
330 if (declareAttr.getDataClause().getValue() ==
331 mlir::acc::DataClause::acc_deviceptr)
336 if (
auto partialAccess =
337 dyn_cast<mlir::acc::PartialEntityAccessOpInterface>(defOp)) {
338 if (
mlir::Value base = partialAccess.getBaseEntity())
343 if (
auto addrOfIface =
344 dyn_cast<mlir::acc::AddressOfGlobalOpInterface>(defOp)) {
345 auto symbol = addrOfIface.getSymbol();
347 return global.isDeviceAccessible();
357 if (
auto mappableTy = dyn_cast<mlir::acc::MappableType>(val.
getType()))
358 if (mappableTy.isInDeviceMemory(val, symbolTables))
361 if (
auto pointerLikeTy = dyn_cast<mlir::acc::PointerLikeType>(val.
getType()))
362 if (pointerLikeTy.isInDeviceMemory(val, symbolTables))
371 if (
auto declareAttr =
374 if (declareAttr.getDataClause().getValue() ==
375 mlir::acc::DataClause::acc_deviceptr)
380 if (
auto partialAccess =
381 dyn_cast<mlir::acc::PartialEntityAccessOpInterface>(defOp)) {
382 if (
mlir::Value base = partialAccess.getBaseEntity())
387 if (
auto addrOfIface =
388 dyn_cast<mlir::acc::AddressOfGlobalOpInterface>(defOp)) {
389 auto symbol = addrOfIface.getSymbol();
391 return global.isInDeviceMemory();
402 llvm::isa<mlir::VectorType>(type))
406 if (isa_and_nonnull<ACC_DATA_ENTRY_OPS>(val.
getDefiningOp()))
419 if (
auto func = parent->getParentOfType<mlir::FunctionOpInterface>()) {
422 llvm::is_contained(
func.getArguments(), val))
434 llvm::SmallSetVector<mlir::Value, 8> dominatingDataClauses;
437 .Case<mlir::acc::ParallelOp, mlir::acc::KernelsOp, mlir::acc::SerialOp>(
439 for (
auto dataClause : op.getDataClauseOperands()) {
440 dominatingDataClauses.insert(dataClause);
447 while (currParentOp) {
448 if (mlir::isa<mlir::acc::DataOp>(currParentOp)) {
449 for (
auto dataClause : mlir::dyn_cast<mlir::acc::DataOp>(currParentOp)
450 .getDataClauseOperands()) {
451 dominatingDataClauses.insert(dataClause);
454 currParentOp = currParentOp->getParentOp();
461 return dominatingDataClauses.takeVector();
466 funcOp->walk([&](mlir::acc::DeclareEnterOp declareEnterOp) {
467 if (domInfo.
dominates(declareEnterOp.getOperation(), computeConstructOp)) {
470 for (
auto *user : declareEnterOp.getToken().getUsers())
471 if (
auto declareExit = mlir::dyn_cast<mlir::acc::DeclareExitOp>(user))
472 exits.push_back(declareExit);
476 if (!exits.empty() &&
477 llvm::all_of(exits, [&](mlir::acc::DeclareExitOp exitOp) {
478 return postDomInfo.postDominates(exitOp, computeConstructOp);
480 for (
auto dataClause : declareEnterOp.getDataClauseOperands())
481 dominatingDataClauses.insert(dataClause);
486 return dominatingDataClauses.takeVector();
490 if (
auto ifOp = mlir::dyn_cast<mlir::scf::IfOp>(op))
491 return ifOp.getCondition();
493 if (!mlir::isa<mlir::RegionBranchOpInterface>(op) ||
494 mlir::isa<mlir::LoopLikeOpInterface>(op))
505 if (deviceTypes.empty())
511 mlir::FunctionOpInterface>(parent);
512 parent = parent->getParentOp()) {
518 auto onDeviceOp = condition.
getDefiningOp<mlir::acc::OnDeviceOp>();
522 std::optional<int64_t> deviceTypeValue =
524 if (!deviceTypeValue)
527 bool onTarget = llvm::is_contained(deviceTypes, *deviceTypeValue);
532 if ((!onTarget && inThen) || (onTarget && inElse))
540 const std::function<std::string()> &messageFn,
541 llvm::StringRef category) {
548 llvm::StringRef funcName;
549 if (
auto func = dyn_cast<mlir::FunctionOpInterface>(op))
550 funcName =
func.getName();
551 else if (
auto funcOp = op->
getParentOfType<mlir::FunctionOpInterface>())
552 funcName = funcOp.getName();
555 if (!funcName.empty())
556 opts = opts.function(funcName);
558 auto remark = engine->emitOptimizationRemark(loc, opts);
static bool isOnlyUsedByOpClauses(mlir::Value val, mlir::Region ®ion)
static mlir::Value getIfCondition(mlir::Operation *op)
static mlir::Operation * lookupSymbolInGPUModules(mlir::Operation *user, mlir::SymbolRefAttr symbol)
Look up symbol in the gpu.modules of the enclosing module.
static mlir::acc::GlobalVariableOpInterface lookupGlobalVariable(mlir::Operation *addrOf, mlir::SymbolRefAttr symbol, mlir::SymbolTableCollection *symbolTables)
Finds the global variable that addrOf refers to, through symbolTables when provided (cached lookup) a...
static std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
MLIRContext * getContext() const
Return the context this attribute belongs to.
This class represents an argument of a Block.
Block represents an ordered list of Operations.
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
A class for computing basic dominance information.
bool dominates(Operation *a, Operation *b) const
Return true if operation A dominates operation B, i.e.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
remark::detail::RemarkEngine * getRemarkEngine()
Returns the remark engine for this context, or nullptr if none has been set.
This class represents an operand of an operation.
unsigned getOperandNumber() const
Return which operand this is in the OpOperand list of the Operation.
Operation is the basic unit of execution within MLIR.
Value getOperand(unsigned idx)
unsigned getNumRegions()
Returns the number of regions held by this operation.
Location getLoc()
The source location the operation was defined or derived from.
Operation * getParentOp()
Returns the closest surrounding operation that contains this operation or nullptr if this is a top-le...
unsigned getNumOperands()
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
bool hasDiscardableAttr(StringRef name)
Return true if this operation has a discardable attribute with the provided name.
AttrClass getDiscardableAttrOfType(StringRef name)
Access a discardable attribute by name and cast it to AttrClass.
Region * getParentRegion()
Returns the region to which the instruction belongs.
A class for computing basic postdominance information.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
bool isAncestor(Region *other)
Return true if this region is ancestor of the other region.
Operation * getParentOp()
Return the parent operation this region is attached to.
ParentT getParentOfType()
Find the first parent operation of the given type, or nullptr if there is no ancestor operation.
This class represents a collection of SymbolTables.
virtual Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
@ Private
The symbol is private and may only be referenced by SymbolRefAttrs local to the operations within the...
static Operation * lookupSymbolIn(Operation *op, StringAttr symbol)
Returns the operation registered with the given symbol name with the regions of 'symbolTableOp'.
static Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
void print(raw_ostream &os) const
Print the current type.
bool isSignlessInteger() const
Return true if this is a signless integer type (with the specified width).
bool isIntOrIndexOrFloat() const
Return true if this is an integer (of any signedness), index, or float type.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
user_range getUsers() const
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Operation * getOwner() const
Return the owner of this operand.
#define ACC_COMPUTE_CONSTRUCT_OPS
mlir::acc::VariableTypeCategory getTypeCategory(mlir::Value var)
Get the type category of an OpenACC variable.
mlir::BlockArgument getACCBlockArgForOperand(mlir::OpOperand &operand)
If operand is a launch or ins operand of an acc.compute_region, returns the body block argument it is...
std::string getVariableName(mlir::Value v)
Attempts to extract the variable name from a value by walking through view-like operations until an a...
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.
bool isAccRoutine(mlir::Operation *op)
Used to check whether the current operation is marked with acc routine.
static constexpr StringLiteral getSpecializedRoutineAttrName()
mlir::Value getACCOperandForBlockArg(mlir::Value v)
If v is not a block argument of an acc.compute_region body, returns nullptr.
mlir::Operation * getACCDataClauseOpForBlockArg(mlir::Value v)
If v is not a block argument of an acc.compute_region body, returns nullptr.
std::optional< ClauseDefaultValue > getDefaultAttr(mlir::Operation *op)
Looks for an OpenACC default attribute on the current operation op or in a parent operation which enc...
bool isSpecializedAccRoutine(mlir::Operation *op)
Used to check whether this is a specialized accelerator version of acc routine function.
bool isOnlyUsedByReductionClauses(mlir::Value val, mlir::Region ®ion)
Returns true if this value is only used by acc.reduction operations in the region.
std::optional< llvm::StringRef > getVarName(mlir::Operation *accOp)
Used to obtain the name from an acc operation.
static constexpr StringLiteral getRoutineInfoAttrName()
mlir::Operation * getEnclosingComputeOp(mlir::Region ®ion)
Used to obtain the enclosing compute construct operation that contains the provided region.
bool isValidValueUse(mlir::Value val, mlir::Region ®ion, mlir::SymbolTableCollection *symbolTables=nullptr)
Check if a value use is valid in an OpenACC region.
llvm::StringLiteral getVarNamePlaceholder()
Returns a placeholder string for use as an acc.var_name attribute value when the actual variable name...
llvm::SmallVector< mlir::Value > getDominatingDataClauses(mlir::Operation *computeConstructOp, mlir::DominanceInfo &domInfo, mlir::PostDominanceInfo &postDomInfo)
Collects all data clauses that dominate the compute construct.
bool isInDeviceMemoryValue(mlir::Value val, mlir::SymbolTableCollection *symbolTables=nullptr)
Check if a value is backed by memory that is residing in the current device, and therefore requires n...
static constexpr StringLiteral getVarNameAttrName()
std::string getRecipeName(mlir::acc::RecipeKind kind, mlir::Type type)
Get the recipe name for a given recipe kind and type.
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.
static constexpr StringLiteral getDeclareAttrName()
Used to obtain the attribute name for declare.
bool isDeviceAccessibleValue(mlir::Value val, mlir::SymbolTableCollection *symbolTables=nullptr)
Check if a value represents device data.
bool isInOffTargetBranch(mlir::Operation *op, llvm::ArrayRef< int64_t > deviceTypes)
Returns true if op is in a branch that does not execute on the target.
mlir::Value getBaseEntity(mlir::Value val)
bool isOnlyUsedByPrivateClauses(mlir::Value val, mlir::Region ®ion)
Returns true if this value is only used by acc.private operations in the region.
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.