Skip to content

[flang] Make adapt.valuebyref attribute work again #73658

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 0 additions & 9 deletions flang/include/flang/Lower/ConvertExpr.h
Original file line number Diff line number Diff line change
Expand Up @@ -225,15 +225,6 @@ mlir::Value createSubroutineCall(AbstractConverter &converter,
SymMap &symMap, StatementContext &stmtCtx,
bool isUserDefAssignment);

// Attribute for an alloca that is a trivial adaptor for converting a value to
// pass-by-ref semantics for a VALUE parameter. The optimizer may be able to
// eliminate these.
inline mlir::NamedAttribute getAdaptToByRefAttr(fir::FirOpBuilder &builder) {
return {mlir::StringAttr::get(builder.getContext(),
fir::getAdaptToByRefAttrName()),
builder.getUnitAttr()};
}

mlir::Value addCrayPointerInst(mlir::Location loc, fir::FirOpBuilder &builder,
mlir::Value ptrVal, mlir::Type ptrTy,
mlir::Type pteTy);
Expand Down
10 changes: 5 additions & 5 deletions flang/include/flang/Optimizer/Builder/HLFIRTools.h
Original file line number Diff line number Diff line change
Expand Up @@ -239,11 +239,11 @@ fir::FortranVariableOpInterface genDeclare(mlir::Location loc,
/// Generate an hlfir.associate to build a variable from an expression value.
/// The type of the variable must be provided so that scalar logicals are
/// properly typed when placed in memory.
hlfir::AssociateOp genAssociateExpr(mlir::Location loc,
fir::FirOpBuilder &builder,
hlfir::Entity value,
mlir::Type variableType,
llvm::StringRef name);
hlfir::AssociateOp
genAssociateExpr(mlir::Location loc, fir::FirOpBuilder &builder,
hlfir::Entity value, mlir::Type variableType,
llvm::StringRef name,
std::optional<mlir::NamedAttribute> attr = std::nullopt);

/// Get the raw address of a variable (simple fir.ref/fir.ptr, or fir.heap
/// value). The returned value should be used with care, it does not contain any
Expand Down
4 changes: 0 additions & 4 deletions flang/include/flang/Optimizer/Dialect/FIROps.h
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,6 @@ mlir::ParseResult parseSelector(mlir::OpAsmParser &parser,
mlir::OpAsmParser::UnresolvedOperand &selector,
mlir::Type &type);

static constexpr llvm::StringRef getAdaptToByRefAttrName() {
return "adapt.valuebyref";
}

static constexpr llvm::StringRef getNormalizedLowerBoundAttrName() {
return "normalized.lb";
}
Expand Down
16 changes: 16 additions & 0 deletions flang/include/flang/Optimizer/Dialect/FIROpsSupport.h
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,22 @@ inline std::optional<std::int64_t> getIntIfConstant(mlir::Value value) {
return {};
}

static constexpr llvm::StringRef getAdaptToByRefAttrName() {
return "adapt.valuebyref";
}

// Attribute for an alloca that is a trivial adaptor for converting a value to
// pass-by-ref semantics for a VALUE parameter. The optimizer may be able to
// eliminate these.
// Template is used to avoid compiler errors in places that don't include
// FIRBuilder.h
template <typename Builder>
inline mlir::NamedAttribute getAdaptToByRefAttr(Builder &builder) {
return {mlir::StringAttr::get(builder.getContext(),
fir::getAdaptToByRefAttrName()),
builder.getUnitAttr()};
}

} // namespace fir

#endif // FORTRAN_OPTIMIZER_DIALECT_FIROPSSUPPORT_H
10 changes: 7 additions & 3 deletions flang/include/flang/Optimizer/HLFIR/HLFIROps.td
Original file line number Diff line number Diff line change
Expand Up @@ -660,7 +660,7 @@ def hlfir_AssociateOp : hlfir_Op<"associate", [AttrSizedOperandSegments,
AnyFortranValue:$source,
Optional<AnyShapeOrShiftType>:$shape,
Variadic<AnyIntegerType>:$typeparams,
Builtin_StringAttr:$uniq_name,
OptionalAttr<Builtin_StringAttr>:$uniq_name,
OptionalAttr<fir_FortranVariableFlagsAttr>:$fortran_attrs
);

