#include "flang/Lower/HostAssociations.h"
#include "flang/Evaluate/check-expression.h"
#include "flang/Lower/AbstractConverter.h"
#include "flang/Lower/Allocatable.h"
#include "flang/Lower/BoxAnalyzer.h"
#include "flang/Lower/CallInterface.h"
#include "flang/Lower/ConvertType.h"
#include "flang/Lower/PFTBuilder.h"
#include "flang/Lower/SymbolMap.h"
#include "flang/Optimizer/Builder/Character.h"
#include "flang/Optimizer/Builder/FIRBuilder.h"
#include "flang/Optimizer/Builder/Todo.h"
#include "flang/Optimizer/Support/FatalError.h"
#include "flang/Semantics/tools.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/Debug.h"
#define DEBUG_TYPE "flang-host-assoc"
struct GetTypeInTuple {
using Result = mlir::Type;
};
struct InstantiateHostTuple {
using Result = void;
fir::ExtendedValue hostValue;
mlir::Value addrInTuple;
mlir::Location loc;
};
struct GetFromTuple {
using Result = void;
Fortran::lower::SymMap &symMap;
mlir::Value valueInTuple;
mlir::Location loc;
};
template <typename SymbolCategory>
class CapturedSymbols {
public:
template <typename T>
static void visit(const T &, Fortran::lower::AbstractConverter &,
const Fortran::semantics::Symbol &,
const Fortran::lower::BoxAnalyzer &) {
static_assert(!std::is_same_v<T, T> &&
"default visit must not be instantiated");
}
static mlir::Type visit(const GetTypeInTuple &,
Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &sym,
const Fortran::lower::BoxAnalyzer &) {
return SymbolCategory::getType(converter, sym);
}
static void visit(const InstantiateHostTuple &args,
Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &sym,
const Fortran::lower::BoxAnalyzer &) {
return SymbolCategory::instantiateHostTuple(args, converter, sym);
}
static void visit(const GetFromTuple &args,
Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &sym,
const Fortran::lower::BoxAnalyzer &ba) {
return SymbolCategory::getFromTuple(args, converter, sym, ba);
}
};
class CapturedSimpleScalars : public CapturedSymbols<CapturedSimpleScalars> {
public:
static mlir::Type getType(Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &sym) {
return fir::ReferenceType::get(converter.genType(sym));
}
static void instantiateHostTuple(const InstantiateHostTuple &args,
Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Type typeInTuple = fir::dyn_cast_ptrEleTy(args.addrInTuple.getType());
assert(typeInTuple && "addrInTuple must be an address");
mlir::Value castBox = builder.createConvert(args.loc, typeInTuple,
fir::getBase(args.hostValue));
builder.create<fir::StoreOp>(args.loc, castBox, args.addrInTuple);
}
static void getFromTuple(const GetFromTuple &args,
Fortran::lower::AbstractConverter &,
const Fortran::semantics::Symbol &sym,
const Fortran::lower::BoxAnalyzer &) {
args.symMap.addSymbol(sym, args.valueInTuple);
}
};
class CapturedProcedure : public CapturedSymbols<CapturedProcedure> {
public:
static mlir::Type getType(Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &sym) {
if (Fortran::semantics::IsPointer(sym))
TODO(converter.getCurrentLocation(),
"capture procedure pointer in internal procedure");
return Fortran::lower::getDummyProcedureType(sym, converter);
}
static void instantiateHostTuple(const InstantiateHostTuple &args,
Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Type typeInTuple = fir::dyn_cast_ptrEleTy(args.addrInTuple.getType());
assert(typeInTuple && "addrInTuple must be an address");
mlir::Value castBox = builder.createConvert(args.loc, typeInTuple,
fir::getBase(args.hostValue));
builder.create<fir::StoreOp>(args.loc, castBox, args.addrInTuple);
}
static void getFromTuple(const GetFromTuple &args,
Fortran::lower::AbstractConverter &,
const Fortran::semantics::Symbol &sym,
const Fortran::lower::BoxAnalyzer &) {
args.symMap.addSymbol(sym, args.valueInTuple);
}
};
class CapturedCharacterScalars
: public CapturedSymbols<CapturedCharacterScalars> {
public:
static mlir::Type getType(Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &sym) {
fir::KindTy kind =
converter.genType(sym).cast<fir::CharacterType>().getFKind();
return fir::BoxCharType::get(&converter.getMLIRContext(), kind);
}
static void instantiateHostTuple(const InstantiateHostTuple &args,
Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &) {
const fir::CharBoxValue *charBox = args.hostValue.getCharBox();
assert(charBox && "host value must be a fir::CharBoxValue");
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Value boxchar = fir::factory::CharacterExprHelper(builder, args.loc)
.createEmbox(*charBox);
builder.create<fir::StoreOp>(args.loc, boxchar, args.addrInTuple);
}
static void getFromTuple(const GetFromTuple &args,
Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &sym,
const Fortran::lower::BoxAnalyzer &) {
fir::factory::CharacterExprHelper charHelp(converter.getFirOpBuilder(),
args.loc);
std::pair<mlir::Value, mlir::Value> unboxchar =
charHelp.createUnboxChar(args.valueInTuple);
args.symMap.addCharSymbol(sym, unboxchar.first, unboxchar.second);
}
};
static bool isDerivedWithLenParameters(const Fortran::semantics::Symbol &sym) {
if (const auto *declTy = sym.GetType())
if (const auto *derived = declTy->AsDerived())
return Fortran::semantics::CountLenParameters(*derived) != 0;
return false;
}
class CapturedAllocatableAndPointer
: public CapturedSymbols<CapturedAllocatableAndPointer> {
public:
static mlir::Type getType(Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &sym) {
return fir::ReferenceType::get(converter.genType(sym));
}
static void instantiateHostTuple(const InstantiateHostTuple &args,
Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &) {
assert(args.hostValue.getBoxOf<fir::MutableBoxValue>() &&
"host value must be a fir::MutableBoxValue");
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Type typeInTuple = fir::dyn_cast_ptrEleTy(args.addrInTuple.getType());
assert(typeInTuple && "addrInTuple must be an address");
mlir::Value castBox = builder.createConvert(args.loc, typeInTuple,
fir::getBase(args.hostValue));
builder.create<fir::StoreOp>(args.loc, castBox, args.addrInTuple);
}
static void getFromTuple(const GetFromTuple &args,
Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &sym,
const Fortran::lower::BoxAnalyzer &ba) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Location loc = args.loc;
llvm::SmallVector<mlir::Value> nonDeferredLenParams;
if (ba.isChar()) {
mlir::IndexType idxTy = builder.getIndexType();
if (llvm::Optional<int64_t> len = ba.getCharLenConst()) {
nonDeferredLenParams.push_back(
builder.createIntegerConstant(loc, idxTy, *len));
} else if (Fortran::semantics::IsAssumedLengthCharacter(sym) ||
ba.getCharLenExpr()) {
auto readLength = [&]() {
fir::BoxValue boxLoad =
builder.create<fir::LoadOp>(loc, fir::getBase(args.valueInTuple))
.getResult();
return fir::factory::readCharLen(builder, loc, boxLoad);
};
if (Fortran::semantics::IsOptional(sym)) {
auto isPresent = builder.create<fir::IsPresentOp>(
loc, builder.getI1Type(), fir::getBase(args.valueInTuple));
mlir::Value len =
builder.genIfOp(loc, {idxTy}, isPresent, true)
.genThen([&]() {
builder.create<fir::ResultOp>(loc, readLength());
})
.genElse([&]() {
auto undef = builder.create<fir::UndefOp>(loc, idxTy);
builder.create<fir::ResultOp>(loc, undef.getResult());
})
.getResults()[0];
nonDeferredLenParams.push_back(len);
} else {
nonDeferredLenParams.push_back(readLength());
}
}
} else if (isDerivedWithLenParameters(sym)) {
TODO(loc, "host associated derived type allocatable or pointer with "
"length parameters");
}
args.symMap.addSymbol(
sym, fir::MutableBoxValue(args.valueInTuple, nonDeferredLenParams, {}));
}
};
class CapturedArrays : public CapturedSymbols<CapturedArrays> {
public:
static mlir::Type getType(Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &sym) {
mlir::Type type = converter.genType(sym);
assert(type.isa<fir::SequenceType>() && "must be a sequence type");
return fir::BoxType::get(type);
}
static void instantiateHostTuple(const InstantiateHostTuple &args,
Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &sym) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Location loc = args.loc;
fir::MutableBoxValue boxInTuple(args.addrInTuple, {}, {});
if (args.hostValue.getBoxOf<fir::BoxValue>() &&
Fortran::semantics::IsOptional(sym)) {
auto isPresent = builder.create<fir::IsPresentOp>(
loc, builder.getI1Type(), fir::getBase(args.hostValue));
builder.genIfThenElse(loc, isPresent)
.genThen([&]() {
fir::factory::associateMutableBox(builder, loc, boxInTuple,
args.hostValue,
llvm::None);
})
.genElse([&]() {
fir::factory::disassociateMutableBox(builder, loc, boxInTuple);
})
.end();
} else {
fir::factory::associateMutableBox(builder, loc, boxInTuple,
args.hostValue, llvm::None);
}
}
static void getFromTuple(const GetFromTuple &args,
Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &sym,
const Fortran::lower::BoxAnalyzer &ba) {
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Location loc = args.loc;
mlir::Value box = args.valueInTuple;
mlir::IndexType idxTy = builder.getIndexType();
llvm::SmallVector<mlir::Value> lbounds;
if (!ba.lboundIsAllOnes()) {
if (ba.isStaticArray()) {
for (std::int64_t lb : ba.staticLBound())
lbounds.emplace_back(builder.createIntegerConstant(loc, idxTy, lb));
} else {
const unsigned rank = sym.Rank();
for (unsigned dim = 0; dim < rank; ++dim) {
mlir::Value dimVal = builder.createIntegerConstant(loc, idxTy, dim);
auto dims = builder.create<fir::BoxDimsOp>(loc, idxTy, idxTy, idxTy,
box, dimVal);
lbounds.emplace_back(dims.getResult(0));
}
}
}
if (canReadCapturedBoxValue(converter, sym)) {
fir::BoxValue boxValue(box, lbounds, llvm::None);
args.symMap.addSymbol(sym,
fir::factory::readBoxValue(builder, loc, boxValue));
} else {
if (Fortran::semantics::IsOptional(sym)) {
auto boxTy = box.getType().cast<fir::BoxType>();
auto eleTy = boxTy.getEleTy();
if (!fir::isa_ref_type(eleTy))
eleTy = builder.getRefType(eleTy);
auto addr = builder.create<fir::BoxAddrOp>(loc, eleTy, box);
mlir::Value isPresent = builder.genIsNotNullAddr(loc, addr);
auto absentBox = builder.create<fir::AbsentOp>(loc, boxTy);
box = builder.create<mlir::arith::SelectOp>(loc, isPresent, box,
absentBox);
}
fir::BoxValue boxValue(box, lbounds, llvm::None);
args.symMap.addSymbol(sym, boxValue);
}
}
private:
static bool
canReadCapturedBoxValue(Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &sym) {
bool isScalarOrContiguous =
sym.Rank() == 0 || Fortran::evaluate::IsSimplyContiguous(
Fortran::evaluate::AsGenericExpr(sym).value(),
converter.getFoldingContext());
const Fortran::semantics::DeclTypeSpec *type = sym.GetType();
bool isPolymorphic = type && type->IsPolymorphic();
return isScalarOrContiguous && !isPolymorphic &&
!isDerivedWithLenParameters(sym);
}
};
template <typename T>
typename T::Result
walkCaptureCategories(T visitor, Fortran::lower::AbstractConverter &converter,
const Fortran::semantics::Symbol &sym) {
if (isDerivedWithLenParameters(sym))
TODO(converter.genLocation(sym.name()),
"host associated derived type with length parameters");
Fortran::lower::BoxAnalyzer ba;
if (Fortran::semantics::IsProcedure(sym))
return CapturedProcedure::visit(visitor, converter, sym, ba);
ba.analyze(sym);
if (Fortran::evaluate::IsAllocatableOrPointer(sym))
return CapturedAllocatableAndPointer::visit(visitor, converter, sym, ba);
if (ba.isArray())
return CapturedArrays::visit(visitor, converter, sym, ba);
if (ba.isChar())
return CapturedCharacterScalars::visit(visitor, converter, sym, ba);
assert(ba.isTrivial() && "must be trivial scalar");
return CapturedSimpleScalars::visit(visitor, converter, sym, ba);
}
static mlir::TupleType unwrapTupleTy(mlir::Type t) {
return fir::dyn_cast_ptrEleTy(t).cast<mlir::TupleType>();
}
static mlir::Value genTupleCoor(fir::FirOpBuilder &builder, mlir::Location loc,
mlir::Type varTy, mlir::Value tupleArg,
mlir::Value offset) {
auto ty = varTy.isa<fir::ReferenceType>()
? mlir::Type(fir::LLVMPointerType::get(varTy))
: mlir::Type(builder.getRefType(varTy));
return builder.create<fir::CoordinateOp>(loc, ty, tupleArg, offset);
}
void Fortran::lower::HostAssociations::hostProcedureBindings(
Fortran::lower::AbstractConverter &converter,
Fortran::lower::SymMap &symMap) {
if (symbols.empty())
return;
mlir::TupleType tupTy = unwrapTupleTy(getArgumentType(converter));
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Location loc = converter.getCurrentLocation();
auto hostTuple = builder.create<fir::AllocaOp>(loc, tupTy);
mlir::IntegerType offTy = builder.getIntegerType(32);
for (auto s : llvm::enumerate(symbols)) {
auto indexInTuple = s.index();
mlir::Value off = builder.createIntegerConstant(loc, offTy, indexInTuple);
mlir::Type varTy = tupTy.getType(indexInTuple);
mlir::Value eleOff = genTupleCoor(builder, loc, varTy, hostTuple, off);
InstantiateHostTuple instantiateHostTuple{
symMap.lookupSymbol(s.value()).toExtendedValue(), eleOff, loc};
walkCaptureCategories(instantiateHostTuple, converter, *s.value());
}
converter.bindHostAssocTuple(hostTuple);
}
void Fortran::lower::HostAssociations::internalProcedureBindings(
Fortran::lower::AbstractConverter &converter,
Fortran::lower::SymMap &symMap) {
if (symbols.empty())
return;
fir::FirOpBuilder &builder = converter.getFirOpBuilder();
mlir::Type argTy = getArgumentType(converter);
mlir::TupleType tupTy = unwrapTupleTy(argTy);
mlir::Location loc = converter.getCurrentLocation();
mlir::func::FuncOp func = builder.getFunction();
mlir::Value tupleArg;
for (auto [ty, arg] : llvm::reverse(llvm::zip(
func.getFunctionType().getInputs(), func.front().getArguments())))
if (ty == argTy) {
tupleArg = arg;
break;
}
if (!tupleArg)
fir::emitFatalError(loc, "no host association argument found");
converter.bindHostAssocTuple(tupleArg);
mlir::IntegerType offTy = builder.getIntegerType(32);
for (auto s : llvm::enumerate(symbols)) {
mlir::Value off = builder.createIntegerConstant(loc, offTy, s.index());
mlir::Type varTy = tupTy.getType(s.index());
mlir::Value eleOff = genTupleCoor(builder, loc, varTy, tupleArg, off);
mlir::Value valueInTuple = builder.create<fir::LoadOp>(loc, eleOff);
GetFromTuple getFromTuple{symMap, valueInTuple, loc};
walkCaptureCategories(getFromTuple, converter, *s.value());
}
}
mlir::Type Fortran::lower::HostAssociations::getArgumentType(
Fortran::lower::AbstractConverter &converter) {
if (symbols.empty())
return {};
if (argType)
return argType;
mlir::MLIRContext *ctxt = &converter.getMLIRContext();
llvm::SmallVector<mlir::Type> tupleTys;
for (const Fortran::semantics::Symbol *sym : symbols)
tupleTys.emplace_back(
walkCaptureCategories(GetTypeInTuple{}, converter, *sym));
argType = fir::ReferenceType::get(mlir::TupleType::get(ctxt, tupleTys));
return argType;
}