MLIR 22.0.0git
ACCImplicitData.cpp
Go to the documentation of this file.
1//===- ACCImplicitData.cpp ------------------------------------------------===//
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 pass implements the OpenACC specification for "Variables with
10// Implicitly Determined Data Attributes" (OpenACC 3.4 spec, section 2.6.2).
11//
12// Overview:
13// ---------
14// The pass automatically generates data clause operations for variables used
15// within OpenACC compute constructs (parallel, kernels, serial) that do not
16// already have explicit data clauses. The semantics follow these rules:
17//
18// 1. If there is a default(none) clause visible, no implicit data actions
19// apply.
20//
21// 2. An aggregate variable (arrays, derived types, etc.) will be treated as:
22// - In a present clause when default(present) is visible.
23// - In a copy clause otherwise.
24//
25// 3. A scalar variable will be treated as if it appears in:
26// - A copy clause if the compute construct is a kernels construct.
27// - A firstprivate clause otherwise (parallel, serial).
28//
29// Requirements:
30// -------------
31// To use this pass in a pipeline, the following requirements must be met:
32//
33// 1. Type Interface Implementation: Variables from the dialect being used
34// must implement one or both of the following MLIR interfaces:
35// `acc::MappableType` and/or `acc::PointerLikeType`
36//
37// These interfaces provide the necessary methods for the pass to:
38// - Determine variable type categories (scalar vs. aggregate)
39// - Generate appropriate bounds information
40// - Generate privatization recipes
41//
42// 2. Operation Interface Implementation: Operations that access partial
43// entities or create views should implement the following MLIR
44// interfaces: `acc::PartialEntityAccess` and/or
45// `mlir::ViewLikeOpInterface`
46//
47// These interfaces are used for proper data clause ordering, ensuring
48// that base entities are mapped before derived entities (e.g., a
49// struct is mapped before its fields, an array is mapped before
50// subarray views).
51//
52// 3. Analysis Registration (Optional): If custom behavior is needed for
53// variable name extraction or alias analysis, the dialect should
54// pre-register the `acc::OpenACCSupport` and `mlir::AliasAnalysis` analyses.
55//
56// If not registered, default behavior will be used.
57//
58// Implementation Details:
59// -----------------------
60// The pass performs the following operations:
61//
62// 1. Finds candidate variables which are live-in to the compute region and
63// are not already in a data clause or private clause.
64//
65// 2. Generates both data "entry" and "exit" clause operations that match
66// the intended action depending on variable type:
67// - copy -> acc.copyin (entry) + acc.copyout (exit)
68// - present -> acc.present (entry) + acc.delete (exit)
69// - firstprivate -> acc.firstprivate (entry only, no exit)
70//
71// 3. Ensures that default clause is taken into consideration by looking
72// through current construct and parent constructs to find the "visible
73// default clause".
74//
75// 4. Fixes up SSA value links so that uses in the acc region reference the
76// result of the newly created data clause operations.
77//
78// 5. When generating implicit data clause operations, it also adds variable
79// name information and marks them with the implicit flag.
80//
81// 6. Recipes are generated by calling the appropriate entrypoints in the
82// MappableType and PointerLikeType interfaces.
83//
84// 7. AliasAnalysis is used to determine if a variable is already covered by
85// an existing data clause (e.g., an interior pointer covered by its parent).
86//
87// Examples:
88// ---------
89//
90// Example 1: Scalar in parallel construct (implicit firstprivate)
91//
92// Before:
93// func.func @test() {
94// %scalar = memref.alloca() {acc.var_name = "x"} : memref<f32>
95// acc.parallel {
96// %val = memref.load %scalar[] : memref<f32>
97// acc.yield
98// }
99// }
100//
101// After:
102// func.func @test() {
103// %scalar = memref.alloca() {acc.var_name = "x"} : memref<f32>
104// %firstpriv = acc.firstprivate varPtr(%scalar : memref<f32>)
105// -> memref<f32> {implicit = true, name = "x"}
106// acc.parallel firstprivate(@recipe -> %firstpriv : memref<f32>) {
107// %val = memref.load %firstpriv[] : memref<f32>
108// acc.yield
109// }
110// }
111//
112// Example 2: Scalar in kernels construct (implicit copy)
113//
114// Before:
115// func.func @test() {
116// %scalar = memref.alloca() {acc.var_name = "n"} : memref<i32>
117// acc.kernels {
118// %val = memref.load %scalar[] : memref<i32>
119// acc.terminator
120// }
121// }
122//
123// After:
124// func.func @test() {
125// %scalar = memref.alloca() {acc.var_name = "n"} : memref<i32>
126// %copyin = acc.copyin varPtr(%scalar : memref<i32>) -> memref<i32>
127// {dataClause = #acc<data_clause acc_copy>,
128// implicit = true, name = "n"}
129// acc.kernels dataOperands(%copyin : memref<i32>) {
130// %val = memref.load %copyin[] : memref<i32>
131// acc.terminator
132// }
133// acc.copyout accPtr(%copyin : memref<i32>)
134// to varPtr(%scalar : memref<i32>)
135// {dataClause = #acc<data_clause acc_copy>,
136// implicit = true, name = "n"}
137// }
138//
139// Example 3: Array (aggregate) in parallel (implicit copy)
140//
141// Before:
142// func.func @test() {
143// %array = memref.alloca() {acc.var_name = "arr"} : memref<100xf32>
144// acc.parallel {
145// %c0 = arith.constant 0 : index
146// %val = memref.load %array[%c0] : memref<100xf32>
147// acc.yield
148// }
149// }
150//
151// After:
152// func.func @test() {
153// %array = memref.alloca() {acc.var_name = "arr"} : memref<100xf32>
154// %copyin = acc.copyin varPtr(%array : memref<100xf32>)
155// -> memref<100xf32>
156// {dataClause = #acc<data_clause acc_copy>,
157// implicit = true, name = "arr"}
158// acc.parallel dataOperands(%copyin : memref<100xf32>) {
159// %c0 = arith.constant 0 : index
160// %val = memref.load %copyin[%c0] : memref<100xf32>
161// acc.yield
162// }
163// acc.copyout accPtr(%copyin : memref<100xf32>)
164// to varPtr(%array : memref<100xf32>)
165// {dataClause = #acc<data_clause acc_copy>,
166// implicit = true, name = "arr"}
167// }
168//
169// Example 4: Array with default(present)
170//
171// Before:
172// func.func @test() {
173// %array = memref.alloca() {acc.var_name = "arr"} : memref<100xf32>
174// acc.parallel {
175// %c0 = arith.constant 0 : index
176// %val = memref.load %array[%c0] : memref<100xf32>
177// acc.yield
178// } attributes {defaultAttr = #acc<defaultvalue present>}
179// }
180//
181// After:
182// func.func @test() {
183// %array = memref.alloca() {acc.var_name = "arr"} : memref<100xf32>
184// %present = acc.present varPtr(%array : memref<100xf32>)
185// -> memref<100xf32>
186// {implicit = true, name = "arr"}
187// acc.parallel dataOperands(%present : memref<100xf32>)
188// attributes {defaultAttr = #acc<defaultvalue present>} {
189// %c0 = arith.constant 0 : index
190// %val = memref.load %present[%c0] : memref<100xf32>
191// acc.yield
192// }
193// acc.delete accPtr(%present : memref<100xf32>)
194// {dataClause = #acc<data_clause acc_present>,
195// implicit = true, name = "arr"}
196// }
197//
198//===----------------------------------------------------------------------===//
199
201
206#include "mlir/IR/Builders.h"
207#include "mlir/IR/BuiltinOps.h"
208#include "mlir/IR/Dominance.h"
209#include "mlir/IR/Operation.h"
210#include "mlir/IR/Value.h"
214#include "llvm/ADT/STLExtras.h"
215#include "llvm/ADT/SmallVector.h"
216#include "llvm/ADT/TypeSwitch.h"
217#include "llvm/Support/ErrorHandling.h"
218#include <type_traits>
219
220namespace mlir {
221namespace acc {
222#define GEN_PASS_DEF_ACCIMPLICITDATA
223#include "mlir/Dialect/OpenACC/Transforms/Passes.h.inc"
224} // namespace acc
225} // namespace mlir
226
227#define DEBUG_TYPE "acc-implicit-data"
228
229using namespace mlir;
230
231namespace {
232
233class ACCImplicitData : public acc::impl::ACCImplicitDataBase<ACCImplicitData> {
234public:
235 using acc::impl::ACCImplicitDataBase<ACCImplicitData>::ACCImplicitDataBase;
236
237 void runOnOperation() override;
238
239private:
240 /// Looks through the `dominatingDataClauses` to find the original data clause
241 /// op for an alias. Returns nullptr if no original data clause op is found.
242 template <typename OpT>
243 Operation *getOriginalDataClauseOpForAlias(
244 Value var, OpBuilder &builder, OpT computeConstructOp,
245 const SmallVector<Value> &dominatingDataClauses);
246
247 /// Generates the appropriate `acc.copyin`, `acc.present`,`acc.firstprivate`,
248 /// etc. data clause op for a candidate variable.
249 template <typename OpT>
250 Operation *generateDataClauseOpForCandidate(
251 Value var, ModuleOp &module, OpBuilder &builder, OpT computeConstructOp,
252 const SmallVector<Value> &dominatingDataClauses,
253 const std::optional<acc::ClauseDefaultValue> &defaultClause);
254
255 /// Generates the implicit data ops for a compute construct.
256 template <typename OpT>
257 void
258 generateImplicitDataOps(ModuleOp &module, OpT computeConstructOp,
259 std::optional<acc::ClauseDefaultValue> &defaultClause,
260 acc::OpenACCSupport &accSupport);
261
262 /// Generates a private recipe for a variable.
263 acc::PrivateRecipeOp generatePrivateRecipe(ModuleOp &module, Value var,
264 Location loc, OpBuilder &builder,
265 acc::OpenACCSupport &accSupport);
266
267 /// Generates a firstprivate recipe for a variable.
268 acc::FirstprivateRecipeOp
269 generateFirstprivateRecipe(ModuleOp &module, Value var, Location loc,
270 OpBuilder &builder,
271 acc::OpenACCSupport &accSupport);
272
273 /// Generates recipes for a list of variables.
274 void generateRecipes(ModuleOp &module, OpBuilder &builder,
275 Operation *computeConstructOp,
276 const SmallVector<Value> &newOperands);
277};
278
279/// Determines if a variable is a candidate for implicit data mapping.
280/// Returns true if the variable is a candidate, false otherwise.
281static bool isCandidateForImplicitData(Value val, Region &accRegion,
282 acc::OpenACCSupport &accSupport) {
283 // Ensure the variable is an allowed type for data clause.
284 if (!acc::isPointerLikeType(val.getType()) &&
286 return false;
287
288 if (accSupport.isValidValueUse(val, accRegion))
289 return false;
290
291 // If this is already coming from a data clause, we do not need to generate
292 // another.
293 if (isa_and_nonnull<ACC_DATA_ENTRY_OPS>(val.getDefiningOp()))
294 return false;
295
296 // If this is only used by private clauses, it is not a real live-in.
297 if (acc::isOnlyUsedByPrivateClauses(val, accRegion))
298 return false;
299
300 return true;
301}
302
303template <typename OpT>
304Operation *ACCImplicitData::getOriginalDataClauseOpForAlias(
305 Value var, OpBuilder &builder, OpT computeConstructOp,
306 const SmallVector<Value> &dominatingDataClauses) {
307 auto &aliasAnalysis = this->getAnalysis<AliasAnalysis>();
308 for (auto dataClause : dominatingDataClauses) {
309 if (auto *dataClauseOp = dataClause.getDefiningOp()) {
310 // Only accept clauses that guarantee that the alias is present.
311 if (isa<acc::CopyinOp, acc::CreateOp, acc::PresentOp, acc::NoCreateOp,
312 acc::DevicePtrOp>(dataClauseOp))
313 if (aliasAnalysis.alias(acc::getVar(dataClauseOp), var).isMust())
314 return dataClauseOp;
315 }
316 }
317 return nullptr;
318}
319
320// Generates bounds for variables that have unknown dimensions
321static void fillInBoundsForUnknownDimensions(Operation *dataClauseOp,
322 OpBuilder &builder) {
323
324 if (!acc::getBounds(dataClauseOp).empty())
325 // If bounds are already present, do not overwrite them.
326 return;
327
328 // For types that have unknown dimensions, attempt to generate bounds by
329 // relying on MappableType being able to extract it from the IR.
330 auto var = acc::getVar(dataClauseOp);
331 auto type = var.getType();
332 if (auto mappableTy = dyn_cast<acc::MappableType>(type)) {
333 if (mappableTy.hasUnknownDimensions()) {
334 TypeSwitch<Operation *>(dataClauseOp)
335 .Case<ACC_DATA_ENTRY_OPS, ACC_DATA_EXIT_OPS>([&](auto dataClauseOp) {
336 if (std::is_same_v<decltype(dataClauseOp), acc::DevicePtrOp>)
337 return;
338 OpBuilder::InsertionGuard guard(builder);
339 builder.setInsertionPoint(dataClauseOp);
340 auto bounds = mappableTy.generateAccBounds(var, builder);
341 if (!bounds.empty())
342 dataClauseOp.getBoundsMutable().assign(bounds);
343 });
344 }
345 }
346}
347
348acc::PrivateRecipeOp
349ACCImplicitData::generatePrivateRecipe(ModuleOp &module, Value var,
350 Location loc, OpBuilder &builder,
351 acc::OpenACCSupport &accSupport) {
352 auto type = var.getType();
353 std::string recipeName =
354 accSupport.getRecipeName(acc::RecipeKind::private_recipe, type, var);
355
356 // Check if recipe already exists
357 auto existingRecipe = module.lookupSymbol<acc::PrivateRecipeOp>(recipeName);
358 if (existingRecipe)
359 return existingRecipe;
360
361 // Set insertion point to module body in a scoped way
362 OpBuilder::InsertionGuard guard(builder);
363 builder.setInsertionPointToStart(module.getBody());
364
365 auto recipe =
366 acc::PrivateRecipeOp::createAndPopulate(builder, loc, recipeName, type);
367 if (!recipe.has_value())
368 return accSupport.emitNYI(loc, "implicit private"), nullptr;
369 return recipe.value();
370}
371
372acc::FirstprivateRecipeOp
373ACCImplicitData::generateFirstprivateRecipe(ModuleOp &module, Value var,
374 Location loc, OpBuilder &builder,
375 acc::OpenACCSupport &accSupport) {
376 auto type = var.getType();
377 std::string recipeName =
378 accSupport.getRecipeName(acc::RecipeKind::firstprivate_recipe, type, var);
379
380 // Check if recipe already exists
381 auto existingRecipe =
382 module.lookupSymbol<acc::FirstprivateRecipeOp>(recipeName);
383 if (existingRecipe)
384 return existingRecipe;
385
386 // Set insertion point to module body in a scoped way
387 OpBuilder::InsertionGuard guard(builder);
388 builder.setInsertionPointToStart(module.getBody());
389
390 auto recipe = acc::FirstprivateRecipeOp::createAndPopulate(builder, loc,
391 recipeName, type);
392 if (!recipe.has_value())
393 return accSupport.emitNYI(loc, "implicit firstprivate"), nullptr;
394 return recipe.value();
395}
396
397void ACCImplicitData::generateRecipes(ModuleOp &module, OpBuilder &builder,
398 Operation *computeConstructOp,
399 const SmallVector<Value> &newOperands) {
400 auto &accSupport = this->getAnalysis<acc::OpenACCSupport>();
401 for (auto var : newOperands) {
402 auto loc{var.getLoc()};
403 if (auto privateOp = var.getDefiningOp<acc::PrivateOp>()) {
404 auto recipe = generatePrivateRecipe(
405 module, acc::getVar(var.getDefiningOp()), loc, builder, accSupport);
406 if (recipe)
407 privateOp.setRecipeAttr(
408 SymbolRefAttr::get(module->getContext(), recipe.getSymName()));
409 } else if (auto firstprivateOp = var.getDefiningOp<acc::FirstprivateOp>()) {
410 auto recipe = generateFirstprivateRecipe(
411 module, acc::getVar(var.getDefiningOp()), loc, builder, accSupport);
412 if (recipe)
413 firstprivateOp.setRecipeAttr(SymbolRefAttr::get(
414 module->getContext(), recipe.getSymName().str()));
415 } else {
416 accSupport.emitNYI(var.getLoc(), "implicit reduction");
417 }
418 }
419}
420
421// Generates the data entry data op clause so that it adheres to OpenACC
422// rules as follows (line numbers and specification from OpenACC 3.4):
423// 1388 An aggregate variable will be treated as if it appears either:
424// 1389 - In a present clause if there is a default(present) clause visible at
425// the compute construct.
426// 1391 - In a copy clause otherwise.
427// 1392 A scalar variable will be treated as if it appears either:
428// 1393 - In a copy clause if the compute construct is a kernels construct.
429// 1394 - In a firstprivate clause otherwise.
430template <typename OpT>
431Operation *ACCImplicitData::generateDataClauseOpForCandidate(
432 Value var, ModuleOp &module, OpBuilder &builder, OpT computeConstructOp,
433 const SmallVector<Value> &dominatingDataClauses,
434 const std::optional<acc::ClauseDefaultValue> &defaultClause) {
435 auto &accSupport = this->getAnalysis<acc::OpenACCSupport>();
436 acc::VariableTypeCategory typeCategory =
437 acc::VariableTypeCategory::uncategorized;
438 if (auto mappableTy = dyn_cast<acc::MappableType>(var.getType())) {
439 typeCategory = mappableTy.getTypeCategory(var);
440 } else if (auto pointerLikeTy =
441 dyn_cast<acc::PointerLikeType>(var.getType())) {
442 typeCategory = pointerLikeTy.getPointeeTypeCategory(
444 pointerLikeTy.getElementType());
445 }
446
447 bool isScalar =
448 acc::bitEnumContainsAny(typeCategory, acc::VariableTypeCategory::scalar);
449 bool isAnyAggregate = acc::bitEnumContainsAny(
450 typeCategory, acc::VariableTypeCategory::aggregate);
451 Location loc = computeConstructOp->getLoc();
452
453 Operation *op = nullptr;
454 op = getOriginalDataClauseOpForAlias(var, builder, computeConstructOp,
455 dominatingDataClauses);
456 if (op) {
457 if (isa<acc::NoCreateOp>(op))
458 return acc::NoCreateOp::create(builder, loc, var,
459 /*structured=*/true, /*implicit=*/true,
460 accSupport.getVariableName(var),
461 acc::getBounds(op));
462
463 if (isa<acc::DevicePtrOp>(op))
464 return acc::DevicePtrOp::create(builder, loc, var,
465 /*structured=*/true, /*implicit=*/true,
466 accSupport.getVariableName(var),
467 acc::getBounds(op));
468
469 // The original data clause op is a PresentOp, CopyinOp, or CreateOp,
470 // hence guaranteed to be present.
471 return acc::PresentOp::create(builder, loc, var,
472 /*structured=*/true, /*implicit=*/true,
473 accSupport.getVariableName(var),
474 acc::getBounds(op));
475 } else if (isScalar) {
476 if (enableImplicitReductionCopy &&
478 computeConstructOp->getRegion(0))) {
479 auto copyinOp =
480 acc::CopyinOp::create(builder, loc, var,
481 /*structured=*/true, /*implicit=*/true,
482 accSupport.getVariableName(var));
483 copyinOp.setDataClause(acc::DataClause::acc_reduction);
484 return copyinOp.getOperation();
485 }
486 if constexpr (std::is_same_v<OpT, acc::KernelsOp> ||
487 std::is_same_v<OpT, acc::KernelEnvironmentOp>) {
488 // Scalars are implicit copyin in kernels construct.
489 // We also do the same for acc.kernel_environment because semantics
490 // of user variable mappings should be applied while ACC construct exists
491 // and at this point we should only be dealing with unmapped variables
492 // that were made live-in by the compiler.
493 // TODO: This may be revisited.
494 auto copyinOp =
495 acc::CopyinOp::create(builder, loc, var,
496 /*structured=*/true, /*implicit=*/true,
497 accSupport.getVariableName(var));
498 copyinOp.setDataClause(acc::DataClause::acc_copy);
499 return copyinOp.getOperation();
500 } else {
501 // Scalars are implicit firstprivate in parallel and serial construct.
502 return acc::FirstprivateOp::create(builder, loc, var,
503 /*structured=*/true, /*implicit=*/true,
504 accSupport.getVariableName(var));
505 }
506 } else if (isAnyAggregate) {
507 Operation *newDataOp = nullptr;
508
509 // When default(present) is true, the implicit behavior is present.
510 if (defaultClause.has_value() &&
511 defaultClause.value() == acc::ClauseDefaultValue::Present) {
512 newDataOp = acc::PresentOp::create(builder, loc, var,
513 /*structured=*/true, /*implicit=*/true,
514 accSupport.getVariableName(var));
516 builder.getUnitAttr());
517 } else {
518 auto copyinOp =
519 acc::CopyinOp::create(builder, loc, var,
520 /*structured=*/true, /*implicit=*/true,
521 accSupport.getVariableName(var));
522 copyinOp.setDataClause(acc::DataClause::acc_copy);
523 newDataOp = copyinOp.getOperation();
524 }
525
526 return newDataOp;
527 } else {
528 // This is not a fatal error - for example when the element type is
529 // pointer type (aka we have a pointer of pointer), it is potentially a
530 // deep copy scenario which is not being handled here.
531 // Other types need to be canonicalized. Thus just log unhandled cases.
532 LLVM_DEBUG(llvm::dbgs()
533 << "Unhandled case for implicit data mapping " << var << "\n");
534 }
535 return nullptr;
536}
537
538// Ensures that result values from the acc data clause ops are used inside the
539// acc region. ie:
540// acc.kernels {
541// use %val
542// }
543// =>
544// %dev = acc.dataop %val
545// acc.kernels {
546// use %dev
547// }
548static void legalizeValuesInRegion(Region &accRegion,
549 SmallVector<Value> &newPrivateOperands,
550 SmallVector<Value> &newDataClauseOperands) {
551 for (Value dataClause :
552 llvm::concat<Value>(newDataClauseOperands, newPrivateOperands)) {
553 Value var = acc::getVar(dataClause.getDefiningOp());
554 replaceAllUsesInRegionWith(var, dataClause, accRegion);
555 }
556}
557
558// Adds the private operands to the compute construct operation.
559template <typename OpT>
560static void addNewPrivateOperands(OpT &accOp,
561 const SmallVector<Value> &privateOperands) {
562 if (privateOperands.empty())
563 return;
564
565 for (auto priv : privateOperands) {
566 if (isa<acc::PrivateOp>(priv.getDefiningOp())) {
567 accOp.getPrivateOperandsMutable().append(priv);
568 } else if (isa<acc::FirstprivateOp>(priv.getDefiningOp())) {
569 accOp.getFirstprivateOperandsMutable().append(priv);
570 } else {
571 llvm_unreachable("unhandled reduction operand");
572 }
573 }
574}
575
576static Operation *findDataExitOp(Operation *dataEntryOp) {
577 auto res = acc::getAccVar(dataEntryOp);
578 for (auto *user : res.getUsers())
579 if (isa<ACC_DATA_EXIT_OPS>(user))
580 return user;
581 return nullptr;
582}
583
584// Generates matching data exit operation as described in the acc dialect
585// for how data clauses are decomposed:
586// https://mlir.llvm.org/docs/Dialects/OpenACCDialect/#operation-categories
587// Key ones used here:
588// * acc {construct} copy -> acc.copyin (before region) + acc.copyout (after
589// region)
590// * acc {construct} present -> acc.present (before region) + acc.delete
591// (after region)
592static void
593generateDataExitOperations(OpBuilder &builder, Operation *accOp,
594 const SmallVector<Value> &newDataClauseOperands,
595 const SmallVector<Value> &sortedDataClauseOperands) {
596 builder.setInsertionPointAfter(accOp);
597 Value lastDataClause = nullptr;
598 for (auto dataEntry : llvm::reverse(sortedDataClauseOperands)) {
599 if (llvm::find(newDataClauseOperands, dataEntry) ==
600 newDataClauseOperands.end()) {
601 // If this is not a new data clause operand, we should not generate an
602 // exit operation for it.
603 lastDataClause = dataEntry;
604 continue;
605 }
606 if (lastDataClause)
607 if (auto *dataExitOp = findDataExitOp(lastDataClause.getDefiningOp()))
608 builder.setInsertionPointAfter(dataExitOp);
609 Operation *dataEntryOp = dataEntry.getDefiningOp();
610 if (isa<acc::CopyinOp>(dataEntryOp)) {
611 auto copyoutOp = acc::CopyoutOp::create(
612 builder, dataEntryOp->getLoc(), dataEntry, acc::getVar(dataEntryOp),
613 /*structured=*/true, /*implicit=*/true,
614 acc::getVarName(dataEntryOp).value(), acc::getBounds(dataEntryOp));
615 copyoutOp.setDataClause(acc::DataClause::acc_copy);
616 } else if (isa<acc::PresentOp, acc::NoCreateOp>(dataEntryOp)) {
617 auto deleteOp = acc::DeleteOp::create(
618 builder, dataEntryOp->getLoc(), dataEntry,
619 /*structured=*/true, /*implicit=*/true,
620 acc::getVarName(dataEntryOp).value(), acc::getBounds(dataEntryOp));
621 deleteOp.setDataClause(acc::getDataClause(dataEntryOp).value());
622 } else if (isa<acc::DevicePtrOp>(dataEntryOp)) {
623 // Do nothing.
624 } else {
625 llvm_unreachable("unhandled data exit");
626 }
627 lastDataClause = dataEntry;
628 }
629}
630
631/// Returns all base references of a value in order.
632/// So for example, if we have a reference to a struct field like
633/// s.f1.f2.f3, this will return <s, s.f1, s.f1.f2, s.f1.f2.f3>.
634/// Any intermediate casts/view-like operations are included in the
635/// chain as well.
636static SmallVector<Value> getBaseRefsChain(Value val) {
637 SmallVector<Value> baseRefs;
638 baseRefs.push_back(val);
639 while (true) {
640 Value prevVal = val;
641
642 val = acc::getBaseEntity(val);
643 if (val != baseRefs.front())
644 baseRefs.insert(baseRefs.begin(), val);
645
646 // If this is a view-like operation, it is effectively another
647 // view of the same entity so we should add it to the chain also.
648 if (auto viewLikeOp = val.getDefiningOp<ViewLikeOpInterface>()) {
649 val = viewLikeOp.getViewSource();
650 baseRefs.insert(baseRefs.begin(), val);
651 }
652
653 // Continue loop if we made any progress
654 if (val == prevVal)
655 break;
656 }
657
658 return baseRefs;
659}
660
661static void insertInSortedOrder(SmallVector<Value> &sortedDataClauseOperands,
662 Operation *newClause) {
663 auto *insertPos =
664 std::find_if(sortedDataClauseOperands.begin(),
665 sortedDataClauseOperands.end(), [&](Value dataClauseVal) {
666 // Get the base refs for the current clause we are looking
667 // at.
668 auto var = acc::getVar(dataClauseVal.getDefiningOp());
669 auto baseRefs = getBaseRefsChain(var);
670
671 // If the newClause is of a base ref of an existing clause,
672 // we should insert it right before the current clause.
673 // Thus return true to stop iteration when this is the
674 // case.
675 return std::find(baseRefs.begin(), baseRefs.end(),
676 acc::getVar(newClause)) != baseRefs.end();
677 });
678
679 if (insertPos != sortedDataClauseOperands.end()) {
680 newClause->moveBefore(insertPos->getDefiningOp());
681 sortedDataClauseOperands.insert(insertPos, acc::getAccVar(newClause));
682 } else {
683 sortedDataClauseOperands.push_back(acc::getAccVar(newClause));
684 }
685}
686
687template <typename OpT>
688void ACCImplicitData::generateImplicitDataOps(
689 ModuleOp &module, OpT computeConstructOp,
690 std::optional<acc::ClauseDefaultValue> &defaultClause,
691 acc::OpenACCSupport &accSupport) {
692 // Implicit data attributes are only applied if "[t]here is no default(none)
693 // clause visible at the compute construct."
694 if (defaultClause.has_value() &&
695 defaultClause.value() == acc::ClauseDefaultValue::None)
696 return;
697 assert(!defaultClause.has_value() ||
698 defaultClause.value() == acc::ClauseDefaultValue::Present);
699
700 // 1) Collect live-in values.
701 Region &accRegion = computeConstructOp->getRegion(0);
702 SetVector<Value> liveInValues;
703 getUsedValuesDefinedAbove(accRegion, liveInValues);
704
705 // 2) Run the filtering to find relevant pointers that need copied.
706 auto isCandidate{[&](Value val) -> bool {
707 return isCandidateForImplicitData(val, accRegion, accSupport);
708 }};
709 auto candidateVars(
710 llvm::to_vector(llvm::make_filter_range(liveInValues, isCandidate)));
711 if (candidateVars.empty())
712 return;
713
714 // 3) Generate data clauses for the variables.
715 SmallVector<Value> newPrivateOperands;
716 SmallVector<Value> newDataClauseOperands;
717 OpBuilder builder(computeConstructOp);
718 if (!candidateVars.empty()) {
719 LLVM_DEBUG(llvm::dbgs() << "== Generating clauses for ==\n"
720 << computeConstructOp << "\n");
721 }
722 auto &domInfo = this->getAnalysis<DominanceInfo>();
723 auto &postDomInfo = this->getAnalysis<PostDominanceInfo>();
724 auto dominatingDataClauses =
725 acc::getDominatingDataClauses(computeConstructOp, domInfo, postDomInfo);
726 for (auto var : candidateVars) {
727 auto newDataClauseOp = generateDataClauseOpForCandidate(
728 var, module, builder, computeConstructOp, dominatingDataClauses,
729 defaultClause);
730 fillInBoundsForUnknownDimensions(newDataClauseOp, builder);
731 LLVM_DEBUG(llvm::dbgs() << "Generated data clause for " << var << ":\n"
732 << "\t" << *newDataClauseOp << "\n");
733 if (isa_and_nonnull<acc::PrivateOp, acc::FirstprivateOp, acc::ReductionOp>(
734 newDataClauseOp)) {
735 newPrivateOperands.push_back(acc::getAccVar(newDataClauseOp));
736 } else if (isa_and_nonnull<ACC_DATA_CLAUSE_OPS>(newDataClauseOp)) {
737 newDataClauseOperands.push_back(acc::getAccVar(newDataClauseOp));
738 dominatingDataClauses.push_back(acc::getAccVar(newDataClauseOp));
739 }
740 }
741
742 // 4) Legalize values in region (aka the uses in the region are the result
743 // of the data clause ops)
744 legalizeValuesInRegion(accRegion, newPrivateOperands, newDataClauseOperands);
745
746 // 5) Generate private recipes which are required for properly attaching
747 // private operands.
748 if constexpr (!std::is_same_v<OpT, acc::KernelsOp> &&
749 !std::is_same_v<OpT, acc::KernelEnvironmentOp>)
750 generateRecipes(module, builder, computeConstructOp, newPrivateOperands);
751
752 // 6) Figure out insertion order for the new data clause operands.
753 SmallVector<Value> sortedDataClauseOperands(
754 computeConstructOp.getDataClauseOperands());
755 for (auto newClause : newDataClauseOperands)
756 insertInSortedOrder(sortedDataClauseOperands, newClause.getDefiningOp());
757
758 // 7) Generate the data exit operations.
759 generateDataExitOperations(builder, computeConstructOp, newDataClauseOperands,
760 sortedDataClauseOperands);
761 // 8) Add all of the new operands to the compute construct op.
762 if constexpr (!std::is_same_v<OpT, acc::KernelsOp> &&
763 !std::is_same_v<OpT, acc::KernelEnvironmentOp>)
764 addNewPrivateOperands(computeConstructOp, newPrivateOperands);
765 computeConstructOp.getDataClauseOperandsMutable().assign(
766 sortedDataClauseOperands);
767}
768
769void ACCImplicitData::runOnOperation() {
770 ModuleOp module = this->getOperation();
771
772 acc::OpenACCSupport &accSupport = getAnalysis<acc::OpenACCSupport>();
773
774 module.walk([&](Operation *op) {
775 if (isa<ACC_COMPUTE_CONSTRUCT_OPS, acc::KernelEnvironmentOp>(op)) {
776 assert(op->getNumRegions() == 1 && "must have 1 region");
777
778 auto defaultClause = acc::getDefaultAttr(op);
780 .Case<ACC_COMPUTE_CONSTRUCT_OPS, acc::KernelEnvironmentOp>(
781 [&](auto op) {
782 generateImplicitDataOps(module, op, defaultClause, accSupport);
783 })
784 .Default([&](Operation *) {});
785 }
786 });
787}
788
789} // namespace
#define ACC_COMPUTE_CONSTRUCT_OPS
Definition OpenACC.h:57
#define ACC_DATA_ENTRY_OPS
Definition OpenACC.h:45
#define ACC_DATA_EXIT_OPS
Definition OpenACC.h:53
UnitAttr getUnitAttr()
Definition Builders.cpp:98
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:348
This class helps build Operations.
Definition Builders.h:207
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:431
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:398
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:412
Operation is the basic unit of execution within MLIR.
Definition Operation.h:88
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:223
void setAttr(StringAttr name, Attribute value)
If the an attribute exists with the specified name, change it to the new value.
Definition Operation.h:582
void moveBefore(Operation *existingOp)
Unlink this operation from its current block and insert it right before existingOp which may be in th...
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 an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
Location getLoc() const
Return the location of this value.
Definition Value.cpp:24
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
InFlightDiagnostic emitNYI(Location loc, const Twine &message)
Report a case that is not yet supported by the implementation.
bool isValidValueUse(Value v, Region &region)
Check if a value use is legal in an OpenACC region.
std::string getVariableName(Value v)
Get the variable name for a given value.
std::string getRecipeName(RecipeKind kind, Type type, Value var)
Get the recipe name for a given type and value.
static constexpr StringLiteral getFromDefaultClauseAttrName()
Definition OpenACC.h:199
mlir::Value getAccVar(mlir::Operation *accDataClauseOp)
Used to obtain the accVar from a data clause operation.
Definition OpenACC.cpp:4854
mlir::Value getVar(mlir::Operation *accDataClauseOp)
Used to obtain the var from a data clause operation.
Definition OpenACC.cpp:4823
std::optional< mlir::acc::DataClause > getDataClause(mlir::Operation *accDataEntryOp)
Used to obtain the dataClause from a data entry operation.
Definition OpenACC.cpp:4927
bool isPointerLikeType(mlir::Type type)
Used to check whether the provided type implements the PointerLikeType interface.
Definition OpenACC.h:160
mlir::SmallVector< mlir::Value > getBounds(mlir::Operation *accDataClauseOp)
Used to obtain bounds from an acc data clause operation.
Definition OpenACC.cpp:4872
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 isOnlyUsedByReductionClauses(mlir::Value val, mlir::Region &region)
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.
Definition OpenACC.cpp:4916
llvm::SmallVector< mlir::Value > getDominatingDataClauses(mlir::Operation *computeConstructOp, mlir::DominanceInfo &domInfo, mlir::PostDominanceInfo &postDomInfo)
Collects all data clauses that dominate the compute construct.
bool isMappableType(mlir::Type type)
Used to check whether the provided type implements the MappableType interface.
Definition OpenACC.h:166
mlir::Value getBaseEntity(mlir::Value val)
bool isOnlyUsedByPrivateClauses(mlir::Value val, mlir::Region &region)
Returns true if this value is only used by acc.private operations in the region.
Include the generated interface declarations.
void replaceAllUsesInRegionWith(Value orig, Value replacement, Region &region)
Replace all uses of orig within the given region with replacement.
llvm::SetVector< T, Vector, Set, N > SetVector
Definition LLVM.h:131
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.
Definition Value.h:497
void getUsedValuesDefinedAbove(Region &region, Region &limit, SetVector< Value > &values)
Fill values with a list of values defined at the ancestors of the limit region and used within region...
llvm::TypeSwitch< T, ResultT > TypeSwitch
Definition LLVM.h:144