Expand All @@ -672,9 +672,13 @@ def hlfir_AssociateOp : hlfir_Op<"associate", [AttrSizedOperandSegments,
}];

let builders = [
OpBuilder<(ins "mlir::Value":$source, "llvm::StringRef":$uniq_name,
OpBuilder<(ins "mlir::Value":$source, CArg<"llvm::StringRef", "{}">:$uniq_name,
CArg<"mlir::Value", "{}">:$shape, CArg<"mlir::ValueRange", "{}">:$typeparams,
CArg<"fir::FortranVariableFlagsAttr", "{}">:$fortran_attrs)>];
CArg<"fir::FortranVariableFlagsAttr", "{}">:$fortran_attrs)>,
OpBuilder<(ins "mlir::Value":$memref, CArg<"mlir::Value", "{}">:$shape,
CArg<"mlir::ValueRange", "{}">:$typeparams,
CArg<"fir::FortranVariableFlagsAttr", "{}">:$fortran_attrs,
CArg<"llvm::ArrayRef<mlir::NamedAttribute>", "{}">:$attributes)>];

let extraClassDeclaration = [{
/// Override FortranVariableInterface default implementation
Expand Down
8 changes: 4 additions & 4 deletions flang/lib/Lower/Bridge.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2083,10 +2083,10 @@ class FirConverter : public Fortran::lower::AbstractConverter {
assert(sym && "There must be a symbol to bind");
mlir::Type toTy = genType(*sym);
// FIXME: this should be a "per iteration" temporary.
mlir::Value tmp = builder->createTemporary(
loc, toTy, toStringRef(sym->name()),
llvm::ArrayRef<mlir::NamedAttribute>{
Fortran::lower::getAdaptToByRefAttr(*builder)});
mlir::Value tmp =
builder->createTemporary(loc, toTy, toStringRef(sym->name()),
llvm::ArrayRef<mlir::NamedAttribute>{
fir::getAdaptToByRefAttr(*builder)});
mlir::Value cast = builder->createConvert(loc, toTy, inducVar);
builder->create<fir::StoreOp>(loc, cast, tmp);
addSymbol(*sym, tmp, /*force=*/true);
Expand Down
12 changes: 8 additions & 4 deletions flang/lib/Lower/ConvertCall.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

#include "flang/Lower/ConvertCall.h"
#include "flang/Lower/Allocatable.h"
#include "flang/Lower/ConvertExpr.h"
#include "flang/Lower/ConvertExprToHLFIR.h"
#include "flang/Lower/ConvertVariable.h"
#include "flang/Lower/CustomIntrinsicCall.h"
Expand Down Expand Up @@ -958,8 +959,9 @@ static PreparedDummyArgument preparePresentUserCallActualArgument(
// Make a copy in a temporary.
auto copy = builder.create<hlfir::AsExprOp>(loc, entity);
mlir::Type storageType = entity.getType();
mlir::NamedAttribute byRefAttr = fir::getAdaptToByRefAttr(builder);
hlfir::AssociateOp associate = hlfir::genAssociateExpr(
loc, builder, hlfir::Entity{copy}, storageType, "adapt.valuebyref");
loc, builder, hlfir::Entity{copy}, storageType, "", byRefAttr);
entity = hlfir::Entity{associate.getBase()};
// Register the temporary destruction after the call.
preparedDummy.pushExprAssociateCleanUp(associate);
Expand All @@ -986,8 +988,9 @@ static PreparedDummyArgument preparePresentUserCallActualArgument(
// The actual is an expression value, place it into a temporary
// and register the temporary destruction after the call.
mlir::Type storageType = converter.genType(expr);
mlir::NamedAttribute byRefAttr = fir::getAdaptToByRefAttr(builder);
hlfir::AssociateOp associate = hlfir::genAssociateExpr(
loc, builder, entity, storageType, "adapt.valuebyref");
loc, builder, entity, storageType, "", byRefAttr);
entity = hlfir::Entity{associate.getBase()};
preparedDummy.pushExprAssociateCleanUp(associate);
if (mustSetDynamicTypeToDummyType) {
Expand Down Expand Up @@ -1395,8 +1398,9 @@ static std::optional<hlfir::EntityWithAttributes> genCustomIntrinsicRefCore(
CallContext &callContext) {
auto &builder = callContext.getBuilder();
const auto &loc = callContext.loc;
assert(intrinsic && Fortran::lower::intrinsicRequiresCustomOptionalHandling(
callContext.procRef, *intrinsic, callContext.converter));
assert(intrinsic &&
Fortran::lower::intrinsicRequiresCustomOptionalHandling(
callContext.procRef, *intrinsic, callContext.converter));

// helper to get a particular prepared argument
auto getArgument = [&](std::size_t i, bool loadArg) -> fir::ExtendedValue {
Expand Down
36 changes: 17 additions & 19 deletions flang/lib/Lower/ConvertExpr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -358,8 +358,7 @@ placeScalarValueInMemory(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::Value val = builder.createConvert(loc, storageType, valBase);
mlir::Value temp = builder.createTemporary(
loc, storageType,
llvm::ArrayRef<mlir::NamedAttribute>{
Fortran::lower::getAdaptToByRefAttr(builder)});
llvm::ArrayRef<mlir::NamedAttribute>{fir::getAdaptToByRefAttr(builder)});
builder.create<fir::StoreOp>(loc, val, temp);
return fir::substBase(exv, temp);
}
Expand Down Expand Up @@ -2401,19 +2400,18 @@ class ScalarExprLowering {
mlir::Value len = charBox->getLen();
mlir::Value zero = builder.createIntegerConstant(loc, len.getType(), 0);
len = builder.create<mlir::arith::SelectOp>(loc, isPresent, len, zero);
mlir::Value temp = builder.createTemporary(
loc, type, /*name=*/{},
/*shape=*/{}, mlir::ValueRange{len},
llvm::ArrayRef<mlir::NamedAttribute>{
Fortran::lower::getAdaptToByRefAttr(builder)});
mlir::Value temp =
builder.createTemporary(loc, type, /*name=*/{},
/*shape=*/{}, mlir::ValueRange{len},
llvm::ArrayRef<mlir::NamedAttribute>{
fir::getAdaptToByRefAttr(builder)});
return fir::CharBoxValue{temp, len};
}
assert((fir::isa_trivial(type) || type.isa<fir::RecordType>()) &&
"must be simple scalar");
return builder.createTemporary(
loc, type,
llvm::ArrayRef<mlir::NamedAttribute>{
Fortran::lower::getAdaptToByRefAttr(builder)});
return builder.createTemporary(loc, type,
llvm::ArrayRef<mlir::NamedAttribute>{
fir::getAdaptToByRefAttr(builder)});
}

template <typename A>
Expand Down Expand Up @@ -4752,10 +4750,10 @@ class ArrayExprLowering {
} else {
// Store scalar value in a temp to fulfill VALUE attribute.
mlir::Value val = fir::getBase(asScalar(*expr));
mlir::Value temp = builder.createTemporary(
loc, val.getType(),
llvm::ArrayRef<mlir::NamedAttribute>{
Fortran::lower::getAdaptToByRefAttr(builder)});
mlir::Value temp =
builder.createTemporary(loc, val.getType(),
llvm::ArrayRef<mlir::NamedAttribute>{
fir::getAdaptToByRefAttr(builder)});
builder.create<fir::StoreOp>(loc, val, temp);
operands.emplace_back(
[=](IterSpace iters) -> ExtValue { return temp; });
Expand Down Expand Up @@ -5843,10 +5841,10 @@ class ArrayExprLowering {
base = builder.create<fir::ArrayFetchOp>(
loc, eleTy, arrLd, iters.iterVec(), arrLdTypeParams);
}
mlir::Value temp = builder.createTemporary(
loc, base.getType(),
llvm::ArrayRef<mlir::NamedAttribute>{
Fortran::lower::getAdaptToByRefAttr(builder)});
mlir::Value temp =
builder.createTemporary(loc, base.getType(),
llvm::ArrayRef<mlir::NamedAttribute>{
fir::getAdaptToByRefAttr(builder)});
builder.create<fir::StoreOp>(loc, base, temp);
return fir::factory::arraySectionElementToExtendedValue(
builder, loc, extMemref, temp, slice);
Expand Down
2 changes: 1 addition & 1 deletion flang/lib/Lower/OpenMP.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2104,7 +2104,7 @@ createAndSetPrivatizedLoopVar(Fortran::lower::AbstractConverter &converter,
loc, tempTy, /*pinned=*/true, /*lengthParams=*/mlir::ValueRange{},
/*shapeParams*/ mlir::ValueRange{},
llvm::ArrayRef<mlir::NamedAttribute>{
Fortran::lower::getAdaptToByRefAttr(firOpBuilder)});
fir::getAdaptToByRefAttr(firOpBuilder)});
converter.bindSymbol(*sym, temp);
firOpBuilder.restoreInsertionPoint(insPt);
mlir::Value cvtVal = firOpBuilder.createConvert(loc, tempTy, indexVal);
Expand Down
1 change: 1 addition & 0 deletions flang/lib/Optimizer/Builder/Character.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#include "flang/Optimizer/Builder/DoLoopHelper.h"
#include "flang/Optimizer/Builder/FIRBuilder.h"
#include "flang/Optimizer/Builder/Todo.h"
#include "flang/Optimizer/Dialect/FIROpsSupport.h"
#include "llvm/Support/Debug.h"
#include <optional>

Expand Down
22 changes: 15 additions & 7 deletions flang/lib/Optimizer/Builder/HLFIRTools.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
//===----------------------------------------------------------------------===//

#include "flang/Optimizer/Builder/HLFIRTools.h"
#include "flang/Lower/ConvertExpr.h"
#include "flang/Optimizer/Builder/Character.h"
#include "flang/Optimizer/Builder/FIRBuilder.h"
#include "flang/Optimizer/Builder/MutableBox.h"
Expand Down Expand Up @@ -232,11 +233,11 @@ hlfir::genDeclare(mlir::Location loc, fir::FirOpBuilder &builder,
return mlir::cast<fir::FortranVariableOpInterface>(declareOp.getOperation());
}

hlfir::AssociateOp hlfir::genAssociateExpr(mlir::Location loc,
fir::FirOpBuilder &builder,
hlfir::Entity value,
mlir::Type variableType,
llvm::StringRef name) {
hlfir::AssociateOp
hlfir::genAssociateExpr(mlir::Location loc, fir::FirOpBuilder &builder,
hlfir::Entity value, mlir::Type variableType,
llvm::StringRef name,
std::optional<mlir::NamedAttribute> attr) {
assert(value.isValue() && "must not be a variable");
mlir::Value shape{};
if (value.isArray())
Expand All @@ -259,6 +260,12 @@ hlfir::AssociateOp hlfir::genAssociateExpr(mlir::Location loc,
}
llvm::SmallVector<mlir::Value> lenParams;
genLengthParameters(loc, builder, value, lenParams);
if (attr) {
assert(name.empty() && "It attribute is provided, no-name is expected");
return builder.create<hlfir::AssociateOp>(loc, source, shape, lenParams,
fir::FortranVariableFlagsAttr{},
llvm::ArrayRef{*attr});
}
return builder.create<hlfir::AssociateOp>(loc, source, name, shape, lenParams,
fir::FortranVariableFlagsAttr{});
}
Expand Down Expand Up @@ -914,8 +921,9 @@ hlfir::translateToExtendedValue(mlir::Location loc, fir::FirOpBuilder &builder,
}

if (entity.getType().isa<hlfir::ExprType>()) {
mlir::NamedAttribute byRefAttr = fir::getAdaptToByRefAttr(builder);
hlfir::AssociateOp associate = hlfir::genAssociateExpr(
loc, builder, entity, entity.getType(), "adapt.valuebyref");
loc, builder, entity, entity.getType(), "", byRefAttr);
auto *bldr = &builder;
hlfir::CleanupFunction cleanup = [bldr, loc, associate]() -> void {
bldr->create<hlfir::EndAssociateOp>(loc, associate);
Expand Down Expand Up @@ -1175,7 +1183,7 @@ hlfir::genTypeAndKindConvert(mlir::Location loc, fir::FirOpBuilder &builder,
mlir::Value shapeShift =
builder.create<fir::ShapeShiftOp>(loc, shapeShiftType, lbAndExtents);
auto declareOp = builder.create<hlfir::DeclareOp>(
loc, associate.getFirBase(), associate.getUniqName(), shapeShift,
loc, associate.getFirBase(), *associate.getUniqName(), shapeShift,
associate.getTypeparams(), /*flags=*/fir::FortranVariableFlagsAttr{});
hlfir::Entity castWithLbounds =
mlir::cast<fir::FortranVariableOpInterface>(declareOp.getOperation());
Expand Down
23 changes: 23 additions & 0 deletions flang/lib/Optimizer/HLFIR/IR/HLFIROps.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1230,6 +1230,29 @@ void hlfir::AssociateOp::build(mlir::OpBuilder &builder,
typeparams, nameAttr, fortran_attrs);
}

void hlfir::AssociateOp::build(
mlir::OpBuilder &builder, mlir::OperationState &result, mlir::Value source,
mlir::Value shape, mlir::ValueRange typeparams,
fir::FortranVariableFlagsAttr fortran_attrs,
llvm::ArrayRef<mlir::NamedAttribute> attributes) {
mlir::Type dataType = getFortranElementOrSequenceType(source.getType());

// Preserve polymorphism of polymorphic expr.
mlir::Type firVarType;
auto sourceExprType = mlir::dyn_cast<hlfir::ExprType>(source.getType());
if (sourceExprType && sourceExprType.isPolymorphic())
firVarType = fir::ClassType::get(fir::HeapType::get(dataType));
else
firVarType = fir::ReferenceType::get(dataType);

mlir::Type hlfirVariableType =
DeclareOp::getHLFIRVariableType(firVarType, /*hasExplicitLbs=*/false);
mlir::Type i1Type = builder.getI1Type();
build(builder, result, {hlfirVariableType, firVarType, i1Type}, source, shape,
typeparams, {}, fortran_attrs);
result.addAttributes(attributes);
}

//===----------------------------------------------------------------------===//
// EndAssociateOp
//===----------------------------------------------------------------------===//
Expand Down
14 changes: 11 additions & 3 deletions flang/lib/Optimizer/HLFIR/Transforms/BufferizeHLFIR.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
// on the heap.
//===----------------------------------------------------------------------===//

#include "flang/Lower/ConvertExpr.h"
#include "flang/Optimizer/Builder/Character.h"
#include "flang/Optimizer/Builder/FIRBuilder.h"
#include "flang/Optimizer/Builder/HLFIRTools.h"
Expand Down Expand Up @@ -452,7 +453,7 @@ struct AssociateOpConversion
// %0 = hlfir.as_expr %x move %true :
// (!fir.box<!fir.heap<!fir.type<_T{y:i32}>>>, i1) ->
// !hlfir.expr<!fir.type<_T{y:i32}>>
// %1:3 = hlfir.associate %0 {uniq_name = "adapt.valuebyref"} :
// %1:3 = hlfir.associate %0 {adapt.valuebyref} :
// (!hlfir.expr<!fir.type<_T{y:i32}>>) ->
// (!fir.ref<!fir.type<_T{y:i32}>>,
// !fir.ref<!fir.type<_T{y:i32}>>,
Expand Down Expand Up @@ -525,8 +526,15 @@ struct AssociateOpConversion
return mlir::success();
}
if (isTrivialValue) {
auto temp = builder.createTemporary(loc, bufferizedExpr.getType(),
associate.getUniqName());
llvm::SmallVector<mlir::NamedAttribute, 1> attrs;
if (associate->hasAttr(fir::getAdaptToByRefAttrName())) {
attrs.push_back(fir::getAdaptToByRefAttr(builder));
}
llvm::StringRef name = "";
if (associate.getUniqName())
name = *associate.getUniqName();
auto temp =
builder.createTemporary(loc, bufferizedExpr.getType(), name, attrs);
builder.create<fir::StoreOp>(loc, bufferizedExpr, temp);
mlir::Value mustFree = builder.createBool(loc, false);
replaceWith(temp, temp, mustFree);
Expand Down
Loading