MLIR 24.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#include "llvm/ADT/SmallVectorExtras.h"
202
207#include "mlir/IR/Builders.h"
208#include "mlir/IR/BuiltinOps.h"
209#include "mlir/IR/Dominance.h"
210#include "mlir/IR/Operation.h"
211#include "mlir/IR/Value.h"
215#include "llvm/ADT/STLExtras.h"
216#include "llvm/ADT/SmallVector.h"
217#include "llvm/ADT/TypeSwitch.h"
218#include "llvm/Support/ErrorHandling.h"
219#include "llvm/Support/raw_ostream.h"
220#include <string>
221#include <type_traits>
222
223namespace mlir {
224namespace acc {
225#define GEN_PASS_DEF_ACCIMPLICITDATA
226#include "mlir/Dialect/OpenACC/Transforms/Passes.h.inc"
227} // namespace acc
228} // namespace mlir
229
230#define DEBUG_TYPE "acc-implicit-data"
231
232using namespace mlir;
233
234namespace {
235
236class ACCImplicitData : public acc::impl::ACCImplicitDataBase<ACCImplicitData> {
237public:
238 using acc::impl::ACCImplicitDataBase<ACCImplicitData>::ACCImplicitDataBase;
239
240 void runOnOperation() override;
241
242private:
243 /// Looks through the `dominatingDataClauses` to find the original data clause
244 /// op for an alias. Returns nullptr if no original data clause op is found.
245 template <typename OpT>
246 Operation *getOriginalDataClauseOpForAlias(
247 Value var, OpBuilder &builder, OpT computeConstructOp,
248 const SmallVector<Value> &dominatingDataClauses);
249
250 /// Generates the appropriate `acc.copyin`, `acc.present`,`acc.firstprivate`,
251 /// etc. data clause op for a candidate variable.
252 template <typename OpT>
253 Operation *generateDataClauseOpForCandidate(
254 Value var, ModuleOp &module, OpBuilder &builder, OpT computeConstructOp,
255 const SmallVector<Value> &dominatingDataClauses,
256 const std::optional<acc::ClauseDefaultValue> &defaultClause);
257
258 /// Generates the implicit data ops for a compute construct.
259 template <typename OpT>
260 void
261 generateImplicitDataOps(ModuleOp &module, OpT computeConstructOp,
262 std::optional<acc::ClauseDefaultValue> &defaultClause,
263 acc::OpenACCSupport &accSupport);
264
265 /// Generates a private recipe for a variable.
266 acc::PrivateRecipeOp generatePrivateRecipe(ModuleOp &module, Value var,
267 Location loc, OpBuilder &builder,
268 acc::OpenACCSupport &accSupport);
269
270 /// Generates a firstprivate recipe for a variable.
271 acc::FirstprivateRecipeOp
272 generateFirstprivateRecipe(ModuleOp &module, Value var, Location loc,
273 OpBuilder &builder,
274 acc::OpenACCSupport &accSupport);
275
276 /// Generates recipes for a list of variables.
277 void generateRecipes(ModuleOp &module, OpBuilder &builder,
278 Operation *computeConstructOp,
279 const SmallVector<Value> &newOperands);
280};
281
282/// Determines if a variable is a candidate for implicit data mapping.
283/// Returns true if the variable is a candidate, false otherwise.
284static bool isCandidateForImplicitData(Value val, Region &accRegion,
285 acc::OpenACCSupport &accSupport) {
286 // Ensure the variable is an allowed type for data clause.
287 if (!acc::isPointerLikeType(val.getType()) &&
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 // Device data is a candidate - it will get a deviceptr clause.
298 return true;
299
300 // If it is otherwise valid, skip it.
301 if (accSupport.isValidValueUse(val, accRegion))
302 return false;
303
304 return true;
305}
306
307template <typename OpT>
308Operation *ACCImplicitData::getOriginalDataClauseOpForAlias(
309 Value var, OpBuilder &builder, OpT computeConstructOp,
310 const SmallVector<Value> &dominatingDataClauses) {
311 auto &aliasAnalysis = this->getAnalysis<AliasAnalysis>();
312 for (auto dataClause : dominatingDataClauses) {
313 if (auto *dataClauseOp = dataClause.getDefiningOp()) {
314 // Only accept clauses that guarantee that the alias is present.
315 if (isa<acc::CopyinOp, acc::CreateOp, acc::PresentOp, acc::NoCreateOp,
316 acc::DevicePtrOp>(dataClauseOp))
317 if (aliasAnalysis.alias(acc::getVar(dataClauseOp), var).isMust()) {
318 LLVM_DEBUG(llvm::dbgs()
319 << "Using existing data clause:\n\t" << *dataClauseOp
320 << "\n\tas reference when processing var:\n\t" << var
321 << "\n";);
322 return dataClauseOp;
323 }
324 }
325 }
326 return nullptr;
327}
328
329// Generates bounds for variables that have unknown dimensions
330static void fillInBoundsForUnknownDimensions(Operation *dataClauseOp,
331 OpBuilder &builder) {
332
333 if (!acc::getBounds(dataClauseOp).empty())
334 // If bounds are already present, do not overwrite them.
335 return;
336
337 // For types that have unknown dimensions, attempt to generate bounds by
338 // relying on MappableType being able to extract it from the IR.
339 auto var = acc::getVar(dataClauseOp);
340 auto type = var.getType();
341 if (auto mappableTy = dyn_cast<acc::MappableType>(type)) {
342 if (mappableTy.hasUnknownDimensions()) {
343 TypeSwitch<Operation *>(dataClauseOp)
344 .Case<ACC_DATA_ENTRY_OPS, ACC_DATA_EXIT_OPS>([&](auto dataClauseOp) {
345 if (std::is_same_v<decltype(dataClauseOp), acc::DevicePtrOp>)
346 return;
347 OpBuilder::InsertionGuard guard(builder);
348 builder.setInsertionPoint(dataClauseOp);
349 auto bounds = mappableTy.generateAccBounds(var, builder);
350 if (!bounds.empty())
351 dataClauseOp.getBoundsMutable().assign(bounds);
352 });
353 }
354 }
355}
356
357acc::PrivateRecipeOp
358ACCImplicitData::generatePrivateRecipe(ModuleOp &module, Value var,
359 Location loc, OpBuilder &builder,
360 acc::OpenACCSupport &accSupport) {
361 auto type = var.getType();
362 std::string recipeName =
363 accSupport.getRecipeName(acc::RecipeKind::private_recipe, type, var);
364
365 // Check if recipe already exists
366 auto existingRecipe = module.lookupSymbol<acc::PrivateRecipeOp>(recipeName);
367 if (existingRecipe)
368 return existingRecipe;
369
370 // Set insertion point to module body in a scoped way
371 OpBuilder::InsertionGuard guard(builder);
372 builder.setInsertionPointToStart(module.getBody());
373
374 auto recipe =
375 acc::PrivateRecipeOp::createAndPopulate(builder, loc, recipeName, var);
376 if (!recipe.has_value())
377 return accSupport.emitNYI(loc, "implicit private"), nullptr;
378 return recipe.value();
379}
380
381acc::FirstprivateRecipeOp
382ACCImplicitData::generateFirstprivateRecipe(ModuleOp &module, Value var,
383 Location loc, OpBuilder &builder,
384 acc::OpenACCSupport &accSupport) {
385 auto type = var.getType();
386 std::string recipeName =
387 accSupport.getRecipeName(acc::RecipeKind::firstprivate_recipe, type, var);
388
389 // Check if recipe already exists
390 auto existingRecipe =
391 module.lookupSymbol<acc::FirstprivateRecipeOp>(recipeName);
392 if (existingRecipe)
393 return existingRecipe;
394
395 // Set insertion point to module body in a scoped way
396 OpBuilder::InsertionGuard guard(builder);
397 builder.setInsertionPointToStart(module.getBody());
398
399 auto recipe = acc::FirstprivateRecipeOp::createAndPopulate(builder, loc,
400 recipeName, var);
401 if (!recipe.has_value())
402 return accSupport.emitNYI(loc, "implicit firstprivate"), nullptr;
403 return recipe.value();
404}
405
406void ACCImplicitData::generateRecipes(ModuleOp &module, OpBuilder &builder,
407 Operation *computeConstructOp,
408 const SmallVector<Value> &newOperands) {
409 auto &accSupport = this->getAnalysis<acc::OpenACCSupport>();
410 for (auto var : newOperands) {
411 auto loc{var.getLoc()};
412 if (auto privateOp = var.getDefiningOp<acc::PrivateOp>()) {
413 auto recipe = generatePrivateRecipe(
414 module, acc::getVar(var.getDefiningOp()), loc, builder, accSupport);
415 if (recipe)
416 privateOp.setRecipeAttr(
417 SymbolRefAttr::get(module->getContext(), recipe.getSymName()));
418 } else if (auto firstprivateOp = var.getDefiningOp<acc::FirstprivateOp>()) {
419 auto recipe = generateFirstprivateRecipe(
420 module, acc::getVar(var.getDefiningOp()), loc, builder, accSupport);
421 if (recipe)
422 firstprivateOp.setRecipeAttr(SymbolRefAttr::get(
423 module->getContext(), recipe.getSymName().str()));
424 } else {
425 accSupport.emitNYI(var.getLoc(), "implicit reduction");
426 }
427 }
428}
429
430// Generates the data entry data op clause so that it adheres to OpenACC
431// rules as follows (line numbers and specification from OpenACC 3.4):
432// 1388 An aggregate variable will be treated as if it appears either:
433// 1389 - In a present clause if there is a default(present) clause visible at
434// the compute construct.
435// 1391 - In a copy clause otherwise.
436// 1392 A scalar variable will be treated as if it appears either:
437// 1393 - In a copy clause if the compute construct is a kernels construct.
438// 1394 - In a firstprivate clause otherwise.
439template <typename OpT>
440Operation *ACCImplicitData::generateDataClauseOpForCandidate(
441 Value var, ModuleOp &module, OpBuilder &builder, OpT computeConstructOp,
442 const SmallVector<Value> &dominatingDataClauses,
443 const std::optional<acc::ClauseDefaultValue> &defaultClause) {
444 auto &accSupport = this->getAnalysis<acc::OpenACCSupport>();
445 acc::VariableTypeCategory typeCategory =
446 acc::VariableTypeCategory::uncategorized;
447 if (auto mappableTy = dyn_cast<acc::MappableType>(var.getType())) {
448 typeCategory = mappableTy.getTypeCategory(var);
449 } else if (auto pointerLikeTy =
450 dyn_cast<acc::PointerLikeType>(var.getType())) {
451 typeCategory = pointerLikeTy.getPointeeTypeCategory(
453 pointerLikeTy.getElementType());
454 }
455
456 bool isScalar =
457 acc::bitEnumContainsAny(typeCategory, acc::VariableTypeCategory::scalar);
458 bool isAnyAggregate = acc::bitEnumContainsAny(
459 typeCategory, acc::VariableTypeCategory::aggregate);
460 Location loc = computeConstructOp->getLoc();
461
462 // `deviceptr` asserts the value's storage is already in device memory; no
463 // runtime mapping or attach is performed. Storage that is device-accessible
464 // but physically shared with the host may migrate on demand, so it is not
465 // guaranteed to be in device memory and must still be mapped rather than
466 // treated as deviceptr.
468 // If the variable is in device memory, use deviceptr clause.
469 LLVM_DEBUG(llvm::dbgs() << "Using deviceptr clause because variable is "
470 "in device memory\n");
471 return acc::DevicePtrOp::create(builder, loc, var,
472 /*structured=*/true, /*implicit=*/true,
473 accSupport.getVariableName(var));
474 }
475
476 Operation *op = nullptr;
477 op = getOriginalDataClauseOpForAlias(var, builder, computeConstructOp,
478 dominatingDataClauses);
479 if (op) {
480 if (isa<acc::NoCreateOp>(op))
481 return acc::NoCreateOp::create(builder, loc, var,
482 /*structured=*/true, /*implicit=*/true,
483 accSupport.getVariableName(var),
484 acc::getBounds(op));
485
486 if (isa<acc::DevicePtrOp>(op))
487 return acc::DevicePtrOp::create(builder, loc, var,
488 /*structured=*/true, /*implicit=*/true,
489 accSupport.getVariableName(var),
490 acc::getBounds(op));
491
492 // The original data clause op is a PresentOp, CopyinOp, or CreateOp,
493 // hence guaranteed to be present.
494 return acc::PresentOp::create(builder, loc, var,
495 /*structured=*/true, /*implicit=*/true,
496 accSupport.getVariableName(var),
497 acc::getBounds(op));
498 }
499
500 if (isScalar) {
501 if (enableImplicitReductionCopy &&
503 computeConstructOp->getRegion(0))) {
504 auto copyinOp =
505 acc::CopyinOp::create(builder, loc, var,
506 /*structured=*/true, /*implicit=*/true,
507 accSupport.getVariableName(var));
508 copyinOp.setDataClause(acc::DataClause::acc_reduction);
509 return copyinOp.getOperation();
510 }
511 if constexpr (std::is_same_v<OpT, acc::KernelsOp>) {
512 // Scalars are implicit copyin in kernels construct.
513 auto copyinOp =
514 acc::CopyinOp::create(builder, loc, var,
515 /*structured=*/true, /*implicit=*/true,
516 accSupport.getVariableName(var));
517 copyinOp.setDataClause(acc::DataClause::acc_copy);
518 return copyinOp.getOperation();
519 } else {
520 // Scalars are implicit firstprivate in parallel and serial construct.
521 return acc::FirstprivateOp::create(builder, loc, var,
522 /*structured=*/true, /*implicit=*/true,
523 accSupport.getVariableName(var));
524 }
525 } else if (isAnyAggregate) {
526 Operation *newDataOp = nullptr;
527
528 // When default(present) is true, the implicit behavior is present.
529 if (defaultClause.has_value() &&
530 defaultClause.value() == acc::ClauseDefaultValue::Present) {
531 newDataOp = acc::PresentOp::create(builder, loc, var,
532 /*structured=*/true, /*implicit=*/true,
533 accSupport.getVariableName(var));
535 builder.getUnitAttr());
536 } else {
537 auto copyinOp =
538 acc::CopyinOp::create(builder, loc, var,
539 /*structured=*/true, /*implicit=*/true,
540 accSupport.getVariableName(var));
541 copyinOp.setDataClause(acc::DataClause::acc_copy);
542 newDataOp = copyinOp.getOperation();
543 }
544
545 return newDataOp;
546 } else {
547 // This is not a fatal error - for example when the element type is
548 // pointer type (aka we have a pointer of pointer), it is potentially a
549 // deep copy scenario which is not being handled here.
550 // Other types need to be canonicalized. Thus just log unhandled cases.
551 LLVM_DEBUG(llvm::dbgs()
552 << "Unhandled case for implicit data mapping " << var << "\n");
553 }
554 return nullptr;
555}
556
557// Ensures that result values from the acc data clause ops are used inside the
558// acc region. ie:
559// acc.kernels {
560// use %val
561// }
562// =>
563// %dev = acc.dataop %val
564// acc.kernels {
565// use %dev
566// }
567static void legalizeValuesInRegion(Region &accRegion,
568 SmallVector<Value> &newPrivateOperands,
569 SmallVector<Value> &newDataClauseOperands) {
570 for (Value dataClause :
571 llvm::concat<Value>(newDataClauseOperands, newPrivateOperands)) {
572 Value var = acc::getVar(dataClause.getDefiningOp());
573 replaceAllUsesInRegionWith(var, dataClause, accRegion);
574 }
575}
576
577// Adds the private operands to the compute construct operation.
578template <typename OpT>
579static void addNewPrivateOperands(OpT &accOp,
580 const SmallVector<Value> &privateOperands) {
581 if (privateOperands.empty())
582 return;
583
584 for (auto priv : privateOperands) {
585 if (isa<acc::PrivateOp>(priv.getDefiningOp())) {
586 accOp.getPrivateOperandsMutable().append(priv);
587 } else if (isa<acc::FirstprivateOp>(priv.getDefiningOp())) {
588 accOp.getFirstprivateOperandsMutable().append(priv);
589 } else {
590 llvm_unreachable("unhandled reduction operand");
591 }
592 }
593}
594
595static Operation *findDataExitOp(Operation *dataEntryOp) {
596 auto res = acc::getAccVar(dataEntryOp);
597 for (auto *user : res.getUsers())
598 if (isa<ACC_DATA_EXIT_OPS>(user))
599 return user;
600 return nullptr;
601}
602
603// Generates matching data exit operation as described in the acc dialect
604// for how data clauses are decomposed:
605// https://mlir.llvm.org/docs/Dialects/OpenACCDialect/#operation-categories
606// Key ones used here:
607// * acc {construct} copy -> acc.copyin (before region) + acc.copyout (after
608// region)
609// * acc {construct} present -> acc.present (before region) + acc.delete
610// (after region)
611static void
612generateDataExitOperations(OpBuilder &builder, Operation *accOp,
613 const SmallVector<Value> &newDataClauseOperands,
614 const SmallVector<Value> &sortedDataClauseOperands) {
615 builder.setInsertionPointAfter(accOp);
616 Value lastDataClause = nullptr;
617 for (auto dataEntry : llvm::reverse(sortedDataClauseOperands)) {
618 if (llvm::find(newDataClauseOperands, dataEntry) ==
619 newDataClauseOperands.end()) {
620 // If this is not a new data clause operand, we should not generate an
621 // exit operation for it.
622 lastDataClause = dataEntry;
623 continue;
624 }
625 if (lastDataClause)
626 if (auto *dataExitOp = findDataExitOp(lastDataClause.getDefiningOp()))
627 builder.setInsertionPointAfter(dataExitOp);
628 Operation *dataEntryOp = dataEntry.getDefiningOp();
629 if (isa<acc::CopyinOp>(dataEntryOp)) {
630 auto copyoutOp = acc::CopyoutOp::create(
631 builder, dataEntryOp->getLoc(), dataEntry, acc::getVar(dataEntryOp),
632 /*structured=*/true, /*implicit=*/true,
633 acc::getVarName(dataEntryOp).value(), acc::getBounds(dataEntryOp));
634 copyoutOp.setDataClause(acc::DataClause::acc_copy);
635 } else if (isa<acc::PresentOp, acc::NoCreateOp>(dataEntryOp)) {
636 auto deleteOp = acc::DeleteOp::create(
637 builder, dataEntryOp->getLoc(), dataEntry,
638 /*structured=*/true, /*implicit=*/true,
639 acc::getVarName(dataEntryOp).value(), acc::getBounds(dataEntryOp));
640 deleteOp.setDataClause(acc::getDataClause(dataEntryOp).value());
641 } else if (isa<acc::DevicePtrOp>(dataEntryOp)) {
642 // Do nothing.
643 } else {
644 llvm_unreachable("unhandled data exit");
645 }
646 lastDataClause = dataEntry;
647 }
648}
649
650/// Returns all base references of a value in order.
651/// So for example, if we have a reference to a struct field like
652/// s.f1.f2.f3, this will return <s, s.f1, s.f1.f2, s.f1.f2.f3>.
653/// Any intermediate casts/view-like operations are included in the
654/// chain as well.
655static SmallVector<Value> getBaseRefsChain(Value val) {
656 SmallVector<Value> baseRefs;
657 baseRefs.push_back(val);
658 while (true) {
659 Value prevVal = val;
660
661 val = acc::getBaseEntity(val);
662 if (val != baseRefs.front())
663 baseRefs.insert(baseRefs.begin(), val);
664
665 // If this is a view-like operation, it is effectively another
666 // view of the same entity so we should add it to the chain also.
667 if (auto viewLikeOp = val.getDefiningOp<ViewLikeOpInterface>()) {
668 val = viewLikeOp.getViewSource();
669 baseRefs.insert(baseRefs.begin(), val);
670 }
671
672 // Continue loop if we made any progress
673 if (val == prevVal)
674 break;
675 }
676
677 return baseRefs;
678}
679
680static void insertInSortedOrder(SmallVector<Value> &sortedDataClauseOperands,
681 Operation *newClause) {
682 auto *insertPos =
683 std::find_if(sortedDataClauseOperands.begin(),
684 sortedDataClauseOperands.end(), [&](Value dataClauseVal) {
685 // Get the base refs for the current clause we are looking
686 // at.
687 auto var = acc::getVar(dataClauseVal.getDefiningOp());
688 auto baseRefs = getBaseRefsChain(var);
689
690 // If the newClause is of a base ref of an existing clause,
691 // we should insert it right before the current clause.
692 // Thus return true to stop iteration when this is the
693 // case.
694 return std::find(baseRefs.begin(), baseRefs.end(),
695 acc::getVar(newClause)) != baseRefs.end();
696 });
697
698 if (insertPos != sortedDataClauseOperands.end()) {
699 newClause->moveBefore(insertPos->getDefiningOp());
700 sortedDataClauseOperands.insert(insertPos, acc::getAccVar(newClause));
701 } else {
702 sortedDataClauseOperands.push_back(acc::getAccVar(newClause));
703 }
704}
705
706template <typename OpT>
707void ACCImplicitData::generateImplicitDataOps(
708 ModuleOp &module, OpT computeConstructOp,
709 std::optional<acc::ClauseDefaultValue> &defaultClause,
710 acc::OpenACCSupport &accSupport) {
711 // Implicit data attributes are only applied if "[t]here is no default(none)
712 // clause visible at the compute construct", unless ignoreDefaultNone is set.
713 if (!ignoreDefaultNone && defaultClause.has_value() &&
714 defaultClause.value() == acc::ClauseDefaultValue::None)
715 return;
716 assert(!defaultClause.has_value() ||
717 defaultClause.value() == acc::ClauseDefaultValue::Present ||
718 (ignoreDefaultNone &&
719 defaultClause.value() == acc::ClauseDefaultValue::None));
720
721 // 1) Collect live-in values.
722 Region &accRegion = computeConstructOp->getRegion(0);
723 SetVector<Value> liveInValues;
724 getUsedValuesDefinedAbove(accRegion, liveInValues);
725
726 // 2) Run the filtering to find relevant pointers that need copied.
727 auto isCandidate{[&](Value val) -> bool {
728 return isCandidateForImplicitData(val, accRegion, accSupport);
729 }};
730 auto candidateVars(llvm::filter_to_vector(liveInValues, isCandidate));
731 if (candidateVars.empty())
732 return;
733
734 // 3) Generate data clauses for the variables.
735 SmallVector<Value> newPrivateOperands;
736 SmallVector<Value> newDataClauseOperands;
737 OpBuilder builder(computeConstructOp);
738 if (!candidateVars.empty()) {
739 LLVM_DEBUG(llvm::dbgs() << "== Generating clauses for ==\n"
740 << computeConstructOp << "\n");
741 }
742 auto &domInfo = this->getAnalysis<DominanceInfo>();
743 auto &postDomInfo = this->getAnalysis<PostDominanceInfo>();
744 auto dominatingDataClauses =
745 acc::getDominatingDataClauses(computeConstructOp, domInfo, postDomInfo);
746 for (auto var : candidateVars) {
747 auto newDataClauseOp = generateDataClauseOpForCandidate(
748 var, module, builder, computeConstructOp, dominatingDataClauses,
749 defaultClause);
750 fillInBoundsForUnknownDimensions(newDataClauseOp, builder);
751 LLVM_DEBUG(llvm::dbgs() << "Generated data clause for " << var << ":\n"
752 << "\t" << *newDataClauseOp << "\n");
753 if (isa_and_nonnull<acc::PrivateOp, acc::FirstprivateOp, acc::ReductionOp>(
754 newDataClauseOp)) {
755 newPrivateOperands.push_back(acc::getAccVar(newDataClauseOp));
756 } else if (isa_and_nonnull<ACC_DATA_CLAUSE_OPS>(newDataClauseOp)) {
757 newDataClauseOperands.push_back(acc::getAccVar(newDataClauseOp));
758 dominatingDataClauses.push_back(acc::getAccVar(newDataClauseOp));
759 }
760 }
761
762 // 4) Legalize values in region (aka the uses in the region are the result
763 // of the data clause ops)
764 legalizeValuesInRegion(accRegion, newPrivateOperands, newDataClauseOperands);
765
766 // 5) Generate private recipes which are required for properly attaching
767 // private operands.
768 if constexpr (!std::is_same_v<OpT, acc::KernelsOp>)
769 generateRecipes(module, builder, computeConstructOp, newPrivateOperands);
770
771 // 6) Figure out insertion order for the new data clause operands.
772 SmallVector<Value> sortedDataClauseOperands(
773 computeConstructOp.getDataClauseOperands());
774 for (auto newClause : newDataClauseOperands)
775 insertInSortedOrder(sortedDataClauseOperands, newClause.getDefiningOp());
776
777 // 7) Generate the data exit operations.
778 generateDataExitOperations(builder, computeConstructOp, newDataClauseOperands,
779 sortedDataClauseOperands);
780 // 8) Add all of the new operands to the compute construct op.
781 if constexpr (!std::is_same_v<OpT, acc::KernelsOp>)
782 addNewPrivateOperands(computeConstructOp, newPrivateOperands);
783 computeConstructOp.getDataClauseOperandsMutable().assign(
784 sortedDataClauseOperands);
785}
786
787void ACCImplicitData::runOnOperation() {
788 ModuleOp module = this->getOperation();
789
790 acc::OpenACCSupport &accSupport = getAnalysis<acc::OpenACCSupport>();
791
792 module.walk([&](Operation *op) {
793 if (isa<ACC_COMPUTE_CONSTRUCT_OPS>(op)) {
794 assert(op->getNumRegions() == 1 && "must have 1 region");
795
796 auto defaultClause = acc::getDefaultAttr(op);
798 .Case<ACC_COMPUTE_CONSTRUCT_OPS>([&](auto op) {
799 generateImplicitDataOps(module, op, defaultClause, accSupport);
800 })
801 .Default([&](Operation *) {});
802 }
803 });
804}
805
806} // namespace
UnitAttr getUnitAttr()
Definition Builders.cpp:106
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:351
This class helps build Operations.
Definition Builders.h:210
void setInsertionPointToStart(Block *block)
Sets the insertion point to the start of the specified block.
Definition Builders.h:434
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
void setInsertionPointAfter(Operation *op)
Sets the insertion point to the node after the specified operation, which will cause subsequent inser...
Definition Builders.h:415
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
void setDiscardableAttr(StringAttr name, Attribute value)
Set a discardable attribute by name.
Definition Operation.h:512
Location getLoc()
The source location the operation was defined or derived from.
Definition Operation.h:240
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
std::string getVariableName(Value v, VariableNameConfig config={})
Get the variable name for a given value.
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 getRecipeName(RecipeKind kind, Type type, Value var)
Get the recipe name for a given type and value.
#define ACC_COMPUTE_CONSTRUCT_OPS
Definition OpenACC.h:64
#define ACC_DATA_ENTRY_OPS
Definition OpenACC.h:50
#define ACC_DATA_EXIT_OPS
Definition OpenACC.h:60
static constexpr StringLiteral getFromDefaultClauseAttrName()
Definition OpenACC.h:225
mlir::Value getAccVar(mlir::Operation *accDataClauseOp)
Used to obtain the accVar from a data clause operation.
Definition OpenACC.cpp:5435
mlir::Value getVar(mlir::Operation *accDataClauseOp)
Used to obtain the var from a data clause operation.
Definition OpenACC.cpp:5403
std::optional< mlir::acc::DataClause > getDataClause(mlir::Operation *accDataEntryOp)
Used to obtain the dataClause from a data entry operation.
Definition OpenACC.cpp:5522
bool isPointerLikeType(mlir::Type type)
Used to check whether the provided type implements the PointerLikeType interface.
Definition OpenACC.h:185
mlir::SmallVector< mlir::Value > getBounds(mlir::Operation *accDataClauseOp)
Used to obtain bounds from an acc data clause operation.
Definition OpenACC.cpp:5454
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:5510
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:191
bool isDeviceAccessibleValue(mlir::Value val)
Check if a value represents device data.
bool isInDeviceMemoryValue(mlir::Value val)
Check if a value is backed by memory that is residing in the current device, and therefore requires n...
mlir::Value getBaseEntity(mlir::Value val)
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:128
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:494
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:147