================
@@ -1250,6 +1253,508 @@ getSafeRepackAttrs(Fortran::lower::AbstractConverter
&converter) {
return attrs.empty() ? mlir::ArrayAttr{} : builder.getArrayAttr(attrs);
}
+//===----------------------------------------------------------------------===//
+// -finit-local= helpers
+//===----------------------------------------------------------------------===//
+
+/// Returns true if \p derived or any of its components (recursively) is a
+/// PowerPC vector type. fir::VectorType does not implement
+/// DataLayoutTypeInterface. Two pre-fix failure modes existed:
+/// - Direct vector local: silently initialized to zero regardless of mode
+/// (historical behavior); at the current head genByteSplatInit would
+/// hit llvm_unreachable instead.
+/// - Derived-type local with a vector component: crashed in record-size
+/// calculation when DataLayoutTypeInterface was queried.
+/// Excluding both cases at eligibility time avoids both failure modes.
+static bool
+containsVectorComponent(const Fortran::semantics::DerivedTypeSpec &derived) {
+ if (derived.IsVectorType())
+ return true;
+ const Fortran::semantics::Scope *scope = derived.GetScope();
+ if (!scope)
+ return false;
+ const Fortran::semantics::Symbol &typeSym = derived.typeSymbol();
+ const auto *details =
+ typeSym.detailsIf<Fortran::semantics::DerivedTypeDetails>();
+ if (!details)
+ return false;
+ for (const Fortran::semantics::SourceName &compName :
+ details->componentNames()) {
+ auto it = scope->find(compName);
+ if (it == scope->cend())
+ continue;
+ const Fortran::semantics::Symbol &comp = it->second.get();
+ if (const Fortran::semantics::DeclTypeSpec *compTy = comp.GetType())
+ if (const Fortran::semantics::DerivedTypeSpec *compDerived =
+ compTy->AsDerived())
+ if (containsVectorComponent(*compDerived))
+ return true;
+ }
+ return false;
+}
+
+/// Returns true when \p var is an automatic local variable eligible for
+/// -finit-local= initialization. Excluded: variables without a symbol,
+/// globals, dummy arguments, SAVE'd vars, ALLOCATABLE/POINTER, vars in
+/// an EQUIVALENCE set, vars with explicit or default initialization, and
+/// CUDA variables whose storage is always unreachable by a plain fir.store
+/// (constant, shared, usedevice). The Device case is deferred to genInitLocal
+/// which applies cuf::isCUDADeviceContext to distinguish cuf.alloc from
+/// fir.alloca storage.
+static bool shouldInitLocal(const Fortran::lower::pft::Variable &var) {
+ if (!var.hasSymbol() || var.isGlobal())
+ return false;
+ const Fortran::semantics::Symbol &sym = var.getSymbol();
+ if (Fortran::semantics::IsDummy(sym))
+ return false;
+ // Function result variables own the return-value storage and must not be
+ // pre-initialized: the function body is responsible for setting the result.
+ if (sym.IsFuncResult())
+ return false;
+ // Main-program locals have implicit SAVE semantics (Fortran 2018 8.5.16p4).
+ // IsSaved() does not catch this case because the SAVE attribute is implicit
+ // rather than explicit, so check the enclosing scope kind directly.
+ if (sym.owner().kind() == Fortran::semantics::Scope::Kind::MainProgram)
+ return false;
+ if (Fortran::semantics::IsSaved(sym))
+ return false;
+ if (Fortran::semantics::IsAllocatableOrPointer(sym))
+ return false;
+ if (Fortran::lower::hasDefaultInitialization(sym))
+ return false;
+ if (const auto *obj =
+ sym.detailsIf<Fortran::semantics::ObjectEntityDetails>())
+ if (obj->init())
+ return false;
+ if (Fortran::semantics::FindEquivalenceSet(sym))
+ return false;
+ // Cray pointees own no storage of their own; their FIR base is a
+ // pointer-box descriptor. Initializing it would overwrite the
+ // descriptor, not the pointee storage.
+ if (sym.test(Fortran::semantics::Symbol::Flag::CrayPointee))
+ return false;
+ // PowerPC vector types (vector(real(4)) etc.) lower to fir::VectorType
+ // which does not implement DataLayoutTypeInterface at the HLFIR level.
+ // Without this guard:
+ // - A direct vector local would hit llvm_unreachable in genByteSplatInit
+ // (historically it silently fell back to zero before that assert was
+ // added).
+ // - A derived-type local with a vector component would crash in
+ // record-size calculation when DataLayoutTypeInterface was queried.
+ // Exclude both cases by walking components recursively.
+ if (const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType())
+ if (const Fortran::semantics::DerivedTypeSpec *derived =
+ declTy->AsDerived())
+ if (containsVectorComponent(*derived))
+ return false;
+ // CUDA storage accessibility:
+ // constant / shared / usedevice: always unreachable by a plain fir.store
+ // from the host -- skip.
+ // device: the allocation choice (cuf.alloc vs fir.alloca) depends on
+ // whether the insertion point is in a device context; that check
+ // requires the MLIR builder and is deferred to genInitLocal, which
+ // calls cuf::isCUDADeviceContext(builder.getRegion()) after this
+ // predicate returns true.
+ // managed / unified / pinned: host-accessible unified memory --
initialize.
+ if (auto cudaAttr = Fortran::semantics::GetCUDADataAttr(&sym)) {
+ switch (*cudaAttr) {
+ case Fortran::common::CUDADataAttr::Constant:
+ case Fortran::common::CUDADataAttr::Shared:
+ case Fortran::common::CUDADataAttr::UseDevice:
+ return false;
+ default:
+ break;
+ }
+ }
+ return true;
+}
+
+/// Build a constant whose every byte equals \p bytePat.
+/// Handles: integer, float (bitcast from integer splat), complex (both parts),
+/// and logical (raw integer, stored via bitcasted address by the caller).
+/// Character, derived-type, and sequence types are all intercepted by
+/// genInitLocalStore or initAddr before this function is called and must
+/// not reach it. fir::VectorType (PowerPC vector types, direct or as a
+/// derived-type component) is excluded upstream by shouldInitLocal via
+/// containsVectorComponent and will never reach this function.
+static mlir::Value genByteSplatInit(fir::FirOpBuilder &builder,
+ mlir::Location loc, mlir::Type ty,
+ uint8_t bytePat) {
+ mlir::Type eleTy = fir::unwrapSequenceType(ty);
+
+ // Build a signless integer constant from a byte splat. arith.constant
+ // requires a signless integer type; callers that need a non-signless result
+ // (e.g. unsigned ui32) must fir.convert the returned value themselves.
+ auto makeIntCst = [&](unsigned bits) -> mlir::Value {
+ llvm::APInt byteVal(8, bytePat);
+ llvm::APInt splat = llvm::APInt::getSplat(bits, byteVal);
+ mlir::Type intTy = builder.getIntegerType(bits);
+ return mlir::arith::ConstantOp::create(
+ builder, loc, intTy, builder.getIntegerAttr(intTy, splat));
+ };
+
+ if (auto fpTy = mlir::dyn_cast<mlir::FloatType>(eleTy)) {
+ mlir::Value intCst = makeIntCst(fpTy.getWidth());
+ return mlir::arith::BitcastOp::create(builder, loc, fpTy, intCst);
+ }
+ if (auto intTy = mlir::dyn_cast<mlir::IntegerType>(eleTy)) {
+ mlir::Value cst = makeIntCst(intTy.getWidth());
+ // arith.constant only supports signless integers; fir.convert reinterprets
+ // the bit pattern into the declared signed or unsigned type without
+ // changing any bits, satisfying FIR verification for !fir.ref<ui32> etc.
+ if (!intTy.isSignless())
+ cst = builder.createConvert(loc, intTy, cst);
+ return cst;
+ }
+ // Complex: apply the byte pattern to each (real, imag) part.
+ if (auto cplxTy = mlir::dyn_cast<mlir::ComplexType>(eleTy)) {
+ mlir::Type partTy = cplxTy.getElementType();
+ mlir::Value partVal = genByteSplatInit(builder, loc, partTy, bytePat);
+ return mlir::complex::CreateOp::create(builder, loc, cplxTy, partVal,
+ partVal);
+ }
+ // LOGICAL(k) has a fixed size of k bytes under the default kind mapping,
+ // but a non-default mapping (e.g. --kind-mapping=l4:8) may map LOGICAL(4)
+ // to a single byte. Use KindMapping::getLogicalBitsize so the constant
+ // width matches the actual allocation size.
+ // The caller stores it via a bitcasted address to preserve the bit pattern
+ // (fir.convert from integer to !fir.logical normalizes nonzero -> true).
+ if (auto logTy = mlir::dyn_cast<fir::LogicalType>(eleTy)) {
+ return
makeIntCst(builder.getKindMap().getLogicalBitsize(logTy.getFKind()));
----------------
MattPD wrote:
A mapped LOGICAL width below eight bits reaches `APInt::getSplat` and aborts
the compiler.
`KindMapping::parse` accepts `l4:1`. This path then passes a one-bit
destination width together with an eight-bit source pattern. `APInt::getSplat`
asserts on `NewLen >= V.getBitWidth()`. Before this change the width was
`getFKind() * 8`, so it never fell below eight.
Save this as `repro.f90`:
```fortran
subroutine s(res)
logical(kind=4) :: l
integer :: res
if (l) res = 1
end
```
```console
flang -fc1 -emit-hlfir -mmlir --kind-mapping=l4:1 -finit-local=0xAA repro.f90
-o -
```
Could an unsupported width take a controlled diagnostic instead? The
alternative would be to build the pattern over the physical storage bytes. A
regression case at `l4:1` would pin whichever behavior you choose, since the
committed test covers only `l4:8`.
https://github.com/llvm/llvm-project/pull/216164
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits