[clang] [CIR][OpenACC] Implement the PointerLikeType APIs for known-size objects (PR #244703)
Razvan Lupusoru via cfe-commits
cfe-commits at lists.llvm.org
Fri Dec 4 08:49:51 PST 2026
https://github.com/razvanlupusoru updated https://github.com/llvm/llvm-project/pull/244703
>From 19d9e3eb090dd07710e91e572e43dd866dcbe1a6 Mon Sep 17 00:00:00 2001
From: Razvan Lupusoru <rlupusoru at nvidia.com>
Date: Fri, 20 Nov 2026 12:02:00 -0800
Subject: [PATCH 1/3] [CIR][OpenACC] Implement the PointerLikeType APIs for
known-size objects
This is an initial implementation of every PointerLikeType API for CIR, primarily for objects whose size is known. Where the pointer type does not describe the whole entity, the implementation recovers that information from how the pointer was formed.
Assisted-by: Cursor
---
.../OpenACC/CIROpenACCTypeInterfaces.h | 38 +-
.../OpenACC/CIROpenACCTypeInterfaces.cpp | 469 ++++++++++++++-
clang/lib/CIR/Dialect/OpenACC/CMakeLists.txt | 1 +
.../acc-recipe-populate-firstprivate.cir | 246 ++++++++
.../OpenACC/acc-recipe-populate-private.cir | 211 +++++++
.../OpenACC/acc-recipe-populate-unsized.cir | 43 ++
clang/tools/cir-opt/CMakeLists.txt | 5 +-
clang/tools/cir-opt/cir-opt.cpp | 5 +
clang/unittests/CIR/PointerLikeTest.cpp | 546 +++++++++++++++++-
9 files changed, 1543 insertions(+), 21 deletions(-)
create mode 100644 clang/test/CIR/OpenACC/acc-recipe-populate-firstprivate.cir
create mode 100644 clang/test/CIR/OpenACC/acc-recipe-populate-private.cir
create mode 100644 clang/test/CIR/OpenACC/acc-recipe-populate-unsized.cir
diff --git a/clang/include/clang/CIR/Dialect/OpenACC/CIROpenACCTypeInterfaces.h b/clang/include/clang/CIR/Dialect/OpenACC/CIROpenACCTypeInterfaces.h
index 3011245cd8a03a..5972c92c3b2357 100644
--- a/clang/include/clang/CIR/Dialect/OpenACC/CIROpenACCTypeInterfaces.h
+++ b/clang/include/clang/CIR/Dialect/OpenACC/CIROpenACCTypeInterfaces.h
@@ -6,7 +6,7 @@
//
//===----------------------------------------------------------------------===//
//
-// This file contains external dialect interfaces for CIR.
+// This file contains external OpenACC type interfaces for CIR.
//
//===----------------------------------------------------------------------===//
@@ -28,6 +28,42 @@ struct OpenACCPointerLikeModel
getPointeeTypeCategory(mlir::Type pointer,
mlir::TypedValue<mlir::acc::PointerLikeType> varPtr,
mlir::Type varType) const;
+
+ mlir::Value genAllocate(mlir::Type pointer, mlir::OpBuilder &builder,
+ mlir::Location loc, llvm::StringRef varName,
+ mlir::Type varType, mlir::Value originalVar,
+ bool &needsFree) const;
+
+ bool genFree(mlir::Type pointer, mlir::OpBuilder &builder, mlir::Location loc,
+ mlir::TypedValue<mlir::acc::PointerLikeType> varToFree,
+ mlir::Value allocRes, mlir::Type varType) const;
+
+ bool genCopy(mlir::Type pointer, mlir::OpBuilder &builder, mlir::Location loc,
+ mlir::TypedValue<mlir::acc::PointerLikeType> destination,
+ mlir::TypedValue<mlir::acc::PointerLikeType> source,
+ mlir::Type varType) const;
+
+ mlir::Value genLoad(mlir::Type pointer, mlir::OpBuilder &builder,
+ mlir::Location loc,
+ mlir::TypedValue<mlir::acc::PointerLikeType> srcPtr,
+ mlir::Type valueType) const;
+
+ bool genStore(mlir::Type pointer, mlir::OpBuilder &builder,
+ mlir::Location loc, mlir::Value valueToStore,
+ mlir::TypedValue<mlir::acc::PointerLikeType> destPtr) const;
+
+ mlir::Value genCast(mlir::Type pointer, mlir::OpBuilder &builder,
+ mlir::Location loc, mlir::Value value,
+ mlir::Type resultType) const;
+
+ mlir::MemRefType getAsMemRefType(mlir::Type pointer,
+ mlir::ModuleOp module) const;
+
+ bool isDeviceAccessible(mlir::Type pointer, mlir::Value var,
+ mlir::SymbolTableCollection *symbolTables) const;
+
+ bool isInDeviceMemory(mlir::Type pointer, mlir::Value var,
+ mlir::SymbolTableCollection *symbolTables) const;
};
} // namespace cir::acc
diff --git a/clang/lib/CIR/Dialect/OpenACC/CIROpenACCTypeInterfaces.cpp b/clang/lib/CIR/Dialect/OpenACC/CIROpenACCTypeInterfaces.cpp
index de8dd9c55ee329..854f23ed711740 100644
--- a/clang/lib/CIR/Dialect/OpenACC/CIROpenACCTypeInterfaces.cpp
+++ b/clang/lib/CIR/Dialect/OpenACC/CIROpenACCTypeInterfaces.cpp
@@ -6,35 +6,70 @@
//
//===----------------------------------------------------------------------===//
//
-// Implementation of external dialect interfaces for CIR.
+// Implementation of external OpenACC type interfaces for CIR.
//
//===----------------------------------------------------------------------===//
#include "clang/CIR/Dialect/OpenACC/CIROpenACCTypeInterfaces.h"
+#include "mlir/Dialect/OpenACC/OpenACCUtilsCG.h"
+#include "mlir/IR/BuiltinTypes.h"
+#include "mlir/Interfaces/DataLayoutInterfaces.h"
#include "clang/CIR/Dialect/IR/CIRDialect.h"
#include "clang/CIR/Dialect/IR/CIRTypes.h"
+#include "clang/CIR/Dialect/OpenACC/CIROpenACCUtils.h"
+#include "llvm/Support/ErrorHandling.h"
namespace cir::acc {
-mlir::Type getBaseType(mlir::Value varPtr) {
- mlir::Operation *op = varPtr.getDefiningOp();
- assert(op && "Expected a defining operation");
+// The alloca reached from a pointer. `baseEntity` is true when the pointer
+// still refers to that whole allocation.
+struct AllocaInfo {
+ cir::AllocaOp alloca;
+ bool baseEntity = false;
+ explicit operator bool() const { return static_cast<bool>(alloca); }
+};
- // This is the variable definition we're looking for.
- if (auto allocaOp = mlir::dyn_cast<cir::AllocaOp>(*op))
- return allocaOp.getAllocaType();
-
- // Look through casts to the source pointer.
- if (auto castOp = mlir::dyn_cast<cir::CastOp>(*op))
- return getBaseType(castOp.getSrc());
-
- // Follow the source of ptr strides.
- if (auto ptrStrideOp = mlir::dyn_cast<cir::PtrStrideOp>(*op))
- return getBaseType(ptrStrideOp.getBase());
+static bool isZero(mlir::Value value) {
+ auto constant = value.getDefiningOp<cir::ConstantOp>();
+ if (!constant)
+ return false;
+ auto attr = mlir::dyn_cast<cir::IntAttr>(constant.getValue());
+ return attr && attr.getValue() == 0;
+}
- if (auto getMemberOp = mlir::dyn_cast<cir::GetMemberOp>(*op))
- return getBaseType(getMemberOp.getAddr());
+// The pointee type does not describe the allocated entity. Walk the
+// operations that constructed `value` and recover that entity from its alloca.
+static AllocaInfo findAlloca(mlir::Value value) {
+ bool baseEntity = true;
+ while (mlir::Operation *def = value.getDefiningOp()) {
+ if (auto alloca = mlir::dyn_cast<cir::AllocaOp>(def))
+ return {alloca, baseEntity};
+ if (auto cast = mlir::dyn_cast<cir::CastOp>(def)) {
+ baseEntity &= (cast.getKind() == cir::CastKind::bitcast ||
+ cast.getKind() == cir::CastKind::address_space ||
+ cast.getKind() == cir::CastKind::array_to_ptrdecay);
+ value = cast.getSrc();
+ continue;
+ }
+ if (auto stride = mlir::dyn_cast<cir::PtrStrideOp>(def)) {
+ baseEntity &= isZero(stride.getStride());
+ value = stride.getBase();
+ continue;
+ }
+ if (auto member = mlir::dyn_cast<cir::GetMemberOp>(def)) {
+ baseEntity = false;
+ value = member.getAddr();
+ continue;
+ }
+ break;
+ }
+ return {};
+}
+static mlir::Type getBaseType(mlir::Value varPtr) {
+ if (AllocaInfo found = findAlloca(varPtr))
+ return found.alloca.getAllocaType();
+ // A block argument or other value with no alloca has only its pointer type.
return mlir::cast<cir::PointerType>(varPtr.getType()).getPointee();
}
@@ -43,13 +78,19 @@ mlir::acc::VariableTypeCategory
OpenACCPointerLikeModel<cir::PointerType>::getPointeeTypeCategory(
mlir::Type pointer, mlir::TypedValue<mlir::acc::PointerLikeType> varPtr,
mlir::Type varType) const {
+ // A dynamic alloca is an array of its element. Classifying it from the
+ // pointer type alone would report a scalar.
+ if (AllocaInfo base = findAlloca(varPtr))
+ if (base.alloca.isDynamic())
+ return mlir::acc::VariableTypeCategory::array;
+
mlir::Type eleTy = getBaseType(varPtr);
if (auto mappableTy = mlir::dyn_cast<mlir::acc::MappableType>(eleTy))
return mappableTy.getTypeCategory(varPtr);
if (isAnyIntegerOrFloatingPointType(eleTy) ||
- mlir::isa<cir::BoolType>(eleTy) || mlir::isa<cir::PointerType>(eleTy))
+ mlir::isa<cir::BoolType, cir::PointerType, cir::ComplexType>(eleTy))
return mlir::acc::VariableTypeCategory::scalar;
if (mlir::isa<cir::ArrayType>(eleTy))
return mlir::acc::VariableTypeCategory::array;
@@ -62,4 +103,396 @@ OpenACCPointerLikeModel<cir::PointerType>::getPointeeTypeCategory(
return mlir::acc::VariableTypeCategory::uncategorized;
}
+// Incomplete records and types without a data layout have no size.
+static bool hasKnownLayout(mlir::Type type) {
+ if (auto record = mlir::dyn_cast<cir::RecordType>(type))
+ return record.isComplete();
+ if (auto array = mlir::dyn_cast<cir::ArrayType>(type))
+ return hasKnownLayout(array.getElementType());
+ return type.hasTrait<mlir::DataLayoutTypeInterface::Trait>();
+}
+
+// A scalar whose size comes from the data layout.
+static bool isKnownSizeScalar(mlir::Type type) {
+ return hasKnownLayout(type) &&
+ (isAnyIntegerOrFloatingPointType(type) ||
+ mlir::isa<cir::BoolType, cir::PointerType, cir::ComplexType>(type));
+}
+
+static bool isKnownSizeArray(mlir::Type type) {
+ return mlir::isa<cir::ArrayType>(type) && hasKnownLayout(type);
+}
+
+// Alignment comes from the module that contains the insertion point.
+static std::optional<mlir::IntegerAttr>
+allocaAlignment(mlir::OpBuilder &builder, mlir::Type pointee) {
+ mlir::Operation *scope = nullptr;
+ if (mlir::Block *block = builder.getInsertionBlock())
+ scope = block->getParentOp();
+ std::optional<mlir::DataLayout> layout = mlir::acc::getDataLayout(scope);
+ if (!layout)
+ return std::nullopt;
+ uint64_t align = layout->getTypeABIAlignment(pointee);
+ if (align == 0)
+ return std::nullopt;
+ return builder.getI64IntegerAttr(align);
+}
+
+// A dynamic extent is a non-zero constant.
+static std::optional<uint64_t> constantCount(mlir::Value size) {
+ auto constant = size.getDefiningOp<cir::ConstantOp>();
+ if (!constant)
+ return std::nullopt;
+ auto attr = mlir::dyn_cast<cir::IntAttr>(constant.getValue());
+ if (!attr || attr.getUInt() == 0)
+ return std::nullopt;
+ return attr.getUInt();
+}
+
+static mlir::Value constantSizeHere(mlir::OpBuilder &builder,
+ mlir::Location loc, mlir::Value size) {
+ if (!constantCount(size))
+ return {};
+ return cir::ConstantOp::create(
+ builder, loc, size.getDefiningOp<cir::ConstantOp>().getValue());
+}
+
+static cir::PointerType pointerTo(mlir::Type pointee, cir::PointerType like) {
+ if (like.getAddrSpace())
+ return cir::PointerType::get(pointee, like.getAddrSpace());
+ return cir::PointerType::get(pointee);
+}
+
+// `count` is set for a dynamic alloca. A constant count is folded into
+// `!cir.array` when no size operand is requested.
+struct Object {
+ mlir::Type type;
+ mlir::Value count;
+};
+
+struct Resolved {
+ bool sawAlloca = false;
+ std::optional<Object> object;
+};
+
+// The scalar or constant-size array described by `pointer`. `needCount` keeps
+// a dynamic size as a value. Otherwise a constant count is part of the type.
+static Resolved resolveObject(mlir::OpBuilder &builder, mlir::Location loc,
+ mlir::Value pointer, bool needCount) {
+ AllocaInfo found = pointer ? findAlloca(pointer) : AllocaInfo{};
+ if (!found)
+ return {};
+
+ if (!found.baseEntity)
+ return {true, std::nullopt};
+
+ mlir::Type type = found.alloca.getAllocaType();
+ if (!isKnownSizeScalar(type) && !isKnownSizeArray(type))
+ return {true, std::nullopt};
+ if (!found.alloca.isDynamic())
+ return {true, Object{type, {}}};
+
+ std::optional<uint64_t> count = constantCount(found.alloca.getDynAllocSize());
+ if (!count)
+ return {true, std::nullopt};
+ if (!needCount)
+ return {true, Object{cir::ArrayType::get(type, *count), {}}};
+
+ mlir::Value size =
+ constantSizeHere(builder, loc, found.alloca.getDynAllocSize());
+ if (!size)
+ return {true, std::nullopt};
+ return {true, Object{type, size}};
+}
+
+// The scalar or constant-size array described by `pointer`. Without an
+// alloca, `fallback` is that object when its size is known.
+static std::optional<Object>
+knownSizeObject(mlir::OpBuilder &builder, mlir::Location loc,
+ mlir::Value pointer, mlir::Type fallback, bool needCount) {
+ Resolved resolved = resolveObject(builder, loc, pointer, needCount);
+ if (resolved.sawAlloca && !resolved.object)
+ return std::nullopt;
+ if (resolved.object)
+ return resolved.object;
+ if (fallback && (isKnownSizeScalar(fallback) || isKnownSizeArray(fallback)))
+ return Object{fallback, {}};
+ return std::nullopt;
+}
+
+// Pointer-to-pointer conversions, and integer-to-pointer conversions. A
+// pointer bitcast is used when the pointee changes, then an address-space
+// cast when the address space changes. Value-to-value conversions are left
+// to the caller.
+static mlir::Value castPointer(mlir::OpBuilder &builder, mlir::Location loc,
+ mlir::Value value, mlir::Type resultType) {
+ mlir::Type srcType = value.getType();
+ if (srcType == resultType)
+ return value;
+
+ auto srcPtr = mlir::dyn_cast<cir::PointerType>(srcType);
+ auto dstPtr = mlir::dyn_cast<cir::PointerType>(resultType);
+ if (!dstPtr)
+ return {};
+ if (!srcPtr) {
+ if (!mlir::isa<cir::IntType>(srcType))
+ return {};
+ return cir::CastOp::create(builder, loc, resultType,
+ cir::CastKind::int_to_ptr, value);
+ }
+
+ mlir::Value current = value;
+ if (srcPtr.getPointee() != dstPtr.getPointee()) {
+ auto midTy =
+ cir::PointerType::get(dstPtr.getPointee(), srcPtr.getAddrSpace());
+ if (current.getType() != midTy)
+ current = cir::CastOp::create(builder, loc, midTy, cir::CastKind::bitcast,
+ current);
+ }
+ if (current.getType() != resultType)
+ current = cir::CastOp::create(builder, loc, resultType,
+ cir::CastKind::address_space, current);
+ return current;
+}
+
+// A memref element is a builtin scalar, complex, or fixed vector. CIR signs
+// are dropped: memref storage is signless.
+static mlir::Type convertMemRefElementType(mlir::Type type,
+ const mlir::DataLayout &layout) {
+ if (auto intTy = mlir::dyn_cast<cir::IntType>(type)) {
+ if (intTy.isBitInt() || intTy.getWidth() == 0)
+ return {};
+ return mlir::IntegerType::get(type.getContext(), intTy.getWidth());
+ }
+ if (mlir::isa<cir::BoolType>(type)) {
+ llvm::TypeSize bits = layout.getTypeSizeInBits(type);
+ if (!bits.isFixed() || !bits.getFixedValue())
+ return {};
+ return mlir::IntegerType::get(type.getContext(),
+ static_cast<unsigned>(bits.getFixedValue()));
+ }
+ if (mlir::isa<cir::SingleType>(type))
+ return mlir::Float32Type::get(type.getContext());
+ if (mlir::isa<cir::DoubleType>(type))
+ return mlir::Float64Type::get(type.getContext());
+ if (mlir::isa<cir::FP16Type>(type))
+ return mlir::Float16Type::get(type.getContext());
+ if (mlir::isa<cir::BF16Type>(type))
+ return mlir::BFloat16Type::get(type.getContext());
+ if (mlir::isa<cir::FP80Type>(type))
+ return mlir::Float80Type::get(type.getContext());
+ if (mlir::isa<cir::FP128Type>(type))
+ return mlir::Float128Type::get(type.getContext());
+ if (auto longDouble = mlir::dyn_cast<cir::LongDoubleType>(type))
+ return convertMemRefElementType(longDouble.getUnderlying(), layout);
+ if (auto complex = mlir::dyn_cast<cir::ComplexType>(type)) {
+ mlir::Type element =
+ convertMemRefElementType(complex.getElementType(), layout);
+ if (!element)
+ return {};
+ return mlir::ComplexType::get(element);
+ }
+ if (auto vector = mlir::dyn_cast<cir::VectorType>(type)) {
+ if (vector.isScalable())
+ return {};
+ mlir::Type element =
+ convertMemRefElementType(vector.getElementType(), layout);
+ if (!element || !element.isIntOrIndexOrFloat())
+ return {};
+ return mlir::VectorType::get({static_cast<int64_t>(vector.getFixedSize())},
+ element);
+ }
+ return {};
+}
+
+// `shape` is outermost first, matching `!cir.array` nesting.
+static bool collectMemRefShape(mlir::Type type,
+ llvm::SmallVectorImpl<int64_t> &shape,
+ mlir::Type &element,
+ const mlir::DataLayout &layout) {
+ if (auto array = mlir::dyn_cast<cir::ArrayType>(type)) {
+ shape.push_back(static_cast<int64_t>(array.getSize()));
+ return collectMemRefShape(array.getElementType(), shape, element, layout);
+ }
+ if (mlir::isa<cir::PointerType>(type))
+ return false;
+ element = convertMemRefElementType(type, layout);
+ return static_cast<bool>(element) &&
+ mlir::BaseMemRefType::isValidElementType(element);
+}
+
+static mlir::MemRefType
+convertPointerToMemRefType(mlir::Type pointer, const mlir::DataLayout &layout) {
+ auto ptrTy = mlir::dyn_cast<cir::PointerType>(pointer);
+ if (!ptrTy)
+ return {};
+
+ mlir::Type pointee = ptrTy.getPointee();
+ if (!hasKnownLayout(pointee))
+ return {};
+
+ llvm::SmallVector<int64_t> shape;
+ mlir::Type element;
+ if (!collectMemRefShape(pointee, shape, element, layout))
+ return {};
+ return mlir::MemRefType::get(shape, element);
+}
+
+template <>
+mlir::Value OpenACCPointerLikeModel<cir::PointerType>::genAllocate(
+ mlir::Type pointer, mlir::OpBuilder &builder, mlir::Location loc,
+ llvm::StringRef varName, mlir::Type /*varType*/, mlir::Value originalVar,
+ bool &needsFree) const {
+ auto ptrTy = mlir::cast<cir::PointerType>(pointer);
+ mlir::Type viewPointee = ptrTy.getPointee();
+ std::optional<Object> object = knownSizeObject(
+ builder, loc, originalVar, viewPointee, /*needCount=*/true);
+ if (!object)
+ return {};
+ mlir::Type objectType = object->type;
+ mlir::Value dynSize = object->count;
+
+ mlir::Type objectPtrTy =
+ ptrTy.getAddrSpace()
+ ? cir::PointerType::get(objectType, ptrTy.getAddrSpace())
+ : cir::PointerType::get(objectType);
+ std::optional<mlir::IntegerAttr> alignment =
+ allocaAlignment(builder, objectType);
+ if (!alignment)
+ return {};
+
+ // cir.alloca needs no deallocation.
+ needsFree = false;
+ cir::AllocaOp alloca =
+ dynSize ? cir::AllocaOp::create(builder, loc, objectPtrTy, varName,
+ *alignment, dynSize)
+ : cir::AllocaOp::create(builder, loc, objectPtrTy, varName,
+ *alignment);
+ if (!varName.empty())
+ alloca->setDiscardableAttr(
+ mlir::acc::getVarNameAttrName(),
+ mlir::acc::VarNameAttr::get(builder.getContext(), varName));
+
+ mlir::Value result = alloca.getResult();
+ if (result.getType() == pointer)
+ return result;
+ if (!dynSize) {
+ if (auto array = mlir::dyn_cast<cir::ArrayType>(objectType))
+ if (array.getElementType() == viewPointee)
+ return cir::CastOp::create(builder, loc, pointer,
+ cir::CastKind::array_to_ptrdecay, result);
+ }
+ return castPointer(builder, loc, result, pointer);
+}
+
+template <>
+bool OpenACCPointerLikeModel<cir::PointerType>::genFree(
+ mlir::Type /*pointer*/, mlir::OpBuilder &builder, mlir::Location loc,
+ mlir::TypedValue<mlir::acc::PointerLikeType> varToFree,
+ mlir::Value allocRes, mlir::Type /*varType*/) const {
+ mlir::Value inspected = allocRes ? allocRes : varToFree;
+ return knownSizeObject(builder, loc, inspected, /*fallback=*/{},
+ /*needCount=*/false)
+ .has_value();
+}
+
+template <>
+bool OpenACCPointerLikeModel<cir::PointerType>::genCopy(
+ mlir::Type /*pointer*/, mlir::OpBuilder &builder, mlir::Location loc,
+ mlir::TypedValue<mlir::acc::PointerLikeType> destination,
+ mlir::TypedValue<mlir::acc::PointerLikeType> source,
+ mlir::Type /*varType*/) const {
+ auto destTy = mlir::dyn_cast<cir::PointerType>(destination.getType());
+ auto srcTy = mlir::dyn_cast<cir::PointerType>(source.getType());
+ if (!destTy || !srcTy || destTy.getPointee() != srcTy.getPointee())
+ return false;
+
+ std::optional<Object> object = knownSizeObject(
+ builder, loc, source, destTy.getPointee(), /*needCount=*/false);
+ if (!object)
+ return false;
+ mlir::Type objectType = object->type;
+
+ mlir::Value srcObj =
+ castPointer(builder, loc, source, pointerTo(objectType, srcTy));
+ mlir::Value dstObj =
+ castPointer(builder, loc, destination, pointerTo(objectType, destTy));
+ if (!srcObj || !dstObj)
+ return false;
+ cir::CopyOp::create(builder, loc, dstObj, srcObj, {}, {});
+ return true;
+}
+
+template <>
+mlir::Value OpenACCPointerLikeModel<cir::PointerType>::genLoad(
+ mlir::Type /*pointer*/, mlir::OpBuilder &builder, mlir::Location loc,
+ mlir::TypedValue<mlir::acc::PointerLikeType> srcPtr,
+ mlir::Type valueType) const {
+ auto ptrTy = mlir::dyn_cast<cir::PointerType>(srcPtr.getType());
+ if (!ptrTy || !hasKnownLayout(ptrTy.getPointee()))
+ return {};
+ mlir::Value loaded = cir::LoadOp::create(builder, loc, srcPtr);
+ if (!valueType || loaded.getType() == valueType)
+ return loaded;
+ return castPointer(builder, loc, loaded, valueType);
+}
+
+template <>
+bool OpenACCPointerLikeModel<cir::PointerType>::genStore(
+ mlir::Type /*pointer*/, mlir::OpBuilder &builder, mlir::Location loc,
+ mlir::Value valueToStore,
+ mlir::TypedValue<mlir::acc::PointerLikeType> destPtr) const {
+ auto ptrTy = mlir::dyn_cast<cir::PointerType>(destPtr.getType());
+ if (!ptrTy || !hasKnownLayout(ptrTy.getPointee()))
+ return false;
+ mlir::Value stored = valueToStore;
+ if (stored.getType() != ptrTy.getPointee()) {
+ stored = castPointer(builder, loc, stored, ptrTy.getPointee());
+ if (!stored)
+ return false;
+ }
+ cir::StoreOp::create(builder, loc, stored, destPtr);
+ return true;
+}
+
+template <>
+mlir::Value OpenACCPointerLikeModel<cir::PointerType>::genCast(
+ mlir::Type /*pointer*/, mlir::OpBuilder &builder, mlir::Location loc,
+ mlir::Value value, mlir::Type resultType) const {
+ return castPointer(builder, loc, value, resultType);
+}
+
+template <>
+mlir::MemRefType OpenACCPointerLikeModel<cir::PointerType>::getAsMemRefType(
+ mlir::Type pointer, mlir::ModuleOp module) const {
+ std::optional<mlir::DataLayout> layout = mlir::acc::getDataLayout(module);
+ if (!layout)
+ return {};
+ return convertPointerToMemRefType(pointer, *layout);
+}
+
+template <>
+bool OpenACCPointerLikeModel<cir::PointerType>::isDeviceAccessible(
+ mlir::Type /*pointer*/, mlir::Value var,
+ mlir::SymbolTableCollection * /*symbolTables*/) const {
+ auto ptrTy = mlir::dyn_cast<cir::PointerType>(var.getType());
+ if (!ptrTy)
+ return false;
+ auto lang = mlir::dyn_cast_if_present<cir::LangAddressSpaceAttr>(
+ ptrTy.getAddrSpace());
+ return lang && isDeviceAccessibleAddressSpace(lang.getValue());
+}
+
+template <>
+bool OpenACCPointerLikeModel<cir::PointerType>::isInDeviceMemory(
+ mlir::Type /*pointer*/, mlir::Value var,
+ mlir::SymbolTableCollection * /*symbolTables*/) const {
+ auto ptrTy = mlir::dyn_cast<cir::PointerType>(var.getType());
+ if (!ptrTy)
+ return false;
+ auto lang = mlir::dyn_cast_if_present<cir::LangAddressSpaceAttr>(
+ ptrTy.getAddrSpace());
+ return lang && isDeviceResidentAddressSpace(lang.getValue());
+}
+
} // namespace cir::acc
diff --git a/clang/lib/CIR/Dialect/OpenACC/CMakeLists.txt b/clang/lib/CIR/Dialect/OpenACC/CMakeLists.txt
index 8e0b6143b5fa13..2802bb3c6dffa8 100644
--- a/clang/lib/CIR/Dialect/OpenACC/CMakeLists.txt
+++ b/clang/lib/CIR/Dialect/OpenACC/CMakeLists.txt
@@ -11,4 +11,5 @@ add_clang_library(CIROpenACCSupport
MLIRIR
MLIRCIR
MLIROpenACCDialect
+ MLIROpenACCUtils
)
diff --git a/clang/test/CIR/OpenACC/acc-recipe-populate-firstprivate.cir b/clang/test/CIR/OpenACC/acc-recipe-populate-firstprivate.cir
new file mode 100644
index 00000000000000..5ee3a800690a42
--- /dev/null
+++ b/clang/test/CIR/OpenACC/acc-recipe-populate-firstprivate.cir
@@ -0,0 +1,246 @@
+// RUN: cir-opt %s --split-input-file --pass-pipeline="builtin.module(test-acc-recipe-populate{recipe-type=firstprivate})" | FileCheck %s
+
+// Integer scalar.
+!s32i = !cir.int<s, 32>
+
+cir.func @test_i32() {
+ %0 = cir.alloca "i32" align(4) : !cir.ptr<!s32i> {test.var = "i32"}
+ cir.return
+}
+
+// CHECK: acc.firstprivate.recipe @firstprivate_i32 : !cir.ptr<!s32i> init {
+// CHECK: ^bb0(%{{.*}}: !cir.ptr<!s32i>):
+// CHECK: %[[ALLOC:.*]] = cir.alloca "i32" align(4) : !cir.ptr<!s32i> {acc.var_name = #acc.var_name<"i32">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!s32i>
+// CHECK: } copy {
+// CHECK: ^bb0(%[[SRC:.*]]: !cir.ptr<!s32i>, %[[DST:.*]]: !cir.ptr<!s32i>):
+// CHECK: cir.copy %[[SRC]] to %[[DST]] : !cir.ptr<!s32i>
+// CHECK: acc.terminator
+// CHECK: }
+// CHECK-NOT: destroy
+
+// -----
+
+// Single-precision float.
+cir.func @test_f32() {
+ %0 = cir.alloca "f32" align(4) : !cir.ptr<!cir.float> {test.var = "f32"}
+ cir.return
+}
+
+// CHECK: acc.firstprivate.recipe @firstprivate_f32 : !cir.ptr<!cir.float> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "f32" align(4) : !cir.ptr<!cir.float> {acc.var_name = #acc.var_name<"f32">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!cir.float>
+// CHECK: } copy {
+// CHECK: ^bb0(%[[SRC:.*]]: !cir.ptr<!cir.float>, %[[DST:.*]]: !cir.ptr<!cir.float>):
+// CHECK: cir.copy %[[SRC]] to %[[DST]] : !cir.ptr<!cir.float>
+// CHECK: acc.terminator
+// CHECK: }
+// CHECK-NOT: destroy
+
+// -----
+
+// Double-precision float. Alignment follows the 8-byte pointee.
+cir.func @test_f64() {
+ %0 = cir.alloca "f64" align(8) : !cir.ptr<!cir.double> {test.var = "f64"}
+ cir.return
+}
+
+// CHECK: acc.firstprivate.recipe @firstprivate_f64 : !cir.ptr<!cir.double> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "f64" align(8) : !cir.ptr<!cir.double> {acc.var_name = #acc.var_name<"f64">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!cir.double>
+// CHECK: } copy {
+// CHECK: cir.copy {{.*}} to {{.*}} : !cir.ptr<!cir.double>
+// CHECK: acc.terminator
+// CHECK: }
+// CHECK-NOT: destroy
+
+// -----
+
+// Bool is a 1-byte scalar.
+cir.func @test_bool() {
+ %0 = cir.alloca "bool" align(1) : !cir.ptr<!cir.bool> {test.var = "bool"}
+ cir.return
+}
+
+// CHECK: acc.firstprivate.recipe @firstprivate_bool : !cir.ptr<!cir.bool> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "bool" align(1) : !cir.ptr<!cir.bool> {acc.var_name = #acc.var_name<"bool">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!cir.bool>
+// CHECK: } copy {
+// CHECK: cir.copy {{.*}} to {{.*}} : !cir.ptr<!cir.bool>
+// CHECK: acc.terminator
+// CHECK: }
+// CHECK-NOT: destroy
+
+// -----
+
+// A pointer is a scalar whose size is the pointer size.
+!s32i = !cir.int<s, 32>
+
+cir.func @test_ptr() {
+ %0 = cir.alloca "ptr" align(8) : !cir.ptr<!cir.ptr<!s32i>> {test.var = "ptr"}
+ cir.return
+}
+
+// CHECK: acc.firstprivate.recipe @firstprivate_ptr : !cir.ptr<!cir.ptr<!s32i>> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "ptr" align(8) : !cir.ptr<!cir.ptr<!s32i>> {acc.var_name = #acc.var_name<"ptr">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!cir.ptr<!s32i>>
+// CHECK: } copy {
+// CHECK: cir.copy {{.*}} to {{.*}} : !cir.ptr<!cir.ptr<!s32i>>
+// CHECK: acc.terminator
+// CHECK: }
+// CHECK-NOT: destroy
+
+// -----
+
+// The language address space is part of the pointer type and stays on the
+// private allocation.
+!s32i = !cir.int<s, 32>
+
+cir.func @test_addrspace() {
+ %0 = cir.alloca "addrspace" align(4) : !cir.ptr<!s32i, lang_address_space(offload_global)> {test.var = "addrspace"}
+ cir.return
+}
+
+// CHECK: acc.firstprivate.recipe @firstprivate_addrspace : !cir.ptr<!s32i, lang_address_space(offload_global)> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "addrspace" align(4) : !cir.ptr<!s32i, lang_address_space(offload_global)> {acc.var_name = #acc.var_name<"addrspace">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!s32i, lang_address_space(offload_global)>
+// CHECK: } copy {
+// CHECK: cir.copy {{.*}} to {{.*}} : !cir.ptr<!s32i, lang_address_space(offload_global)>
+// CHECK: acc.terminator
+// CHECK: }
+// CHECK-NOT: destroy
+
+// -----
+
+// Constant one-dimensional array. The recipe allocates the array.
+!s32i = !cir.int<s, 32>
+
+cir.func @test_array_1d() {
+ %0 = cir.alloca "array_1d" align(4) : !cir.ptr<!cir.array<!s32i x 100>> {test.var = "array_1d"}
+ cir.return
+}
+
+// CHECK: acc.firstprivate.recipe @firstprivate_array_1d : !cir.ptr<!cir.array<!s32i x 100>> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "array_1d" align(4) : !cir.ptr<!cir.array<!s32i x 100>> {acc.var_name = #acc.var_name<"array_1d">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!cir.array<!s32i x 100>>
+// CHECK: } copy {
+// CHECK: cir.copy {{.*}} to {{.*}} : !cir.ptr<!cir.array<!s32i x 100>>
+// CHECK: acc.terminator
+// CHECK: }
+// CHECK-NOT: destroy
+
+// -----
+
+// Constant two-dimensional array. Both dimensions are in the type.
+!s32i = !cir.int<s, 32>
+
+cir.func @test_array_2d() {
+ %0 = cir.alloca "array_2d" align(4) : !cir.ptr<!cir.array<!cir.array<!s32i x 20> x 10>> {test.var = "array_2d"}
+ cir.return
+}
+
+// CHECK: acc.firstprivate.recipe @firstprivate_array_2d : !cir.ptr<!cir.array<!cir.array<!s32i x 20> x 10>> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "array_2d" align(4) : !cir.ptr<!cir.array<!cir.array<!s32i x 20> x 10>> {acc.var_name = #acc.var_name<"array_2d">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!cir.array<!cir.array<!s32i x 20> x 10>>
+// CHECK: } copy {
+// CHECK: cir.copy {{.*}} to {{.*}} : !cir.ptr<!cir.array<!cir.array<!s32i x 20> x 10>>
+// CHECK: acc.terminator
+// CHECK: }
+// CHECK-NOT: destroy
+
+// -----
+
+// Global address. There is no alloca.
+!s32i = !cir.int<s, 32>
+
+cir.global external @gscalar = #cir.int<0> : !s32i
+
+cir.func @test_global() {
+ %addr = cir.get_global @gscalar : !cir.ptr<!s32i> {test.var = "global"}
+ cir.return
+}
+
+// CHECK: acc.firstprivate.recipe @firstprivate_global : !cir.ptr<!s32i> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "global" align(4) : !cir.ptr<!s32i> {acc.var_name = #acc.var_name<"global">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!s32i>
+// CHECK: } copy {
+// CHECK: cir.copy {{.*}} to {{.*}} : !cir.ptr<!s32i>
+// CHECK: acc.terminator
+// CHECK: }
+// CHECK-NOT: destroy
+
+// -----
+
+// Loaded pointer. The load result has no alloca.
+!s32i = !cir.int<s, 32>
+
+cir.func @test_loaded() {
+ %slot = cir.alloca "slot" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ %p = cir.load %slot : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i> {test.var = "loaded"}
+ cir.return
+}
+
+// CHECK: acc.firstprivate.recipe @firstprivate_loaded : !cir.ptr<!s32i> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "loaded" align(4) : !cir.ptr<!s32i> {acc.var_name = #acc.var_name<"loaded">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!s32i>
+// CHECK: } copy {
+// CHECK: cir.copy {{.*}} to {{.*}} : !cir.ptr<!s32i>
+// CHECK: acc.terminator
+// CHECK: }
+// CHECK-NOT: destroy
+
+// -----
+
+// Function argument. There is no alloca.
+!s32i = !cir.int<s, 32>
+
+cir.func @test_arg(%arg: !cir.ptr<!s32i>) {
+ %zero = cir.const #cir.int<0> : !s32i
+ %p = cir.ptr_stride %arg, %zero : (!cir.ptr<!s32i>, !s32i) -> !cir.ptr<!s32i> {test.var = "arg"}
+ cir.return
+}
+
+// CHECK: acc.firstprivate.recipe @firstprivate_arg : !cir.ptr<!s32i> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "arg" align(4) : !cir.ptr<!s32i> {acc.var_name = #acc.var_name<"arg">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!s32i>
+// CHECK: } copy {
+// CHECK: cir.copy {{.*}} to {{.*}} : !cir.ptr<!s32i>
+// CHECK: acc.terminator
+// CHECK: }
+// CHECK-NOT: destroy
+
+// -----
+
+// Loaded pointer to a constant array. There is no alloca of the array.
+!s32i = !cir.int<s, 32>
+
+cir.func @test_loaded_array() {
+ %slot = cir.alloca "slot" align(8) : !cir.ptr<!cir.ptr<!cir.array<!s32i x 4>>>
+ %p = cir.load %slot : !cir.ptr<!cir.ptr<!cir.array<!s32i x 4>>>, !cir.ptr<!cir.array<!s32i x 4>> {test.var = "loaded_array"}
+ cir.return
+}
+
+// CHECK: acc.firstprivate.recipe @firstprivate_loaded_array : !cir.ptr<!cir.array<!s32i x 4>> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "loaded_array" align(4) : !cir.ptr<!cir.array<!s32i x 4>> {acc.var_name = #acc.var_name<"loaded_array">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!cir.array<!s32i x 4>>
+// CHECK: } copy {
+// CHECK: cir.copy {{.*}} to {{.*}} : !cir.ptr<!cir.array<!s32i x 4>>
+// CHECK: acc.terminator
+// CHECK: }
+// CHECK-NOT: destroy
+
+// -----
+
+// Complex scalar.
+cir.func @test_complex() {
+ %0 = cir.alloca "complex" align(4) : !cir.ptr<!cir.complex<!cir.float>> {test.var = "complex"}
+ cir.return
+}
+
+// CHECK: acc.firstprivate.recipe @firstprivate_complex : !cir.ptr<!cir.complex<!cir.float>> init {
+// CHECK: cir.alloca "complex" align(4) : !cir.ptr<!cir.complex<!cir.float>>
+// CHECK: } copy {
+// CHECK: cir.copy {{.*}} to {{.*}} : !cir.ptr<!cir.complex<!cir.float>>
+// CHECK: acc.terminator
+// CHECK: }
+// CHECK-NOT: destroy
diff --git a/clang/test/CIR/OpenACC/acc-recipe-populate-private.cir b/clang/test/CIR/OpenACC/acc-recipe-populate-private.cir
new file mode 100644
index 00000000000000..1d7ab91a9122ac
--- /dev/null
+++ b/clang/test/CIR/OpenACC/acc-recipe-populate-private.cir
@@ -0,0 +1,211 @@
+// RUN: cir-opt %s --split-input-file --pass-pipeline="builtin.module(test-acc-recipe-populate{recipe-type=private})" | FileCheck %s
+
+// Integer scalar. Private allocation has no copy and no destroy.
+!s32i = !cir.int<s, 32>
+
+cir.func @test_i32() {
+ %0 = cir.alloca "i32" align(4) : !cir.ptr<!s32i> {test.var = "i32"}
+ cir.return
+}
+
+// CHECK: acc.private.recipe @private_i32 : !cir.ptr<!s32i> init {
+// CHECK: ^bb0(%{{.*}}: !cir.ptr<!s32i>):
+// CHECK: %[[ALLOC:.*]] = cir.alloca "i32" align(4) : !cir.ptr<!s32i> {acc.var_name = #acc.var_name<"i32">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!s32i>
+// CHECK: }
+// CHECK-NOT: copy
+// CHECK-NOT: destroy
+
+// -----
+
+cir.func @test_f32() {
+ %0 = cir.alloca "f32" align(4) : !cir.ptr<!cir.float> {test.var = "f32"}
+ cir.return
+}
+
+// CHECK: acc.private.recipe @private_f32 : !cir.ptr<!cir.float> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "f32" align(4) : !cir.ptr<!cir.float> {acc.var_name = #acc.var_name<"f32">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!cir.float>
+// CHECK: }
+// CHECK-NOT: copy
+// CHECK-NOT: destroy
+
+// -----
+
+cir.func @test_f64() {
+ %0 = cir.alloca "f64" align(8) : !cir.ptr<!cir.double> {test.var = "f64"}
+ cir.return
+}
+
+// CHECK: acc.private.recipe @private_f64 : !cir.ptr<!cir.double> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "f64" align(8) : !cir.ptr<!cir.double> {acc.var_name = #acc.var_name<"f64">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!cir.double>
+// CHECK: }
+// CHECK-NOT: copy
+// CHECK-NOT: destroy
+
+// -----
+
+cir.func @test_bool() {
+ %0 = cir.alloca "bool" align(1) : !cir.ptr<!cir.bool> {test.var = "bool"}
+ cir.return
+}
+
+// CHECK: acc.private.recipe @private_bool : !cir.ptr<!cir.bool> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "bool" align(1) : !cir.ptr<!cir.bool> {acc.var_name = #acc.var_name<"bool">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!cir.bool>
+// CHECK: }
+// CHECK-NOT: copy
+// CHECK-NOT: destroy
+
+// -----
+
+!s32i = !cir.int<s, 32>
+
+cir.func @test_ptr() {
+ %0 = cir.alloca "ptr" align(8) : !cir.ptr<!cir.ptr<!s32i>> {test.var = "ptr"}
+ cir.return
+}
+
+// CHECK: acc.private.recipe @private_ptr : !cir.ptr<!cir.ptr<!s32i>> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "ptr" align(8) : !cir.ptr<!cir.ptr<!s32i>> {acc.var_name = #acc.var_name<"ptr">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!cir.ptr<!s32i>>
+// CHECK: }
+// CHECK-NOT: copy
+// CHECK-NOT: destroy
+
+// -----
+
+!s32i = !cir.int<s, 32>
+
+cir.func @test_addrspace() {
+ %0 = cir.alloca "addrspace" align(4) : !cir.ptr<!s32i, lang_address_space(offload_global)> {test.var = "addrspace"}
+ cir.return
+}
+
+// CHECK: acc.private.recipe @private_addrspace : !cir.ptr<!s32i, lang_address_space(offload_global)> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "addrspace" align(4) : !cir.ptr<!s32i, lang_address_space(offload_global)> {acc.var_name = #acc.var_name<"addrspace">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!s32i, lang_address_space(offload_global)>
+// CHECK: }
+// CHECK-NOT: copy
+// CHECK-NOT: destroy
+
+// -----
+
+!s32i = !cir.int<s, 32>
+
+cir.func @test_array_1d() {
+ %0 = cir.alloca "array_1d" align(4) : !cir.ptr<!cir.array<!s32i x 100>> {test.var = "array_1d"}
+ cir.return
+}
+
+// CHECK: acc.private.recipe @private_array_1d : !cir.ptr<!cir.array<!s32i x 100>> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "array_1d" align(4) : !cir.ptr<!cir.array<!s32i x 100>> {acc.var_name = #acc.var_name<"array_1d">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!cir.array<!s32i x 100>>
+// CHECK: }
+// CHECK-NOT: copy
+// CHECK-NOT: destroy
+
+// -----
+
+!s32i = !cir.int<s, 32>
+
+cir.func @test_array_2d() {
+ %0 = cir.alloca "array_2d" align(4) : !cir.ptr<!cir.array<!cir.array<!s32i x 20> x 10>> {test.var = "array_2d"}
+ cir.return
+}
+
+// CHECK: acc.private.recipe @private_array_2d : !cir.ptr<!cir.array<!cir.array<!s32i x 20> x 10>> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "array_2d" align(4) : !cir.ptr<!cir.array<!cir.array<!s32i x 20> x 10>> {acc.var_name = #acc.var_name<"array_2d">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!cir.array<!cir.array<!s32i x 20> x 10>>
+// CHECK: }
+// CHECK-NOT: copy
+// CHECK-NOT: destroy
+
+// -----
+
+// Global address. There is no alloca.
+!s32i = !cir.int<s, 32>
+
+cir.global external @gscalar = #cir.int<0> : !s32i
+
+cir.func @test_global() {
+ %addr = cir.get_global @gscalar : !cir.ptr<!s32i> {test.var = "global"}
+ cir.return
+}
+
+// CHECK: acc.private.recipe @private_global : !cir.ptr<!s32i> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "global" align(4) : !cir.ptr<!s32i> {acc.var_name = #acc.var_name<"global">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!s32i>
+// CHECK: }
+// CHECK-NOT: copy
+// CHECK-NOT: destroy
+
+// -----
+
+// Loaded pointer. The load result has no alloca.
+!s32i = !cir.int<s, 32>
+
+cir.func @test_loaded() {
+ %slot = cir.alloca "slot" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ %p = cir.load %slot : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i> {test.var = "loaded"}
+ cir.return
+}
+
+// CHECK: acc.private.recipe @private_loaded : !cir.ptr<!s32i> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "loaded" align(4) : !cir.ptr<!s32i> {acc.var_name = #acc.var_name<"loaded">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!s32i>
+// CHECK: }
+// CHECK-NOT: copy
+// CHECK-NOT: destroy
+
+// -----
+
+// Function argument. There is no alloca.
+!s32i = !cir.int<s, 32>
+
+cir.func @test_arg(%arg: !cir.ptr<!s32i>) {
+ %zero = cir.const #cir.int<0> : !s32i
+ %p = cir.ptr_stride %arg, %zero : (!cir.ptr<!s32i>, !s32i) -> !cir.ptr<!s32i> {test.var = "arg"}
+ cir.return
+}
+
+// CHECK: acc.private.recipe @private_arg : !cir.ptr<!s32i> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "arg" align(4) : !cir.ptr<!s32i> {acc.var_name = #acc.var_name<"arg">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!s32i>
+// CHECK: }
+// CHECK-NOT: copy
+// CHECK-NOT: destroy
+
+// -----
+
+// Loaded pointer to a constant array. There is no alloca of the array.
+!s32i = !cir.int<s, 32>
+
+cir.func @test_loaded_array() {
+ %slot = cir.alloca "slot" align(8) : !cir.ptr<!cir.ptr<!cir.array<!s32i x 4>>>
+ %p = cir.load %slot : !cir.ptr<!cir.ptr<!cir.array<!s32i x 4>>>, !cir.ptr<!cir.array<!s32i x 4>> {test.var = "loaded_array"}
+ cir.return
+}
+
+// CHECK: acc.private.recipe @private_loaded_array : !cir.ptr<!cir.array<!s32i x 4>> init {
+// CHECK: %[[ALLOC:.*]] = cir.alloca "loaded_array" align(4) : !cir.ptr<!cir.array<!s32i x 4>> {acc.var_name = #acc.var_name<"loaded_array">}
+// CHECK: acc.yield %[[ALLOC]] : !cir.ptr<!cir.array<!s32i x 4>>
+// CHECK: }
+// CHECK-NOT: copy
+// CHECK-NOT: destroy
+
+// -----
+
+// Complex scalar.
+cir.func @test_complex() {
+ %0 = cir.alloca "complex" align(4) : !cir.ptr<!cir.complex<!cir.float>> {test.var = "complex"}
+ cir.return
+}
+
+// CHECK: acc.private.recipe @private_complex : !cir.ptr<!cir.complex<!cir.float>> init {
+// CHECK: cir.alloca "complex" align(4) : !cir.ptr<!cir.complex<!cir.float>>
+// CHECK: acc.yield
+// CHECK: }
+// CHECK-NOT: copy
+// CHECK-NOT: destroy
diff --git a/clang/test/CIR/OpenACC/acc-recipe-populate-unsized.cir b/clang/test/CIR/OpenACC/acc-recipe-populate-unsized.cir
new file mode 100644
index 00000000000000..f28eb3982fbcce
--- /dev/null
+++ b/clang/test/CIR/OpenACC/acc-recipe-populate-unsized.cir
@@ -0,0 +1,43 @@
+// RUN: cir-opt %s -test-acc-recipe-populate=recipe-type=firstprivate -verify-diagnostics
+
+// A recipe is created for a scalar or a constant array.
+
+!s32i = !cir.int<s, 32>
+!u8i = !cir.int<u, 8>
+!rec_incomplete = !cir.struct<"incomplete" incomplete>
+!rec_point = !cir.struct<"point" {data !s32i, data !s32i, data !s32i}>
+!rec_u = !cir.union<"u" {data !s32i, data !u8i}>
+
+cir.func @test_unsized() {
+ // expected-error @below {{Failed to create firstprivate recipe for voidp}}
+ %voidp = cir.alloca "voidp" align(1) : !cir.ptr<!cir.void> {test.var = "voidp"}
+ // expected-error @below {{Failed to create firstprivate recipe for funcp}}
+ %funcp = cir.alloca "funcp" align(8) : !cir.ptr<!cir.func<() -> !s32i>> {test.var = "funcp"}
+ // expected-error @below {{Failed to create firstprivate recipe for incomplete}}
+ %incomplete = cir.alloca "incomplete" align(1) : !cir.ptr<!rec_incomplete> {test.var = "incomplete"}
+ // expected-error @below {{Failed to create firstprivate recipe for record}}
+ %record = cir.alloca "record" align(4) : !cir.ptr<!rec_point> {test.var = "record"}
+ // expected-error @below {{Failed to create firstprivate recipe for union}}
+ %union = cir.alloca "union" align(4) : !cir.ptr<!rec_u> {test.var = "union"}
+ // expected-error @below {{Failed to create firstprivate recipe for vector}}
+ %vector = cir.alloca "vector" align(16) : !cir.ptr<!cir.vector<4 x !s32i>> {test.var = "vector"}
+ // expected-error @below {{Failed to create firstprivate recipe for scalable}}
+ %scalable = cir.alloca "scalable" align(16) : !cir.ptr<!cir.vector<[4] x !s32i>> {test.var = "scalable"}
+ cir.return
+}
+
+// A function argument and a loaded pointer have no alloca. A record is not
+// allocated from the pointer type either.
+cir.func @test_record_arg(%arg: !cir.ptr<!rec_point>) {
+ %zero = cir.const #cir.int<0> : !s32i
+ // expected-error @below {{Failed to create firstprivate recipe for record_arg}}
+ %p = cir.ptr_stride %arg, %zero : (!cir.ptr<!rec_point>, !s32i) -> !cir.ptr<!rec_point> {test.var = "record_arg"}
+ cir.return
+}
+
+cir.func @test_loaded_record() {
+ %slot = cir.alloca "slot" align(8) : !cir.ptr<!cir.ptr<!rec_point>>
+ // expected-error @below {{Failed to create firstprivate recipe for loaded_record}}
+ %p = cir.load %slot : !cir.ptr<!cir.ptr<!rec_point>>, !cir.ptr<!rec_point> {test.var = "loaded_record"}
+ cir.return
+}
diff --git a/clang/tools/cir-opt/CMakeLists.txt b/clang/tools/cir-opt/CMakeLists.txt
index cd0c3507e29fd3..b1802ee925c956 100644
--- a/clang/tools/cir-opt/CMakeLists.txt
+++ b/clang/tools/cir-opt/CMakeLists.txt
@@ -2,7 +2,10 @@ include_directories(${LLVM_MAIN_SRC_DIR}/../mlir/include)
include_directories(${LLVM_BINARY_DIR}/tools/mlir/include)
if(CLANG_INCLUDE_TESTS)
- set(cir_opt_test_libs CIRTestAnalysis)
+ set(cir_opt_test_libs
+ CIRTestAnalysis
+ MLIROpenACCTestPasses
+ )
endif()
add_clang_tool(cir-opt
diff --git a/clang/tools/cir-opt/cir-opt.cpp b/clang/tools/cir-opt/cir-opt.cpp
index 63c52a046c4414..b7ee4ccde7f556 100644
--- a/clang/tools/cir-opt/cir-opt.cpp
+++ b/clang/tools/cir-opt/cir-opt.cpp
@@ -31,6 +31,10 @@
namespace cir::test {
void registerTestCIRAliasAnalysisPass();
} // namespace cir::test
+
+namespace mlir::test {
+void registerTestOpenACC();
+} // namespace mlir::test
#endif
struct CIRToLLVMPipelineOptions
@@ -48,6 +52,7 @@ int main(int argc, char **argv) {
#ifdef CLANG_INCLUDE_TESTS
cir::test::registerTestCIRAliasAnalysisPass();
+ mlir::test::registerTestOpenACC();
#endif
registry.insert<mlir::gpu::GPUDialect, mlir::memref::MemRefDialect,
mlir::LLVM::LLVMDialect>();
diff --git a/clang/unittests/CIR/PointerLikeTest.cpp b/clang/unittests/CIR/PointerLikeTest.cpp
index 01707738a4c00a..ee5f2116c8dad5 100644
--- a/clang/unittests/CIR/PointerLikeTest.cpp
+++ b/clang/unittests/CIR/PointerLikeTest.cpp
@@ -6,11 +6,12 @@
//
//===----------------------------------------------------------------------===//
//
-// Unit tests for CIR implementation of OpenACC's PointertLikeType interface
+// Unit tests for CIR implementation of OpenACC's PointerLikeType interface
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/OpenACC/OpenACC.h"
+#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/IR/MLIRContext.h"
@@ -306,6 +307,10 @@ TEST_F(CIROpenACCPointerLikeTest, testPointerToFloat) {
testScalarType(cir::DoubleType::get(&context));
}
+TEST_F(CIROpenACCPointerLikeTest, testPointerToComplex) {
+ testScalarType(cir::ComplexType::get(cir::SingleType::get(&context)));
+}
+
TEST_F(CIROpenACCPointerLikeTest, testPointerToPointer) {
mlir::Type i32Ty = cir::IntType::get(&context, 32, true);
mlir::Type ptrTy = cir::PointerType::get(i32Ty);
@@ -371,3 +376,542 @@ TEST_F(CIROpenACCPointerLikeTest, testPointerToStructMember) {
cir::RecordType::getAllDataKinds(members));
testPointerToMemberType(structTy, mlir::acc::VariableTypeCategory::composite);
}
+
+TEST_F(CIROpenACCPointerLikeTest, testPointerCast) {
+ OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
+ b.setInsertionPointToStart(module->getBody());
+
+ Type i32Ty = cir::IntType::get(&context, 32, true);
+ Type ptrTy = cir::PointerType::get(i32Ty);
+ Value host = cir::AllocaOp::create(b, loc, ptrTy, "n", getAlignOne(&context));
+ auto pointerLike = cast<mlir::acc::PointerLikeType>(ptrTy);
+
+ Type i8Ptr = cir::PointerType::get(cir::IntType::get(&context, 8, true));
+ Value asI8Ptr = pointerLike.genCast(b, loc, host, i8Ptr);
+ ASSERT_TRUE(asI8Ptr);
+ EXPECT_EQ(asI8Ptr.getDefiningOp<cir::CastOp>().getKind(),
+ cir::CastKind::bitcast);
+
+ auto globalSpace = cir::LangAddressSpaceAttr::get(
+ &context, cir::LangAddressSpace::OffloadGlobal);
+ Type globalPtr = cir::PointerType::get(i32Ty, globalSpace);
+ Value asGlobal = pointerLike.genCast(b, loc, host, globalPtr);
+ ASSERT_TRUE(asGlobal);
+ EXPECT_EQ(asGlobal.getDefiningOp<cir::CastOp>().getKind(),
+ cir::CastKind::address_space);
+
+ Value loaded = pointerLike.genLoad(
+ b, loc, cast<TypedValue<mlir::acc::PointerLikeType>>(host), i32Ty);
+ ASSERT_TRUE(loaded);
+ Value asPtr = pointerLike.genCast(b, loc, loaded, ptrTy);
+ ASSERT_TRUE(asPtr);
+ EXPECT_EQ(asPtr.getDefiningOp<cir::CastOp>().getKind(),
+ cir::CastKind::int_to_ptr);
+
+ Type i64Ty = cir::IntType::get(&context, 64, true);
+ // Pointer-to-integer produces no cast because that conversion is not
+ // implemented. This records the current gap; update the check when support
+ // is added.
+ EXPECT_FALSE(pointerLike.genCast(b, loc, host, i64Ty));
+ // Value-to-value casts are not produced here.
+ EXPECT_FALSE(pointerLike.genCast(b, loc, loaded, i64Ty));
+}
+
+// A pointee with no size cannot be allocated or copied.
+TEST_F(CIROpenACCPointerLikeTest, testUnsizedPointeeIsNotAllocated) {
+ OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
+ b.setInsertionPointToStart(module->getBody());
+ Type voidPtr = cir::PointerType::get(cir::VoidType::get(&context));
+ auto pointerLike = cast<mlir::acc::PointerLikeType>(voidPtr);
+ bool needsFree = false;
+ Value host =
+ cir::AllocaOp::create(b, loc, voidPtr, "p", getAlignOne(&context));
+ EXPECT_FALSE(pointerLike.genAllocate(b, loc, "p", voidPtr, host, needsFree));
+ EXPECT_FALSE(pointerLike.genCopy(
+ b, loc, cast<TypedValue<mlir::acc::PointerLikeType>>(host),
+ cast<TypedValue<mlir::acc::PointerLikeType>>(host), voidPtr));
+}
+
+TEST_F(CIROpenACCPointerLikeTest, testOffloadAddressSpace) {
+ Type i32Ty = cir::IntType::get(&context, 32, true);
+ auto global = cir::LangAddressSpaceAttr::get(
+ &context, cir::LangAddressSpace::OffloadGlobal);
+ auto generic = cir::LangAddressSpaceAttr::get(
+ &context, cir::LangAddressSpace::OffloadGeneric);
+ Type globalPtr = cir::PointerType::get(i32Ty, global);
+ Type genericPtr = cir::PointerType::get(i32Ty, generic);
+ Type hostPtr = cir::PointerType::get(i32Ty);
+
+ OwningOpRef<cir::AllocaOp> globalAlloca =
+ cir::AllocaOp::create(b, loc, globalPtr, "g", getAlignOne(&context));
+ OwningOpRef<cir::AllocaOp> genericAlloca =
+ cir::AllocaOp::create(b, loc, genericPtr, "n", getAlignOne(&context));
+ OwningOpRef<cir::AllocaOp> hostAlloca =
+ cir::AllocaOp::create(b, loc, hostPtr, "h", getAlignOne(&context));
+
+ auto hostShared = cir::LangAddressSpaceAttr::get(
+ &context, cir::LangAddressSpace::OffloadGlobalHost);
+ Type hostSharedPtr = cir::PointerType::get(i32Ty, hostShared);
+ OwningOpRef<cir::AllocaOp> hostSharedAlloca =
+ cir::AllocaOp::create(b, loc, hostSharedPtr, "hs", getAlignOne(&context));
+
+ auto globalLike = cast<mlir::acc::PointerLikeType>(globalPtr);
+ auto genericLike = cast<mlir::acc::PointerLikeType>(genericPtr);
+ auto hostLike = cast<mlir::acc::PointerLikeType>(hostPtr);
+ auto hostSharedLike = cast<mlir::acc::PointerLikeType>(hostSharedPtr);
+ EXPECT_TRUE(globalLike.isDeviceAccessible(globalAlloca.get(), nullptr));
+ EXPECT_TRUE(globalLike.isInDeviceMemory(globalAlloca.get(), nullptr));
+ EXPECT_TRUE(genericLike.isDeviceAccessible(genericAlloca.get(), nullptr));
+ EXPECT_FALSE(genericLike.isInDeviceMemory(genericAlloca.get(), nullptr));
+ EXPECT_TRUE(
+ hostSharedLike.isDeviceAccessible(hostSharedAlloca.get(), nullptr));
+ EXPECT_FALSE(
+ hostSharedLike.isInDeviceMemory(hostSharedAlloca.get(), nullptr));
+ EXPECT_FALSE(hostLike.isDeviceAccessible(hostAlloca.get(), nullptr));
+ EXPECT_FALSE(hostLike.isInDeviceMemory(hostAlloca.get(), nullptr));
+}
+
+TEST_F(CIROpenACCPointerLikeTest, testGetAsMemRefType) {
+ OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
+ Type f32 = cir::SingleType::get(&context);
+ Type i32 = cir::IntType::get(&context, 32, true);
+
+ auto asMemRef = [&](Type pointer) {
+ return cast<mlir::acc::PointerLikeType>(pointer).getAsMemRefType(*module);
+ };
+
+ EXPECT_EQ(asMemRef(cir::PointerType::get(f32)),
+ MemRefType::get({}, Float32Type::get(&context)));
+ EXPECT_EQ(asMemRef(cir::PointerType::get(cir::BoolType::get(&context))),
+ MemRefType::get({}, IntegerType::get(&context, 8)));
+
+ EXPECT_EQ(asMemRef(cir::PointerType::get(cir::ArrayType::get(f32, 8))),
+ MemRefType::get({8}, Float32Type::get(&context)));
+
+ Type inner = cir::ArrayType::get(f32, 4);
+ EXPECT_EQ(asMemRef(cir::PointerType::get(cir::ArrayType::get(inner, 3))),
+ MemRefType::get({3, 4}, Float32Type::get(&context)));
+
+ EXPECT_FALSE(asMemRef(cir::PointerType::get(cir::PointerType::get(f32))));
+ EXPECT_FALSE(asMemRef(cir::PointerType::get(cir::VoidType::get(&context))));
+
+ cir::RecordType structTy = cir::StructType::get(
+ &context, getUniqueRecordName("Mem"), /*is_class=*/false);
+ Type members[] = {i32};
+ structTy.complete(members, /*packed=*/false, /*padding=*/{},
+ cir::RecordType::getAllDataKinds(members));
+ EXPECT_FALSE(asMemRef(cir::PointerType::get(structTy)));
+}
+
+TEST_F(CIROpenACCPointerLikeTest, testDynamicArrayIsNotScalar) {
+ OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
+ b.setInsertionPointToStart(module->getBody());
+
+ Type i32Ty = cir::IntType::get(&context, 32, true);
+ Type ptrTy = cir::PointerType::get(i32Ty);
+ Type countTy = cir::IntType::get(&context, 64, false);
+ Value count = cir::ConstantOp::create(b, loc, cir::IntAttr::get(countTy, 4));
+ Value vla =
+ cir::AllocaOp::create(b, loc, ptrTy, "vla", getAlignOne(&context), count);
+
+ auto pointerLike = cast<mlir::acc::PointerLikeType>(ptrTy);
+ EXPECT_EQ(pointerLike.getPointeeTypeCategory(
+ cast<TypedValue<mlir::acc::PointerLikeType>>(vla), i32Ty),
+ mlir::acc::VariableTypeCategory::array);
+
+ Type i8Ptr = cir::PointerType::get(cir::IntType::get(&context, 8, true));
+ Value casted =
+ cir::CastOp::create(b, loc, i8Ptr, cir::CastKind::bitcast, vla);
+ EXPECT_EQ(cast<mlir::acc::PointerLikeType>(i8Ptr).getPointeeTypeCategory(
+ cast<TypedValue<mlir::acc::PointerLikeType>>(casted), i32Ty),
+ mlir::acc::VariableTypeCategory::array);
+
+ Value index = cir::ConstantOp::create(b, loc, cir::IntAttr::get(i32Ty, 1));
+ Value element = cir::PtrStrideOp::create(b, loc, ptrTy, vla, index);
+ EXPECT_EQ(pointerLike.getPointeeTypeCategory(
+ cast<TypedValue<mlir::acc::PointerLikeType>>(element), i32Ty),
+ mlir::acc::VariableTypeCategory::array);
+
+ bool needsFree = true;
+ Value privatized =
+ pointerLike.genAllocate(b, loc, "vla", ptrTy, vla, needsFree);
+ ASSERT_TRUE(privatized);
+ auto privAlloca = privatized.getDefiningOp<cir::AllocaOp>();
+ ASSERT_TRUE(privAlloca);
+ EXPECT_TRUE(privAlloca.isDynamic());
+ auto privCount =
+ privAlloca.getDynAllocSize().getDefiningOp<cir::ConstantOp>();
+ ASSERT_TRUE(privCount);
+ EXPECT_EQ(privCount.getValue(),
+ count.getDefiningOp<cir::ConstantOp>().getValue());
+ EXPECT_EQ(privAlloca.getAllocaType(), i32Ty);
+}
+
+// When the pointer is not produced by an allocation, only its type describes
+// the object. A scalar or a fixed-size array is complete in that type, so it
+// is allocated. A type with no size cannot be.
+TEST_F(CIROpenACCPointerLikeTest, testAllocateWithoutAlloca) {
+ OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
+ b.setInsertionPointToStart(module->getBody());
+
+ Type i32 = cir::IntType::get(&context, 32, true);
+ Type i32Ptr = cir::PointerType::get(i32);
+ Type arrayPtr = cir::PointerType::get(cir::ArrayType::get(i32, 4));
+ Type voidPtr = cir::PointerType::get(cir::VoidType::get(&context));
+
+ auto allocateArg = [&](Type ptrTy, StringRef name) {
+ b.setInsertionPointToStart(module->getBody());
+ auto funcTy = cir::FuncType::get(SmallVector<Type, 1>{ptrTy},
+ cir::VoidType::get(&context));
+ cir::FuncOp func = cir::FuncOp::create(b, loc, name, funcTy);
+ b.setInsertionPointToStart(func.addEntryBlock());
+ bool needsFree = true;
+ Value arg = func.getBody().front().getArgument(0);
+ Value allocated = cast<mlir::acc::PointerLikeType>(ptrTy).genAllocate(
+ b, loc, name, ptrTy, arg, needsFree);
+ return std::pair<Value, bool>(allocated, needsFree);
+ };
+
+ auto [scalar, scalarNeedsFree] = allocateArg(i32Ptr, "scalar");
+ ASSERT_TRUE(scalar);
+ EXPECT_FALSE(scalarNeedsFree);
+ auto scalarAlloca = scalar.getDefiningOp<cir::AllocaOp>();
+ ASSERT_TRUE(scalarAlloca);
+ EXPECT_FALSE(scalarAlloca.isDynamic());
+ EXPECT_EQ(scalarAlloca.getAllocaType(), i32);
+
+ auto [array, arrayNeedsFree] = allocateArg(arrayPtr, "array");
+ ASSERT_TRUE(array);
+ EXPECT_FALSE(arrayNeedsFree);
+ auto arrayAlloca = array.getDefiningOp<cir::AllocaOp>();
+ ASSERT_TRUE(arrayAlloca);
+ EXPECT_EQ(arrayAlloca.getAllocaType(), cir::ArrayType::get(i32, 4));
+ EXPECT_FALSE(arrayAlloca.isDynamic());
+
+ auto [voidArg, voidNeedsFree] = allocateArg(voidPtr, "voidp");
+ EXPECT_FALSE(voidArg);
+
+ // A loaded pointer describes the object it points to, not the slot it was
+ // loaded from.
+ b.setInsertionPointToStart(module->getBody());
+ Type ptrPtr = cir::PointerType::get(i32Ptr);
+ Value slot =
+ cir::AllocaOp::create(b, loc, ptrPtr, "slot", getAlignOne(&context));
+ Value loaded = cir::LoadOp::create(b, loc, slot);
+ bool needsFree = true;
+ Value fromLoad = cast<mlir::acc::PointerLikeType>(i32Ptr).genAllocate(
+ b, loc, "loaded", i32Ptr, loaded, needsFree);
+ ASSERT_TRUE(fromLoad);
+ EXPECT_FALSE(needsFree);
+ auto loadedAlloca = fromLoad.getDefiningOp<cir::AllocaOp>();
+ ASSERT_TRUE(loadedAlloca);
+ EXPECT_EQ(loadedAlloca.getAllocaType(), i32);
+ EXPECT_FALSE(loadedAlloca.isDynamic());
+}
+
+// A conversion that still names the whole allocation allocates that object,
+// and a constant element count is part of its extent. An offset or a member
+// names only part of the allocation, so the whole object is not allocated.
+TEST_F(CIROpenACCPointerLikeTest, testAllocateThroughPointerViews) {
+ OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
+ b.setInsertionPointToStart(module->getBody());
+
+ Type i32 = cir::IntType::get(&context, 32, true);
+ Type i8 = cir::IntType::get(&context, 8, true);
+ Type i32Ptr = cir::PointerType::get(i32);
+ Type i8Ptr = cir::PointerType::get(i8);
+ Type arrayTy = cir::ArrayType::get(i32, 4);
+ Type arrayPtr = cir::PointerType::get(arrayTy);
+ IntegerAttr align = getAlignOne(&context);
+
+ auto allocate = [&](Value view) {
+ bool needsFree = true;
+ Value allocated =
+ cast<mlir::acc::PointerLikeType>(view.getType())
+ .genAllocate(b, loc, "priv", view.getType(), view, needsFree);
+ if (allocated)
+ EXPECT_FALSE(needsFree);
+ return allocated;
+ };
+
+ Value scalar = cir::AllocaOp::create(b, loc, i32Ptr, "scalar", align);
+ Value scalarCast =
+ cir::CastOp::create(b, loc, i8Ptr, cir::CastKind::bitcast, scalar);
+ Value scalarStride = cir::PtrStrideOp::create(
+ b, loc, i32Ptr, scalar,
+ cir::ConstantOp::create(b, loc, cir::IntAttr::get(i32, 1)));
+
+ Value castAlloc = allocate(scalarCast);
+ auto castOp = castAlloc.getDefiningOp<cir::CastOp>();
+ ASSERT_TRUE(castOp);
+ EXPECT_EQ(castOp.getKind(), cir::CastKind::bitcast);
+ auto castBase = castOp.getSrc().getDefiningOp<cir::AllocaOp>();
+ ASSERT_TRUE(castBase);
+ EXPECT_EQ(castBase.getAllocaType(), i32);
+ EXPECT_FALSE(castBase.isDynamic());
+
+ EXPECT_FALSE(allocate(scalarStride));
+
+ Value array = cir::AllocaOp::create(b, loc, arrayPtr, "array", align);
+ Value decay = cir::CastOp::create(b, loc, i32Ptr,
+ cir::CastKind::array_to_ptrdecay, array);
+ Value element = cir::PtrStrideOp::create(
+ b, loc, i32Ptr, decay,
+ cir::ConstantOp::create(b, loc, cir::IntAttr::get(i32, 2)));
+ Value decayedByte =
+ cir::CastOp::create(b, loc, i8Ptr, cir::CastKind::bitcast, element);
+
+ EXPECT_FALSE(allocate(element));
+ EXPECT_FALSE(allocate(decayedByte));
+
+ Type countTy = cir::IntType::get(&context, 64, false);
+ Value count = cir::ConstantOp::create(b, loc, cir::IntAttr::get(countTy, 4));
+ Value vla = cir::AllocaOp::create(b, loc, i32Ptr, "vla", align, count);
+ Value vlaCast =
+ cir::CastOp::create(b, loc, i8Ptr, cir::CastKind::bitcast, vla);
+ Value vlaElement = cir::PtrStrideOp::create(
+ b, loc, i32Ptr, vla,
+ cir::ConstantOp::create(b, loc, cir::IntAttr::get(i32, 1)));
+
+ Value vlaCastAlloc = allocate(vlaCast);
+ auto vlaCastOp = vlaCastAlloc.getDefiningOp<cir::CastOp>();
+ ASSERT_TRUE(vlaCastOp);
+ auto vlaCastBase = vlaCastOp.getSrc().getDefiningOp<cir::AllocaOp>();
+ ASSERT_TRUE(vlaCastBase);
+ EXPECT_TRUE(vlaCastBase.isDynamic());
+ auto vlaCastCount =
+ vlaCastBase.getDynAllocSize().getDefiningOp<cir::ConstantOp>();
+ ASSERT_TRUE(vlaCastCount);
+ EXPECT_EQ(vlaCastCount.getValue(),
+ count.getDefiningOp<cir::ConstantOp>().getValue());
+ EXPECT_EQ(vlaCastBase.getAllocaType(), i32);
+
+ EXPECT_FALSE(allocate(vlaElement));
+
+ cir::RecordType record =
+ cir::StructType::get(&context, getUniqueRecordName("Point"),
+ /*is_class=*/false);
+ Type fields[] = {i32, arrayTy};
+ record.complete(fields, /*packed=*/false, /*padding=*/{},
+ cir::RecordType::getAllDataKinds(fields));
+ Type recordPtr = cir::PointerType::get(record);
+ Value object = cir::AllocaOp::create(b, loc, recordPtr, "object", align);
+ Value field = cir::GetMemberOp::create(b, loc, i32Ptr, object, "x", 0u);
+ Value arrayField =
+ cir::GetMemberOp::create(b, loc, arrayPtr, object, "a", 1u);
+ EXPECT_FALSE(allocate(field));
+ EXPECT_FALSE(allocate(arrayField));
+}
+
+// Decaying an array to a pointer does not change the allocated object, so
+// the copy covers the array.
+TEST_F(CIROpenACCPointerLikeTest, testCopyCoversAllocatedObject) {
+ OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
+ b.setInsertionPointToStart(module->getBody());
+
+ Type i32 = cir::IntType::get(&context, 32, true);
+ Type i32Ptr = cir::PointerType::get(i32);
+ Type arrayTy = cir::ArrayType::get(i32, 4);
+ Type arrayPtr = cir::PointerType::get(arrayTy);
+ auto pointerLike = cast<mlir::acc::PointerLikeType>(i32Ptr);
+
+ Value array =
+ cir::AllocaOp::create(b, loc, arrayPtr, "array", getAlignOne(&context));
+ Value decay = cir::CastOp::create(b, loc, i32Ptr,
+ cir::CastKind::array_to_ptrdecay, array);
+ bool needsFree = true;
+ Value privatized =
+ pointerLike.genAllocate(b, loc, "array", i32Ptr, decay, needsFree);
+ ASSERT_TRUE(privatized);
+ EXPECT_TRUE(pointerLike.genCopy(
+ b, loc, cast<TypedValue<mlir::acc::PointerLikeType>>(privatized),
+ cast<TypedValue<mlir::acc::PointerLikeType>>(decay), i32Ptr));
+ cir::CopyOp copy;
+ module->walk([&](cir::CopyOp op) { copy = op; });
+ ASSERT_TRUE(copy);
+ EXPECT_EQ(cast<cir::PointerType>(copy.getSrc().getType()).getPointee(),
+ arrayTy);
+}
+
+// An offset of zero still names the allocated object, so that object is
+// allocated.
+TEST_F(CIROpenACCPointerLikeTest, testZeroStrideAllocatesBase) {
+ OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
+ b.setInsertionPointToStart(module->getBody());
+
+ Type i32 = cir::IntType::get(&context, 32, true);
+ Type i32Ptr = cir::PointerType::get(i32);
+ Value scalar =
+ cir::AllocaOp::create(b, loc, i32Ptr, "scalar", getAlignOne(&context));
+ Value zero = cir::ConstantOp::create(b, loc, cir::IntAttr::get(i32, 0));
+ Value view = cir::PtrStrideOp::create(b, loc, i32Ptr, scalar, zero);
+
+ bool needsFree = true;
+ Value allocated = cast<mlir::acc::PointerLikeType>(i32Ptr).genAllocate(
+ b, loc, "priv", i32Ptr, view, needsFree);
+ ASSERT_TRUE(allocated);
+ EXPECT_FALSE(needsFree);
+ auto alloca = allocated.getDefiningOp<cir::AllocaOp>();
+ ASSERT_TRUE(alloca);
+ EXPECT_EQ(alloca.getAllocaType(), i32);
+ EXPECT_FALSE(alloca.isDynamic());
+}
+
+// The number of elements is known only at run time, so it is not part of the
+// type. The amount copied comes from the type, so this object cannot be
+// copied. Allocating an object of runtime size is not supported.
+TEST_F(CIROpenACCPointerLikeTest, testRuntimeSizeIsNotAllocated) {
+ OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
+ b.setInsertionPointToStart(module->getBody());
+
+ Type i32 = cir::IntType::get(&context, 32, true);
+ Type i32Ptr = cir::PointerType::get(i32);
+ Type countTy = cir::IntType::get(&context, 64, false);
+ Type countPtr = cir::PointerType::get(countTy);
+ IntegerAttr align = getAlignOne(&context);
+
+ Value countSlot = cir::AllocaOp::create(b, loc, countPtr, "n.addr", align);
+ Value count = cir::LoadOp::create(b, loc, countSlot);
+ Value vla = cir::AllocaOp::create(b, loc, i32Ptr, "vla", align, count);
+ Value dst = cir::AllocaOp::create(b, loc, i32Ptr, "dst", align);
+
+ auto pointerLike = cast<mlir::acc::PointerLikeType>(i32Ptr);
+ bool needsFree = true;
+ EXPECT_FALSE(pointerLike.genAllocate(b, loc, "vla", i32Ptr, vla, needsFree));
+ EXPECT_FALSE(pointerLike.genCopy(
+ b, loc, cast<TypedValue<mlir::acc::PointerLikeType>>(dst),
+ cast<TypedValue<mlir::acc::PointerLikeType>>(vla), i32Ptr));
+}
+
+// The element count is a constant, so the object is the whole array and the
+// copy covers it.
+TEST_F(CIROpenACCPointerLikeTest, testConstantSizeCopyCoversArray) {
+ OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
+ b.setInsertionPointToStart(module->getBody());
+
+ Type i32 = cir::IntType::get(&context, 32, true);
+ Type i32Ptr = cir::PointerType::get(i32);
+ Type countTy = cir::IntType::get(&context, 64, false);
+ Type arrayTy = cir::ArrayType::get(i32, 4);
+ IntegerAttr align = getAlignOne(&context);
+
+ Value count = cir::ConstantOp::create(b, loc, cir::IntAttr::get(countTy, 4));
+ Value src = cir::AllocaOp::create(b, loc, i32Ptr, "src", align, count);
+ Value dst = cir::AllocaOp::create(b, loc, i32Ptr, "dst", align, count);
+
+ auto pointerLike = cast<mlir::acc::PointerLikeType>(i32Ptr);
+ EXPECT_TRUE(pointerLike.genCopy(
+ b, loc, cast<TypedValue<mlir::acc::PointerLikeType>>(dst),
+ cast<TypedValue<mlir::acc::PointerLikeType>>(src), i32Ptr));
+
+ cir::CopyOp copy;
+ module->walk([&](cir::CopyOp op) { copy = op; });
+ ASSERT_TRUE(copy);
+ EXPECT_EQ(cast<cir::PointerType>(copy.getSrc().getType()).getPointee(),
+ arrayTy);
+ EXPECT_EQ(cast<cir::PointerType>(copy.getDst().getType()).getPointee(),
+ arrayTy);
+}
+
+// Moving the pointer to another address space does not change the object.
+// The allocated pointer remains in that address space.
+TEST_F(CIROpenACCPointerLikeTest, testAddressSpaceCastKeepsAddressSpace) {
+ OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
+ b.setInsertionPointToStart(module->getBody());
+
+ Type i32 = cir::IntType::get(&context, 32, true);
+ Type hostPtr = cir::PointerType::get(i32);
+ auto global = cir::LangAddressSpaceAttr::get(
+ &context, cir::LangAddressSpace::OffloadGlobal);
+ Type globalPtr = cir::PointerType::get(i32, global);
+
+ Value host =
+ cir::AllocaOp::create(b, loc, hostPtr, "h", getAlignOne(&context));
+ Value view = cir::CastOp::create(b, loc, globalPtr,
+ cir::CastKind::address_space, host);
+
+ bool needsFree = true;
+ Value allocated = cast<mlir::acc::PointerLikeType>(globalPtr).genAllocate(
+ b, loc, "priv", globalPtr, view, needsFree);
+ ASSERT_TRUE(allocated);
+ EXPECT_FALSE(needsFree);
+ EXPECT_EQ(allocated.getType(), globalPtr);
+ auto alloca = allocated.getDefiningOp<cir::AllocaOp>();
+ ASSERT_TRUE(alloca);
+ EXPECT_EQ(alloca.getAllocaType(), i32);
+}
+
+// The allocated object is the pointer. The memory it refers to belongs to a
+// different object.
+TEST_F(CIROpenACCPointerLikeTest, testPointerObjectAllocatesOnePointer) {
+ OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
+ b.setInsertionPointToStart(module->getBody());
+
+ Type i32 = cir::IntType::get(&context, 32, true);
+ Type i32Ptr = cir::PointerType::get(i32);
+ Type ptrPtr = cir::PointerType::get(i32Ptr);
+ Value slot =
+ cir::AllocaOp::create(b, loc, ptrPtr, "p", getAlignOne(&context));
+
+ bool needsFree = true;
+ Value allocated = cast<mlir::acc::PointerLikeType>(ptrPtr).genAllocate(
+ b, loc, "priv", ptrPtr, slot, needsFree);
+ ASSERT_TRUE(allocated);
+ EXPECT_FALSE(needsFree);
+ auto alloca = allocated.getDefiningOp<cir::AllocaOp>();
+ ASSERT_TRUE(alloca);
+ EXPECT_EQ(alloca.getAllocaType(), i32Ptr);
+ EXPECT_FALSE(alloca.isDynamic());
+}
+
+// Records, including a constant number of them, are an implementation
+// limitation. This test anchors that decision so it can be updated if
+// support is added.
+TEST_F(CIROpenACCPointerLikeTest, testRecordObjectIsNotAllocated) {
+ OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
+ b.setInsertionPointToStart(module->getBody());
+
+ Type i32 = cir::IntType::get(&context, 32, true);
+ Type countTy = cir::IntType::get(&context, 64, false);
+ cir::RecordType record =
+ cir::StructType::get(&context, getUniqueRecordName("S"),
+ /*is_class=*/false);
+ Type members[] = {i32, i32};
+ record.complete(members, /*packed=*/false, /*padding=*/{},
+ cir::RecordType::getAllDataKinds(members));
+ Type recordPtr = cir::PointerType::get(record);
+ IntegerAttr align = getAlignOne(&context);
+
+ Value plain = cir::AllocaOp::create(b, loc, recordPtr, "s", align);
+ Value count = cir::ConstantOp::create(b, loc, cir::IntAttr::get(countTy, 4));
+ Value sized = cir::AllocaOp::create(b, loc, recordPtr, "arr", align, count);
+
+ auto pointerLike = cast<mlir::acc::PointerLikeType>(recordPtr);
+ bool needsFree = true;
+ EXPECT_FALSE(
+ pointerLike.genAllocate(b, loc, "s", recordPtr, plain, needsFree));
+ EXPECT_FALSE(
+ pointerLike.genAllocate(b, loc, "arr", recordPtr, sized, needsFree));
+ EXPECT_FALSE(pointerLike.genCopy(
+ b, loc, cast<TypedValue<mlir::acc::PointerLikeType>>(plain),
+ cast<TypedValue<mlir::acc::PointerLikeType>>(sized), recordPtr));
+ EXPECT_FALSE(pointerLike.genFree(
+ b, loc, cast<TypedValue<mlir::acc::PointerLikeType>>(plain), Value(),
+ recordPtr));
+}
+
+// An object that can be allocated can be freed, even if there is nothing to
+// free.
+TEST_F(CIROpenACCPointerLikeTest, testFreeFollowsAllocaObject) {
+ OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
+ b.setInsertionPointToStart(module->getBody());
+
+ Type i32 = cir::IntType::get(&context, 32, true);
+ Type i32Ptr = cir::PointerType::get(i32);
+ Value scalar =
+ cir::AllocaOp::create(b, loc, i32Ptr, "scalar", getAlignOne(&context));
+
+ EXPECT_TRUE(cast<mlir::acc::PointerLikeType>(i32Ptr).genFree(
+ b, loc, cast<TypedValue<mlir::acc::PointerLikeType>>(scalar), Value(),
+ i32Ptr));
+}
>From 114ee092a6b252488b52eb2530a8306c2d54ac5d Mon Sep 17 00:00:00 2001
From: Razvan Lupusoru <rlupusoru at nvidia.com>
Date: Fri, 4 Dec 2026 07:39:30 -0800
Subject: [PATCH 2/3] For alloca search only consider alloca-preserving casts
---
.../OpenACC/CIROpenACCTypeInterfaces.cpp | 34 ++++-----
.../OpenACC/acc-recipe-populate-unsized.cir | 2 +-
clang/unittests/CIR/PointerLikeTest.cpp | 71 ++++++++++++++++---
3 files changed, 76 insertions(+), 31 deletions(-)
diff --git a/clang/lib/CIR/Dialect/OpenACC/CIROpenACCTypeInterfaces.cpp b/clang/lib/CIR/Dialect/OpenACC/CIROpenACCTypeInterfaces.cpp
index 854f23ed711740..2d96f6e2e06c4e 100644
--- a/clang/lib/CIR/Dialect/OpenACC/CIROpenACCTypeInterfaces.cpp
+++ b/clang/lib/CIR/Dialect/OpenACC/CIROpenACCTypeInterfaces.cpp
@@ -45,9 +45,7 @@ static AllocaInfo findAlloca(mlir::Value value) {
if (auto alloca = mlir::dyn_cast<cir::AllocaOp>(def))
return {alloca, baseEntity};
if (auto cast = mlir::dyn_cast<cir::CastOp>(def)) {
- baseEntity &= (cast.getKind() == cir::CastKind::bitcast ||
- cast.getKind() == cir::CastKind::address_space ||
- cast.getKind() == cir::CastKind::array_to_ptrdecay);
+ baseEntity &= cast.isAllocaPreservingCast();
value = cast.getSrc();
continue;
}
@@ -66,32 +64,32 @@ static AllocaInfo findAlloca(mlir::Value value) {
return {};
}
-static mlir::Type getBaseType(mlir::Value varPtr) {
- if (AllocaInfo found = findAlloca(varPtr))
- return found.alloca.getAllocaType();
- // A block argument or other value with no alloca has only its pointer type.
- return mlir::cast<cir::PointerType>(varPtr.getType()).getPointee();
-}
-
template <>
mlir::acc::VariableTypeCategory
OpenACCPointerLikeModel<cir::PointerType>::getPointeeTypeCategory(
mlir::Type pointer, mlir::TypedValue<mlir::acc::PointerLikeType> varPtr,
mlir::Type varType) const {
+ AllocaInfo base = findAlloca(varPtr);
+
// A dynamic alloca is an array of its element. Classifying it from the
// pointer type alone would report a scalar.
- if (AllocaInfo base = findAlloca(varPtr))
- if (base.alloca.isDynamic())
- return mlir::acc::VariableTypeCategory::array;
+ if (base && base.alloca.isDynamic())
+ return mlir::acc::VariableTypeCategory::array;
- mlir::Type eleTy = getBaseType(varPtr);
+ // A block argument or other value with no alloca has only its pointer type.
+ mlir::Type eleTy =
+ base ? base.alloca.getAllocaType()
+ : mlir::cast<cir::PointerType>(varPtr.getType()).getPointee();
if (auto mappableTy = mlir::dyn_cast<mlir::acc::MappableType>(eleTy))
return mappableTy.getTypeCategory(varPtr);
+ // A pointer to a scalar type may also address an element of an array, so
+ // without the allocation the type alone does not make it a scalar.
if (isAnyIntegerOrFloatingPointType(eleTy) ||
mlir::isa<cir::BoolType, cir::PointerType, cir::ComplexType>(eleTy))
- return mlir::acc::VariableTypeCategory::scalar;
+ return base ? mlir::acc::VariableTypeCategory::scalar
+ : mlir::acc::VariableTypeCategory::uncategorized;
if (mlir::isa<cir::ArrayType>(eleTy))
return mlir::acc::VariableTypeCategory::array;
if (mlir::isa<cir::RecordType>(eleTy))
@@ -376,12 +374,6 @@ mlir::Value OpenACCPointerLikeModel<cir::PointerType>::genAllocate(
mlir::Value result = alloca.getResult();
if (result.getType() == pointer)
return result;
- if (!dynSize) {
- if (auto array = mlir::dyn_cast<cir::ArrayType>(objectType))
- if (array.getElementType() == viewPointee)
- return cir::CastOp::create(builder, loc, pointer,
- cir::CastKind::array_to_ptrdecay, result);
- }
return castPointer(builder, loc, result, pointer);
}
diff --git a/clang/test/CIR/OpenACC/acc-recipe-populate-unsized.cir b/clang/test/CIR/OpenACC/acc-recipe-populate-unsized.cir
index f28eb3982fbcce..0bdf06b632d7d6 100644
--- a/clang/test/CIR/OpenACC/acc-recipe-populate-unsized.cir
+++ b/clang/test/CIR/OpenACC/acc-recipe-populate-unsized.cir
@@ -22,7 +22,7 @@ cir.func @test_unsized() {
// expected-error @below {{Failed to create firstprivate recipe for vector}}
%vector = cir.alloca "vector" align(16) : !cir.ptr<!cir.vector<4 x !s32i>> {test.var = "vector"}
// expected-error @below {{Failed to create firstprivate recipe for scalable}}
- %scalable = cir.alloca "scalable" align(16) : !cir.ptr<!cir.vector<[4] x !s32i>> {test.var = "scalable"}
+ %scalable = cir.alloca "scalable" align(16) : !cir.ptr<!cir.vector<[4] x !s32i, sve_data>> {test.var = "scalable"}
cir.return
}
diff --git a/clang/unittests/CIR/PointerLikeTest.cpp b/clang/unittests/CIR/PointerLikeTest.cpp
index ee5f2116c8dad5..9c536a2da0542d 100644
--- a/clang/unittests/CIR/PointerLikeTest.cpp
+++ b/clang/unittests/CIR/PointerLikeTest.cpp
@@ -357,7 +357,10 @@ TEST_F(CIROpenACCPointerLikeTest, testPointerToVoid) {
TEST_F(CIROpenACCPointerLikeTest, testPointerToIntMember) {
mlir::Type i32Ty = cir::IntType::get(&context, 32, true);
- testPointerToMemberType(i32Ty, mlir::acc::VariableTypeCategory::scalar);
+ // The loaded pointer may address an element of an array, so it is not known
+ // to be a scalar.
+ testPointerToMemberType(i32Ty,
+ mlir::acc::VariableTypeCategory::uncategorized);
}
TEST_F(CIROpenACCPointerLikeTest, testPointerToArrayMember) {
@@ -547,6 +550,45 @@ TEST_F(CIROpenACCPointerLikeTest, testDynamicArrayIsNotScalar) {
EXPECT_EQ(privAlloca.getAllocaType(), i32Ty);
}
+// A pointer to a scalar type may address an element of an array. Without the
+// allocation the type alone does not show that the object is a scalar. An
+// array type is complete in itself, so it is still an array.
+TEST_F(CIROpenACCPointerLikeTest, testPointerWithoutAllocaIsNotScalar) {
+ OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
+ b.setInsertionPointToStart(module->getBody());
+
+ Type i32 = cir::IntType::get(&context, 32, true);
+ Type i32Ptr = cir::PointerType::get(i32);
+ Type ptrPtr = cir::PointerType::get(i32Ptr);
+ Type arrayPtr = cir::PointerType::get(cir::ArrayType::get(i32, 4));
+ auto funcTy = cir::FuncType::get(SmallVector<Type, 2>{i32Ptr, arrayPtr},
+ cir::VoidType::get(&context));
+ cir::FuncOp func = cir::FuncOp::create(b, loc, "f", funcTy);
+ b.setInsertionPointToStart(func.addEntryBlock());
+
+ auto category = [&](Value ptr, Type varType) {
+ return cast<mlir::acc::PointerLikeType>(ptr.getType())
+ .getPointeeTypeCategory(
+ cast<TypedValue<mlir::acc::PointerLikeType>>(ptr), varType);
+ };
+
+ Value scalarArg = func.getBody().front().getArgument(0);
+ Value arrayArg = func.getBody().front().getArgument(1);
+ EXPECT_EQ(category(scalarArg, i32),
+ mlir::acc::VariableTypeCategory::uncategorized);
+ EXPECT_EQ(category(arrayArg, i32), mlir::acc::VariableTypeCategory::array);
+
+ // A loaded pointer has no allocation either.
+ Value slot =
+ cir::AllocaOp::create(b, loc, ptrPtr, "slot", getAlignOne(&context));
+ Value loaded = cir::LoadOp::create(b, loc, slot);
+ EXPECT_EQ(category(loaded, i32),
+ mlir::acc::VariableTypeCategory::uncategorized);
+
+ // The pointer variable itself is an allocation, so it is a scalar.
+ EXPECT_EQ(category(slot, i32Ptr), mlir::acc::VariableTypeCategory::scalar);
+}
+
// When the pointer is not produced by an allocation, only its type describes
// the object. A scalar or a fixed-size array is complete in that type, so it
// is allocated. A type with no size cannot be.
@@ -610,8 +652,9 @@ TEST_F(CIROpenACCPointerLikeTest, testAllocateWithoutAlloca) {
}
// A conversion that still names the whole allocation allocates that object,
-// and a constant element count is part of its extent. An offset or a member
-// names only part of the allocation, so the whole object is not allocated.
+// and a constant element count is part of its extent. An offset, a member, or
+// the first element of a decayed array names only part of the allocation, so
+// the whole object is not allocated.
TEST_F(CIROpenACCPointerLikeTest, testAllocateThroughPointerViews) {
OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
b.setInsertionPointToStart(module->getBody());
@@ -661,6 +704,7 @@ TEST_F(CIROpenACCPointerLikeTest, testAllocateThroughPointerViews) {
Value decayedByte =
cir::CastOp::create(b, loc, i8Ptr, cir::CastKind::bitcast, element);
+ EXPECT_FALSE(allocate(decay));
EXPECT_FALSE(allocate(element));
EXPECT_FALSE(allocate(decayedByte));
@@ -703,8 +747,9 @@ TEST_F(CIROpenACCPointerLikeTest, testAllocateThroughPointerViews) {
EXPECT_FALSE(allocate(arrayField));
}
-// Decaying an array to a pointer does not change the allocated object, so
-// the copy covers the array.
+// A conversion that still names the whole allocation is copied as that
+// object. Decaying an array designates its first element, so the array is
+// neither allocated nor copied through the decayed pointer.
TEST_F(CIROpenACCPointerLikeTest, testCopyCoversAllocatedObject) {
OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
b.setInsertionPointToStart(module->getBody());
@@ -717,20 +762,28 @@ TEST_F(CIROpenACCPointerLikeTest, testCopyCoversAllocatedObject) {
Value array =
cir::AllocaOp::create(b, loc, arrayPtr, "array", getAlignOne(&context));
- Value decay = cir::CastOp::create(b, loc, i32Ptr,
- cir::CastKind::array_to_ptrdecay, array);
+ Value view =
+ cir::CastOp::create(b, loc, i32Ptr, cir::CastKind::bitcast, array);
bool needsFree = true;
Value privatized =
- pointerLike.genAllocate(b, loc, "array", i32Ptr, decay, needsFree);
+ pointerLike.genAllocate(b, loc, "array", i32Ptr, view, needsFree);
ASSERT_TRUE(privatized);
EXPECT_TRUE(pointerLike.genCopy(
b, loc, cast<TypedValue<mlir::acc::PointerLikeType>>(privatized),
- cast<TypedValue<mlir::acc::PointerLikeType>>(decay), i32Ptr));
+ cast<TypedValue<mlir::acc::PointerLikeType>>(view), i32Ptr));
cir::CopyOp copy;
module->walk([&](cir::CopyOp op) { copy = op; });
ASSERT_TRUE(copy);
EXPECT_EQ(cast<cir::PointerType>(copy.getSrc().getType()).getPointee(),
arrayTy);
+
+ Value decay = cir::CastOp::create(b, loc, i32Ptr,
+ cir::CastKind::array_to_ptrdecay, array);
+ EXPECT_FALSE(
+ pointerLike.genAllocate(b, loc, "array", i32Ptr, decay, needsFree));
+ EXPECT_FALSE(pointerLike.genCopy(
+ b, loc, cast<TypedValue<mlir::acc::PointerLikeType>>(privatized),
+ cast<TypedValue<mlir::acc::PointerLikeType>>(decay), i32Ptr));
}
// An offset of zero still names the allocated object, so that object is
>From 725eeeef5f8d88bc2684229f5ddee957cbbe02c6 Mon Sep 17 00:00:00 2001
From: Razvan Lupusoru <rlupusoru at nvidia.com>
Date: Fri, 4 Dec 2026 08:34:26 -0800
Subject: [PATCH 3/3] [CIR][OpenACC] Implement PartialEntityAccessOpInterface
for CIR element and member access
Member, element, base and derived class, complex part, and runtime member addresses name a part of the object they are computed from. Implement PartialEntityAccessOpInterface for these operations and use it in the PointerLikeType implementation to find the object behind a derived pointer.
Assisted-by: Cursor
---
.../Dialect/OpenACC/CIROpenACCOpsInterfaces.h | 11 ++
.../OpenACC/CIROpenACCOpsInterfaces.cpp | 36 ++++++
.../OpenACC/CIROpenACCTypeInterfaces.cpp | 12 +-
.../OpenACC/RegisterOpenACCExtensions.cpp | 15 +++
clang/unittests/CIR/PointerLikeTest.cpp | 108 ++++++++++++++++++
5 files changed, 180 insertions(+), 2 deletions(-)
diff --git a/clang/include/clang/CIR/Dialect/OpenACC/CIROpenACCOpsInterfaces.h b/clang/include/clang/CIR/Dialect/OpenACC/CIROpenACCOpsInterfaces.h
index a9fb5ee7e040e9..0c5f3a7580a112 100644
--- a/clang/include/clang/CIR/Dialect/OpenACC/CIROpenACCOpsInterfaces.h
+++ b/clang/include/clang/CIR/Dialect/OpenACC/CIROpenACCOpsInterfaces.h
@@ -24,6 +24,17 @@ struct AddressOfGlobalModel
mlir::SymbolRefAttr getSymbol(mlir::Operation *op) const;
};
+// Operations that compute a pointer to part of the object behind an operand,
+// such as a member, an element, or a base class subobject. Each is a partial
+// view of the entity its operand points to.
+template <typename Op>
+struct PartialEntityAccessModel
+ : public mlir::acc::PartialEntityAccessOpInterface::ExternalModel<
+ PartialEntityAccessModel<Op>, Op> {
+ mlir::Value getBaseEntity(mlir::Operation *op) const;
+ bool isCompleteView(mlir::Operation *op) const { return false; }
+};
+
struct GlobalVariableModel
: public mlir::acc::GlobalVariableOpInterface::ExternalModel<
GlobalVariableModel, cir::GlobalOp> {
diff --git a/clang/lib/CIR/Dialect/OpenACC/CIROpenACCOpsInterfaces.cpp b/clang/lib/CIR/Dialect/OpenACC/CIROpenACCOpsInterfaces.cpp
index b7bd93704f3b44..b00784b48125be 100644
--- a/clang/lib/CIR/Dialect/OpenACC/CIROpenACCOpsInterfaces.cpp
+++ b/clang/lib/CIR/Dialect/OpenACC/CIROpenACCOpsInterfaces.cpp
@@ -17,6 +17,42 @@
namespace cir::acc {
+static mlir::Value getEnclosingObject(cir::GetMemberOp op) {
+ return op.getAddr();
+}
+static mlir::Value getEnclosingObject(cir::GetElementOp op) {
+ return op.getBase();
+}
+static mlir::Value getEnclosingObject(cir::GetRuntimeMemberOp op) {
+ return op.getAddr();
+}
+static mlir::Value getEnclosingObject(cir::BaseClassAddrOp op) {
+ return op.getSrcAddr();
+}
+static mlir::Value getEnclosingObject(cir::DerivedClassAddrOp op) {
+ return op.getSrcAddr();
+}
+static mlir::Value getEnclosingObject(cir::ComplexRealPtrOp op) {
+ return op.getOperand();
+}
+static mlir::Value getEnclosingObject(cir::ComplexImagPtrOp op) {
+ return op.getOperand();
+}
+
+template <typename Op>
+mlir::Value
+PartialEntityAccessModel<Op>::getBaseEntity(mlir::Operation *op) const {
+ return getEnclosingObject(llvm::cast<Op>(op));
+}
+
+template struct PartialEntityAccessModel<cir::GetMemberOp>;
+template struct PartialEntityAccessModel<cir::GetElementOp>;
+template struct PartialEntityAccessModel<cir::GetRuntimeMemberOp>;
+template struct PartialEntityAccessModel<cir::BaseClassAddrOp>;
+template struct PartialEntityAccessModel<cir::DerivedClassAddrOp>;
+template struct PartialEntityAccessModel<cir::ComplexRealPtrOp>;
+template struct PartialEntityAccessModel<cir::ComplexImagPtrOp>;
+
mlir::SymbolRefAttr AddressOfGlobalModel::getSymbol(mlir::Operation *op) const {
return llvm::cast<cir::GetGlobalOp>(op).getNameAttr();
}
diff --git a/clang/lib/CIR/Dialect/OpenACC/CIROpenACCTypeInterfaces.cpp b/clang/lib/CIR/Dialect/OpenACC/CIROpenACCTypeInterfaces.cpp
index 2d96f6e2e06c4e..1e7b3cc26626aa 100644
--- a/clang/lib/CIR/Dialect/OpenACC/CIROpenACCTypeInterfaces.cpp
+++ b/clang/lib/CIR/Dialect/OpenACC/CIROpenACCTypeInterfaces.cpp
@@ -54,9 +54,17 @@ static AllocaInfo findAlloca(mlir::Value value) {
value = stride.getBase();
continue;
}
- if (auto member = mlir::dyn_cast<cir::GetMemberOp>(def)) {
+ if (auto partial =
+ mlir::dyn_cast<mlir::acc::PartialEntityAccessOpInterface>(def)) {
+ baseEntity &= partial.isCompleteView();
+ value = partial.getBaseEntity();
+ continue;
+ }
+ // Only the adjusted `this` of a method lookup points into the object.
+ if (auto method = mlir::dyn_cast<cir::GetMethodOp>(def);
+ method && value == method.getAdjustedThis()) {
baseEntity = false;
- value = member.getAddr();
+ value = method.getObject();
continue;
}
break;
diff --git a/clang/lib/CIR/Dialect/OpenACC/RegisterOpenACCExtensions.cpp b/clang/lib/CIR/Dialect/OpenACC/RegisterOpenACCExtensions.cpp
index 8226a9f3a4bc9e..c754ad7e2406bc 100644
--- a/clang/lib/CIR/Dialect/OpenACC/RegisterOpenACCExtensions.cpp
+++ b/clang/lib/CIR/Dialect/OpenACC/RegisterOpenACCExtensions.cpp
@@ -23,6 +23,21 @@ void registerOpenACCExtensions(mlir::DialectRegistry ®istry) {
cir::PointerType::attachInterface<
OpenACCPointerLikeModel<cir::PointerType>>(*ctx);
+ cir::GetMemberOp::attachInterface<
+ PartialEntityAccessModel<cir::GetMemberOp>>(*ctx);
+ cir::GetElementOp::attachInterface<
+ PartialEntityAccessModel<cir::GetElementOp>>(*ctx);
+ cir::GetRuntimeMemberOp::attachInterface<
+ PartialEntityAccessModel<cir::GetRuntimeMemberOp>>(*ctx);
+ cir::BaseClassAddrOp::attachInterface<
+ PartialEntityAccessModel<cir::BaseClassAddrOp>>(*ctx);
+ cir::DerivedClassAddrOp::attachInterface<
+ PartialEntityAccessModel<cir::DerivedClassAddrOp>>(*ctx);
+ cir::ComplexRealPtrOp::attachInterface<
+ PartialEntityAccessModel<cir::ComplexRealPtrOp>>(*ctx);
+ cir::ComplexImagPtrOp::attachInterface<
+ PartialEntityAccessModel<cir::ComplexImagPtrOp>>(*ctx);
+
cir::GetGlobalOp::attachInterface<AddressOfGlobalModel>(*ctx);
cir::GlobalOp::attachInterface<GlobalVariableModel>(*ctx);
});
diff --git a/clang/unittests/CIR/PointerLikeTest.cpp b/clang/unittests/CIR/PointerLikeTest.cpp
index 9c536a2da0542d..6250f0b04bbec3 100644
--- a/clang/unittests/CIR/PointerLikeTest.cpp
+++ b/clang/unittests/CIR/PointerLikeTest.cpp
@@ -11,6 +11,7 @@
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/OpenACC/OpenACC.h"
+#include "mlir/Dialect/OpenACC/OpenACCUtils.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Diagnostics.h"
@@ -747,6 +748,113 @@ TEST_F(CIROpenACCPointerLikeTest, testAllocateThroughPointerViews) {
EXPECT_FALSE(allocate(arrayField));
}
+// An operation that derives a pointer to part of an object leads back to the
+// allocation of that object, which gives the category. The derived pointer
+// does not name the whole allocation, so it is not allocated.
+TEST_F(CIROpenACCPointerLikeTest, testPointerDerivedFromAllocation) {
+ OwningOpRef<ModuleOp> module = ModuleOp::create(loc);
+ b.setInsertionPointToStart(module->getBody());
+
+ Type i32 = cir::IntType::get(&context, 32, true);
+ Type f32 = cir::SingleType::get(&context);
+ Type i32Ptr = cir::PointerType::get(i32);
+ Type f32Ptr = cir::PointerType::get(f32);
+ Type voidPtr = cir::PointerType::get(cir::VoidType::get(&context));
+ Type arrayTy = cir::ArrayType::get(i32, 4);
+ Type complexTy = cir::ComplexType::get(f32);
+ IntegerAttr align = getAlignOne(&context);
+
+ cir::RecordType base =
+ cir::StructType::get(&context, getUniqueRecordName("Base"),
+ /*is_class=*/false);
+ Type baseFields[] = {i32};
+ base.complete(baseFields, /*packed=*/false, /*padding=*/{},
+ cir::RecordType::getAllDataKinds(baseFields));
+ cir::RecordType derived =
+ cir::StructType::get(&context, getUniqueRecordName("Derived"),
+ /*is_class=*/false);
+ Type derivedFields[] = {base, i32};
+ derived.complete(derivedFields, /*packed=*/false, /*padding=*/{},
+ cir::RecordType::getAllDataKinds(derivedFields));
+ Type basePtr = cir::PointerType::get(base);
+ Type derivedPtr = cir::PointerType::get(derived);
+
+ // The pointer to a data member and to a member function are only available
+ // as values, so they are arguments of a function.
+ Type dataMemberTy = cir::DataMemberType::get(i32, derived);
+ auto methodFuncTy = cir::FuncType::get(SmallVector<Type, 1>{voidPtr},
+ cir::VoidType::get(&context));
+ Type methodTy = cir::MethodType::get(methodFuncTy, derived);
+ auto funcTy = cir::FuncType::get(SmallVector<Type, 2>{dataMemberTy, methodTy},
+ cir::VoidType::get(&context));
+ cir::FuncOp func = cir::FuncOp::create(b, loc, "f", funcTy);
+ mlir::Block *entry = func.addEntryBlock();
+ b.setInsertionPointToStart(entry);
+
+ Value arrayVar = cir::AllocaOp::create(b, loc, cir::PointerType::get(arrayTy),
+ "array", align);
+ Value derivedVar = cir::AllocaOp::create(b, loc, derivedPtr, "d", align);
+ Value complexVar = cir::AllocaOp::create(
+ b, loc, cir::PointerType::get(complexTy), "c", align);
+ Value index = cir::ConstantOp::create(b, loc, cir::IntAttr::get(i32, 1));
+
+ auto category = [&](Value ptr, Type varType) {
+ return cast<mlir::acc::PointerLikeType>(ptr.getType())
+ .getPointeeTypeCategory(
+ cast<TypedValue<mlir::acc::PointerLikeType>>(ptr), varType);
+ };
+ auto allocate = [&](Value view) {
+ bool needsFree = true;
+ return cast<mlir::acc::PointerLikeType>(view.getType())
+ .genAllocate(b, loc, "priv", view.getType(), view, needsFree);
+ };
+
+ Value element = cir::GetElementOp::create(b, loc, i32Ptr, arrayVar, index,
+ /*in_bounds=*/false,
+ /*no_unsigned_wrap=*/false);
+ EXPECT_EQ(category(element, i32), mlir::acc::VariableTypeCategory::array);
+ EXPECT_FALSE(allocate(element));
+
+ Value toBase = cir::BaseClassAddrOp::create(
+ b, loc, basePtr, derivedVar, mlir::APInt(64, 0), /*assumeNotNull=*/true);
+ EXPECT_EQ(category(toBase, base), mlir::acc::VariableTypeCategory::composite);
+ EXPECT_FALSE(allocate(toBase));
+
+ Value toDerived = cir::DerivedClassAddrOp::create(
+ b, loc, derivedPtr, toBase, mlir::APInt(64, 0), /*assumeNotNull=*/true);
+ EXPECT_EQ(category(toDerived, derived),
+ mlir::acc::VariableTypeCategory::composite);
+ EXPECT_FALSE(allocate(toDerived));
+
+ Value real = cir::ComplexRealPtrOp::create(b, loc, f32Ptr, complexVar);
+ Value imag = cir::ComplexImagPtrOp::create(b, loc, f32Ptr, complexVar);
+ EXPECT_EQ(category(real, f32), mlir::acc::VariableTypeCategory::scalar);
+ EXPECT_EQ(category(imag, f32), mlir::acc::VariableTypeCategory::scalar);
+ EXPECT_FALSE(allocate(real));
+ EXPECT_FALSE(allocate(imag));
+
+ Value runtimeMember = cir::GetRuntimeMemberOp::create(
+ b, loc, i32Ptr, derivedVar, entry->getArgument(0));
+ EXPECT_EQ(category(runtimeMember, i32),
+ mlir::acc::VariableTypeCategory::composite);
+ EXPECT_FALSE(allocate(runtimeMember));
+
+ auto method =
+ cir::GetMethodOp::create(b, loc, cir::PointerType::get(methodFuncTy),
+ voidPtr, entry->getArgument(1), derivedVar);
+ EXPECT_EQ(category(method.getAdjustedThis(), derived),
+ mlir::acc::VariableTypeCategory::composite);
+ EXPECT_FALSE(allocate(method.getAdjustedThis()));
+
+ // The operations are partial accesses of the entity they derive from.
+ EXPECT_EQ(mlir::acc::getBaseEntity(element), arrayVar);
+ EXPECT_EQ(mlir::acc::getBaseEntity(toBase), derivedVar);
+ EXPECT_EQ(mlir::acc::getBaseEntity(toDerived), toBase);
+ EXPECT_EQ(mlir::acc::getBaseEntity(real), complexVar);
+ EXPECT_EQ(mlir::acc::getBaseEntity(imag), complexVar);
+ EXPECT_EQ(mlir::acc::getBaseEntity(runtimeMember), derivedVar);
+}
+
// A conversion that still names the whole allocation is copied as that
// object. Decaying an array designates its first element, so the array is
// neither allocated nor copied through the decayed pointer.
More information about the cfe-commits
mailing list