1 //===-- ConvertVariable.cpp -- bridge to lower to MLIR --------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/ 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "flang/Lower/ConvertVariable.h" 14 #include "flang/Lower/AbstractConverter.h" 15 #include "flang/Lower/Allocatable.h" 16 #include "flang/Lower/BoxAnalyzer.h" 17 #include "flang/Lower/CallInterface.h" 18 #include "flang/Lower/ConvertExpr.h" 19 #include "flang/Lower/IntrinsicCall.h" 20 #include "flang/Lower/Mangler.h" 21 #include "flang/Lower/PFTBuilder.h" 22 #include "flang/Lower/StatementContext.h" 23 #include "flang/Lower/Support/Utils.h" 24 #include "flang/Lower/SymbolMap.h" 25 #include "flang/Optimizer/Builder/Character.h" 26 #include "flang/Optimizer/Builder/FIRBuilder.h" 27 #include "flang/Optimizer/Builder/Runtime/Derived.h" 28 #include "flang/Optimizer/Builder/Todo.h" 29 #include "flang/Optimizer/Dialect/FIRAttr.h" 30 #include "flang/Optimizer/Dialect/FIRDialect.h" 31 #include "flang/Optimizer/Dialect/FIROps.h" 32 #include "flang/Optimizer/Support/FIRContext.h" 33 #include "flang/Optimizer/Support/FatalError.h" 34 #include "flang/Semantics/runtime-type-info.h" 35 #include "flang/Semantics/tools.h" 36 #include "llvm/Support/Debug.h" 37 38 #define DEBUG_TYPE "flang-lower-variable" 39 40 /// Helper to lower a scalar expression using a specific symbol mapping. 41 static mlir::Value genScalarValue(Fortran::lower::AbstractConverter &converter, 42 mlir::Location loc, 43 const Fortran::lower::SomeExpr &expr, 44 Fortran::lower::SymMap &symMap, 45 Fortran::lower::StatementContext &context) { 46 // This does not use the AbstractConverter member function to override the 47 // symbol mapping to be used expression lowering. 48 return fir::getBase(Fortran::lower::createSomeExtendedExpression( 49 loc, converter, expr, symMap, context)); 50 } 51 52 /// Does this variable have a default initialization? 53 static bool hasDefaultInitialization(const Fortran::semantics::Symbol &sym) { 54 if (sym.has<Fortran::semantics::ObjectEntityDetails>() && sym.size()) 55 if (!Fortran::semantics::IsAllocatableOrPointer(sym)) 56 if (const Fortran::semantics::DeclTypeSpec *declTypeSpec = sym.GetType()) 57 if (const Fortran::semantics::DerivedTypeSpec *derivedTypeSpec = 58 declTypeSpec->AsDerived()) 59 return derivedTypeSpec->HasDefaultInitialization(); 60 return false; 61 } 62 63 //===----------------------------------------------------------------===// 64 // Global variables instantiation (not for alias and common) 65 //===----------------------------------------------------------------===// 66 67 /// Helper to generate expression value inside global initializer. 68 static fir::ExtendedValue 69 genInitializerExprValue(Fortran::lower::AbstractConverter &converter, 70 mlir::Location loc, 71 const Fortran::lower::SomeExpr &expr, 72 Fortran::lower::StatementContext &stmtCtx) { 73 // Data initializer are constant value and should not depend on other symbols 74 // given the front-end fold parameter references. In any case, the "current" 75 // map of the converter should not be used since it holds mapping to 76 // mlir::Value from another mlir region. If these value are used by accident 77 // in the initializer, this will lead to segfaults in mlir code. 78 Fortran::lower::SymMap emptyMap; 79 return Fortran::lower::createSomeInitializerExpression(loc, converter, expr, 80 emptyMap, stmtCtx); 81 } 82 83 /// Can this symbol constant be placed in read-only memory? 84 static bool isConstant(const Fortran::semantics::Symbol &sym) { 85 return sym.attrs().test(Fortran::semantics::Attr::PARAMETER) || 86 sym.test(Fortran::semantics::Symbol::Flag::ReadOnly); 87 } 88 89 /// Is this a compiler generated symbol to describe derived types ? 90 static bool isRuntimeTypeInfoData(const Fortran::semantics::Symbol &sym) { 91 // So far, use flags to detect if this symbol were generated during 92 // semantics::BuildRuntimeDerivedTypeTables(). Scope cannot be used since the 93 // symbols are injected in the user scopes defining the described derived 94 // types. A robustness improvement for this test could be to get hands on the 95 // semantics::RuntimeDerivedTypeTables and to check if the symbol names 96 // belongs to this structure. 97 return sym.test(Fortran::semantics::Symbol::Flag::CompilerCreated) && 98 sym.test(Fortran::semantics::Symbol::Flag::ReadOnly); 99 } 100 101 static fir::GlobalOp defineGlobal(Fortran::lower::AbstractConverter &converter, 102 const Fortran::lower::pft::Variable &var, 103 llvm::StringRef globalName, 104 mlir::StringAttr linkage); 105 106 /// Create the global op declaration without any initializer 107 static fir::GlobalOp declareGlobal(Fortran::lower::AbstractConverter &converter, 108 const Fortran::lower::pft::Variable &var, 109 llvm::StringRef globalName, 110 mlir::StringAttr linkage) { 111 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 112 if (fir::GlobalOp global = builder.getNamedGlobal(globalName)) 113 return global; 114 // Always define linkonce data since it may be optimized out from the module 115 // that actually owns the variable if it does not refers to it. 116 if (linkage == builder.createLinkOnceODRLinkage() || 117 linkage == builder.createLinkOnceLinkage()) 118 return defineGlobal(converter, var, globalName, linkage); 119 const Fortran::semantics::Symbol &sym = var.getSymbol(); 120 mlir::Location loc = converter.genLocation(sym.name()); 121 // Resolve potential host and module association before checking that this 122 // symbol is an object of a function pointer. 123 const Fortran::semantics::Symbol &ultimate = sym.GetUltimate(); 124 if (!ultimate.has<Fortran::semantics::ObjectEntityDetails>() && 125 !Fortran::semantics::IsProcedurePointer(ultimate)) 126 mlir::emitError(loc, "lowering global declaration: symbol '") 127 << toStringRef(sym.name()) << "' has unexpected details\n"; 128 return builder.createGlobal(loc, converter.genType(var), globalName, linkage, 129 mlir::Attribute{}, isConstant(ultimate)); 130 } 131 132 /// Temporary helper to catch todos in initial data target lowering. 133 static bool 134 hasDerivedTypeWithLengthParameters(const Fortran::semantics::Symbol &sym) { 135 if (const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType()) 136 if (const Fortran::semantics::DerivedTypeSpec *derived = 137 declTy->AsDerived()) 138 return Fortran::semantics::CountLenParameters(*derived) > 0; 139 return false; 140 } 141 142 static mlir::Type unwrapElementType(mlir::Type type) { 143 if (mlir::Type ty = fir::dyn_cast_ptrOrBoxEleTy(type)) 144 type = ty; 145 if (auto seqType = type.dyn_cast<fir::SequenceType>()) 146 type = seqType.getEleTy(); 147 return type; 148 } 149 150 fir::ExtendedValue Fortran::lower::genExtAddrInInitializer( 151 Fortran::lower::AbstractConverter &converter, mlir::Location loc, 152 const Fortran::lower::SomeExpr &addr) { 153 Fortran::lower::SymMap globalOpSymMap; 154 Fortran::lower::AggregateStoreMap storeMap; 155 Fortran::lower::StatementContext stmtCtx; 156 if (const Fortran::semantics::Symbol *sym = 157 Fortran::evaluate::GetFirstSymbol(addr)) { 158 // Length parameters processing will need care in global initializer 159 // context. 160 if (hasDerivedTypeWithLengthParameters(*sym)) 161 TODO(loc, "initial-data-target with derived type length parameters"); 162 163 auto var = Fortran::lower::pft::Variable(*sym, /*global=*/true); 164 Fortran::lower::instantiateVariable(converter, var, globalOpSymMap, 165 storeMap); 166 } 167 return Fortran::lower::createInitializerAddress(loc, converter, addr, 168 globalOpSymMap, stmtCtx); 169 } 170 171 /// create initial-data-target fir.box in a global initializer region. 172 mlir::Value Fortran::lower::genInitialDataTarget( 173 Fortran::lower::AbstractConverter &converter, mlir::Location loc, 174 mlir::Type boxType, const Fortran::lower::SomeExpr &initialTarget) { 175 Fortran::lower::SymMap globalOpSymMap; 176 Fortran::lower::AggregateStoreMap storeMap; 177 Fortran::lower::StatementContext stmtCtx; 178 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 179 if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>( 180 initialTarget)) 181 return fir::factory::createUnallocatedBox(builder, loc, boxType, 182 /*nonDeferredParams=*/llvm::None); 183 // Pointer initial data target, and NULL(mold). 184 if (const Fortran::semantics::Symbol *sym = 185 Fortran::evaluate::GetFirstSymbol(initialTarget)) { 186 // Length parameters processing will need care in global initializer 187 // context. 188 if (hasDerivedTypeWithLengthParameters(*sym)) 189 TODO(loc, "initial-data-target with derived type length parameters"); 190 191 auto var = Fortran::lower::pft::Variable(*sym, /*global=*/true); 192 Fortran::lower::instantiateVariable(converter, var, globalOpSymMap, 193 storeMap); 194 } 195 mlir::Value box; 196 if (initialTarget.Rank() > 0) { 197 box = fir::getBase(Fortran::lower::createSomeArrayBox( 198 converter, initialTarget, globalOpSymMap, stmtCtx)); 199 } else { 200 fir::ExtendedValue addr = Fortran::lower::createInitializerAddress( 201 loc, converter, initialTarget, globalOpSymMap, stmtCtx); 202 box = builder.createBox(loc, addr); 203 } 204 // box is a fir.box<T>, not a fir.box<fir.ptr<T>> as it should to be used 205 // for pointers. A fir.convert should not be used here, because it would 206 // not actually set the pointer attribute in the descriptor. 207 // In a normal context, fir.rebox would be used to set the pointer attribute 208 // while copying the projection from another fir.box. But fir.rebox cannot be 209 // used in initializer because its current codegen expects that the input 210 // fir.box is in memory, which is not the case in initializers. 211 // So, just replace the fir.embox that created addr with one with 212 // fir.box<fir.ptr<T>> result type. 213 // Note that the descriptor cannot have been created with fir.rebox because 214 // the initial-data-target cannot be a fir.box itself (it cannot be 215 // assumed-shape, deferred-shape, or polymorphic as per C765). However the 216 // case where the initial data target is a derived type with length parameters 217 // will most likely be a bit trickier, hence the TODO above. 218 219 mlir::Operation *op = box.getDefiningOp(); 220 if (!op || !mlir::isa<fir::EmboxOp>(*op)) 221 fir::emitFatalError( 222 loc, "fir.box must be created with embox in global initializers"); 223 mlir::Type targetEleTy = unwrapElementType(box.getType()); 224 if (!fir::isa_char(targetEleTy)) 225 return builder.create<fir::EmboxOp>(loc, boxType, op->getOperands(), 226 op->getAttrs()); 227 228 // Handle the character case length particularities: embox takes a length 229 // value argument when the result type has unknown length, but not when the 230 // result type has constant length. The type of the initial target must be 231 // constant length, but the one of the pointer may not be. In this case, a 232 // length operand must be added. 233 auto targetLen = targetEleTy.cast<fir::CharacterType>().getLen(); 234 auto ptrLen = unwrapElementType(boxType).cast<fir::CharacterType>().getLen(); 235 if (ptrLen == targetLen) 236 // Nothing to do 237 return builder.create<fir::EmboxOp>(loc, boxType, op->getOperands(), 238 op->getAttrs()); 239 auto embox = mlir::cast<fir::EmboxOp>(*op); 240 auto ptrType = boxType.cast<fir::BoxType>().getEleTy(); 241 mlir::Value memref = builder.createConvert(loc, ptrType, embox.getMemref()); 242 if (targetLen == fir::CharacterType::unknownLen()) 243 // Drop the length argument. 244 return builder.create<fir::EmboxOp>(loc, boxType, memref, embox.getShape(), 245 embox.getSlice()); 246 // targetLen is constant and ptrLen is unknown. Add a length argument. 247 mlir::Value targetLenValue = 248 builder.createIntegerConstant(loc, builder.getIndexType(), targetLen); 249 return builder.create<fir::EmboxOp>(loc, boxType, memref, embox.getShape(), 250 embox.getSlice(), 251 mlir::ValueRange{targetLenValue}); 252 } 253 254 static mlir::Value genDefaultInitializerValue( 255 Fortran::lower::AbstractConverter &converter, mlir::Location loc, 256 const Fortran::semantics::Symbol &sym, mlir::Type symTy, 257 Fortran::lower::StatementContext &stmtCtx) { 258 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 259 mlir::Type scalarType = symTy; 260 fir::SequenceType sequenceType; 261 if (auto ty = symTy.dyn_cast<fir::SequenceType>()) { 262 sequenceType = ty; 263 scalarType = ty.getEleTy(); 264 } 265 // Build a scalar default value of the symbol type, looping through the 266 // components to build each component initial value. 267 auto recTy = scalarType.cast<fir::RecordType>(); 268 auto fieldTy = fir::FieldType::get(scalarType.getContext()); 269 mlir::Value initialValue = builder.create<fir::UndefOp>(loc, scalarType); 270 const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType(); 271 assert(declTy && "var with default initialization must have a type"); 272 Fortran::semantics::OrderedComponentIterator components( 273 declTy->derivedTypeSpec()); 274 for (const auto &component : components) { 275 // Skip parent components, the sub-components of parent types are part of 276 // components and will be looped through right after. 277 if (component.test(Fortran::semantics::Symbol::Flag::ParentComp)) 278 continue; 279 mlir::Value componentValue; 280 llvm::StringRef name = toStringRef(component.name()); 281 mlir::Type componentTy = recTy.getType(name); 282 assert(componentTy && "component not found in type"); 283 if (const auto *object{ 284 component.detailsIf<Fortran::semantics::ObjectEntityDetails>()}) { 285 if (const auto &init = object->init()) { 286 // Component has explicit initialization. 287 if (Fortran::semantics::IsPointer(component)) 288 // Initial data target. 289 componentValue = 290 genInitialDataTarget(converter, loc, componentTy, *init); 291 else 292 // Initial value. 293 componentValue = fir::getBase( 294 genInitializerExprValue(converter, loc, *init, stmtCtx)); 295 } else if (Fortran::semantics::IsAllocatableOrPointer(component)) { 296 // Pointer or allocatable without initialization. 297 // Create deallocated/disassociated value. 298 // From a standard point of view, pointer without initialization do not 299 // need to be disassociated, but for sanity and simplicity, do it in 300 // global constructor since this has no runtime cost. 301 componentValue = fir::factory::createUnallocatedBox( 302 builder, loc, componentTy, llvm::None); 303 } else if (hasDefaultInitialization(component)) { 304 // Component type has default initialization. 305 componentValue = genDefaultInitializerValue(converter, loc, component, 306 componentTy, stmtCtx); 307 } else { 308 // Component has no initial value. 309 componentValue = builder.create<fir::UndefOp>(loc, componentTy); 310 } 311 } else if (const auto *proc{ 312 component 313 .detailsIf<Fortran::semantics::ProcEntityDetails>()}) { 314 if (proc->init().has_value()) 315 TODO(loc, "procedure pointer component default initialization"); 316 else 317 componentValue = builder.create<fir::UndefOp>(loc, componentTy); 318 } 319 assert(componentValue && "must have been computed"); 320 componentValue = builder.createConvert(loc, componentTy, componentValue); 321 // FIXME: type parameters must come from the derived-type-spec 322 auto field = builder.create<fir::FieldIndexOp>( 323 loc, fieldTy, name, scalarType, 324 /*typeParams=*/mlir::ValueRange{} /*TODO*/); 325 initialValue = builder.create<fir::InsertValueOp>( 326 loc, recTy, initialValue, componentValue, 327 builder.getArrayAttr(field.getAttributes())); 328 } 329 330 if (sequenceType) { 331 // For arrays, duplicate the scalar value to all elements with an 332 // fir.insert_range covering the whole array. 333 auto arrayInitialValue = builder.create<fir::UndefOp>(loc, sequenceType); 334 llvm::SmallVector<int64_t> rangeBounds; 335 for (int64_t extent : sequenceType.getShape()) { 336 if (extent == fir::SequenceType::getUnknownExtent()) 337 TODO(loc, 338 "default initial value of array component with length parameters"); 339 rangeBounds.push_back(0); 340 rangeBounds.push_back(extent - 1); 341 } 342 return builder.create<fir::InsertOnRangeOp>( 343 loc, sequenceType, arrayInitialValue, initialValue, 344 builder.getIndexVectorAttr(rangeBounds)); 345 } 346 return initialValue; 347 } 348 349 /// Does this global already have an initializer ? 350 static bool globalIsInitialized(fir::GlobalOp global) { 351 return !global.getRegion().empty() || global.getInitVal(); 352 } 353 354 /// Call \p genInit to generate code inside \p global initializer region. 355 static void 356 createGlobalInitialization(fir::FirOpBuilder &builder, fir::GlobalOp global, 357 std::function<void(fir::FirOpBuilder &)> genInit) { 358 mlir::Region ®ion = global.getRegion(); 359 region.push_back(new mlir::Block); 360 mlir::Block &block = region.back(); 361 auto insertPt = builder.saveInsertionPoint(); 362 builder.setInsertionPointToStart(&block); 363 genInit(builder); 364 builder.restoreInsertionPoint(insertPt); 365 } 366 367 /// Create the global op and its init if it has one 368 static fir::GlobalOp defineGlobal(Fortran::lower::AbstractConverter &converter, 369 const Fortran::lower::pft::Variable &var, 370 llvm::StringRef globalName, 371 mlir::StringAttr linkage) { 372 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 373 const Fortran::semantics::Symbol &sym = var.getSymbol(); 374 mlir::Location loc = converter.genLocation(sym.name()); 375 bool isConst = isConstant(sym); 376 fir::GlobalOp global = builder.getNamedGlobal(globalName); 377 mlir::Type symTy = converter.genType(var); 378 379 if (global && globalIsInitialized(global)) 380 return global; 381 382 if (Fortran::semantics::IsProcedurePointer(sym)) 383 TODO(loc, "procedure pointer globals"); 384 385 // If this is an array, check to see if we can use a dense attribute 386 // with a tensor mlir type. This optimization currently only supports 387 // rank-1 Fortran arrays of integer, real, or logical. The tensor 388 // type does not support nested structures which are needed for 389 // complex numbers. 390 // To get multidimensional arrays to work, we will have to use column major 391 // array ordering with the tensor type (so it matches column major ordering 392 // with the Fortran fir.array). By default, tensor types assume row major 393 // ordering. How to create this tensor type is to be determined. 394 if (symTy.isa<fir::SequenceType>() && sym.Rank() == 1 && 395 !Fortran::semantics::IsAllocatableOrPointer(sym)) { 396 mlir::Type eleTy = symTy.cast<fir::SequenceType>().getEleTy(); 397 if (eleTy.isa<mlir::IntegerType, mlir::FloatType, fir::LogicalType>()) { 398 const auto *details = 399 sym.detailsIf<Fortran::semantics::ObjectEntityDetails>(); 400 if (details->init()) { 401 global = Fortran::lower::createDenseGlobal( 402 loc, symTy, globalName, linkage, isConst, details->init().value(), 403 converter); 404 if (global) { 405 global.setVisibility(mlir::SymbolTable::Visibility::Public); 406 return global; 407 } 408 } 409 } 410 } 411 if (!global) 412 global = builder.createGlobal(loc, symTy, globalName, linkage, 413 mlir::Attribute{}, isConst); 414 if (Fortran::semantics::IsAllocatableOrPointer(sym)) { 415 const auto *details = 416 sym.detailsIf<Fortran::semantics::ObjectEntityDetails>(); 417 if (details && details->init()) { 418 auto expr = *details->init(); 419 createGlobalInitialization(builder, global, [&](fir::FirOpBuilder &b) { 420 mlir::Value box = 421 Fortran::lower::genInitialDataTarget(converter, loc, symTy, expr); 422 b.create<fir::HasValueOp>(loc, box); 423 }); 424 } else { 425 // Create unallocated/disassociated descriptor if no explicit init 426 createGlobalInitialization(builder, global, [&](fir::FirOpBuilder &b) { 427 mlir::Value box = 428 fir::factory::createUnallocatedBox(b, loc, symTy, llvm::None); 429 b.create<fir::HasValueOp>(loc, box); 430 }); 431 } 432 433 } else if (const auto *details = 434 sym.detailsIf<Fortran::semantics::ObjectEntityDetails>()) { 435 if (details->init()) { 436 createGlobalInitialization( 437 builder, global, [&](fir::FirOpBuilder &builder) { 438 Fortran::lower::StatementContext stmtCtx( 439 /*cleanupProhibited=*/true); 440 fir::ExtendedValue initVal = genInitializerExprValue( 441 converter, loc, details->init().value(), stmtCtx); 442 mlir::Value castTo = 443 builder.createConvert(loc, symTy, fir::getBase(initVal)); 444 builder.create<fir::HasValueOp>(loc, castTo); 445 }); 446 } else if (hasDefaultInitialization(sym)) { 447 createGlobalInitialization( 448 builder, global, [&](fir::FirOpBuilder &builder) { 449 Fortran::lower::StatementContext stmtCtx( 450 /*cleanupProhibited=*/true); 451 mlir::Value initVal = 452 genDefaultInitializerValue(converter, loc, sym, symTy, stmtCtx); 453 mlir::Value castTo = builder.createConvert(loc, symTy, initVal); 454 builder.create<fir::HasValueOp>(loc, castTo); 455 }); 456 } 457 } else if (sym.has<Fortran::semantics::CommonBlockDetails>()) { 458 mlir::emitError(loc, "COMMON symbol processed elsewhere"); 459 } else { 460 TODO(loc, "global"); // Procedure pointer or something else 461 } 462 // Creates undefined initializer for globals without initializers 463 if (!globalIsInitialized(global)) { 464 // TODO: Is it really required to add the undef init if the Public 465 // visibility is set ? We need to make sure the global is not optimized out 466 // by LLVM if unused in the current compilation unit, but at least for 467 // BIND(C) variables, an initial value may be given in another compilation 468 // unit (on the C side), and setting an undef init here creates linkage 469 // conflicts. 470 if (sym.attrs().test(Fortran::semantics::Attr::BIND_C)) 471 TODO(loc, "BIND(C) module variable linkage"); 472 createGlobalInitialization( 473 builder, global, [&](fir::FirOpBuilder &builder) { 474 builder.create<fir::HasValueOp>( 475 loc, builder.create<fir::UndefOp>(loc, symTy)); 476 }); 477 } 478 // Set public visibility to prevent global definition to be optimized out 479 // even if they have no initializer and are unused in this compilation unit. 480 global.setVisibility(mlir::SymbolTable::Visibility::Public); 481 return global; 482 } 483 484 /// Return linkage attribute for \p var. 485 static mlir::StringAttr 486 getLinkageAttribute(fir::FirOpBuilder &builder, 487 const Fortran::lower::pft::Variable &var) { 488 // Runtime type info for a same derived type is identical in each compilation 489 // unit. It desired to avoid having to link against module that only define a 490 // type. Therefore the runtime type info is generated everywhere it is needed 491 // with `linkonce_odr` LLVM linkage. 492 if (var.hasSymbol() && isRuntimeTypeInfoData(var.getSymbol())) 493 return builder.createLinkOnceODRLinkage(); 494 if (var.isModuleVariable()) 495 return {}; // external linkage 496 // Otherwise, the variable is owned by a procedure and must not be visible in 497 // other compilation units. 498 return builder.createInternalLinkage(); 499 } 500 501 /// Instantiate a global variable. If it hasn't already been processed, add 502 /// the global to the ModuleOp as a new uniqued symbol and initialize it with 503 /// the correct value. It will be referenced on demand using `fir.addr_of`. 504 static void instantiateGlobal(Fortran::lower::AbstractConverter &converter, 505 const Fortran::lower::pft::Variable &var, 506 Fortran::lower::SymMap &symMap) { 507 const Fortran::semantics::Symbol &sym = var.getSymbol(); 508 assert(!var.isAlias() && "must be handled in instantiateAlias"); 509 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 510 std::string globalName = Fortran::lower::mangle::mangleName(sym); 511 mlir::Location loc = converter.genLocation(sym.name()); 512 fir::GlobalOp global = builder.getNamedGlobal(globalName); 513 mlir::StringAttr linkage = getLinkageAttribute(builder, var); 514 if (var.isModuleVariable()) { 515 // A module global was or will be defined when lowering the module. Emit 516 // only a declaration if the global does not exist at that point. 517 global = declareGlobal(converter, var, globalName, linkage); 518 } else { 519 global = defineGlobal(converter, var, globalName, linkage); 520 } 521 auto addrOf = builder.create<fir::AddrOfOp>(loc, global.resultType(), 522 global.getSymbol()); 523 Fortran::lower::StatementContext stmtCtx; 524 mapSymbolAttributes(converter, var, symMap, stmtCtx, addrOf); 525 } 526 527 //===----------------------------------------------------------------===// 528 // Local variables instantiation (not for alias) 529 //===----------------------------------------------------------------===// 530 531 /// Create a stack slot for a local variable. Precondition: the insertion 532 /// point of the builder must be in the entry block, which is currently being 533 /// constructed. 534 static mlir::Value createNewLocal(Fortran::lower::AbstractConverter &converter, 535 mlir::Location loc, 536 const Fortran::lower::pft::Variable &var, 537 mlir::Value preAlloc, 538 llvm::ArrayRef<mlir::Value> shape = {}, 539 llvm::ArrayRef<mlir::Value> lenParams = {}) { 540 if (preAlloc) 541 return preAlloc; 542 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 543 std::string nm = Fortran::lower::mangle::mangleName(var.getSymbol()); 544 mlir::Type ty = converter.genType(var); 545 const Fortran::semantics::Symbol &ultimateSymbol = 546 var.getSymbol().GetUltimate(); 547 llvm::StringRef symNm = toStringRef(ultimateSymbol.name()); 548 bool isTarg = var.isTarget(); 549 // Let the builder do all the heavy lifting. 550 return builder.allocateLocal(loc, ty, nm, symNm, shape, lenParams, isTarg); 551 } 552 553 /// Must \p var be default initialized at runtime when entering its scope. 554 static bool 555 mustBeDefaultInitializedAtRuntime(const Fortran::lower::pft::Variable &var) { 556 if (!var.hasSymbol()) 557 return false; 558 const Fortran::semantics::Symbol &sym = var.getSymbol(); 559 if (var.isGlobal()) 560 // Global variables are statically initialized. 561 return false; 562 if (Fortran::semantics::IsDummy(sym) && !Fortran::semantics::IsIntentOut(sym)) 563 return false; 564 // Local variables (including function results), and intent(out) dummies must 565 // be default initialized at runtime if their type has default initialization. 566 return hasDefaultInitialization(sym); 567 } 568 569 /// Call default initialization runtime routine to initialize \p var. 570 static void 571 defaultInitializeAtRuntime(Fortran::lower::AbstractConverter &converter, 572 const Fortran::lower::pft::Variable &var, 573 Fortran::lower::SymMap &symMap) { 574 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 575 mlir::Location loc = converter.getCurrentLocation(); 576 const Fortran::semantics::Symbol &sym = var.getSymbol(); 577 fir::ExtendedValue exv = symMap.lookupSymbol(sym).toExtendedValue(); 578 if (Fortran::semantics::IsOptional(sym)) { 579 // 15.5.2.12 point 3, absent optional dummies are not initialized. 580 // Creating descriptor/passing null descriptor to the runtime would 581 // create runtime crashes. 582 auto isPresent = builder.create<fir::IsPresentOp>(loc, builder.getI1Type(), 583 fir::getBase(exv)); 584 builder.genIfThen(loc, isPresent) 585 .genThen([&]() { 586 auto box = builder.createBox(loc, exv); 587 fir::runtime::genDerivedTypeInitialize(builder, loc, box); 588 }) 589 .end(); 590 } else { 591 mlir::Value box = builder.createBox(loc, exv); 592 fir::runtime::genDerivedTypeInitialize(builder, loc, box); 593 } 594 } 595 596 /// Instantiate a local variable. Precondition: Each variable will be visited 597 /// such that if its properties depend on other variables, the variables upon 598 /// which its properties depend will already have been visited. 599 static void instantiateLocal(Fortran::lower::AbstractConverter &converter, 600 const Fortran::lower::pft::Variable &var, 601 Fortran::lower::SymMap &symMap) { 602 assert(!var.isAlias()); 603 Fortran::lower::StatementContext stmtCtx; 604 mapSymbolAttributes(converter, var, symMap, stmtCtx); 605 if (mustBeDefaultInitializedAtRuntime(var)) 606 defaultInitializeAtRuntime(converter, var, symMap); 607 } 608 609 //===----------------------------------------------------------------===// 610 // Aliased (EQUIVALENCE) variables instantiation 611 //===----------------------------------------------------------------===// 612 613 /// Insert \p aggregateStore instance into an AggregateStoreMap. 614 static void insertAggregateStore(Fortran::lower::AggregateStoreMap &storeMap, 615 const Fortran::lower::pft::Variable &var, 616 mlir::Value aggregateStore) { 617 std::size_t off = var.getAggregateStore().getOffset(); 618 Fortran::lower::AggregateStoreKey key = {var.getOwningScope(), off}; 619 storeMap[key] = aggregateStore; 620 } 621 622 /// Retrieve the aggregate store instance of \p alias from an 623 /// AggregateStoreMap. 624 static mlir::Value 625 getAggregateStore(Fortran::lower::AggregateStoreMap &storeMap, 626 const Fortran::lower::pft::Variable &alias) { 627 Fortran::lower::AggregateStoreKey key = {alias.getOwningScope(), 628 alias.getAlias()}; 629 auto iter = storeMap.find(key); 630 assert(iter != storeMap.end()); 631 return iter->second; 632 } 633 634 /// Build the name for the storage of a global equivalence. 635 static std::string mangleGlobalAggregateStore( 636 const Fortran::lower::pft::Variable::AggregateStore &st) { 637 return Fortran::lower::mangle::mangleName(st.getNamingSymbol()); 638 } 639 640 /// Build the type for the storage of an equivalence. 641 static mlir::Type 642 getAggregateType(Fortran::lower::AbstractConverter &converter, 643 const Fortran::lower::pft::Variable::AggregateStore &st) { 644 if (const Fortran::semantics::Symbol *initSym = st.getInitialValueSymbol()) 645 return converter.genType(*initSym); 646 mlir::IntegerType byteTy = converter.getFirOpBuilder().getIntegerType(8); 647 return fir::SequenceType::get(std::get<1>(st.interval), byteTy); 648 } 649 650 /// Define a GlobalOp for the storage of a global equivalence described 651 /// by \p aggregate. The global is named \p aggName and is created with 652 /// the provided \p linkage. 653 /// If any of the equivalence members are initialized, an initializer is 654 /// created for the equivalence. 655 /// This is to be used when lowering the scope that owns the equivalence 656 /// (as opposed to simply using it through host or use association). 657 /// This is not to be used for equivalence of common block members (they 658 /// already have the common block GlobalOp for them, see defineCommonBlock). 659 static fir::GlobalOp defineGlobalAggregateStore( 660 Fortran::lower::AbstractConverter &converter, 661 const Fortran::lower::pft::Variable::AggregateStore &aggregate, 662 llvm::StringRef aggName, mlir::StringAttr linkage) { 663 assert(aggregate.isGlobal() && "not a global interval"); 664 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 665 fir::GlobalOp global = builder.getNamedGlobal(aggName); 666 if (global && globalIsInitialized(global)) 667 return global; 668 mlir::Location loc = converter.getCurrentLocation(); 669 mlir::Type aggTy = getAggregateType(converter, aggregate); 670 if (!global) 671 global = builder.createGlobal(loc, aggTy, aggName, linkage); 672 673 if (const Fortran::semantics::Symbol *initSym = 674 aggregate.getInitialValueSymbol()) 675 if (const auto *objectDetails = 676 initSym->detailsIf<Fortran::semantics::ObjectEntityDetails>()) 677 if (objectDetails->init()) { 678 createGlobalInitialization( 679 builder, global, [&](fir::FirOpBuilder &builder) { 680 Fortran::lower::StatementContext stmtCtx; 681 mlir::Value initVal = fir::getBase(genInitializerExprValue( 682 converter, loc, objectDetails->init().value(), stmtCtx)); 683 builder.create<fir::HasValueOp>(loc, initVal); 684 }); 685 return global; 686 } 687 // Equivalence has no Fortran initial value. Create an undefined FIR initial 688 // value to ensure this is consider an object definition in the IR regardless 689 // of the linkage. 690 createGlobalInitialization(builder, global, [&](fir::FirOpBuilder &builder) { 691 Fortran::lower::StatementContext stmtCtx; 692 mlir::Value initVal = builder.create<fir::UndefOp>(loc, aggTy); 693 builder.create<fir::HasValueOp>(loc, initVal); 694 }); 695 return global; 696 } 697 698 /// Declare a GlobalOp for the storage of a global equivalence described 699 /// by \p aggregate. The global is named \p aggName and is created with 700 /// the provided \p linkage. 701 /// No initializer is built for the created GlobalOp. 702 /// This is to be used when lowering the scope that uses members of an 703 /// equivalence it through host or use association. 704 /// This is not to be used for equivalence of common block members (they 705 /// already have the common block GlobalOp for them, see defineCommonBlock). 706 static fir::GlobalOp declareGlobalAggregateStore( 707 Fortran::lower::AbstractConverter &converter, mlir::Location loc, 708 const Fortran::lower::pft::Variable::AggregateStore &aggregate, 709 llvm::StringRef aggName, mlir::StringAttr linkage) { 710 assert(aggregate.isGlobal() && "not a global interval"); 711 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 712 if (fir::GlobalOp global = builder.getNamedGlobal(aggName)) 713 return global; 714 mlir::Type aggTy = getAggregateType(converter, aggregate); 715 return builder.createGlobal(loc, aggTy, aggName, linkage); 716 } 717 718 /// This is an aggregate store for a set of EQUIVALENCED variables. Create the 719 /// storage on the stack or global memory and add it to the map. 720 static void 721 instantiateAggregateStore(Fortran::lower::AbstractConverter &converter, 722 const Fortran::lower::pft::Variable &var, 723 Fortran::lower::AggregateStoreMap &storeMap) { 724 assert(var.isAggregateStore() && "not an interval"); 725 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 726 mlir::IntegerType i8Ty = builder.getIntegerType(8); 727 mlir::Location loc = converter.getCurrentLocation(); 728 std::string aggName = mangleGlobalAggregateStore(var.getAggregateStore()); 729 if (var.isGlobal()) { 730 fir::GlobalOp global; 731 auto &aggregate = var.getAggregateStore(); 732 mlir::StringAttr linkage = getLinkageAttribute(builder, var); 733 if (var.isModuleVariable()) { 734 // A module global was or will be defined when lowering the module. Emit 735 // only a declaration if the global does not exist at that point. 736 global = declareGlobalAggregateStore(converter, loc, aggregate, aggName, 737 linkage); 738 } else { 739 global = 740 defineGlobalAggregateStore(converter, aggregate, aggName, linkage); 741 } 742 auto addr = builder.create<fir::AddrOfOp>(loc, global.resultType(), 743 global.getSymbol()); 744 auto size = std::get<1>(var.getInterval()); 745 fir::SequenceType::Shape shape(1, size); 746 auto seqTy = fir::SequenceType::get(shape, i8Ty); 747 mlir::Type refTy = builder.getRefType(seqTy); 748 mlir::Value aggregateStore = builder.createConvert(loc, refTy, addr); 749 insertAggregateStore(storeMap, var, aggregateStore); 750 return; 751 } 752 // This is a local aggregate, allocate an anonymous block of memory. 753 auto size = std::get<1>(var.getInterval()); 754 fir::SequenceType::Shape shape(1, size); 755 auto seqTy = fir::SequenceType::get(shape, i8Ty); 756 mlir::Value local = 757 builder.allocateLocal(loc, seqTy, aggName, "", llvm::None, llvm::None, 758 /*target=*/false); 759 insertAggregateStore(storeMap, var, local); 760 } 761 762 /// Cast an alias address (variable part of an equivalence) to fir.ptr so that 763 /// the optimizer is conservative and avoids doing copy elision in assignment 764 /// involving equivalenced variables. 765 /// TODO: Represent the equivalence aliasing constraint in another way to avoid 766 /// pessimizing array assignments involving equivalenced variables. 767 static mlir::Value castAliasToPointer(fir::FirOpBuilder &builder, 768 mlir::Location loc, mlir::Type aliasType, 769 mlir::Value aliasAddr) { 770 return builder.createConvert(loc, fir::PointerType::get(aliasType), 771 aliasAddr); 772 } 773 774 /// Instantiate a member of an equivalence. Compute its address in its 775 /// aggregate storage and lower its attributes. 776 static void instantiateAlias(Fortran::lower::AbstractConverter &converter, 777 const Fortran::lower::pft::Variable &var, 778 Fortran::lower::SymMap &symMap, 779 Fortran::lower::AggregateStoreMap &storeMap) { 780 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 781 assert(var.isAlias()); 782 const Fortran::semantics::Symbol &sym = var.getSymbol(); 783 const mlir::Location loc = converter.genLocation(sym.name()); 784 mlir::IndexType idxTy = builder.getIndexType(); 785 std::size_t aliasOffset = var.getAlias(); 786 mlir::Value store = getAggregateStore(storeMap, var); 787 mlir::IntegerType i8Ty = builder.getIntegerType(8); 788 mlir::Type i8Ptr = builder.getRefType(i8Ty); 789 mlir::Value offset = builder.createIntegerConstant( 790 loc, idxTy, sym.GetUltimate().offset() - aliasOffset); 791 auto ptr = builder.create<fir::CoordinateOp>(loc, i8Ptr, store, 792 mlir::ValueRange{offset}); 793 mlir::Value preAlloc = 794 castAliasToPointer(builder, loc, converter.genType(sym), ptr); 795 Fortran::lower::StatementContext stmtCtx; 796 mapSymbolAttributes(converter, var, symMap, stmtCtx, preAlloc); 797 // Default initialization is possible for equivalence members: see 798 // F2018 19.5.3.4. Note that if several equivalenced entities have 799 // default initialization, they must have the same type, and the standard 800 // allows the storage to be default initialized several times (this has 801 // no consequences other than wasting some execution time). For now, 802 // do not try optimizing this to single default initializations of 803 // the equivalenced storages. Keep lowering simple. 804 if (mustBeDefaultInitializedAtRuntime(var)) 805 defaultInitializeAtRuntime(converter, var, symMap); 806 } 807 808 //===--------------------------------------------------------------===// 809 // COMMON blocks instantiation 810 //===--------------------------------------------------------------===// 811 812 /// Does any member of the common block has an initializer ? 813 static bool 814 commonBlockHasInit(const Fortran::semantics::MutableSymbolVector &cmnBlkMems) { 815 for (const Fortran::semantics::MutableSymbolRef &mem : cmnBlkMems) { 816 if (const auto *memDet = 817 mem->detailsIf<Fortran::semantics::ObjectEntityDetails>()) 818 if (memDet->init()) 819 return true; 820 } 821 return false; 822 } 823 824 /// Build a tuple type for a common block based on the common block 825 /// members and the common block size. 826 /// This type is only needed to build common block initializers where 827 /// the initial value is the collection of the member initial values. 828 static mlir::TupleType getTypeOfCommonWithInit( 829 Fortran::lower::AbstractConverter &converter, 830 const Fortran::semantics::MutableSymbolVector &cmnBlkMems, 831 std::size_t commonSize) { 832 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 833 llvm::SmallVector<mlir::Type> members; 834 std::size_t counter = 0; 835 for (const Fortran::semantics::MutableSymbolRef &mem : cmnBlkMems) { 836 if (const auto *memDet = 837 mem->detailsIf<Fortran::semantics::ObjectEntityDetails>()) { 838 if (mem->offset() > counter) { 839 fir::SequenceType::Shape len = { 840 static_cast<fir::SequenceType::Extent>(mem->offset() - counter)}; 841 mlir::IntegerType byteTy = builder.getIntegerType(8); 842 auto memTy = fir::SequenceType::get(len, byteTy); 843 members.push_back(memTy); 844 counter = mem->offset(); 845 } 846 if (memDet->init()) { 847 mlir::Type memTy = converter.genType(*mem); 848 members.push_back(memTy); 849 counter = mem->offset() + mem->size(); 850 } 851 } 852 } 853 if (counter < commonSize) { 854 fir::SequenceType::Shape len = { 855 static_cast<fir::SequenceType::Extent>(commonSize - counter)}; 856 mlir::IntegerType byteTy = builder.getIntegerType(8); 857 auto memTy = fir::SequenceType::get(len, byteTy); 858 members.push_back(memTy); 859 } 860 return mlir::TupleType::get(builder.getContext(), members); 861 } 862 863 /// Common block members may have aliases. They are not in the common block 864 /// member list from the symbol. We need to know about these aliases if they 865 /// have initializer to generate the common initializer. 866 /// This function takes care of adding aliases with initializer to the member 867 /// list. 868 static Fortran::semantics::MutableSymbolVector 869 getCommonMembersWithInitAliases(const Fortran::semantics::Symbol &common) { 870 const auto &commonDetails = 871 common.get<Fortran::semantics::CommonBlockDetails>(); 872 auto members = commonDetails.objects(); 873 874 // The number and size of equivalence and common is expected to be small, so 875 // no effort is given to optimize this loop of complexity equivalenced 876 // common members * common members 877 for (const Fortran::semantics::EquivalenceSet &set : 878 common.owner().equivalenceSets()) 879 for (const Fortran::semantics::EquivalenceObject &obj : set) { 880 if (!obj.symbol.test(Fortran::semantics::Symbol::Flag::CompilerCreated)) { 881 if (const auto &details = 882 obj.symbol 883 .detailsIf<Fortran::semantics::ObjectEntityDetails>()) { 884 const Fortran::semantics::Symbol *com = 885 FindCommonBlockContaining(obj.symbol); 886 if (!details->init() || com != &common) 887 continue; 888 // This is an alias with an init that belongs to the list 889 if (std::find(members.begin(), members.end(), obj.symbol) == 890 members.end()) 891 members.emplace_back(obj.symbol); 892 } 893 } 894 } 895 return members; 896 } 897 898 /// Return the fir::GlobalOp that was created of COMMON block \p common. 899 /// It is an error if the fir::GlobalOp was not created before this is 900 /// called (it cannot be created on the flight because it is not known here 901 /// what mlir type the GlobalOp should have to satisfy all the 902 /// appearances in the program). 903 static fir::GlobalOp 904 getCommonBlockGlobal(Fortran::lower::AbstractConverter &converter, 905 const Fortran::semantics::Symbol &common) { 906 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 907 std::string commonName = Fortran::lower::mangle::mangleName(common); 908 fir::GlobalOp global = builder.getNamedGlobal(commonName); 909 // Common blocks are lowered before any subprograms to deal with common 910 // whose size may not be the same in every subprograms. 911 if (!global) 912 fir::emitFatalError(converter.genLocation(common.name()), 913 "COMMON block was not lowered before its usage"); 914 return global; 915 } 916 917 /// Create the fir::GlobalOp for COMMON block \p common. If \p common has an 918 /// initial value, it is not created yet. Instead, the common block list 919 /// members is returned to later create the initial value in 920 /// finalizeCommonBlockDefinition. 921 static std::optional<std::tuple< 922 fir::GlobalOp, Fortran::semantics::MutableSymbolVector, mlir::Location>> 923 declareCommonBlock(Fortran::lower::AbstractConverter &converter, 924 const Fortran::semantics::Symbol &common, 925 std::size_t commonSize) { 926 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 927 std::string commonName = Fortran::lower::mangle::mangleName(common); 928 fir::GlobalOp global = builder.getNamedGlobal(commonName); 929 if (global) 930 return std::nullopt; 931 Fortran::semantics::MutableSymbolVector cmnBlkMems = 932 getCommonMembersWithInitAliases(common); 933 mlir::Location loc = converter.genLocation(common.name()); 934 mlir::StringAttr linkage = builder.createCommonLinkage(); 935 if (!commonBlockHasInit(cmnBlkMems)) { 936 // A COMMON block sans initializers is initialized to zero. 937 // mlir::Vector types must have a strictly positive size, so at least 938 // temporarily, force a zero size COMMON block to have one byte. 939 const auto sz = 940 static_cast<fir::SequenceType::Extent>(commonSize > 0 ? commonSize : 1); 941 fir::SequenceType::Shape shape = {sz}; 942 mlir::IntegerType i8Ty = builder.getIntegerType(8); 943 auto commonTy = fir::SequenceType::get(shape, i8Ty); 944 auto vecTy = mlir::VectorType::get(sz, i8Ty); 945 mlir::Attribute zero = builder.getIntegerAttr(i8Ty, 0); 946 auto init = mlir::DenseElementsAttr::get(vecTy, llvm::makeArrayRef(zero)); 947 builder.createGlobal(loc, commonTy, commonName, linkage, init); 948 // No need to add any initial value later. 949 return std::nullopt; 950 } 951 // COMMON block with initializer (note that initialized blank common are 952 // accepted as an extension by semantics). Sort members by offset before 953 // generating the type and initializer. 954 std::sort(cmnBlkMems.begin(), cmnBlkMems.end(), 955 [](auto &s1, auto &s2) { return s1->offset() < s2->offset(); }); 956 mlir::TupleType commonTy = 957 getTypeOfCommonWithInit(converter, cmnBlkMems, commonSize); 958 // Create the global object, the initial value will be added later. 959 global = builder.createGlobal(loc, commonTy, commonName); 960 return std::make_tuple(global, std::move(cmnBlkMems), loc); 961 } 962 963 /// Add initial value to a COMMON block fir::GlobalOp \p global given the list 964 /// \p cmnBlkMems of the common block member symbols that contains symbols with 965 /// an initial value. 966 static void finalizeCommonBlockDefinition( 967 mlir::Location loc, Fortran::lower::AbstractConverter &converter, 968 fir::GlobalOp global, 969 const Fortran::semantics::MutableSymbolVector &cmnBlkMems) { 970 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 971 mlir::TupleType commonTy = global.getType().cast<mlir::TupleType>(); 972 auto initFunc = [&](fir::FirOpBuilder &builder) { 973 mlir::IndexType idxTy = builder.getIndexType(); 974 mlir::Value cb = builder.create<fir::UndefOp>(loc, commonTy); 975 unsigned tupIdx = 0; 976 std::size_t offset = 0; 977 LLVM_DEBUG(llvm::dbgs() << "block {\n"); 978 for (const Fortran::semantics::MutableSymbolRef &mem : cmnBlkMems) { 979 if (const auto *memDet = 980 mem->detailsIf<Fortran::semantics::ObjectEntityDetails>()) { 981 if (mem->offset() > offset) { 982 ++tupIdx; 983 offset = mem->offset(); 984 } 985 if (memDet->init()) { 986 LLVM_DEBUG(llvm::dbgs() 987 << "offset: " << mem->offset() << " is " << *mem << '\n'); 988 Fortran::lower::StatementContext stmtCtx; 989 auto initExpr = memDet->init().value(); 990 fir::ExtendedValue initVal = 991 Fortran::semantics::IsPointer(*mem) 992 ? Fortran::lower::genInitialDataTarget( 993 converter, loc, converter.genType(*mem), initExpr) 994 : genInitializerExprValue(converter, loc, initExpr, stmtCtx); 995 mlir::IntegerAttr offVal = builder.getIntegerAttr(idxTy, tupIdx); 996 mlir::Value castVal = builder.createConvert( 997 loc, commonTy.getType(tupIdx), fir::getBase(initVal)); 998 cb = builder.create<fir::InsertValueOp>(loc, commonTy, cb, castVal, 999 builder.getArrayAttr(offVal)); 1000 ++tupIdx; 1001 offset = mem->offset() + mem->size(); 1002 } 1003 } 1004 } 1005 LLVM_DEBUG(llvm::dbgs() << "}\n"); 1006 builder.create<fir::HasValueOp>(loc, cb); 1007 }; 1008 createGlobalInitialization(builder, global, initFunc); 1009 } 1010 1011 void Fortran::lower::defineCommonBlocks( 1012 Fortran::lower::AbstractConverter &converter, 1013 const Fortran::semantics::CommonBlockList &commonBlocks) { 1014 // Common blocks may depend on another common block address (if they contain 1015 // pointers with initial targets). To cover this case, create all common block 1016 // fir::Global before creating the initial values (if any). 1017 std::vector<std::tuple<fir::GlobalOp, Fortran::semantics::MutableSymbolVector, 1018 mlir::Location>> 1019 delayedInitializations; 1020 for (const auto &[common, size] : commonBlocks) 1021 if (auto delayedInit = declareCommonBlock(converter, common, size)) 1022 delayedInitializations.emplace_back(std::move(*delayedInit)); 1023 for (auto &[global, cmnBlkMems, loc] : delayedInitializations) 1024 finalizeCommonBlockDefinition(loc, converter, global, cmnBlkMems); 1025 } 1026 1027 /// The COMMON block is a global structure. `var` will be at some offset 1028 /// within the COMMON block. Adds the address of `var` (COMMON + offset) to 1029 /// the symbol map. 1030 static void instantiateCommon(Fortran::lower::AbstractConverter &converter, 1031 const Fortran::semantics::Symbol &common, 1032 const Fortran::lower::pft::Variable &var, 1033 Fortran::lower::SymMap &symMap) { 1034 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 1035 const Fortran::semantics::Symbol &varSym = var.getSymbol(); 1036 mlir::Location loc = converter.genLocation(varSym.name()); 1037 1038 mlir::Value commonAddr; 1039 if (Fortran::lower::SymbolBox symBox = symMap.lookupSymbol(common)) 1040 commonAddr = symBox.getAddr(); 1041 if (!commonAddr) { 1042 // introduce a local AddrOf and add it to the map 1043 fir::GlobalOp global = getCommonBlockGlobal(converter, common); 1044 commonAddr = builder.create<fir::AddrOfOp>(loc, global.resultType(), 1045 global.getSymbol()); 1046 1047 symMap.addSymbol(common, commonAddr); 1048 } 1049 std::size_t byteOffset = varSym.GetUltimate().offset(); 1050 mlir::IntegerType i8Ty = builder.getIntegerType(8); 1051 mlir::Type i8Ptr = builder.getRefType(i8Ty); 1052 mlir::Type seqTy = builder.getRefType(builder.getVarLenSeqTy(i8Ty)); 1053 mlir::Value base = builder.createConvert(loc, seqTy, commonAddr); 1054 mlir::Value offs = 1055 builder.createIntegerConstant(loc, builder.getIndexType(), byteOffset); 1056 auto varAddr = builder.create<fir::CoordinateOp>(loc, i8Ptr, base, 1057 mlir::ValueRange{offs}); 1058 mlir::Type symType = converter.genType(var.getSymbol()); 1059 mlir::Value local; 1060 if (Fortran::semantics::FindEquivalenceSet(var.getSymbol()) != nullptr) 1061 local = castAliasToPointer(builder, loc, symType, varAddr); 1062 else 1063 local = builder.createConvert(loc, builder.getRefType(symType), varAddr); 1064 Fortran::lower::StatementContext stmtCtx; 1065 mapSymbolAttributes(converter, var, symMap, stmtCtx, local); 1066 } 1067 1068 //===--------------------------------------------------------------===// 1069 // Lower Variables specification expressions and attributes 1070 //===--------------------------------------------------------------===// 1071 1072 /// Helper to decide if a dummy argument must be tracked in an BoxValue. 1073 static bool lowerToBoxValue(const Fortran::semantics::Symbol &sym, 1074 mlir::Value dummyArg) { 1075 // Only dummy arguments coming as fir.box can be tracked in an BoxValue. 1076 if (!dummyArg || !dummyArg.getType().isa<fir::BoxType>()) 1077 return false; 1078 // Non contiguous arrays must be tracked in an BoxValue. 1079 if (sym.Rank() > 0 && !sym.attrs().test(Fortran::semantics::Attr::CONTIGUOUS)) 1080 return true; 1081 // Assumed rank and optional fir.box cannot yet be read while lowering the 1082 // specifications. 1083 if (Fortran::evaluate::IsAssumedRank(sym) || 1084 Fortran::semantics::IsOptional(sym)) 1085 return true; 1086 // Polymorphic entity should be tracked through a fir.box that has the 1087 // dynamic type info. 1088 if (const Fortran::semantics::DeclTypeSpec *type = sym.GetType()) 1089 if (type->IsPolymorphic()) 1090 return true; 1091 return false; 1092 } 1093 1094 /// Compute extent from lower and upper bound. 1095 static mlir::Value computeExtent(fir::FirOpBuilder &builder, mlir::Location loc, 1096 mlir::Value lb, mlir::Value ub) { 1097 mlir::IndexType idxTy = builder.getIndexType(); 1098 // Let the folder deal with the common `ub - <const> + 1` case. 1099 auto diff = builder.create<mlir::arith::SubIOp>(loc, idxTy, ub, lb); 1100 mlir::Value one = builder.createIntegerConstant(loc, idxTy, 1); 1101 auto rawExtent = builder.create<mlir::arith::AddIOp>(loc, idxTy, diff, one); 1102 return fir::factory::genMaxWithZero(builder, loc, rawExtent); 1103 } 1104 1105 /// Lower explicit lower bounds into \p result. Does nothing if this is not an 1106 /// array, or if the lower bounds are deferred, or all implicit or one. 1107 static void lowerExplicitLowerBounds( 1108 Fortran::lower::AbstractConverter &converter, mlir::Location loc, 1109 const Fortran::lower::BoxAnalyzer &box, 1110 llvm::SmallVectorImpl<mlir::Value> &result, Fortran::lower::SymMap &symMap, 1111 Fortran::lower::StatementContext &stmtCtx) { 1112 if (!box.isArray() || box.lboundIsAllOnes()) 1113 return; 1114 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 1115 mlir::IndexType idxTy = builder.getIndexType(); 1116 if (box.isStaticArray()) { 1117 for (int64_t lb : box.staticLBound()) 1118 result.emplace_back(builder.createIntegerConstant(loc, idxTy, lb)); 1119 return; 1120 } 1121 for (const Fortran::semantics::ShapeSpec *spec : box.dynamicBound()) { 1122 if (auto low = spec->lbound().GetExplicit()) { 1123 auto expr = Fortran::lower::SomeExpr{*low}; 1124 mlir::Value lb = builder.createConvert( 1125 loc, idxTy, genScalarValue(converter, loc, expr, symMap, stmtCtx)); 1126 result.emplace_back(lb); 1127 } 1128 } 1129 assert(result.empty() || result.size() == box.dynamicBound().size()); 1130 } 1131 1132 /// Lower explicit extents into \p result if this is an explicit-shape or 1133 /// assumed-size array. Does nothing if this is not an explicit-shape or 1134 /// assumed-size array. 1135 static void 1136 lowerExplicitExtents(Fortran::lower::AbstractConverter &converter, 1137 mlir::Location loc, const Fortran::lower::BoxAnalyzer &box, 1138 llvm::SmallVectorImpl<mlir::Value> &lowerBounds, 1139 llvm::SmallVectorImpl<mlir::Value> &result, 1140 Fortran::lower::SymMap &symMap, 1141 Fortran::lower::StatementContext &stmtCtx) { 1142 if (!box.isArray()) 1143 return; 1144 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 1145 mlir::IndexType idxTy = builder.getIndexType(); 1146 if (box.isStaticArray()) { 1147 for (int64_t extent : box.staticShape()) 1148 result.emplace_back(builder.createIntegerConstant(loc, idxTy, extent)); 1149 return; 1150 } 1151 for (const auto &spec : llvm::enumerate(box.dynamicBound())) { 1152 if (auto up = spec.value()->ubound().GetExplicit()) { 1153 auto expr = Fortran::lower::SomeExpr{*up}; 1154 mlir::Value ub = builder.createConvert( 1155 loc, idxTy, genScalarValue(converter, loc, expr, symMap, stmtCtx)); 1156 if (lowerBounds.empty()) 1157 result.emplace_back(fir::factory::genMaxWithZero(builder, loc, ub)); 1158 else 1159 result.emplace_back( 1160 computeExtent(builder, loc, lowerBounds[spec.index()], ub)); 1161 } else if (spec.value()->ubound().isStar()) { 1162 // Assumed extent is undefined. Must be provided by user's code. 1163 result.emplace_back(builder.create<fir::UndefOp>(loc, idxTy)); 1164 } 1165 } 1166 assert(result.empty() || result.size() == box.dynamicBound().size()); 1167 } 1168 1169 /// Lower explicit character length if any. Return empty mlir::Value if no 1170 /// explicit length. 1171 static mlir::Value 1172 lowerExplicitCharLen(Fortran::lower::AbstractConverter &converter, 1173 mlir::Location loc, const Fortran::lower::BoxAnalyzer &box, 1174 Fortran::lower::SymMap &symMap, 1175 Fortran::lower::StatementContext &stmtCtx) { 1176 if (!box.isChar()) 1177 return mlir::Value{}; 1178 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 1179 mlir::Type lenTy = builder.getCharacterLengthType(); 1180 if (llvm::Optional<int64_t> len = box.getCharLenConst()) 1181 return builder.createIntegerConstant(loc, lenTy, *len); 1182 if (llvm::Optional<Fortran::lower::SomeExpr> lenExpr = box.getCharLenExpr()) 1183 // If the length expression is negative, the length is zero. See F2018 1184 // 7.4.4.2 point 5. 1185 return fir::factory::genMaxWithZero( 1186 builder, loc, 1187 genScalarValue(converter, loc, *lenExpr, symMap, stmtCtx)); 1188 return mlir::Value{}; 1189 } 1190 1191 /// Treat negative values as undefined. Assumed size arrays will return -1 from 1192 /// the front end for example. Using negative values can produce hard to find 1193 /// bugs much further along in the compilation. 1194 static mlir::Value genExtentValue(fir::FirOpBuilder &builder, 1195 mlir::Location loc, mlir::Type idxTy, 1196 long frontEndExtent) { 1197 if (frontEndExtent >= 0) 1198 return builder.createIntegerConstant(loc, idxTy, frontEndExtent); 1199 return builder.create<fir::UndefOp>(loc, idxTy); 1200 } 1201 1202 /// Lower specification expressions and attributes of variable \p var and 1203 /// add it to the symbol map. For a global or an alias, the address must be 1204 /// pre-computed and provided in \p preAlloc. A dummy argument for the current 1205 /// entry point has already been mapped to an mlir block argument in 1206 /// mapDummiesAndResults. Its mapping may be updated here. 1207 void Fortran::lower::mapSymbolAttributes( 1208 AbstractConverter &converter, const Fortran::lower::pft::Variable &var, 1209 Fortran::lower::SymMap &symMap, Fortran::lower::StatementContext &stmtCtx, 1210 mlir::Value preAlloc) { 1211 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 1212 const Fortran::semantics::Symbol &sym = var.getSymbol(); 1213 const mlir::Location loc = converter.genLocation(sym.name()); 1214 mlir::IndexType idxTy = builder.getIndexType(); 1215 const bool isDeclaredDummy = Fortran::semantics::IsDummy(sym); 1216 // An active dummy from the current entry point. 1217 const bool isDummy = isDeclaredDummy && symMap.lookupSymbol(sym).getAddr(); 1218 // An unused dummy from another entry point. 1219 const bool isUnusedEntryDummy = isDeclaredDummy && !isDummy; 1220 const bool isResult = Fortran::semantics::IsFunctionResult(sym); 1221 const bool replace = isDummy || isResult; 1222 fir::factory::CharacterExprHelper charHelp{builder, loc}; 1223 1224 if (Fortran::semantics::IsProcedure(sym)) { 1225 if (isUnusedEntryDummy) { 1226 // Additional discussion below. 1227 mlir::Type dummyProcType = 1228 Fortran::lower::getDummyProcedureType(sym, converter); 1229 mlir::Value undefOp = builder.create<fir::UndefOp>(loc, dummyProcType); 1230 symMap.addSymbol(sym, undefOp); 1231 } 1232 if (Fortran::semantics::IsPointer(sym)) 1233 TODO(loc, "procedure pointers"); 1234 return; 1235 } 1236 1237 Fortran::lower::BoxAnalyzer ba; 1238 ba.analyze(sym); 1239 1240 // First deal with pointers and allocatables, because their handling here 1241 // is the same regardless of their rank. 1242 if (Fortran::semantics::IsAllocatableOrPointer(sym)) { 1243 // Get address of fir.box describing the entity. 1244 // global 1245 mlir::Value boxAlloc = preAlloc; 1246 // dummy or passed result 1247 if (!boxAlloc) 1248 if (Fortran::lower::SymbolBox symbox = symMap.lookupSymbol(sym)) 1249 boxAlloc = symbox.getAddr(); 1250 // local 1251 if (!boxAlloc) 1252 boxAlloc = createNewLocal(converter, loc, var, preAlloc); 1253 // Lower non deferred parameters. 1254 llvm::SmallVector<mlir::Value> nonDeferredLenParams; 1255 if (ba.isChar()) { 1256 if (mlir::Value len = 1257 lowerExplicitCharLen(converter, loc, ba, symMap, stmtCtx)) 1258 nonDeferredLenParams.push_back(len); 1259 else if (Fortran::semantics::IsAssumedLengthCharacter(sym)) 1260 TODO(loc, "assumed length character allocatable"); 1261 } else if (const Fortran::semantics::DeclTypeSpec *declTy = sym.GetType()) { 1262 if (const Fortran::semantics::DerivedTypeSpec *derived = 1263 declTy->AsDerived()) 1264 if (Fortran::semantics::CountLenParameters(*derived) != 0) 1265 TODO(loc, 1266 "derived type allocatable or pointer with length parameters"); 1267 } 1268 fir::MutableBoxValue box = Fortran::lower::createMutableBox( 1269 converter, loc, var, boxAlloc, nonDeferredLenParams); 1270 symMap.addAllocatableOrPointer(var.getSymbol(), box, replace); 1271 return; 1272 } 1273 1274 if (isDummy) { 1275 mlir::Value dummyArg = symMap.lookupSymbol(sym).getAddr(); 1276 if (lowerToBoxValue(sym, dummyArg)) { 1277 llvm::SmallVector<mlir::Value> lbounds; 1278 llvm::SmallVector<mlir::Value> explicitExtents; 1279 llvm::SmallVector<mlir::Value> explicitParams; 1280 // Lower lower bounds, explicit type parameters and explicit 1281 // extents if any. 1282 if (ba.isChar()) 1283 if (mlir::Value len = 1284 lowerExplicitCharLen(converter, loc, ba, symMap, stmtCtx)) 1285 explicitParams.push_back(len); 1286 // TODO: derived type length parameters. 1287 lowerExplicitLowerBounds(converter, loc, ba, lbounds, symMap, stmtCtx); 1288 lowerExplicitExtents(converter, loc, ba, lbounds, explicitExtents, symMap, 1289 stmtCtx); 1290 symMap.addBoxSymbol(sym, dummyArg, lbounds, explicitParams, 1291 explicitExtents, replace); 1292 return; 1293 } 1294 } 1295 1296 // A dummy from another entry point that is not declared in the current 1297 // entry point requires a skeleton definition. Most such "unused" dummies 1298 // will not survive into final generated code, but some will. It is illegal 1299 // to reference one at run time if it does. Such a dummy is mapped to a 1300 // value in one of three ways: 1301 // 1302 // - Generate a fir::UndefOp value. This is lightweight, easy to clean up, 1303 // and often valid, but it may fail for a dummy with dynamic bounds, 1304 // or a dummy used to define another dummy. Information to distinguish 1305 // valid cases is not generally available here, with the exception of 1306 // dummy procedures. See the first function exit above. 1307 // 1308 // - Allocate an uninitialized stack slot. This is an intermediate-weight 1309 // solution that is harder to clean up. It is often valid, but may fail 1310 // for an object with dynamic bounds. This option is "automatically" 1311 // used by default for cases that do not use one of the other options. 1312 // 1313 // - Allocate a heap box/descriptor, initialized to zero. This always 1314 // works, but is more heavyweight and harder to clean up. It is used 1315 // for dynamic objects via calls to genUnusedEntryPointBox. 1316 1317 auto genUnusedEntryPointBox = [&]() { 1318 if (isUnusedEntryDummy) { 1319 assert(!Fortran::semantics::IsAllocatableOrPointer(sym) && 1320 "handled above"); 1321 // The box is read right away because lowering code does not expect 1322 // a non pointer/allocatable symbol to be mapped to a MutableBox. 1323 symMap.addSymbol(sym, fir::factory::genMutableBoxRead( 1324 builder, loc, 1325 fir::factory::createTempMutableBox( 1326 builder, loc, converter.genType(var)))); 1327 return true; 1328 } 1329 return false; 1330 }; 1331 1332 // Helper to generate scalars for the symbol properties. 1333 auto genValue = [&](const Fortran::lower::SomeExpr &expr) { 1334 return genScalarValue(converter, loc, expr, symMap, stmtCtx); 1335 }; 1336 1337 // For symbols reaching this point, all properties are constant and can be 1338 // read/computed already into ssa values. 1339 1340 // The origin must be \vec{1}. 1341 auto populateShape = [&](auto &shapes, const auto &bounds, mlir::Value box) { 1342 for (auto iter : llvm::enumerate(bounds)) { 1343 auto *spec = iter.value(); 1344 assert(spec->lbound().GetExplicit() && 1345 "lbound must be explicit with constant value 1"); 1346 if (auto high = spec->ubound().GetExplicit()) { 1347 Fortran::lower::SomeExpr highEx{*high}; 1348 mlir::Value ub = genValue(highEx); 1349 ub = builder.createConvert(loc, idxTy, ub); 1350 shapes.emplace_back(fir::factory::genMaxWithZero(builder, loc, ub)); 1351 } else if (spec->ubound().isColon()) { 1352 assert(box && "assumed bounds require a descriptor"); 1353 mlir::Value dim = 1354 builder.createIntegerConstant(loc, idxTy, iter.index()); 1355 auto dimInfo = 1356 builder.create<fir::BoxDimsOp>(loc, idxTy, idxTy, idxTy, box, dim); 1357 shapes.emplace_back(dimInfo.getResult(1)); 1358 } else if (spec->ubound().isStar()) { 1359 shapes.emplace_back(builder.create<fir::UndefOp>(loc, idxTy)); 1360 } else { 1361 llvm::report_fatal_error("unknown bound category"); 1362 } 1363 } 1364 }; 1365 1366 // The origin is not \vec{1}. 1367 auto populateLBoundsExtents = [&](auto &lbounds, auto &extents, 1368 const auto &bounds, mlir::Value box) { 1369 for (auto iter : llvm::enumerate(bounds)) { 1370 auto *spec = iter.value(); 1371 fir::BoxDimsOp dimInfo; 1372 mlir::Value ub, lb; 1373 if (spec->lbound().isColon() || spec->ubound().isColon()) { 1374 // This is an assumed shape because allocatables and pointers extents 1375 // are not constant in the scope and are not read here. 1376 assert(box && "deferred bounds require a descriptor"); 1377 mlir::Value dim = 1378 builder.createIntegerConstant(loc, idxTy, iter.index()); 1379 dimInfo = 1380 builder.create<fir::BoxDimsOp>(loc, idxTy, idxTy, idxTy, box, dim); 1381 extents.emplace_back(dimInfo.getResult(1)); 1382 if (auto low = spec->lbound().GetExplicit()) { 1383 auto expr = Fortran::lower::SomeExpr{*low}; 1384 mlir::Value lb = builder.createConvert(loc, idxTy, genValue(expr)); 1385 lbounds.emplace_back(lb); 1386 } else { 1387 // Implicit lower bound is 1 (Fortran 2018 section 8.5.8.3 point 3.) 1388 lbounds.emplace_back(builder.createIntegerConstant(loc, idxTy, 1)); 1389 } 1390 } else { 1391 if (auto low = spec->lbound().GetExplicit()) { 1392 auto expr = Fortran::lower::SomeExpr{*low}; 1393 lb = builder.createConvert(loc, idxTy, genValue(expr)); 1394 } else { 1395 TODO(loc, "assumed rank lowering"); 1396 } 1397 lbounds.emplace_back(lb); 1398 1399 if (auto high = spec->ubound().GetExplicit()) { 1400 auto expr = Fortran::lower::SomeExpr{*high}; 1401 ub = builder.createConvert(loc, idxTy, genValue(expr)); 1402 extents.emplace_back(computeExtent(builder, loc, lb, ub)); 1403 } else { 1404 // An assumed size array. The extent is not computed. 1405 assert(spec->ubound().isStar() && "expected assumed size"); 1406 extents.emplace_back(builder.create<fir::UndefOp>(loc, idxTy)); 1407 } 1408 } 1409 } 1410 }; 1411 1412 // Lower length expression for non deferred and non dummy assumed length 1413 // characters. 1414 auto genExplicitCharLen = 1415 [&](llvm::Optional<Fortran::lower::SomeExpr> charLen) -> mlir::Value { 1416 if (!charLen) 1417 fir::emitFatalError(loc, "expected explicit character length"); 1418 mlir::Value rawLen = genValue(*charLen); 1419 // If the length expression is negative, the length is zero. See 1420 // F2018 7.4.4.2 point 5. 1421 return fir::factory::genMaxWithZero(builder, loc, rawLen); 1422 }; 1423 1424 ba.match( 1425 //===--------------------------------------------------------------===// 1426 // Trivial case. 1427 //===--------------------------------------------------------------===// 1428 [&](const Fortran::lower::details::ScalarSym &) { 1429 if (isDummy) { 1430 // This is an argument. 1431 if (!symMap.lookupSymbol(sym)) 1432 mlir::emitError(loc, "symbol \"") 1433 << toStringRef(sym.name()) << "\" must already be in map"; 1434 return; 1435 } else if (isResult) { 1436 // Some Fortran results may be passed by argument (e.g. derived 1437 // types) 1438 if (symMap.lookupSymbol(sym)) 1439 return; 1440 } 1441 // Otherwise, it's a local variable or function result. 1442 mlir::Value local = createNewLocal(converter, loc, var, preAlloc); 1443 symMap.addSymbol(sym, local); 1444 }, 1445 1446 //===--------------------------------------------------------------===// 1447 // The non-trivial cases are when we have an argument or local that has 1448 // a repetition value. Arguments might be passed as simple pointers and 1449 // need to be cast to a multi-dimensional array with constant bounds 1450 // (possibly with a missing column), bounds computed in the callee 1451 // (here), or with bounds from the caller (boxed somewhere else). Locals 1452 // have the same properties except they are never boxed arguments from 1453 // the caller and never having a missing column size. 1454 //===--------------------------------------------------------------===// 1455 1456 [&](const Fortran::lower::details::ScalarStaticChar &x) { 1457 // type is a CHARACTER, determine the LEN value 1458 auto charLen = x.charLen(); 1459 if (replace) { 1460 Fortran::lower::SymbolBox symBox = symMap.lookupSymbol(sym); 1461 std::pair<mlir::Value, mlir::Value> unboxchar = 1462 charHelp.createUnboxChar(symBox.getAddr()); 1463 mlir::Value boxAddr = unboxchar.first; 1464 // Set/override LEN with a constant 1465 mlir::Value len = builder.createIntegerConstant(loc, idxTy, charLen); 1466 symMap.addCharSymbol(sym, boxAddr, len, true); 1467 return; 1468 } 1469 mlir::Value len = builder.createIntegerConstant(loc, idxTy, charLen); 1470 if (preAlloc) { 1471 symMap.addCharSymbol(sym, preAlloc, len); 1472 return; 1473 } 1474 mlir::Value local = createNewLocal(converter, loc, var, preAlloc); 1475 symMap.addCharSymbol(sym, local, len); 1476 }, 1477 1478 //===--------------------------------------------------------------===// 1479 1480 [&](const Fortran::lower::details::ScalarDynamicChar &x) { 1481 if (genUnusedEntryPointBox()) 1482 return; 1483 // type is a CHARACTER, determine the LEN value 1484 auto charLen = x.charLen(); 1485 if (replace) { 1486 Fortran::lower::SymbolBox symBox = symMap.lookupSymbol(sym); 1487 mlir::Value boxAddr = symBox.getAddr(); 1488 mlir::Value len; 1489 mlir::Type addrTy = boxAddr.getType(); 1490 if (addrTy.isa<fir::BoxCharType>() || addrTy.isa<fir::BoxType>()) 1491 std::tie(boxAddr, len) = charHelp.createUnboxChar(symBox.getAddr()); 1492 // Override LEN with an expression 1493 if (charLen) 1494 len = genExplicitCharLen(charLen); 1495 symMap.addCharSymbol(sym, boxAddr, len, true); 1496 return; 1497 } 1498 // local CHARACTER variable 1499 mlir::Value len = genExplicitCharLen(charLen); 1500 if (preAlloc) { 1501 symMap.addCharSymbol(sym, preAlloc, len); 1502 return; 1503 } 1504 llvm::SmallVector<mlir::Value> lengths = {len}; 1505 mlir::Value local = 1506 createNewLocal(converter, loc, var, preAlloc, llvm::None, lengths); 1507 symMap.addCharSymbol(sym, local, len); 1508 }, 1509 1510 //===--------------------------------------------------------------===// 1511 1512 [&](const Fortran::lower::details::StaticArray &x) { 1513 // object shape is constant, not a character 1514 mlir::Type castTy = builder.getRefType(converter.genType(var)); 1515 mlir::Value addr = symMap.lookupSymbol(sym).getAddr(); 1516 if (addr) 1517 addr = builder.createConvert(loc, castTy, addr); 1518 if (x.lboundAllOnes()) { 1519 // if lower bounds are all ones, build simple shaped object 1520 llvm::SmallVector<mlir::Value> shape; 1521 for (int64_t i : x.shapes) 1522 shape.push_back(genExtentValue(builder, loc, idxTy, i)); 1523 mlir::Value local = 1524 isDummy ? addr : createNewLocal(converter, loc, var, preAlloc); 1525 symMap.addSymbolWithShape(sym, local, shape, isDummy); 1526 return; 1527 } 1528 // If object is an array process the lower bound and extent values by 1529 // constructing constants and populating the lbounds and extents. 1530 llvm::SmallVector<mlir::Value> extents; 1531 llvm::SmallVector<mlir::Value> lbounds; 1532 for (auto [fst, snd] : llvm::zip(x.lbounds, x.shapes)) { 1533 lbounds.emplace_back(builder.createIntegerConstant(loc, idxTy, fst)); 1534 extents.emplace_back(genExtentValue(builder, loc, idxTy, snd)); 1535 } 1536 mlir::Value local = 1537 isDummy ? addr 1538 : createNewLocal(converter, loc, var, preAlloc, extents); 1539 assert(isDummy || Fortran::lower::isExplicitShape(sym)); 1540 symMap.addSymbolWithBounds(sym, local, extents, lbounds, isDummy); 1541 }, 1542 1543 //===--------------------------------------------------------------===// 1544 1545 [&](const Fortran::lower::details::DynamicArray &x) { 1546 if (genUnusedEntryPointBox()) 1547 return; 1548 // cast to the known constant parts from the declaration 1549 mlir::Type varType = converter.genType(var); 1550 mlir::Value addr = symMap.lookupSymbol(sym).getAddr(); 1551 mlir::Value argBox; 1552 mlir::Type castTy = builder.getRefType(varType); 1553 if (addr) { 1554 if (auto boxTy = addr.getType().dyn_cast<fir::BoxType>()) { 1555 argBox = addr; 1556 mlir::Type refTy = builder.getRefType(boxTy.getEleTy()); 1557 addr = builder.create<fir::BoxAddrOp>(loc, refTy, argBox); 1558 } 1559 addr = builder.createConvert(loc, castTy, addr); 1560 } 1561 if (x.lboundAllOnes()) { 1562 // if lower bounds are all ones, build simple shaped object 1563 llvm::SmallVector<mlir::Value> shapes; 1564 populateShape(shapes, x.bounds, argBox); 1565 if (isDummy) { 1566 symMap.addSymbolWithShape(sym, addr, shapes, true); 1567 return; 1568 } 1569 // local array with computed bounds 1570 assert(Fortran::lower::isExplicitShape(sym) || 1571 Fortran::semantics::IsAllocatableOrPointer(sym)); 1572 mlir::Value local = 1573 createNewLocal(converter, loc, var, preAlloc, shapes); 1574 symMap.addSymbolWithShape(sym, local, shapes); 1575 return; 1576 } 1577 // if object is an array process the lower bound and extent values 1578 llvm::SmallVector<mlir::Value> extents; 1579 llvm::SmallVector<mlir::Value> lbounds; 1580 populateLBoundsExtents(lbounds, extents, x.bounds, argBox); 1581 if (isDummy) { 1582 symMap.addSymbolWithBounds(sym, addr, extents, lbounds, true); 1583 return; 1584 } 1585 // local array with computed bounds 1586 assert(Fortran::lower::isExplicitShape(sym)); 1587 mlir::Value local = 1588 createNewLocal(converter, loc, var, preAlloc, extents); 1589 symMap.addSymbolWithBounds(sym, local, extents, lbounds); 1590 }, 1591 1592 //===--------------------------------------------------------------===// 1593 1594 [&](const Fortran::lower::details::StaticArrayStaticChar &x) { 1595 // if element type is a CHARACTER, determine the LEN value 1596 auto charLen = x.charLen(); 1597 mlir::Value addr; 1598 mlir::Value len; 1599 if (isDummy) { 1600 Fortran::lower::SymbolBox symBox = symMap.lookupSymbol(sym); 1601 std::pair<mlir::Value, mlir::Value> unboxchar = 1602 charHelp.createUnboxChar(symBox.getAddr()); 1603 addr = unboxchar.first; 1604 // Set/override LEN with a constant 1605 len = builder.createIntegerConstant(loc, idxTy, charLen); 1606 } else { 1607 // local CHARACTER variable 1608 len = builder.createIntegerConstant(loc, idxTy, charLen); 1609 } 1610 1611 // object shape is constant 1612 mlir::Type castTy = builder.getRefType(converter.genType(var)); 1613 if (addr) 1614 addr = builder.createConvert(loc, castTy, addr); 1615 1616 if (x.lboundAllOnes()) { 1617 // if lower bounds are all ones, build simple shaped object 1618 llvm::SmallVector<mlir::Value> shape; 1619 for (int64_t i : x.shapes) 1620 shape.push_back(genExtentValue(builder, loc, idxTy, i)); 1621 mlir::Value local = 1622 isDummy ? addr : createNewLocal(converter, loc, var, preAlloc); 1623 symMap.addCharSymbolWithShape(sym, local, len, shape, isDummy); 1624 return; 1625 } 1626 1627 // if object is an array process the lower bound and extent values 1628 llvm::SmallVector<mlir::Value> extents; 1629 llvm::SmallVector<mlir::Value> lbounds; 1630 // construct constants and populate `bounds` 1631 for (auto [fst, snd] : llvm::zip(x.lbounds, x.shapes)) { 1632 lbounds.emplace_back(builder.createIntegerConstant(loc, idxTy, fst)); 1633 extents.emplace_back(genExtentValue(builder, loc, idxTy, snd)); 1634 } 1635 1636 if (isDummy) { 1637 symMap.addCharSymbolWithBounds(sym, addr, len, extents, lbounds, 1638 true); 1639 return; 1640 } 1641 // local CHARACTER array with computed bounds 1642 assert(Fortran::lower::isExplicitShape(sym)); 1643 mlir::Value local = 1644 createNewLocal(converter, loc, var, preAlloc, extents); 1645 symMap.addCharSymbolWithBounds(sym, local, len, extents, lbounds); 1646 }, 1647 1648 //===--------------------------------------------------------------===// 1649 1650 [&](const Fortran::lower::details::StaticArrayDynamicChar &x) { 1651 if (genUnusedEntryPointBox()) 1652 return; 1653 mlir::Value addr; 1654 mlir::Value len; 1655 [[maybe_unused]] bool mustBeDummy = false; 1656 auto charLen = x.charLen(); 1657 // if element type is a CHARACTER, determine the LEN value 1658 if (isDummy) { 1659 Fortran::lower::SymbolBox symBox = symMap.lookupSymbol(sym); 1660 std::pair<mlir::Value, mlir::Value> unboxchar = 1661 charHelp.createUnboxChar(symBox.getAddr()); 1662 addr = unboxchar.first; 1663 if (charLen) { 1664 // Set/override LEN with an expression 1665 len = genExplicitCharLen(charLen); 1666 } else { 1667 // LEN is from the boxchar 1668 len = unboxchar.second; 1669 mustBeDummy = true; 1670 } 1671 } else { 1672 // local CHARACTER variable 1673 len = genExplicitCharLen(charLen); 1674 } 1675 llvm::SmallVector<mlir::Value> lengths = {len}; 1676 1677 // cast to the known constant parts from the declaration 1678 mlir::Type castTy = builder.getRefType(converter.genType(var)); 1679 if (addr) 1680 addr = builder.createConvert(loc, castTy, addr); 1681 1682 if (x.lboundAllOnes()) { 1683 // if lower bounds are all ones, build simple shaped object 1684 llvm::SmallVector<mlir::Value> shape; 1685 for (int64_t i : x.shapes) 1686 shape.push_back(genExtentValue(builder, loc, idxTy, i)); 1687 if (isDummy) { 1688 symMap.addCharSymbolWithShape(sym, addr, len, shape, true); 1689 return; 1690 } 1691 // local CHARACTER array with constant size 1692 mlir::Value local = createNewLocal(converter, loc, var, preAlloc, 1693 llvm::None, lengths); 1694 symMap.addCharSymbolWithShape(sym, local, len, shape); 1695 return; 1696 } 1697 1698 // if object is an array process the lower bound and extent values 1699 llvm::SmallVector<mlir::Value> extents; 1700 llvm::SmallVector<mlir::Value> lbounds; 1701 1702 // construct constants and populate `bounds` 1703 for (auto [fst, snd] : llvm::zip(x.lbounds, x.shapes)) { 1704 lbounds.emplace_back(builder.createIntegerConstant(loc, idxTy, fst)); 1705 extents.emplace_back(genExtentValue(builder, loc, idxTy, snd)); 1706 } 1707 if (isDummy) { 1708 symMap.addCharSymbolWithBounds(sym, addr, len, extents, lbounds, 1709 true); 1710 return; 1711 } 1712 // local CHARACTER array with computed bounds 1713 assert((!mustBeDummy) && (Fortran::lower::isExplicitShape(sym))); 1714 mlir::Value local = 1715 createNewLocal(converter, loc, var, preAlloc, llvm::None, lengths); 1716 symMap.addCharSymbolWithBounds(sym, local, len, extents, lbounds); 1717 }, 1718 1719 //===--------------------------------------------------------------===// 1720 1721 [&](const Fortran::lower::details::DynamicArrayStaticChar &x) { 1722 if (genUnusedEntryPointBox()) 1723 return; 1724 mlir::Value addr; 1725 mlir::Value len; 1726 mlir::Value argBox; 1727 auto charLen = x.charLen(); 1728 // if element type is a CHARACTER, determine the LEN value 1729 if (isDummy) { 1730 mlir::Value actualArg = symMap.lookupSymbol(sym).getAddr(); 1731 if (auto boxTy = actualArg.getType().dyn_cast<fir::BoxType>()) { 1732 argBox = actualArg; 1733 mlir::Type refTy = builder.getRefType(boxTy.getEleTy()); 1734 addr = builder.create<fir::BoxAddrOp>(loc, refTy, argBox); 1735 } else { 1736 addr = charHelp.createUnboxChar(actualArg).first; 1737 } 1738 // Set/override LEN with a constant 1739 len = builder.createIntegerConstant(loc, idxTy, charLen); 1740 } else { 1741 // local CHARACTER variable 1742 len = builder.createIntegerConstant(loc, idxTy, charLen); 1743 } 1744 1745 // cast to the known constant parts from the declaration 1746 mlir::Type castTy = builder.getRefType(converter.genType(var)); 1747 if (addr) 1748 addr = builder.createConvert(loc, castTy, addr); 1749 if (x.lboundAllOnes()) { 1750 // if lower bounds are all ones, build simple shaped object 1751 llvm::SmallVector<mlir::Value> shape; 1752 populateShape(shape, x.bounds, argBox); 1753 if (isDummy) { 1754 symMap.addCharSymbolWithShape(sym, addr, len, shape, true); 1755 return; 1756 } 1757 // local CHARACTER array 1758 mlir::Value local = 1759 createNewLocal(converter, loc, var, preAlloc, shape); 1760 symMap.addCharSymbolWithShape(sym, local, len, shape); 1761 return; 1762 } 1763 // if object is an array process the lower bound and extent values 1764 llvm::SmallVector<mlir::Value> extents; 1765 llvm::SmallVector<mlir::Value> lbounds; 1766 populateLBoundsExtents(lbounds, extents, x.bounds, argBox); 1767 if (isDummy) { 1768 symMap.addCharSymbolWithBounds(sym, addr, len, extents, lbounds, 1769 true); 1770 return; 1771 } 1772 // local CHARACTER array with computed bounds 1773 assert(Fortran::lower::isExplicitShape(sym)); 1774 mlir::Value local = 1775 createNewLocal(converter, loc, var, preAlloc, extents); 1776 symMap.addCharSymbolWithBounds(sym, local, len, extents, lbounds); 1777 }, 1778 1779 //===--------------------------------------------------------------===// 1780 1781 [&](const Fortran::lower::details::DynamicArrayDynamicChar &x) { 1782 if (genUnusedEntryPointBox()) 1783 return; 1784 mlir::Value addr; 1785 mlir::Value len; 1786 mlir::Value argBox; 1787 auto charLen = x.charLen(); 1788 // if element type is a CHARACTER, determine the LEN value 1789 if (isDummy) { 1790 mlir::Value actualArg = symMap.lookupSymbol(sym).getAddr(); 1791 if (auto boxTy = actualArg.getType().dyn_cast<fir::BoxType>()) { 1792 argBox = actualArg; 1793 mlir::Type refTy = builder.getRefType(boxTy.getEleTy()); 1794 addr = builder.create<fir::BoxAddrOp>(loc, refTy, argBox); 1795 if (charLen) 1796 // Set/override LEN with an expression. 1797 len = genExplicitCharLen(charLen); 1798 else 1799 // Get the length from the actual arguments. 1800 len = charHelp.readLengthFromBox(argBox); 1801 } else { 1802 std::pair<mlir::Value, mlir::Value> unboxchar = 1803 charHelp.createUnboxChar(actualArg); 1804 addr = unboxchar.first; 1805 if (charLen) { 1806 // Set/override LEN with an expression 1807 len = genExplicitCharLen(charLen); 1808 } else { 1809 // Get the length from the actual arguments. 1810 len = unboxchar.second; 1811 } 1812 } 1813 } else { 1814 // local CHARACTER variable 1815 len = genExplicitCharLen(charLen); 1816 } 1817 llvm::SmallVector<mlir::Value> lengths = {len}; 1818 1819 // cast to the known constant parts from the declaration 1820 mlir::Type castTy = builder.getRefType(converter.genType(var)); 1821 if (addr) 1822 addr = builder.createConvert(loc, castTy, addr); 1823 if (x.lboundAllOnes()) { 1824 // if lower bounds are all ones, build simple shaped object 1825 llvm::SmallVector<mlir::Value> shape; 1826 populateShape(shape, x.bounds, argBox); 1827 if (isDummy) { 1828 symMap.addCharSymbolWithShape(sym, addr, len, shape, true); 1829 return; 1830 } 1831 // local CHARACTER array 1832 mlir::Value local = 1833 createNewLocal(converter, loc, var, preAlloc, shape, lengths); 1834 symMap.addCharSymbolWithShape(sym, local, len, shape); 1835 return; 1836 } 1837 // Process the lower bound and extent values. 1838 llvm::SmallVector<mlir::Value> extents; 1839 llvm::SmallVector<mlir::Value> lbounds; 1840 populateLBoundsExtents(lbounds, extents, x.bounds, argBox); 1841 if (isDummy) { 1842 symMap.addCharSymbolWithBounds(sym, addr, len, extents, lbounds, 1843 true); 1844 return; 1845 } 1846 // local CHARACTER array with computed bounds 1847 assert(Fortran::lower::isExplicitShape(sym)); 1848 mlir::Value local = 1849 createNewLocal(converter, loc, var, preAlloc, extents, lengths); 1850 symMap.addCharSymbolWithBounds(sym, local, len, extents, lbounds); 1851 }, 1852 1853 //===--------------------------------------------------------------===// 1854 1855 [&](const Fortran::lower::BoxAnalyzer::None &) { 1856 mlir::emitError(loc, "symbol analysis failed on ") 1857 << toStringRef(sym.name()); 1858 }); 1859 } 1860 1861 void Fortran::lower::defineModuleVariable( 1862 AbstractConverter &converter, const Fortran::lower::pft::Variable &var) { 1863 // Use empty linkage for module variables, which makes them available 1864 // for use in another unit. 1865 mlir::StringAttr linkage = 1866 getLinkageAttribute(converter.getFirOpBuilder(), var); 1867 if (!var.isGlobal()) 1868 fir::emitFatalError(converter.getCurrentLocation(), 1869 "attempting to lower module variable as local"); 1870 // Define aggregate storages for equivalenced objects. 1871 if (var.isAggregateStore()) { 1872 const Fortran::lower::pft::Variable::AggregateStore &aggregate = 1873 var.getAggregateStore(); 1874 std::string aggName = mangleGlobalAggregateStore(aggregate); 1875 defineGlobalAggregateStore(converter, aggregate, aggName, linkage); 1876 return; 1877 } 1878 const Fortran::semantics::Symbol &sym = var.getSymbol(); 1879 if (const Fortran::semantics::Symbol *common = 1880 Fortran::semantics::FindCommonBlockContaining(var.getSymbol())) { 1881 // Nothing to do, common block are generated before everything. Ensure 1882 // this was done by calling getCommonBlockGlobal. 1883 getCommonBlockGlobal(converter, *common); 1884 } else if (var.isAlias()) { 1885 // Do nothing. Mapping will be done on user side. 1886 } else { 1887 std::string globalName = Fortran::lower::mangle::mangleName(sym); 1888 defineGlobal(converter, var, globalName, linkage); 1889 } 1890 } 1891 1892 void Fortran::lower::instantiateVariable(AbstractConverter &converter, 1893 const pft::Variable &var, 1894 Fortran::lower::SymMap &symMap, 1895 AggregateStoreMap &storeMap) { 1896 if (var.isAggregateStore()) { 1897 instantiateAggregateStore(converter, var, storeMap); 1898 } else if (const Fortran::semantics::Symbol *common = 1899 Fortran::semantics::FindCommonBlockContaining( 1900 var.getSymbol().GetUltimate())) { 1901 instantiateCommon(converter, *common, var, symMap); 1902 } else if (var.isAlias()) { 1903 instantiateAlias(converter, var, symMap, storeMap); 1904 } else if (var.isGlobal()) { 1905 instantiateGlobal(converter, var, symMap); 1906 } else { 1907 instantiateLocal(converter, var, symMap); 1908 } 1909 } 1910 1911 void Fortran::lower::mapCallInterfaceSymbols( 1912 AbstractConverter &converter, const Fortran::lower::CallerInterface &caller, 1913 SymMap &symMap) { 1914 Fortran::lower::AggregateStoreMap storeMap; 1915 const Fortran::semantics::Symbol &result = caller.getResultSymbol(); 1916 for (Fortran::lower::pft::Variable var : 1917 Fortran::lower::pft::buildFuncResultDependencyList(result)) { 1918 if (var.isAggregateStore()) { 1919 instantiateVariable(converter, var, symMap, storeMap); 1920 } else { 1921 const Fortran::semantics::Symbol &sym = var.getSymbol(); 1922 const auto *hostDetails = 1923 sym.detailsIf<Fortran::semantics::HostAssocDetails>(); 1924 if (hostDetails && !var.isModuleVariable()) { 1925 // The callee is an internal procedure `A` whose result properties 1926 // depend on host variables. The caller may be the host, or another 1927 // internal procedure `B` contained in the same host. In the first 1928 // case, the host symbol is obviously mapped, in the second case, it 1929 // must also be mapped because 1930 // HostAssociations::internalProcedureBindings that was called when 1931 // lowering `B` will have mapped all host symbols of captured variables 1932 // to the tuple argument containing the composite of all host associated 1933 // variables, whether or not the host symbol is actually referred to in 1934 // `B`. Hence it is possible to simply lookup the variable associated to 1935 // the host symbol without having to go back to the tuple argument. 1936 Fortran::lower::SymbolBox hostValue = 1937 symMap.lookupSymbol(hostDetails->symbol()); 1938 assert(hostValue && "callee host symbol must be mapped on caller side"); 1939 symMap.addSymbol(sym, hostValue.toExtendedValue()); 1940 // The SymbolBox associated to the host symbols is complete, skip 1941 // instantiateVariable that would try to allocate a new storage. 1942 continue; 1943 } 1944 if (Fortran::semantics::IsDummy(sym) && sym.owner() == result.owner()) { 1945 // Get the argument for the dummy argument symbols of the current call. 1946 symMap.addSymbol(sym, caller.getArgumentValue(sym)); 1947 // All the properties of the dummy variable may not come from the actual 1948 // argument, let instantiateVariable handle this. 1949 } 1950 // If this is neither a host associated or dummy symbol, it must be a 1951 // module or common block variable to satisfy specification expression 1952 // requirements in 10.1.11, instantiateVariable will get its address and 1953 // properties. 1954 instantiateVariable(converter, var, symMap, storeMap); 1955 } 1956 } 1957 } 1958 1959 void Fortran::lower::createRuntimeTypeInfoGlobal( 1960 Fortran::lower::AbstractConverter &converter, mlir::Location loc, 1961 const Fortran::semantics::Symbol &typeInfoSym) { 1962 fir::FirOpBuilder &builder = converter.getFirOpBuilder(); 1963 std::string globalName = Fortran::lower::mangle::mangleName(typeInfoSym); 1964 auto var = Fortran::lower::pft::Variable(typeInfoSym, /*global=*/true); 1965 mlir::StringAttr linkage = getLinkageAttribute(builder, var); 1966 defineGlobal(converter, var, globalName, linkage); 1967 } 1968