26#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/SmallVectorExtras.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/raw_ostream.h"
33#define DEBUG_TYPE "acc-data-runtime"
39 ConversionPatternRewriter &rewriter) {
40 Type ptrTy = LLVM::LLVMPointerType::get(rewriter.getContext());
42 return LLVM::ZeroOp::create(rewriter, loc, ptrTy);
46 if (isa<PointerLikeType>(value.
getType()))
49 Value one = LLVM::ConstantOp::create(rewriter, loc, rewriter.getI32Type(), 1);
51 LLVM::AllocaOp::create(rewriter, loc, ptrTy, value.
getType(), one);
52 LLVM::StoreOp::create(rewriter, loc, value, storage);
59 ConversionPatternRewriter &rewriter) {
60 Type ptrTy = LLVM::LLVMPointerType::get(rewriter.getContext());
61 Value one = LLVM::ConstantOp::create(rewriter, loc, rewriter.getI32Type(), 1);
63 LLVM::AllocaOp::create(rewriter, loc, ptrTy, value.
getType(), one);
64 LLVM::StoreOp::create(rewriter, loc, value, storage);
72 Value count = LLVM::ConstantOp::create(rewriter, loc, i32Ty, values.size());
74 LLVM::AllocaOp::create(rewriter, loc, ptrTy, elementType, count);
75 for (
auto [
index, value] : llvm::enumerate(values)) {
76 Value indexValue = LLVM::ConstantOp::create(rewriter, loc, i32Ty,
index);
77 Value element = LLVM::GEPOp::create(rewriter, loc, ptrTy, elementType,
79 LLVM::StoreOp::create(rewriter, loc, value, element);
101 LLVM::ConstantOp::create(rewriter, loc, i32Ty, objects.size());
108 runtimeArgs.
argMappers = LLVM::ZeroOp::create(rewriter, loc, ptrTy);
118 Value converted, MapFlags mapFlags,
119 ConversionPatternRewriter &rewriter) {
120 Type ptrTy = LLVM::LLVMPointerType::get(rewriter.getContext());
121 if (isa<PrivateType>(operand.
getType()))
122 return LLVM::ZeroOp::create(rewriter, loc, ptrTy);
123 if (converted && converted.
getType() == ptrTy &&
124 (bitEnumContainsAny(mapFlags, MapFlags::devptr) ||
133 ConversionPatternRewriter &rewriter) {
138 else if (bitEnumContainsAny(mapFlags, MapFlags::ptr_and_obj))
146 Region &globalSymbolRegion,
148 ConversionPatternRewriter &rewriter) {
156 return LLVM::ZeroOp::create(
157 rewriter, loc, LLVM::LLVMPointerType::get(rewriter.getContext()));
160 globalSymbolRegion, symbolTable);
164 if (
auto mapInfo = dyn_cast<MapInfoOp>(mapOp))
165 return mapInfo.getMapFlags();
166 if (isa<ACC_DATA_ENTRY_OPS>(mapOp))
174 ConversionPatternRewriter &rewriter) {
175 Operation *scope = rewriter.getInsertionBlock()->getParentOp();
176 auto module = dyn_cast<ModuleOp>(scope);
178 module = scope->getParentOfType<ModuleOp>();
182 if (bitEnumContainsAny(mapFlags, MapFlags::literal) && converted) {
183 auto sizeAndAlignment =
185 if (!sizeAndAlignment) {
187 llvm::raw_string_ostream os(message);
188 os <<
"unhandled type size computation for type: " << converted.
getType();
192 return constantI64(loc, sizeAndAlignment->first.getFixedValue(), rewriter);
208 if (isa<MemRefType>(var.
getType()) || isa<MemRefType>(varType))
218 return constantI64(loc, std::max<int64_t>(size, 0), rewriter);
222 ConversionPatternRewriter &rewriter) {
229 if (
auto shaped = dyn_cast<ShapedType>(type))
230 type = shaped.getElementType();
233 if (
auto sizeAndAlignment =
235 return constantI64(loc, sizeAndAlignment->first.getFixedValue(), rewriter);
240 ConversionPatternRewriter &rewriter) {
247 Type baseDescriptorType, uint32_t version,
249 ConversionPatternRewriter &rewriter) {
251 Type i8Ty = rewriter.getI8Type();
252 Type i32Ty = rewriter.getI32Type();
253 Type i64Ty = rewriter.getI64Type();
254 Type ptrTy = LLVM::LLVMPointerType::get(context);
256 Value versionValue = LLVM::ConstantOp::create(
257 rewriter, loc, i32Ty,
258 version |
static_cast<uint32_t
>(
260 baseDescriptor = LLVM::InsertValueOp::create(
261 rewriter, loc, baseDescriptorType, baseDescriptor, versionValue,
265 context, DataDescriptor::AccDataDescOpenACC, baseDescriptorType);
266 Value descriptor = LLVM::ZeroOp::create(rewriter, loc, descriptorType);
267 Value rank = LLVM::ConstantOp::create(rewriter, loc, i8Ty, bounds.size());
274 for (
Value boundValue : bounds) {
275 auto bound = cast<DataBoundsOp>(boundValue.getDefiningOp());
276 lowerBounds.push_back(
277 getBoundValue(bound.getLowerbound(), bound.getLoc(), rewriter));
278 upperBounds.push_back(
279 getBoundValue(bound.getUpperbound(), bound.getLoc(), rewriter));
281 bound.getSourceExtent() ? bound.getSourceExtent() : bound.getExtent();
284 if (!bound.getStrideInBytes())
286 LLVM::MulOp::create(rewriter, bound.getLoc(), stride, elementSize);
287 strides.push_back(stride);
289 getBoundValue(bound.getStartIdx(), bound.getLoc(), rewriter));
292 Value lowerBoundsArray =
294 Value upperBoundsArray =
300 using Field = AccDataDescOpenACCField;
301 auto insert = [&](
Value value, Field field) {
302 descriptor = LLVM::InsertValueOp::create(
303 rewriter, loc, descriptorType, descriptor, value,
306 insert(baseDescriptor, Field::Base);
307 insert(rank, Field::Rank);
308 insert(elementSize, Field::ElementSize);
309 insert(lowerBoundsArray, Field::LowerBounds);
310 insert(upperBoundsArray, Field::UpperBounds);
311 insert(extentsArray, Field::Extents);
312 insert(stridesArray, Field::StridesInBytes);
313 insert(startsArray, Field::StartIndices);
315 Value one = LLVM::ConstantOp::create(rewriter, loc, i32Ty, 1);
317 LLVM::AllocaOp::create(rewriter, loc, ptrTy, descriptorType, one);
318 LLVM::StoreOp::create(rewriter, loc, descriptor, storage);
324 ValueRange bounds,
Value elementSize, ConversionPatternRewriter &rewriter) {
326 Type i8Ty = rewriter.getI8Type();
327 Type i32Ty = rewriter.getI32Type();
328 Type ptrTy = LLVM::LLVMPointerType::get(context);
329 using Field = AccDataDescMemRefField;
330 Type descriptorType =
332 auto version =
static_cast<uint32_t
>(
334 Value descriptor = LLVM::ZeroOp::create(rewriter, loc, descriptorType);
336 LLVM::ConstantOp::create(rewriter, loc, i8Ty, memrefType.getRank());
337 auto insert = [&](
Value value, Field field) {
338 descriptor = LLVM::InsertValueOp::create(
339 rewriter, loc, descriptorType, descriptor, value,
342 insert(rank, Field::Rank);
343 insert(elementSize, Field::ElementSize);
344 insert(
getPointer(loc, convertedMemref, rewriter), Field::MemRefDescriptor);
347 bounds, elementSize, rewriter);
349 insert(LLVM::ConstantOp::create(rewriter, loc, i32Ty, version),
351 Value one = LLVM::ConstantOp::create(rewriter, loc, i32Ty, 1);
353 LLVM::AllocaOp::create(rewriter, loc, ptrTy, descriptorType, one);
354 LLVM::StoreOp::create(rewriter, loc, descriptor, storage);
359 Value convertedOperand,
361 ConversionPatternRewriter &rewriter) {
364 Type i32Ty = rewriter.getI32Type();
365 Type ptrTy = LLVM::LLVMPointerType::get(context);
371 auto elementSize = [&] {
376 if (var && isa<MemRefType>(var.
getType())) {
377 auto memrefType = cast<MemRefType>(var.
getType());
379 loc, memrefType, convertedOperand, bounds, elementSize(), rewriter);
382 if (bitEnumContainsAny(descKind, DataDescKind::cfi)) {
383 using Field = AccDataDescCFIField;
384 Type descriptorType =
386 auto version =
static_cast<uint32_t
>(
388 Value descriptor = LLVM::ZeroOp::create(rewriter, loc, descriptorType);
390 if (!descriptorStorage)
391 descriptorStorage = convertedOperand;
392 descriptor = LLVM::InsertValueOp::create(
393 rewriter, loc, descriptorType, descriptor,
398 bounds, elementSize(), rewriter);
401 LLVM::ConstantOp::create(rewriter, loc, i32Ty, version);
402 descriptor = LLVM::InsertValueOp::create(
403 rewriter, loc, descriptorType, descriptor, versionValue,
405 Value one = LLVM::ConstantOp::create(rewriter, loc, i32Ty, 1);
407 LLVM::AllocaOp::create(rewriter, loc, ptrTy, descriptorType, one);
408 LLVM::StoreOp::create(rewriter, loc, descriptor, storage);
412 if (!bounds.empty()) {
413 Type descriptorType =
415 auto version =
static_cast<uint32_t
>(
417 Value descriptor = LLVM::ZeroOp::create(rewriter, loc, descriptorType);
419 bounds, elementSize(), rewriter);
421 return LLVM::ZeroOp::create(rewriter, loc, ptrTy);
431 ConversionPatternRewriter &rewriter,
Region &globalSymbolRegion,
435 if (mappingOperands.size() != convertedOperands.size())
440 globalSymbolRegion, config, symbolTable);
444 runtimeArgs.
argMappers = LLVM::ZeroOp::create(
445 rewriter, loc, LLVM::LLVMPointerType::get(rewriter.getContext()));
451 struct MappedObject {
457 for (
auto [operand, converted] :
458 llvm::zip_equal(mappingOperands, convertedOperands)) {
459 auto structType = dyn_cast<LLVM::LLVMStructType>(converted.
getType());
460 if (structType && !structType.isIdentified() &&
461 structType.getBody().size() > 1) {
462 for (
unsigned field = 0, fields = structType.getBody().size();
463 field != fields; ++field)
464 mappedObjects.push_back(
466 LLVM::ExtractValueOp::create(rewriter, loc, converted, field),
470 mappedObjects.push_back({operand, converted,
true});
475 runtimeArgs.
argNum = LLVM::ConstantOp::create(
476 rewriter, loc, rewriter.getI32Type(), mappedObjects.size());
478 constexpr unsigned noSlot = ~0u;
482 for (
auto [slot,
object] : llvm::enumerate(mappedObjects)) {
483 auto [operand, converted, firstField] = object;
491 LLVM_DEBUG(llvm::dbgs() <<
"mapping " << *mapOp <<
"\n as "
497 *mapFlags, rewriter);
501 bitEnumContainsAny(*mapFlags, MapFlags::device_resident)
509 bitEnumContainsAny(*mapFlags, MapFlags::device_resident)) {
512 !isa_and_nonnull<AddressOfGlobalOpInterface>(var.
getDefiningOp()))
513 *mapFlags = *mapFlags | MapFlags::delete_;
517 for (
auto [
index, returned] :
518 llvm::enumerate(
options.returnAddressOperands)) {
519 if (returned != operand)
521 *mapFlags = *mapFlags | MapFlags::return_param;
528 mapLoc, operand, converted, *mapFlags, accSupport, rewriter);
534 mapLoc, operand, accSupport, globalSymbolRegion, symbolTable, rewriter);
537 objects.push_back(args);
548 ValueRange convertedOperands, ConversionPatternRewriter &rewriter,
553 if (mappingOperands.empty())
554 return returnedAddresses;
558 loc, mappingOperands, convertedOperands, rewriter, globalSymbolRegion,
559 accSupport, config, runtimeArgs,
options, &symbolTable)))
560 return rewriter.notifyMatchFailure(
561 mappingOperands.front().getDefiningOp(),
562 "unsupported OpenACC data-clause operand");
565 arguments.append(trailingArguments.begin(), trailingArguments.end());
567 fn, config, arguments)))
570 Type i32Ty = rewriter.getI32Type();
571 Type ptrTy = LLVM::LLVMPointerType::get(rewriter.getContext());
573 Value index = LLVM::ConstantOp::create(rewriter, loc, i32Ty, slot);
575 LLVM::GEPOp::create(rewriter, loc, ptrTy, ptrTy,
577 returnedAddresses.push_back(
578 LLVM::LoadOp::create(rewriter, loc, ptrTy, element));
580 return returnedAddresses;
static std::optional< MapFlags > computePackedMapFlags(Operation *mapOp)
static Value getBoundValue(Value value, Location loc, ConversionPatternRewriter &rewriter)
static Value getElementSize(Operation *mapOp, OpenACCSupport &accSupport, ConversionPatternRewriter &rewriter)
static Value getPointer(Location loc, Value value, ConversionPatternRewriter &rewriter)
static Value getIndirectPointer(Location loc, Value value, ConversionPatternRewriter &rewriter)
Returns the address of a slot holding value, so that the runtime reads the value from memory rather t...
static llvm::ManagedStatic< PassManagerOptions > options
MLIRContext * getContext() const
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
Operation is the basic unit of execution within MLIR.
Location getLoc()
The source location the operation was defined or derived from.
OpTy getParentOfType()
Return the closest surrounding parent operation that is of type 'OpTy'.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
This class coordinates the application of a rewrite on a set of IR, providing a way for clients to tr...
This class allows for representing and managing the symbol table used by operations with the 'SymbolT...
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...
Type getType() const
Return the type of this value.
Location getLoc() const
Return the location of this value.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Configuration for OpenACC to LLVM runtime lowering.
std::string formatMapFlags(MapFlags flags) const
Renders flags for a diagnostic as the names of the set bits and the decimal and hexadecimal encoding ...
int64_t getDeviceTypeRuntimeValue(DeviceType type) const
int64_t getMapFlagsRuntimeValue(MapFlags flags) const
MapFlags postProcessMapFlags(Operation *mapOp, MapFlags flags) const
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.
std::optional< int64_t > getMapElementSize(Operation *mapEntryOp)
Returns element size in bytes from acc.map_info, if present.
mlir::Value getVar(mlir::Operation *accDataClauseOp)
Used to obtain the var from a data clause operation.
MapFlags computeDataClauseMapFlags(Operation *entryOp, bool ptrAndObj)
Fold enter (+ paired exit) data-clause semantics into offload map flags.
mlir::SmallVector< mlir::Value > getBounds(mlir::Operation *accDataClauseOp)
Used to obtain bounds from an acc data clause operation.
LLVM::LLVMStructType getDataDescriptorType(MLIRContext *ctx, DataDescriptor desc, Type baseType={})
Builds the LLVM type of desc in ctx.
Value getMapSize(Operation *mapEntryOp)
Returns the optional size operand from acc.map_info, or null.
DataDescKind getDataDescriptorKind(DataDescriptor desc)
Returns the descriptor kind the runtime reads from the version field of desc.
bool isDataEntryOp(mlir::Operation *op)
Used to find out whether op is a data entry operation or an acc.map_info.
Value createIdent(Location loc, StringRef functionName, OpBuilder &builder, Region &globalSymbolRegion, const ACCRuntimeCallConfig &config, SymbolTable *symbolTable=nullptr)
Returns a pointer to a constant global holding an ident_t for OpenACC runtime calls.
Value castPointerLikeTypeIfNeeded(OpBuilder &builder, Location loc, Value value, Type resultType)
Cast value to resultType via PointerLikeType::genCast when needed.
DataDescKind getDataDescKind(Operation *mapEntryOp)
Returns descriptor kind from acc.map_info, or none for other ops.
Value remapOrSelf(Value value, ConversionPatternRewriter &rewriter)
Returns the value value was converted to, or value itself when the conversion left it as it was.
RuntimeFunction
IDs for OpenACC compiler-to-runtime entry points (__tgt_acc_*).
Value getDesc(Operation *mapEntryOp)
Returns descriptor value from acc.map_info.
Value constantI64(Location loc, int64_t value, OpBuilder &builder)
Creates an i64 constant.
mlir::Value getVarPtrPtr(mlir::Operation *accDataClauseOp)
Used to obtain the varPtrPtr from a data clause operation.
std::string getInternalGlobalName(StringRef kind, StringRef detail)
Returns the name to give a global that the conversion creates to hold detail of kind,...
StringRef getParentFunctionName(Operation *op)
Returns the symbol name of the function op belongs to, or of op itself when it is a function.
int64_t getDataDescriptorFieldIndex(FieldEnum field)
The index an insert or extract of field addresses.
Value castToI64(Location loc, Value value, OpBuilder &builder)
Sign-extends or truncates value to the i64 the runtime entry points take for values like queue number...
mlir::Type getVarType(mlir::Operation *accDataClauseOp)
Used to obtains the varType from a data clause operation which records the type of variable.
Value getOrCreateGlobalString(Location loc, OpBuilder &builder, StringRef name, StringRef value, Region &globalSymbolRegion, SymbolTable *symbolTable=nullptr)
Creates or reuses a null-terminated string global in globalSymbolRegion.
bool isDeviceAccessibleValue(mlir::Value val, mlir::SymbolTableCollection *symbolTables=nullptr)
Check if a value represents device data.
int64_t computeMapInfoSizeBytes(Value var, Type varType, DataDescKind descKind, ValueRange bounds, const DataLayout &dataLayout, OpenACCSupport *support=nullptr)
Compute total mapped byte size for acc.map_info.
bool hasAttachPoint(Operation *mapEntryOp)
Returns true when mapEntryOp carries an attach point (varPtrPtr).
FailureOr< LLVM::CallOp > createRuntimeCall(Location loc, OpBuilder &builder, Region &globalSymbolRegion, SymbolTable &symbolTable, RuntimeFunction fn, const ACCRuntimeCallConfig &config, ArrayRef< Value > arguments)
Declares (if needed) and returns a call to the runtime function identified by fn using the name from ...
std::optional< TypeSizeAndAlignment > getTypeSizeAndAlignment(Type ty, ModuleOp module, const DataLayout &dl, OpenACCSupport *support=nullptr, Value var={})
Returns the size and ABI alignment in bytes.
Include the generated interface declarations.
Value createACCDataArray(Location loc, Type elementType, ArrayRef< Value > values, RewriterBase &rewriter)
Materialize values as a stack-allocated LLVM array.
Value createACCDataDescriptor(Location loc, Value baseDescriptor, Type baseDescriptorType, uint32_t version, ValueRange bounds, Value elementSize, ConversionPatternRewriter &rewriter)
Wrap baseDescriptor in the OpenACC overlay that carries bounds.
Value createACCMappedObjectName(Location loc, Value operand, acc::OpenACCSupport &accSupport, Region &globalSymbolRegion, SymbolTable *symbolTable, ConversionPatternRewriter &rewriter)
The name of operand for runtime diagnostics, or a null pointer when it has none.
void createACCMappedObjectArrays(Location loc, ArrayRef< ACCMappedObjectArgs > objects, ACCDataRuntimeArgs &runtimeArgs, RewriterBase &rewriter)
Materialize the argument arrays of objects into the argNum through argDescs fields of runtimeArgs.
LogicalResult emitACCDataRuntimeArgs(Location loc, ValueRange mappingOperands, ValueRange convertedOperands, ConversionPatternRewriter &rewriter, Region &globalSymbolRegion, acc::OpenACCSupport &accSupport, const acc::ACCRuntimeCallConfig &config, ACCDataRuntimeArgs &runtimeArgs, const ACCDataCallOptions &options={}, SymbolTable *symbolTable=nullptr)
Emit the OpenACC data runtime arguments for data-clause operands.
FailureOr< SmallVector< Value > > emitACCDataRuntimeCall(Location loc, acc::RuntimeFunction fn, ValueRange mappingOperands, ValueRange convertedOperands, ConversionPatternRewriter &rewriter, acc::OpenACCSupport &accSupport, Region &globalSymbolRegion, SymbolTable &symbolTable, const acc::ACCRuntimeCallConfig &config, ArrayRef< Value > trailingArguments, const ACCDataCallOptions &options={})
Emit the call to the mapping entry point fn for mappingOperands, followed by trailingArguments.
FailureOr< Value > createACCMappedObjectSize(Location loc, Value operand, Value converted, acc::MapFlags mapFlags, acc::OpenACCSupport &accSupport, ConversionPatternRewriter &rewriter)
The size in bytes of operand, or zero where its descriptor or bounds state the extent instead.
Value createACCMappedObjectBase(Location loc, Operation *mapOp, acc::MapFlags mapFlags, ConversionPatternRewriter &rewriter)
The host pointer slot the object mapOp maps is attached to, or a null pointer when it is not attached...
Value createACCArgumentDescriptor(Operation *mapOp, Value convertedOperand, acc::OpenACCSupport &accSupport, ConversionPatternRewriter &rewriter)
Build the runtime argument descriptor for mapOp, or a null pointer when the mapping needs no descript...
Value createACCMappedObjectPointer(Location loc, Value operand, Value converted, acc::MapFlags mapFlags, ConversionPatternRewriter &rewriter)
The address of operand as the runtime expects to receive it, given its type converted value converted...
Value createACCMemRefDescriptorWrapperArg(Location loc, MemRefType memrefType, Value convertedMemref, ValueRange bounds, Value elementSize, ConversionPatternRewriter &rewriter)
Build the runtime argument descriptor wrapping an already converted memref.
What a data runtime call is asked for besides mapping its operands.
The arguments every mapping entry point of the OpenACC runtime takes, in the order they are passed.
Value argNames
Array of variable names for runtime diagnostics, null where unknown.
Value deviceType
Device type the directive applies to, in the runtime encoding.
Value argSizes
Array of object sizes in bytes; zero where the descriptor or the bounds state the extent instead.
Value argMappers
Array of user-defined mappers. OpenACC has none, so this is always null.
Value ident
Source position and enclosing function name of the directive.
Value argTypes
Array of map-type flags, in the runtime encoding of acc::MapFlags.
SmallVector< Value > getCallArgs() const
Returns the fields above in the order the entry points take them, so that a caller only appends the a...
SmallVector< unsigned > returnAddressSlots
The argBasePtrs slot the entry point writes the device address of each requested operand into,...
Value argBasePtrs
Array of pointer slots to attach a mapped object to, null when the object is not attached to anything...
Value argNum
Number of mapped objects, that is, the length of each array below.
Value argDescs
Array of descriptors stating layout and bounds, null for whole objects of a known size.
Value flags
Region flags, in the encoding of ACCDataRegionFlags.
Value argPtrs
Array of addresses of the mapped objects themselves.
The values that describe one object to the runtime, one for each argument array.
How the name of a variable is to be rendered.
bool preferDemangledName
Render the name the source language spells, which is the name a message to the user states.