67#include "llvm/ADT/DenseSet.h"
68#include "llvm/ADT/STLExtras.h"
69#include "llvm/ADT/TypeSwitch.h"
70#include "llvm/Support/Debug.h"
71#include "llvm/Support/ErrorHandling.h"
75#define GEN_PASS_DEF_ACCRECIPEMATERIALIZATION
76#include "mlir/Dialect/OpenACC/Transforms/Passes.h.inc"
80#define DEBUG_TYPE "acc-recipe-materialization"
98static bool isComplexReductionType(
Type type) {
99 while (
auto ptrTy = dyn_cast<acc::PointerLikeType>(type)) {
100 Type elementType = ptrTy.getElementType();
101 if (!elementType || elementType == type)
105 return isa<ComplexType>(type);
108static void saveVarName(StringRef name,
Value dst) {
112 if (dstOp->getDiscardableAttrOfType<acc::VarNameAttr>(
115 if (isa<ACC_DATA_ENTRY_OPS>(dstOp))
118 acc::VarNameAttr::get(dstOp->getContext(), name));
121 auto blockArg = dyn_cast<BlockArgument>(dst);
124 Block *block = blockArg.getOwner();
131 auto funcOp = dyn_cast<FunctionOpInterface>(parent);
134 unsigned argIdx = blockArg.getArgNumber();
135 if (argIdx >= funcOp.getNumArguments())
140 acc::VarNameAttr::get(parent->
getContext(), name));
143static void saveVarName(
Value src,
Value dst) {
150 for (
auto it = block->
begin(); it != std::next(ip); ++it) {
154 if (!attr || attr.getName() != placeholder)
160 acc::VarNameAttr::get(op->
getContext(), name));
168template <
typename RecipeOpTy>
173 Region &destroyRegion = recipe.getDestroyRegion();
174 assert(destroyRegion.
getBlocks().front().getNumArguments() ==
176 "unexpected acc recipe destroy block arguments");
178 setLocation(destroyRegion, loc);
180 mapping.
map(destroyRegion.
getBlocks().front().getArguments(), arguments);
185class ACCRecipeMaterialization
189 ACCRecipeMaterialization>::ACCRecipeMaterializationBase;
193 ACCRecipeMaterialization>::getDependentDialects(registry);
196 void runOnOperation()
override;
212 template <
typename OpTy>
213 void handleInitialValueMapping(OpTy op)
const;
214 template <
typename OpTy>
216 OpTy op, ModuleOp moduleOp,
218 template <
typename OpTy,
typename RecipeOpTy,
typename AccOpTy>
219 LogicalResult materialize(OpTy op, RecipeOpTy recipe, AccOpTy accOp,
222 Value materializationVar = {})
const;
223 template <
typename OpTy>
228template <
typename OpTy>
229void ACCRecipeMaterialization::handleInitialValueMapping(OpTy op)
const {
231 auto mapInitialOp = acc::FirstprivateMapInitialOp::create(
232 builder, op.getLoc(), op.getVar(), op.getStructured(), op.getImplicit(),
234 mapInitialOp.setName(op.getName());
235 op.getVarMutable().assign(mapInitialOp.getAccVar());
241static bool readsVar(
Region ®ion) {
247template <
typename OpTy>
248void ACCRecipeMaterialization::removeRecipe(
249 OpTy op, ModuleOp moduleOp,
251 auto recipeName = op.getNameAttr();
254 bool useEmpty = usedSymbols
255 ? !usedSymbols->contains(recipeName)
258 LLVM_DEBUG(llvm::dbgs() <<
"erasing recipe: " << recipeName <<
"\n");
262 std::optional<SymbolTable::UseRange> symbolUses =
263 op.getSymbolUses(moduleOp);
264 if (symbolUses.has_value()) {
266 llvm::dbgs() <<
"symbol use: ";
267 symbolUse.getUser()->dump();
271 llvm_unreachable(
"expected no use of recipe symbol");
275template <
typename OpTy,
typename RecipeOpTy,
typename AccOpTy>
276LogicalResult ACCRecipeMaterialization::materialize(
279 Region ®ion = accOp.getRegion();
280 Value origPtr = materializationVar ? materializationVar : op.getVar();
281 Value accPtr = op.getAccVar();
282 assert(accPtr &&
"invalid op: null acc var");
288 Region &initRegion = recipe.getInitRegion();
289 unsigned initNumArguments =
290 initRegion.
getBlocks().front().getArguments().size();
291 if (initNumArguments > 1) {
294 if ((initNumArguments - 1) % 3 != 0) {
296 "privatization of array section with extents");
307 initRegion.
getBlocks().front().getArgument(argIdx++).getType(),
311 auto dataBound = bound.getDefiningOp<acc::DataBoundsOp>();
313 "acc.reduction's bound must be defined by acc.bounds");
318 castValueToArgType(dataBound.getLoc(), dataBound.getLowerbound());
320 castValueToArgType(dataBound.getLoc(), dataBound.getUpperbound());
322 castValueToArgType(dataBound.getLoc(), dataBound.getStride());
323 triples.append({lb,
ub, step});
325 assert(triples.size() + 1 == initNumArguments &&
326 "mismatch between number bounds and number of recipe init block "
332 initArgs.append(triples);
333 mapping.
map(initRegion.
getBlocks().front().getArguments(), initArgs);
336 setLocation(initRegion, loc);
338 if constexpr (std::is_same_v<OpTy, acc::PrivateOp>) {
342 &initRegion, block, block->
begin(), mapping, {accPtr});
343 assert(!results.empty() &&
"expected a result from init region");
344 saveVarName(op.getAccVar(), results[0]);
347 if (!recipe.getDestroyRegion().empty()) {
348 results.insert(results.begin(), origPtr);
349 results.append(triples);
350 cloneDestroy(loc, recipe, block, std::prev(block->
end()), results);
352 }
else if constexpr (std::is_same_v<OpTy, acc::FirstprivateOp>) {
356 &initRegion, block, block->
begin(), mapping, {accPtr});
357 assert(!results.empty() &&
"expected a result from init region");
358 saveVarName(op.getAccVar(), results[0]);
362 copyArgs.append(triples);
365 destroyArgs.append(results);
366 destroyArgs.append(triples);
370 mapping.
map(recipe.getCopyRegion().front().getArguments(), copyArgs);
372 Region ©Region = recipe.getCopyRegion();
373 setLocation(copyRegion, loc);
375 if (!recipe.getDestroyRegion().empty()) {
376 cloneDestroy(loc, recipe, block, std::prev(block->
end()), destroyArgs);
378 }
else if constexpr (std::is_same_v<OpTy, acc::ReductionOp>) {
379 if (recipe.getReductionOperator() == acc::ReductionOperator::AccMul &&
380 isComplexReductionType(recipe.getType())) {
381 (
void)accSupport.
emitNYI(loc,
"reduction: complex multiply reduction");
385 auto cloneRegionIntoAccRegion = [&](
Region *src,
Region *dest,
390 b.setInsertionPoint(terminator);
392 acc::YieldOp::create(
b, op.getLoc(), terminator->
getOperands());
394 acc::YieldOp::create(
b, op.getLoc(),
ValueRange{});
399 if constexpr (std::is_same_v<AccOpTy, acc::ParallelOp>)
400 b.setInsertionPointToStart(®ion.
front());
401 else if constexpr (std::is_same_v<AccOpTy, acc::LoopOp>)
402 b.setInsertionPoint(op);
404 llvm_unreachable(
"unexpected acc op with reduction recipe");
408 acc::ReductionInitOp::create(
b, op.getLoc(), origPtr, reductionBounds,
409 recipe.getReductionOperatorAttr());
410 saveVarName(op.getAccVar(), reductionOp.getResult());
411 cloneRegionIntoAccRegion(&initRegion, &reductionOp.getRegion(),
413 Block *initBlock = &reductionOp.getRegion().
front();
414 resolveVarNamePlaceholders(initBlock, std::prev(initBlock->
end()),
421 Region &combinerRegion = recipe.getCombinerRegion();
422 setLocation(combinerRegion, loc);
426 if constexpr (std::is_same_v<AccOpTy, acc::ParallelOp>)
428 else if constexpr (std::is_same_v<AccOpTy, acc::LoopOp>)
429 b.setInsertionPointAfter(accOp);
431 llvm_unreachable(
"unexpected acc op with reduction recipe");
439 argsRemapping.append(triples);
442 auto combineRegionOp = acc::ReductionCombineRegionOp::create(
443 b, op.getLoc(), origPtr, reductionOp.getResult());
444 cloneRegionIntoAccRegion(&combinerRegion, &combineRegionOp.getRegion(),
447 auto *ctx =
b.getContext();
453 if constexpr (std::is_same_v<AccOpTy, acc::ParallelOp>) {
454 acc::GPUParallelDimsAttr parDimsAttr;
455 if (accOp.isEffectivelySerial()) {
467 auto setSeqParDimsForRecipeLoops = [&](
Region *r) {
468 r->walk([&](LoopLikeOpInterface loopLike) {
472 setSeqParDimsForRecipeLoops(&reductionOp.getRegion());
473 setSeqParDimsForRecipeLoops(&combineRegionOp.getRegion());
475 if (!recipe.getDestroyRegion().empty()) {
477 results.append(triples);
479 cloneDestroy(loc, recipe, combineRegionOp->getBlock(), ip, results);
482 llvm_unreachable(
"unexpected op type");
489template <
typename OpTy>
490LogicalResult ACCRecipeMaterialization::materializeForACCOp(
493 assert(isa<ACC_COMPUTE_CONSTRUCT_AND_LOOP_OPS>(accOp));
503 struct ReductionMapping {
508 if constexpr (!std::is_same_v<OpTy, acc::LoopOp>) {
509 for (
Value dataOperand : accOp.getDataClauseOperands()) {
510 Operation *dataOp = dataOperand.getDefiningOp();
511 if (dataOp && isa<ACC_DATA_ENTRY_OPS>(dataOp))
512 mappedReductionVars.push_back({
acc::getVar(dataOp), dataOperand});
516 auto getMappedReductionVar = [&](acc::ReductionOp reductionOp) ->
Value {
517 if constexpr (std::is_same_v<OpTy, acc::LoopOp>) {
518 return reductionOp.getVar();
520 Value originalVar = reductionOp.getVar();
521 if (isa_and_nonnull<ACC_DATA_ENTRY_OPS>(originalVar.
getDefiningOp()))
528 auto existing = llvm::find_if(mappedReductionVars,
529 [&](
const ReductionMapping &mapping) {
530 return mapping.originalVar == originalVar;
532 if (existing != mappedReductionVars.end())
533 return existing->mappedVar;
536 acc::CopyinOp copyinOp;
537 if (std::optional<StringRef> name = reductionOp.getName())
539 acc::CopyinOp::create(builder, reductionOp.getLoc(), originalVar,
541 reductionOp.getBounds());
543 copyinOp = acc::CopyinOp::create(
544 builder, reductionOp.getLoc(), originalVar,
545 true,
true, reductionOp.getBounds());
546 copyinOp.setDataClause(acc::DataClause::acc_reduction);
547 accOp.getDataClauseOperandsMutable().append(copyinOp.getAccVar());
550 acc::CopyoutOp copyoutOp;
551 if (std::optional<StringRef> name = reductionOp.getName())
552 copyoutOp = acc::CopyoutOp::create(
553 builder, reductionOp.getLoc(), copyinOp.getAccVar(), originalVar,
555 reductionOp.getBounds());
557 copyoutOp = acc::CopyoutOp::create(
558 builder, reductionOp.getLoc(), copyinOp.getAccVar(), originalVar,
559 true,
true, reductionOp.getBounds());
560 copyoutOp.setDataClause(acc::DataClause::acc_reduction);
562 mappedReductionVars.push_back({originalVar, copyinOp.getAccVar()});
563 return copyinOp.getAccVar();
567 if (!accOp.getFirstprivateOperands().empty()) {
571 accOp.getFirstprivateOperandsMutable().clear();
572 for (
Value operand : operands) {
573 auto firstprivateOp = cast<acc::FirstprivateOp>(operand.getDefiningOp());
574 auto symbolRef = cast<SymbolRefAttr>(firstprivateOp.getRecipeAttr());
576 auto recipeOp = cast<acc::FirstprivateRecipeOp>(decl);
577 LLVM_DEBUG(llvm::dbgs() <<
"materializing: " << firstprivateOp <<
"\n"
578 << symbolRef <<
"\n");
579 handleInitialValueMapping(firstprivateOp);
581 materialize(firstprivateOp, recipeOp, accOp, accSupport, policy)))
586 if (!accOp.getPrivateOperands().empty()) {
590 accOp.getPrivateOperandsMutable().clear();
591 for (
Value operand : operands) {
592 auto privateOp = cast<acc::PrivateOp>(operand.getDefiningOp());
593 auto symbolRef = cast<SymbolRefAttr>(privateOp.getRecipeAttr());
595 auto recipeOp = cast<acc::PrivateRecipeOp>(decl);
596 LLVM_DEBUG(llvm::dbgs() <<
"materializing: " << privateOp <<
"\n"
597 << symbolRef <<
"\n");
598 if (readsVar(recipeOp.getInitRegion()) ||
599 readsVar(recipeOp.getDestroyRegion()))
600 handleInitialValueMapping(privateOp);
601 if (failed(materialize(privateOp, recipeOp, accOp, accSupport, policy)))
606 if (!accOp.getReductionOperands().empty()) {
610 accOp.getReductionOperandsMutable().clear();
611 for (
Value operand : operands) {
612 auto reductionOp = cast<acc::ReductionOp>(operand.getDefiningOp());
613 auto symbolRef = cast<SymbolRefAttr>(reductionOp.getRecipeAttr());
615 auto recipeOp = cast<acc::ReductionRecipeOp>(decl);
616 LLVM_DEBUG(llvm::dbgs() <<
"materializing: " << reductionOp <<
"\n"
617 << symbolRef <<
"\n");
618 Value mappedVar = getMappedReductionVar(reductionOp);
619 if (failed(materialize(reductionOp, recipeOp, accOp, accSupport, policy,
627void ACCRecipeMaterialization::runOnOperation() {
628 ModuleOp moduleOp = getOperation();
634 bool anyFailed =
false;
639 [&](
auto constructOp) {
640 if (failed(materializeForACCOp(constructOp, accSupport, policy)))
653 std::optional<llvm::DenseSet<StringAttr>> usedSymbols;
656 if (std::optional<SymbolTable::UseRange> uses =
658 usedSymbols.emplace();
660 usedSymbols->insert(use.getSymbolRef().getLeafReference());
664 if (
auto recipe = dyn_cast<acc::ReductionRecipeOp>(op))
665 removeRecipe(recipe, moduleOp, usedSymbols);
666 else if (
auto recipe = dyn_cast<acc::PrivateRecipeOp>(op))
667 removeRecipe(recipe, moduleOp, usedSymbols);
668 else if (
auto recipe = dyn_cast<acc::FirstprivateRecipeOp>(op))
669 removeRecipe(recipe, moduleOp, usedSymbols);
Block represents an ordered list of Operations.
OpListType::iterator iterator
Region * getParent() const
Provide a 'getParent' method for ilist_node_with_parent methods.
Operation * getTerminator()
Get the terminator operation of this block.
BlockArgListType getArguments()
bool isEntryBlock()
Return if this block is the entry block in the parent region.
The DialectRegistry maps a dialect namespace to a constructor for the matching dialect.
This is a utility class for mapping one set of IR entities to another.
void clear()
Clears all mappings held by the mapper.
void map(Value from, Value to)
Inserts a new mapping for 'from' to 'to'.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
This class helps build Operations.
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Operation is the basic unit of execution within MLIR.
void setLoc(Location loc)
Set the source location the operation was defined or derived from.
void setDiscardableAttr(StringAttr name, Attribute value)
Set a discardable attribute by name.
Attribute removeDiscardableAttr(StringAttr name)
Remove the discardable attribute with the specified name if it exists.
operand_range getOperands()
Returns an iterator on the underlying Value's.
AttrClass getDiscardableAttrOfType(StringRef name)
Access a discardable attribute by name and cast it to AttrClass.
MLIRContext * getContext()
Return the context this operation is associated with.
void erase()
Remove this operation from its parent block and delete it.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
void cloneInto(Region *dest, IRMapping &mapper)
Clone the internal blocks from this region into dest.
unsigned getNumArguments()
BlockArgument getArgument(unsigned i)
Operation * getParentOp()
Return the parent operation this region is attached to.
BlockListType & getBlocks()
RetT walk(FnT &&callback)
Walk all nested operations, blocks or regions (including this region), depending on the type of callb...
This class represents a specific symbol use.
static Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
static bool symbolKnownUseEmpty(StringAttr symbol, Operation *from)
Return if the given symbol is known to have no uses that are nested within the given operation 'from'...
static std::optional< UseRange > getSymbolUses(Operation *from)
Get an iterator range for all of the uses, for any symbol, that are nested within the given operation...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
This class provides an abstraction over the different types of ranges over Values.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
bool use_empty() const
Returns true if this value has no uses.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Default policy that provides the standard GPU mapping: gang(dim:1) -> BlockX (gridDim....
InFlightDiagnostic emitNYI(Location loc, const Twine &message)
Report a case that is not yet supported by the implementation.
#define ACC_COMPUTE_CONSTRUCT_AND_LOOP_OPS
std::string getVariableName(mlir::Value v)
Attempts to extract the variable name from a value by walking through view-like operations until an a...
mlir::Value getVar(mlir::Operation *accDataClauseOp)
Used to obtain the var from a data clause operation.
GPUParallelDimsAttr getGangDim1ParDimsAttr(MLIRContext *ctx, ACCToGPUMappingPolicy &policy)
Create a gang dim 1 GPUParallelDimsAttr based on the mapping policy.
mlir::SmallVector< mlir::Value > getBounds(mlir::Operation *accDataClauseOp)
Used to obtain bounds from an acc data clause operation.
GPUParallelDimsAttr getSeqParDimsAttr(MLIRContext *ctx, ACCToGPUMappingPolicy &policy)
Create a sequential GPUParallelDimsAttr based on the mapping policy.
llvm::StringLiteral getVarNamePlaceholder()
Returns a placeholder string for use as an acc.var_name attribute value when the actual variable name...
static constexpr StringLiteral getVarNameAttrName()
void registerAllExtensions(DialectRegistry ®istry)
Register the standard OpenACC models for GPU, LLVM and MemRef IR.
void setParDimsAttr(Operation *op, GPUParallelDimsAttr attr)
Set parallel dimensions on op.
std::pair< llvm::SmallVector< Value >, Block::iterator > cloneACCRegionInto(Region *src, Block *dest, Block::iterator inlinePoint, IRMapping &mapping, ValueRange resultsToReplace)
Clone an ACC region into a destination block at the given insertion point.
ACCParMappingPolicy< mlir::acc::GPUParallelDimAttr > ACCToGPUMappingPolicy
Type alias for the GPU-specific mapping policy.
Include the generated interface declarations.
Value convertScalarToDtype(OpBuilder &b, Location loc, Value operand, Type toType, bool isUnsignedCast)
Converts a scalar value operand to type toType.
void replaceAllUsesInRegionWith(Value orig, Value replacement, Region ®ion)
Replace all uses of orig within the given region with replacement.
llvm::TypeSwitch< T, ResultT > TypeSwitch