1 //===-- Bridge.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/Bridge.h" 14 #include "flang/Lower/Allocatable.h" 15 #include "flang/Lower/CallInterface.h" 16 #include "flang/Lower/Coarray.h" 17 #include "flang/Lower/ConvertExpr.h" 18 #include "flang/Lower/ConvertType.h" 19 #include "flang/Lower/ConvertVariable.h" 20 #include "flang/Lower/HostAssociations.h" 21 #include "flang/Lower/IO.h" 22 #include "flang/Lower/IterationSpace.h" 23 #include "flang/Lower/Mangler.h" 24 #include "flang/Lower/OpenACC.h" 25 #include "flang/Lower/OpenMP.h" 26 #include "flang/Lower/PFTBuilder.h" 27 #include "flang/Lower/Runtime.h" 28 #include "flang/Lower/StatementContext.h" 29 #include "flang/Lower/Support/Utils.h" 30 #include "flang/Lower/Todo.h" 31 #include "flang/Optimizer/Builder/BoxValue.h" 32 #include "flang/Optimizer/Builder/Character.h" 33 #include "flang/Optimizer/Builder/FIRBuilder.h" 34 #include "flang/Optimizer/Builder/Runtime/Character.h" 35 #include "flang/Optimizer/Builder/Runtime/Ragged.h" 36 #include "flang/Optimizer/Dialect/FIRAttr.h" 37 #include "flang/Optimizer/Dialect/FIRDialect.h" 38 #include "flang/Optimizer/Dialect/FIROps.h" 39 #include "flang/Optimizer/Support/FIRContext.h" 40 #include "flang/Optimizer/Support/FatalError.h" 41 #include "flang/Optimizer/Support/InternalNames.h" 42 #include "flang/Optimizer/Transforms/Passes.h" 43 #include "flang/Parser/parse-tree.h" 44 #include "flang/Runtime/iostat.h" 45 #include "flang/Semantics/tools.h" 46 #include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" 47 #include "mlir/IR/PatternMatch.h" 48 #include "mlir/Parser/Parser.h" 49 #include "mlir/Transforms/RegionUtils.h" 50 #include "llvm/Support/CommandLine.h" 51 #include "llvm/Support/Debug.h" 52 #include "llvm/Support/ErrorHandling.h" 53 54 #define DEBUG_TYPE "flang-lower-bridge" 55 56 static llvm::cl::opt<bool> dumpBeforeFir( 57 "fdebug-dump-pre-fir", llvm::cl::init(false), 58 llvm::cl::desc("dump the Pre-FIR tree prior to FIR generation")); 59 60 static llvm::cl::opt<bool> forceLoopToExecuteOnce( 61 "always-execute-loop-body", llvm::cl::init(false), 62 llvm::cl::desc("force the body of a loop to execute at least once")); 63 64 namespace { 65 /// Information for generating a structured or unstructured increment loop. 66 struct IncrementLoopInfo { 67 template <typename T> 68 explicit IncrementLoopInfo(Fortran::semantics::Symbol &sym, const T &lower, 69 const T &upper, const std::optional<T> &step, 70 bool isUnordered = false) 71 : loopVariableSym{sym}, lowerExpr{Fortran::semantics::GetExpr(lower)}, 72 upperExpr{Fortran::semantics::GetExpr(upper)}, 73 stepExpr{Fortran::semantics::GetExpr(step)}, isUnordered{isUnordered} {} 74 75 IncrementLoopInfo(IncrementLoopInfo &&) = default; 76 IncrementLoopInfo &operator=(IncrementLoopInfo &&x) { return x; } 77 78 bool isStructured() const { return !headerBlock; } 79 80 mlir::Type getLoopVariableType() const { 81 assert(loopVariable && "must be set"); 82 return fir::unwrapRefType(loopVariable.getType()); 83 } 84 85 // Data members common to both structured and unstructured loops. 86 const Fortran::semantics::Symbol &loopVariableSym; 87 const Fortran::lower::SomeExpr *lowerExpr; 88 const Fortran::lower::SomeExpr *upperExpr; 89 const Fortran::lower::SomeExpr *stepExpr; 90 bool isUnordered; // do concurrent, forall 91 mlir::Value loopVariable = nullptr; 92 mlir::Value stepValue = nullptr; // possible uses in multiple blocks 93 94 // Data members for structured loops. 95 fir::DoLoopOp doLoop = nullptr; 96 97 // Data members for unstructured loops. 98 bool hasRealControl = false; 99 mlir::Value tripVariable = nullptr; 100 mlir::Block *headerBlock = nullptr; // loop entry and test block 101 mlir::Block *bodyBlock = nullptr; // first loop body block 102 mlir::Block *exitBlock = nullptr; // loop exit target block 103 }; 104 105 /// Helper class to generate the runtime type info global data. This data 106 /// is required to describe the derived type to the runtime so that it can 107 /// operate over it. It must be ensured this data will be generated for every 108 /// derived type lowered in the current translated unit. However, this data 109 /// cannot be generated before FuncOp have been created for functions since the 110 /// initializers may take their address (e.g for type bound procedures). This 111 /// class allows registering all the required runtime type info while it is not 112 /// possible to create globals, and to generate this data after function 113 /// lowering. 114 class RuntimeTypeInfoConverter { 115 /// Store the location and symbols of derived type info to be generated. 116 /// The location of the derived type instantiation is also stored because 117 /// runtime type descriptor symbol are compiler generated and cannot be mapped 118 /// to user code on their own. 119 struct TypeInfoSymbol { 120 Fortran::semantics::SymbolRef symbol; 121 mlir::Location loc; 122 }; 123 124 public: 125 void registerTypeInfoSymbol(Fortran::lower::AbstractConverter &converter, 126 mlir::Location loc, 127 Fortran::semantics::SymbolRef typeInfoSym) { 128 if (seen.contains(typeInfoSym)) 129 return; 130 seen.insert(typeInfoSym); 131 if (!skipRegistration) { 132 registeredTypeInfoSymbols.emplace_back(TypeInfoSymbol{typeInfoSym, loc}); 133 return; 134 } 135 // Once the registration is closed, symbols cannot be added to the 136 // registeredTypeInfoSymbols list because it may be iterated over. 137 // However, after registration is closed, it is safe to directly generate 138 // the globals because all FuncOps whose addresses may be required by the 139 // initializers have been generated. 140 Fortran::lower::createRuntimeTypeInfoGlobal(converter, loc, 141 typeInfoSym.get()); 142 } 143 144 void createTypeInfoGlobals(Fortran::lower::AbstractConverter &converter) { 145 skipRegistration = true; 146 for (const TypeInfoSymbol &info : registeredTypeInfoSymbols) 147 Fortran::lower::createRuntimeTypeInfoGlobal(converter, info.loc, 148 info.symbol.get()); 149 registeredTypeInfoSymbols.clear(); 150 } 151 152 private: 153 /// Store the runtime type descriptors that will be required for the 154 /// derived type that have been converted to FIR derived types. 155 llvm::SmallVector<TypeInfoSymbol> registeredTypeInfoSymbols; 156 /// Create derived type runtime info global immediately without storing the 157 /// symbol in registeredTypeInfoSymbols. 158 bool skipRegistration = false; 159 /// Track symbols symbols processed during and after the registration 160 /// to avoid infinite loops between type conversions and global variable 161 /// creation. 162 llvm::SmallSetVector<Fortran::semantics::SymbolRef, 64> seen; 163 }; 164 165 using IncrementLoopNestInfo = llvm::SmallVector<IncrementLoopInfo>; 166 } // namespace 167 168 //===----------------------------------------------------------------------===// 169 // FirConverter 170 //===----------------------------------------------------------------------===// 171 172 namespace { 173 174 /// Traverse the pre-FIR tree (PFT) to generate the FIR dialect of MLIR. 175 class FirConverter : public Fortran::lower::AbstractConverter { 176 public: 177 explicit FirConverter(Fortran::lower::LoweringBridge &bridge) 178 : bridge{bridge}, foldingContext{bridge.createFoldingContext()} {} 179 virtual ~FirConverter() = default; 180 181 /// Convert the PFT to FIR. 182 void run(Fortran::lower::pft::Program &pft) { 183 // Preliminary translation pass. 184 185 // - Lower common blocks from the PFT common block list that contains a 186 // consolidated list of the common blocks (with the initialization if any in 187 // the Program, and with the common block biggest size in all its 188 // appearance). This is done before lowering any scope declarations because 189 // it is not know at the local scope level what MLIR type common blocks 190 // should have to suit all its usage in the compilation unit. 191 lowerCommonBlocks(pft.getCommonBlocks()); 192 193 // - Declare all functions that have definitions so that definition 194 // signatures prevail over call site signatures. 195 // - Define module variables and OpenMP/OpenACC declarative construct so 196 // that they are available before lowering any function that may use 197 // them. 198 for (Fortran::lower::pft::Program::Units &u : pft.getUnits()) { 199 std::visit(Fortran::common::visitors{ 200 [&](Fortran::lower::pft::FunctionLikeUnit &f) { 201 declareFunction(f); 202 }, 203 [&](Fortran::lower::pft::ModuleLikeUnit &m) { 204 lowerModuleDeclScope(m); 205 for (Fortran::lower::pft::FunctionLikeUnit &f : 206 m.nestedFunctions) 207 declareFunction(f); 208 }, 209 [&](Fortran::lower::pft::BlockDataUnit &b) {}, 210 [&](Fortran::lower::pft::CompilerDirectiveUnit &d) {}, 211 }, 212 u); 213 } 214 215 // Primary translation pass. 216 for (Fortran::lower::pft::Program::Units &u : pft.getUnits()) { 217 std::visit( 218 Fortran::common::visitors{ 219 [&](Fortran::lower::pft::FunctionLikeUnit &f) { lowerFunc(f); }, 220 [&](Fortran::lower::pft::ModuleLikeUnit &m) { lowerMod(m); }, 221 [&](Fortran::lower::pft::BlockDataUnit &b) {}, 222 [&](Fortran::lower::pft::CompilerDirectiveUnit &d) { 223 setCurrentPosition( 224 d.get<Fortran::parser::CompilerDirective>().source); 225 mlir::emitWarning(toLocation(), 226 "ignoring all compiler directives"); 227 }, 228 }, 229 u); 230 } 231 232 /// Once all the code has been translated, create runtime type info 233 /// global data structure for the derived types that have been 234 /// processed. 235 createGlobalOutsideOfFunctionLowering( 236 [&]() { runtimeTypeInfoConverter.createTypeInfoGlobals(*this); }); 237 } 238 239 /// Declare a function. 240 void declareFunction(Fortran::lower::pft::FunctionLikeUnit &funit) { 241 setCurrentPosition(funit.getStartingSourceLoc()); 242 for (int entryIndex = 0, last = funit.entryPointList.size(); 243 entryIndex < last; ++entryIndex) { 244 funit.setActiveEntry(entryIndex); 245 // Calling CalleeInterface ctor will build a declaration 246 // mlir::func::FuncOp with no other side effects. 247 // TODO: when doing some compiler profiling on real apps, it may be worth 248 // to check it's better to save the CalleeInterface instead of recomputing 249 // it later when lowering the body. CalleeInterface ctor should be linear 250 // with the number of arguments, so it is not awful to do it that way for 251 // now, but the linear coefficient might be non negligible. Until 252 // measured, stick to the solution that impacts the code less. 253 Fortran::lower::CalleeInterface{funit, *this}; 254 } 255 funit.setActiveEntry(0); 256 257 // Compute the set of host associated entities from the nested functions. 258 llvm::SetVector<const Fortran::semantics::Symbol *> escapeHost; 259 for (Fortran::lower::pft::FunctionLikeUnit &f : funit.nestedFunctions) 260 collectHostAssociatedVariables(f, escapeHost); 261 funit.setHostAssociatedSymbols(escapeHost); 262 263 // Declare internal procedures 264 for (Fortran::lower::pft::FunctionLikeUnit &f : funit.nestedFunctions) 265 declareFunction(f); 266 } 267 268 /// Collects the canonical list of all host associated symbols. These bindings 269 /// must be aggregated into a tuple which can then be added to each of the 270 /// internal procedure declarations and passed at each call site. 271 void collectHostAssociatedVariables( 272 Fortran::lower::pft::FunctionLikeUnit &funit, 273 llvm::SetVector<const Fortran::semantics::Symbol *> &escapees) { 274 const Fortran::semantics::Scope *internalScope = 275 funit.getSubprogramSymbol().scope(); 276 assert(internalScope && "internal procedures symbol must create a scope"); 277 auto addToListIfEscapee = [&](const Fortran::semantics::Symbol &sym) { 278 const Fortran::semantics::Symbol &ultimate = sym.GetUltimate(); 279 const auto *namelistDetails = 280 ultimate.detailsIf<Fortran::semantics::NamelistDetails>(); 281 if (ultimate.has<Fortran::semantics::ObjectEntityDetails>() || 282 Fortran::semantics::IsProcedurePointer(ultimate) || 283 Fortran::semantics::IsDummy(sym) || namelistDetails) { 284 const Fortran::semantics::Scope &ultimateScope = ultimate.owner(); 285 if (ultimateScope.kind() == 286 Fortran::semantics::Scope::Kind::MainProgram || 287 ultimateScope.kind() == Fortran::semantics::Scope::Kind::Subprogram) 288 if (ultimateScope != *internalScope && 289 ultimateScope.Contains(*internalScope)) { 290 if (namelistDetails) { 291 // So far, namelist symbols are processed on the fly in IO and 292 // the related namelist data structure is not added to the symbol 293 // map, so it cannot be passed to the internal procedures. 294 // Instead, all the symbols of the host namelist used in the 295 // internal procedure must be considered as host associated so 296 // that IO lowering can find them when needed. 297 for (const auto &namelistObject : namelistDetails->objects()) 298 escapees.insert(&*namelistObject); 299 } else { 300 escapees.insert(&ultimate); 301 } 302 } 303 } 304 }; 305 Fortran::lower::pft::visitAllSymbols(funit, addToListIfEscapee); 306 } 307 308 //===--------------------------------------------------------------------===// 309 // AbstractConverter overrides 310 //===--------------------------------------------------------------------===// 311 312 mlir::Value getSymbolAddress(Fortran::lower::SymbolRef sym) override final { 313 return lookupSymbol(sym).getAddr(); 314 } 315 316 mlir::Value impliedDoBinding(llvm::StringRef name) override final { 317 mlir::Value val = localSymbols.lookupImpliedDo(name); 318 if (!val) 319 fir::emitFatalError(toLocation(), "ac-do-variable has no binding"); 320 return val; 321 } 322 323 void copySymbolBinding(Fortran::lower::SymbolRef src, 324 Fortran::lower::SymbolRef target) override final { 325 localSymbols.addSymbol(target, lookupSymbol(src).toExtendedValue()); 326 } 327 328 /// Add the symbol binding to the inner-most level of the symbol map and 329 /// return true if it is not already present. Otherwise, return false. 330 bool bindIfNewSymbol(Fortran::lower::SymbolRef sym, 331 const fir::ExtendedValue &exval) { 332 if (shallowLookupSymbol(sym)) 333 return false; 334 bindSymbol(sym, exval); 335 return true; 336 } 337 338 void bindSymbol(Fortran::lower::SymbolRef sym, 339 const fir::ExtendedValue &exval) override final { 340 localSymbols.addSymbol(sym, exval, /*forced=*/true); 341 } 342 343 bool lookupLabelSet(Fortran::lower::SymbolRef sym, 344 Fortran::lower::pft::LabelSet &labelSet) override final { 345 Fortran::lower::pft::FunctionLikeUnit &owningProc = 346 *getEval().getOwningProcedure(); 347 auto iter = owningProc.assignSymbolLabelMap.find(sym); 348 if (iter == owningProc.assignSymbolLabelMap.end()) 349 return false; 350 labelSet = iter->second; 351 return true; 352 } 353 354 Fortran::lower::pft::Evaluation * 355 lookupLabel(Fortran::lower::pft::Label label) override final { 356 Fortran::lower::pft::FunctionLikeUnit &owningProc = 357 *getEval().getOwningProcedure(); 358 auto iter = owningProc.labelEvaluationMap.find(label); 359 if (iter == owningProc.labelEvaluationMap.end()) 360 return nullptr; 361 return iter->second; 362 } 363 364 fir::ExtendedValue genExprAddr(const Fortran::lower::SomeExpr &expr, 365 Fortran::lower::StatementContext &context, 366 mlir::Location *loc = nullptr) override final { 367 return Fortran::lower::createSomeExtendedAddress( 368 loc ? *loc : toLocation(), *this, expr, localSymbols, context); 369 } 370 fir::ExtendedValue 371 genExprValue(const Fortran::lower::SomeExpr &expr, 372 Fortran::lower::StatementContext &context, 373 mlir::Location *loc = nullptr) override final { 374 return Fortran::lower::createSomeExtendedExpression( 375 loc ? *loc : toLocation(), *this, expr, localSymbols, context); 376 } 377 378 fir::ExtendedValue 379 genExprBox(mlir::Location loc, const Fortran::lower::SomeExpr &expr, 380 Fortran::lower::StatementContext &stmtCtx) override final { 381 return Fortran::lower::createBoxValue(loc, *this, expr, localSymbols, 382 stmtCtx); 383 } 384 385 Fortran::evaluate::FoldingContext &getFoldingContext() override final { 386 return foldingContext; 387 } 388 389 mlir::Type genType(const Fortran::lower::SomeExpr &expr) override final { 390 return Fortran::lower::translateSomeExprToFIRType(*this, expr); 391 } 392 mlir::Type genType(const Fortran::lower::pft::Variable &var) override final { 393 return Fortran::lower::translateVariableToFIRType(*this, var); 394 } 395 mlir::Type genType(Fortran::lower::SymbolRef sym) override final { 396 return Fortran::lower::translateSymbolToFIRType(*this, sym); 397 } 398 mlir::Type 399 genType(Fortran::common::TypeCategory tc, int kind, 400 llvm::ArrayRef<std::int64_t> lenParameters) override final { 401 return Fortran::lower::getFIRType(&getMLIRContext(), tc, kind, 402 lenParameters); 403 } 404 mlir::Type 405 genType(const Fortran::semantics::DerivedTypeSpec &tySpec) override final { 406 return Fortran::lower::translateDerivedTypeToFIRType(*this, tySpec); 407 } 408 mlir::Type genType(Fortran::common::TypeCategory tc) override final { 409 return Fortran::lower::getFIRType( 410 &getMLIRContext(), tc, bridge.getDefaultKinds().GetDefaultKind(tc), 411 llvm::None); 412 } 413 414 bool createHostAssociateVarClone( 415 const Fortran::semantics::Symbol &sym) override final { 416 mlir::Location loc = genLocation(sym.name()); 417 mlir::Type symType = genType(sym); 418 const auto *details = sym.detailsIf<Fortran::semantics::HostAssocDetails>(); 419 assert(details && "No host-association found"); 420 const Fortran::semantics::Symbol &hsym = details->symbol(); 421 Fortran::lower::SymbolBox hsb = lookupSymbol(hsym); 422 423 auto allocate = [&](llvm::ArrayRef<mlir::Value> shape, 424 llvm::ArrayRef<mlir::Value> typeParams) -> mlir::Value { 425 mlir::Value allocVal = builder->allocateLocal( 426 loc, symType, mangleName(sym), toStringRef(sym.GetUltimate().name()), 427 /*pinned=*/true, shape, typeParams, 428 sym.GetUltimate().attrs().test(Fortran::semantics::Attr::TARGET)); 429 return allocVal; 430 }; 431 432 fir::ExtendedValue hexv = getExtendedValue(hsb); 433 fir::ExtendedValue exv = hexv.match( 434 [&](const fir::BoxValue &box) -> fir::ExtendedValue { 435 const Fortran::semantics::DeclTypeSpec *type = sym.GetType(); 436 if (type && type->IsPolymorphic()) 437 TODO(loc, "create polymorphic host associated copy"); 438 // Create a contiguous temp with the same shape and length as 439 // the original variable described by a fir.box. 440 llvm::SmallVector<mlir::Value> extents = 441 fir::factory::getExtents(loc, *builder, hexv); 442 if (box.isDerivedWithLenParameters()) 443 TODO(loc, "get length parameters from derived type BoxValue"); 444 if (box.isCharacter()) { 445 mlir::Value len = fir::factory::readCharLen(*builder, loc, box); 446 mlir::Value temp = allocate(extents, {len}); 447 return fir::CharArrayBoxValue{temp, len, extents}; 448 } 449 return fir::ArrayBoxValue{allocate(extents, {}), extents}; 450 }, 451 [&](const fir::MutableBoxValue &box) -> fir::ExtendedValue { 452 // Allocate storage for a pointer/allocatble descriptor. 453 // No shape/lengths to be passed to the alloca. 454 return fir::MutableBoxValue(allocate({}, {}), 455 box.nonDeferredLenParams(), {}); 456 }, 457 [&](const auto &) -> fir::ExtendedValue { 458 mlir::Value temp = 459 allocate(fir::factory::getExtents(loc, *builder, hexv), 460 fir::getTypeParams(hexv)); 461 return fir::substBase(hexv, temp); 462 }); 463 464 return bindIfNewSymbol(sym, exv); 465 } 466 467 void 468 copyHostAssociateVar(const Fortran::semantics::Symbol &sym) override final { 469 // 1) Fetch the original copy of the variable. 470 assert(sym.has<Fortran::semantics::HostAssocDetails>() && 471 "No host-association found"); 472 const Fortran::semantics::Symbol &hsym = sym.GetUltimate(); 473 Fortran::lower::SymbolBox hsb = lookupSymbol(hsym); 474 fir::ExtendedValue hexv = getExtendedValue(hsb); 475 476 // 2) Create a copy that will mask the original. 477 createHostAssociateVarClone(sym); 478 Fortran::lower::SymbolBox sb = lookupSymbol(sym); 479 fir::ExtendedValue exv = getExtendedValue(sb); 480 481 // 3) Perform the assignment. 482 mlir::Location loc = genLocation(sym.name()); 483 mlir::Type symType = genType(sym); 484 if (auto seqTy = symType.dyn_cast<fir::SequenceType>()) { 485 Fortran::lower::StatementContext stmtCtx; 486 Fortran::lower::createSomeArrayAssignment(*this, exv, hexv, localSymbols, 487 stmtCtx); 488 stmtCtx.finalize(); 489 } else if (hexv.getBoxOf<fir::CharBoxValue>()) { 490 fir::factory::CharacterExprHelper{*builder, loc}.createAssign(exv, hexv); 491 } else if (hexv.getBoxOf<fir::MutableBoxValue>()) { 492 TODO(loc, "firstprivatisation of allocatable variables"); 493 } else { 494 auto loadVal = builder->create<fir::LoadOp>(loc, fir::getBase(hexv)); 495 builder->create<fir::StoreOp>(loc, loadVal, fir::getBase(exv)); 496 } 497 } 498 499 //===--------------------------------------------------------------------===// 500 // Utility methods 501 //===--------------------------------------------------------------------===// 502 503 mlir::Location getCurrentLocation() override final { return toLocation(); } 504 505 /// Generate a dummy location. 506 mlir::Location genUnknownLocation() override final { 507 // Note: builder may not be instantiated yet 508 return mlir::UnknownLoc::get(&getMLIRContext()); 509 } 510 511 /// Generate a `Location` from the `CharBlock`. 512 mlir::Location 513 genLocation(const Fortran::parser::CharBlock &block) override final { 514 if (const Fortran::parser::AllCookedSources *cooked = 515 bridge.getCookedSource()) { 516 if (std::optional<std::pair<Fortran::parser::SourcePosition, 517 Fortran::parser::SourcePosition>> 518 loc = cooked->GetSourcePositionRange(block)) { 519 // loc is a pair (begin, end); use the beginning position 520 Fortran::parser::SourcePosition &filePos = loc->first; 521 return mlir::FileLineColLoc::get(&getMLIRContext(), filePos.file.path(), 522 filePos.line, filePos.column); 523 } 524 } 525 return genUnknownLocation(); 526 } 527 528 fir::FirOpBuilder &getFirOpBuilder() override final { return *builder; } 529 530 mlir::ModuleOp &getModuleOp() override final { return bridge.getModule(); } 531 532 mlir::MLIRContext &getMLIRContext() override final { 533 return bridge.getMLIRContext(); 534 } 535 std::string 536 mangleName(const Fortran::semantics::Symbol &symbol) override final { 537 return Fortran::lower::mangle::mangleName(symbol); 538 } 539 540 const fir::KindMapping &getKindMap() override final { 541 return bridge.getKindMap(); 542 } 543 544 mlir::Value hostAssocTupleValue() override final { return hostAssocTuple; } 545 546 /// Record a binding for the ssa-value of the tuple for this function. 547 void bindHostAssocTuple(mlir::Value val) override final { 548 assert(!hostAssocTuple && val); 549 hostAssocTuple = val; 550 } 551 552 void registerRuntimeTypeInfo( 553 mlir::Location loc, 554 Fortran::lower::SymbolRef typeInfoSym) override final { 555 runtimeTypeInfoConverter.registerTypeInfoSymbol(*this, loc, typeInfoSym); 556 } 557 558 private: 559 FirConverter() = delete; 560 FirConverter(const FirConverter &) = delete; 561 FirConverter &operator=(const FirConverter &) = delete; 562 563 //===--------------------------------------------------------------------===// 564 // Helper member functions 565 //===--------------------------------------------------------------------===// 566 567 mlir::Value createFIRExpr(mlir::Location loc, 568 const Fortran::lower::SomeExpr *expr, 569 Fortran::lower::StatementContext &stmtCtx) { 570 return fir::getBase(genExprValue(*expr, stmtCtx, &loc)); 571 } 572 573 /// Find the symbol in the local map or return null. 574 Fortran::lower::SymbolBox 575 lookupSymbol(const Fortran::semantics::Symbol &sym) { 576 if (Fortran::lower::SymbolBox v = localSymbols.lookupSymbol(sym)) 577 return v; 578 return {}; 579 } 580 581 /// Find the symbol in the inner-most level of the local map or return null. 582 Fortran::lower::SymbolBox 583 shallowLookupSymbol(const Fortran::semantics::Symbol &sym) { 584 if (Fortran::lower::SymbolBox v = localSymbols.shallowLookupSymbol(sym)) 585 return v; 586 return {}; 587 } 588 589 /// Add the symbol to the local map and return `true`. If the symbol is 590 /// already in the map and \p forced is `false`, the map is not updated. 591 /// Instead the value `false` is returned. 592 bool addSymbol(const Fortran::semantics::SymbolRef sym, mlir::Value val, 593 bool forced = false) { 594 if (!forced && lookupSymbol(sym)) 595 return false; 596 localSymbols.addSymbol(sym, val, forced); 597 return true; 598 } 599 600 bool addCharSymbol(const Fortran::semantics::SymbolRef sym, mlir::Value val, 601 mlir::Value len, bool forced = false) { 602 if (!forced && lookupSymbol(sym)) 603 return false; 604 // TODO: ensure val type is fir.array<len x fir.char<kind>> like. Insert 605 // cast if needed. 606 localSymbols.addCharSymbol(sym, val, len, forced); 607 return true; 608 } 609 610 fir::ExtendedValue getExtendedValue(Fortran::lower::SymbolBox sb) { 611 return sb.match( 612 [&](const Fortran::lower::SymbolBox::PointerOrAllocatable &box) { 613 return fir::factory::genMutableBoxRead(*builder, getCurrentLocation(), 614 box); 615 }, 616 [&sb](auto &) { return sb.toExtendedValue(); }); 617 } 618 619 /// Generate the address of loop variable \p sym. 620 mlir::Value genLoopVariableAddress(mlir::Location loc, 621 const Fortran::semantics::Symbol &sym) { 622 assert(lookupSymbol(sym) && "loop control variable must already be in map"); 623 Fortran::lower::StatementContext stmtCtx; 624 return fir::getBase( 625 genExprAddr(Fortran::evaluate::AsGenericExpr(sym).value(), stmtCtx)); 626 } 627 628 static bool isNumericScalarCategory(Fortran::common::TypeCategory cat) { 629 return cat == Fortran::common::TypeCategory::Integer || 630 cat == Fortran::common::TypeCategory::Real || 631 cat == Fortran::common::TypeCategory::Complex || 632 cat == Fortran::common::TypeCategory::Logical; 633 } 634 static bool isLogicalCategory(Fortran::common::TypeCategory cat) { 635 return cat == Fortran::common::TypeCategory::Logical; 636 } 637 static bool isCharacterCategory(Fortran::common::TypeCategory cat) { 638 return cat == Fortran::common::TypeCategory::Character; 639 } 640 static bool isDerivedCategory(Fortran::common::TypeCategory cat) { 641 return cat == Fortran::common::TypeCategory::Derived; 642 } 643 644 /// Insert a new block before \p block. Leave the insertion point unchanged. 645 mlir::Block *insertBlock(mlir::Block *block) { 646 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint(); 647 mlir::Block *newBlock = builder->createBlock(block); 648 builder->restoreInsertionPoint(insertPt); 649 return newBlock; 650 } 651 652 mlir::Block *blockOfLabel(Fortran::lower::pft::Evaluation &eval, 653 Fortran::parser::Label label) { 654 const Fortran::lower::pft::LabelEvalMap &labelEvaluationMap = 655 eval.getOwningProcedure()->labelEvaluationMap; 656 const auto iter = labelEvaluationMap.find(label); 657 assert(iter != labelEvaluationMap.end() && "label missing from map"); 658 mlir::Block *block = iter->second->block; 659 assert(block && "missing labeled evaluation block"); 660 return block; 661 } 662 663 void genFIRBranch(mlir::Block *targetBlock) { 664 assert(targetBlock && "missing unconditional target block"); 665 builder->create<mlir::cf::BranchOp>(toLocation(), targetBlock); 666 } 667 668 void genFIRConditionalBranch(mlir::Value cond, mlir::Block *trueTarget, 669 mlir::Block *falseTarget) { 670 assert(trueTarget && "missing conditional branch true block"); 671 assert(falseTarget && "missing conditional branch false block"); 672 mlir::Location loc = toLocation(); 673 mlir::Value bcc = builder->createConvert(loc, builder->getI1Type(), cond); 674 builder->create<mlir::cf::CondBranchOp>(loc, bcc, trueTarget, llvm::None, 675 falseTarget, llvm::None); 676 } 677 void genFIRConditionalBranch(mlir::Value cond, 678 Fortran::lower::pft::Evaluation *trueTarget, 679 Fortran::lower::pft::Evaluation *falseTarget) { 680 genFIRConditionalBranch(cond, trueTarget->block, falseTarget->block); 681 } 682 void genFIRConditionalBranch(const Fortran::parser::ScalarLogicalExpr &expr, 683 mlir::Block *trueTarget, 684 mlir::Block *falseTarget) { 685 Fortran::lower::StatementContext stmtCtx; 686 mlir::Value cond = 687 createFIRExpr(toLocation(), Fortran::semantics::GetExpr(expr), stmtCtx); 688 stmtCtx.finalize(); 689 genFIRConditionalBranch(cond, trueTarget, falseTarget); 690 } 691 void genFIRConditionalBranch(const Fortran::parser::ScalarLogicalExpr &expr, 692 Fortran::lower::pft::Evaluation *trueTarget, 693 Fortran::lower::pft::Evaluation *falseTarget) { 694 Fortran::lower::StatementContext stmtCtx; 695 mlir::Value cond = 696 createFIRExpr(toLocation(), Fortran::semantics::GetExpr(expr), stmtCtx); 697 stmtCtx.finalize(); 698 genFIRConditionalBranch(cond, trueTarget->block, falseTarget->block); 699 } 700 701 //===--------------------------------------------------------------------===// 702 // Termination of symbolically referenced execution units 703 //===--------------------------------------------------------------------===// 704 705 /// END of program 706 /// 707 /// Generate the cleanup block before the program exits 708 void genExitRoutine() { 709 if (blockIsUnterminated()) 710 builder->create<mlir::func::ReturnOp>(toLocation()); 711 } 712 void genFIR(const Fortran::parser::EndProgramStmt &) { genExitRoutine(); } 713 714 /// END of procedure-like constructs 715 /// 716 /// Generate the cleanup block before the procedure exits 717 void genReturnSymbol(const Fortran::semantics::Symbol &functionSymbol) { 718 const Fortran::semantics::Symbol &resultSym = 719 functionSymbol.get<Fortran::semantics::SubprogramDetails>().result(); 720 Fortran::lower::SymbolBox resultSymBox = lookupSymbol(resultSym); 721 mlir::Location loc = toLocation(); 722 if (!resultSymBox) { 723 mlir::emitError(loc, "failed lowering function return"); 724 return; 725 } 726 mlir::Value resultVal = resultSymBox.match( 727 [&](const fir::CharBoxValue &x) -> mlir::Value { 728 return fir::factory::CharacterExprHelper{*builder, loc} 729 .createEmboxChar(x.getBuffer(), x.getLen()); 730 }, 731 [&](const auto &) -> mlir::Value { 732 mlir::Value resultRef = resultSymBox.getAddr(); 733 mlir::Type resultType = genType(resultSym); 734 mlir::Type resultRefType = builder->getRefType(resultType); 735 // A function with multiple entry points returning different types 736 // tags all result variables with one of the largest types to allow 737 // them to share the same storage. Convert this to the actual type. 738 if (resultRef.getType() != resultRefType) 739 resultRef = builder->createConvert(loc, resultRefType, resultRef); 740 return builder->create<fir::LoadOp>(loc, resultRef); 741 }); 742 builder->create<mlir::func::ReturnOp>(loc, resultVal); 743 } 744 745 /// Get the return value of a call to \p symbol, which is a subroutine entry 746 /// point that has alternative return specifiers. 747 const mlir::Value 748 getAltReturnResult(const Fortran::semantics::Symbol &symbol) { 749 assert(Fortran::semantics::HasAlternateReturns(symbol) && 750 "subroutine does not have alternate returns"); 751 return getSymbolAddress(symbol); 752 } 753 754 void genFIRProcedureExit(Fortran::lower::pft::FunctionLikeUnit &funit, 755 const Fortran::semantics::Symbol &symbol) { 756 if (mlir::Block *finalBlock = funit.finalBlock) { 757 // The current block must end with a terminator. 758 if (blockIsUnterminated()) 759 builder->create<mlir::cf::BranchOp>(toLocation(), finalBlock); 760 // Set insertion point to final block. 761 builder->setInsertionPoint(finalBlock, finalBlock->end()); 762 } 763 if (Fortran::semantics::IsFunction(symbol)) { 764 genReturnSymbol(symbol); 765 } else if (Fortran::semantics::HasAlternateReturns(symbol)) { 766 mlir::Value retval = builder->create<fir::LoadOp>( 767 toLocation(), getAltReturnResult(symbol)); 768 builder->create<mlir::func::ReturnOp>(toLocation(), retval); 769 } else { 770 genExitRoutine(); 771 } 772 } 773 774 // 775 // Statements that have control-flow semantics 776 // 777 778 /// Generate an If[Then]Stmt condition or its negation. 779 template <typename A> 780 mlir::Value genIfCondition(const A *stmt, bool negate = false) { 781 mlir::Location loc = toLocation(); 782 Fortran::lower::StatementContext stmtCtx; 783 mlir::Value condExpr = createFIRExpr( 784 loc, 785 Fortran::semantics::GetExpr( 786 std::get<Fortran::parser::ScalarLogicalExpr>(stmt->t)), 787 stmtCtx); 788 stmtCtx.finalize(); 789 mlir::Value cond = 790 builder->createConvert(loc, builder->getI1Type(), condExpr); 791 if (negate) 792 cond = builder->create<mlir::arith::XOrIOp>( 793 loc, cond, builder->createIntegerConstant(loc, cond.getType(), 1)); 794 return cond; 795 } 796 797 mlir::func::FuncOp getFunc(llvm::StringRef name, mlir::FunctionType ty) { 798 if (mlir::func::FuncOp func = builder->getNamedFunction(name)) { 799 assert(func.getFunctionType() == ty); 800 return func; 801 } 802 return builder->createFunction(toLocation(), name, ty); 803 } 804 805 /// Lowering of CALL statement 806 void genFIR(const Fortran::parser::CallStmt &stmt) { 807 Fortran::lower::StatementContext stmtCtx; 808 Fortran::lower::pft::Evaluation &eval = getEval(); 809 setCurrentPosition(stmt.v.source); 810 assert(stmt.typedCall && "Call was not analyzed"); 811 // Call statement lowering shares code with function call lowering. 812 mlir::Value res = Fortran::lower::createSubroutineCall( 813 *this, *stmt.typedCall, explicitIterSpace, implicitIterSpace, 814 localSymbols, stmtCtx, /*isUserDefAssignment=*/false); 815 if (!res) 816 return; // "Normal" subroutine call. 817 // Call with alternate return specifiers. 818 // The call returns an index that selects an alternate return branch target. 819 llvm::SmallVector<int64_t> indexList; 820 llvm::SmallVector<mlir::Block *> blockList; 821 int64_t index = 0; 822 for (const Fortran::parser::ActualArgSpec &arg : 823 std::get<std::list<Fortran::parser::ActualArgSpec>>(stmt.v.t)) { 824 const auto &actual = std::get<Fortran::parser::ActualArg>(arg.t); 825 if (const auto *altReturn = 826 std::get_if<Fortran::parser::AltReturnSpec>(&actual.u)) { 827 indexList.push_back(++index); 828 blockList.push_back(blockOfLabel(eval, altReturn->v)); 829 } 830 } 831 blockList.push_back(eval.nonNopSuccessor().block); // default = fallthrough 832 stmtCtx.finalize(); 833 builder->create<fir::SelectOp>(toLocation(), res, indexList, blockList); 834 } 835 836 void genFIR(const Fortran::parser::ComputedGotoStmt &stmt) { 837 Fortran::lower::StatementContext stmtCtx; 838 Fortran::lower::pft::Evaluation &eval = getEval(); 839 mlir::Value selectExpr = 840 createFIRExpr(toLocation(), 841 Fortran::semantics::GetExpr( 842 std::get<Fortran::parser::ScalarIntExpr>(stmt.t)), 843 stmtCtx); 844 stmtCtx.finalize(); 845 llvm::SmallVector<int64_t> indexList; 846 llvm::SmallVector<mlir::Block *> blockList; 847 int64_t index = 0; 848 for (Fortran::parser::Label label : 849 std::get<std::list<Fortran::parser::Label>>(stmt.t)) { 850 indexList.push_back(++index); 851 blockList.push_back(blockOfLabel(eval, label)); 852 } 853 blockList.push_back(eval.nonNopSuccessor().block); // default 854 builder->create<fir::SelectOp>(toLocation(), selectExpr, indexList, 855 blockList); 856 } 857 858 void genFIR(const Fortran::parser::ArithmeticIfStmt &stmt) { 859 Fortran::lower::StatementContext stmtCtx; 860 Fortran::lower::pft::Evaluation &eval = getEval(); 861 mlir::Value expr = createFIRExpr( 862 toLocation(), 863 Fortran::semantics::GetExpr(std::get<Fortran::parser::Expr>(stmt.t)), 864 stmtCtx); 865 stmtCtx.finalize(); 866 mlir::Type exprType = expr.getType(); 867 mlir::Location loc = toLocation(); 868 if (exprType.isSignlessInteger()) { 869 // Arithmetic expression has Integer type. Generate a SelectCaseOp 870 // with ranges {(-inf:-1], 0=default, [1:inf)}. 871 mlir::MLIRContext *context = builder->getContext(); 872 llvm::SmallVector<mlir::Attribute> attrList; 873 llvm::SmallVector<mlir::Value> valueList; 874 llvm::SmallVector<mlir::Block *> blockList; 875 attrList.push_back(fir::UpperBoundAttr::get(context)); 876 valueList.push_back(builder->createIntegerConstant(loc, exprType, -1)); 877 blockList.push_back(blockOfLabel(eval, std::get<1>(stmt.t))); 878 attrList.push_back(fir::LowerBoundAttr::get(context)); 879 valueList.push_back(builder->createIntegerConstant(loc, exprType, 1)); 880 blockList.push_back(blockOfLabel(eval, std::get<3>(stmt.t))); 881 attrList.push_back(mlir::UnitAttr::get(context)); // 0 is the "default" 882 blockList.push_back(blockOfLabel(eval, std::get<2>(stmt.t))); 883 builder->create<fir::SelectCaseOp>(loc, expr, attrList, valueList, 884 blockList); 885 return; 886 } 887 // Arithmetic expression has Real type. Generate 888 // sum = expr + expr [ raise an exception if expr is a NaN ] 889 // if (sum < 0.0) goto L1 else if (sum > 0.0) goto L3 else goto L2 890 auto sum = builder->create<mlir::arith::AddFOp>(loc, expr, expr); 891 auto zero = builder->create<mlir::arith::ConstantOp>( 892 loc, exprType, builder->getFloatAttr(exprType, 0.0)); 893 auto cond1 = builder->create<mlir::arith::CmpFOp>( 894 loc, mlir::arith::CmpFPredicate::OLT, sum, zero); 895 mlir::Block *elseIfBlock = 896 builder->getBlock()->splitBlock(builder->getInsertionPoint()); 897 genFIRConditionalBranch(cond1, blockOfLabel(eval, std::get<1>(stmt.t)), 898 elseIfBlock); 899 startBlock(elseIfBlock); 900 auto cond2 = builder->create<mlir::arith::CmpFOp>( 901 loc, mlir::arith::CmpFPredicate::OGT, sum, zero); 902 genFIRConditionalBranch(cond2, blockOfLabel(eval, std::get<3>(stmt.t)), 903 blockOfLabel(eval, std::get<2>(stmt.t))); 904 } 905 906 void genFIR(const Fortran::parser::AssignedGotoStmt &stmt) { 907 // Program requirement 1990 8.2.4 - 908 // 909 // At the time of execution of an assigned GOTO statement, the integer 910 // variable must be defined with the value of a statement label of a 911 // branch target statement that appears in the same scoping unit. 912 // Note that the variable may be defined with a statement label value 913 // only by an ASSIGN statement in the same scoping unit as the assigned 914 // GOTO statement. 915 916 mlir::Location loc = toLocation(); 917 Fortran::lower::pft::Evaluation &eval = getEval(); 918 const Fortran::lower::pft::SymbolLabelMap &symbolLabelMap = 919 eval.getOwningProcedure()->assignSymbolLabelMap; 920 const Fortran::semantics::Symbol &symbol = 921 *std::get<Fortran::parser::Name>(stmt.t).symbol; 922 auto selectExpr = 923 builder->create<fir::LoadOp>(loc, getSymbolAddress(symbol)); 924 auto iter = symbolLabelMap.find(symbol); 925 if (iter == symbolLabelMap.end()) { 926 // Fail for a nonconforming program unit that does not have any ASSIGN 927 // statements. The front end should check for this. 928 mlir::emitError(loc, "(semantics issue) no assigned goto targets"); 929 exit(1); 930 } 931 auto labelSet = iter->second; 932 llvm::SmallVector<int64_t> indexList; 933 llvm::SmallVector<mlir::Block *> blockList; 934 auto addLabel = [&](Fortran::parser::Label label) { 935 indexList.push_back(label); 936 blockList.push_back(blockOfLabel(eval, label)); 937 }; 938 // Add labels from an explicit list. The list may have duplicates. 939 for (Fortran::parser::Label label : 940 std::get<std::list<Fortran::parser::Label>>(stmt.t)) { 941 if (labelSet.count(label) && 942 std::find(indexList.begin(), indexList.end(), label) == 943 indexList.end()) { // ignore duplicates 944 addLabel(label); 945 } 946 } 947 // Absent an explicit list, add all possible label targets. 948 if (indexList.empty()) 949 for (auto &label : labelSet) 950 addLabel(label); 951 // Add a nop/fallthrough branch to the switch for a nonconforming program 952 // unit that violates the program requirement above. 953 blockList.push_back(eval.nonNopSuccessor().block); // default 954 builder->create<fir::SelectOp>(loc, selectExpr, indexList, blockList); 955 } 956 957 /// Generate FIR for a DO construct. There are six variants: 958 /// - unstructured infinite and while loops 959 /// - structured and unstructured increment loops 960 /// - structured and unstructured concurrent loops 961 void genFIR(const Fortran::parser::DoConstruct &doConstruct) { 962 setCurrentPositionAt(doConstruct); 963 // Collect loop nest information. 964 // Generate begin loop code directly for infinite and while loops. 965 Fortran::lower::pft::Evaluation &eval = getEval(); 966 bool unstructuredContext = eval.lowerAsUnstructured(); 967 Fortran::lower::pft::Evaluation &doStmtEval = 968 eval.getFirstNestedEvaluation(); 969 auto *doStmt = doStmtEval.getIf<Fortran::parser::NonLabelDoStmt>(); 970 const auto &loopControl = 971 std::get<std::optional<Fortran::parser::LoopControl>>(doStmt->t); 972 mlir::Block *preheaderBlock = doStmtEval.block; 973 mlir::Block *beginBlock = 974 preheaderBlock ? preheaderBlock : builder->getBlock(); 975 auto createNextBeginBlock = [&]() { 976 // Step beginBlock through unstructured preheader, header, and mask 977 // blocks, created in outermost to innermost order. 978 return beginBlock = beginBlock->splitBlock(beginBlock->end()); 979 }; 980 mlir::Block *headerBlock = 981 unstructuredContext ? createNextBeginBlock() : nullptr; 982 mlir::Block *bodyBlock = doStmtEval.lexicalSuccessor->block; 983 mlir::Block *exitBlock = doStmtEval.parentConstruct->constructExit->block; 984 IncrementLoopNestInfo incrementLoopNestInfo; 985 const Fortran::parser::ScalarLogicalExpr *whileCondition = nullptr; 986 if ((whileCondition = std::get_if<Fortran::parser::ScalarLogicalExpr>( 987 &loopControl->u))) { 988 assert(unstructuredContext && "while loop must be unstructured"); 989 maybeStartBlock(preheaderBlock); // no block or empty block 990 startBlock(headerBlock); 991 genFIRConditionalBranch(*whileCondition, bodyBlock, exitBlock); 992 } else if (const auto *bounds = 993 std::get_if<Fortran::parser::LoopControl::Bounds>( 994 &loopControl->u)) { 995 // Non-concurrent increment loop. 996 IncrementLoopInfo &info = incrementLoopNestInfo.emplace_back( 997 *bounds->name.thing.symbol, bounds->lower, bounds->upper, 998 bounds->step); 999 if (unstructuredContext) { 1000 maybeStartBlock(preheaderBlock); 1001 info.hasRealControl = info.loopVariableSym.GetType()->IsNumeric( 1002 Fortran::common::TypeCategory::Real); 1003 info.headerBlock = headerBlock; 1004 info.bodyBlock = bodyBlock; 1005 info.exitBlock = exitBlock; 1006 } 1007 } else { 1008 TODO(toLocation(), "infinite/unstructured loop/concurrent loop"); 1009 } 1010 1011 // Increment loop begin code. (TODO: Infinite/while code was already 1012 // generated.) 1013 if (!whileCondition) 1014 genFIRIncrementLoopBegin(incrementLoopNestInfo); 1015 1016 // Loop body code - NonLabelDoStmt and EndDoStmt code is generated here. 1017 // Their genFIR calls are nops except for block management in some cases. 1018 for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) 1019 genFIR(e, unstructuredContext); 1020 1021 // Loop end code. (TODO: infinite loop) 1022 if (whileCondition) 1023 genFIRBranch(headerBlock); 1024 else 1025 genFIRIncrementLoopEnd(incrementLoopNestInfo); 1026 } 1027 1028 /// Generate FIR to begin a structured or unstructured increment loop nest. 1029 void genFIRIncrementLoopBegin(IncrementLoopNestInfo &incrementLoopNestInfo) { 1030 assert(!incrementLoopNestInfo.empty() && "empty loop nest"); 1031 mlir::Location loc = toLocation(); 1032 auto genControlValue = [&](const Fortran::lower::SomeExpr *expr, 1033 const IncrementLoopInfo &info) { 1034 mlir::Type controlType = info.isStructured() ? builder->getIndexType() 1035 : info.getLoopVariableType(); 1036 Fortran::lower::StatementContext stmtCtx; 1037 if (expr) 1038 return builder->createConvert(loc, controlType, 1039 createFIRExpr(loc, expr, stmtCtx)); 1040 1041 if (info.hasRealControl) 1042 return builder->createRealConstant(loc, controlType, 1u); 1043 return builder->createIntegerConstant(loc, controlType, 1); // step 1044 }; 1045 for (IncrementLoopInfo &info : incrementLoopNestInfo) { 1046 info.loopVariable = genLoopVariableAddress(loc, info.loopVariableSym); 1047 mlir::Value lowerValue = genControlValue(info.lowerExpr, info); 1048 mlir::Value upperValue = genControlValue(info.upperExpr, info); 1049 info.stepValue = genControlValue(info.stepExpr, info); 1050 1051 // Structured loop - generate fir.do_loop. 1052 if (info.isStructured()) { 1053 info.doLoop = builder->create<fir::DoLoopOp>( 1054 loc, lowerValue, upperValue, info.stepValue, info.isUnordered, 1055 /*finalCountValue=*/!info.isUnordered); 1056 builder->setInsertionPointToStart(info.doLoop.getBody()); 1057 // Update the loop variable value, as it may have non-index references. 1058 mlir::Value value = builder->createConvert( 1059 loc, info.getLoopVariableType(), info.doLoop.getInductionVar()); 1060 builder->create<fir::StoreOp>(loc, value, info.loopVariable); 1061 // TODO: Mask expr 1062 // TODO: handle Locality Spec 1063 continue; 1064 } 1065 1066 // Unstructured loop preheader - initialize tripVariable and loopVariable. 1067 mlir::Value tripCount; 1068 if (info.hasRealControl) { 1069 auto diff1 = 1070 builder->create<mlir::arith::SubFOp>(loc, upperValue, lowerValue); 1071 auto diff2 = 1072 builder->create<mlir::arith::AddFOp>(loc, diff1, info.stepValue); 1073 tripCount = 1074 builder->create<mlir::arith::DivFOp>(loc, diff2, info.stepValue); 1075 tripCount = 1076 builder->createConvert(loc, builder->getIndexType(), tripCount); 1077 1078 } else { 1079 auto diff1 = 1080 builder->create<mlir::arith::SubIOp>(loc, upperValue, lowerValue); 1081 auto diff2 = 1082 builder->create<mlir::arith::AddIOp>(loc, diff1, info.stepValue); 1083 tripCount = 1084 builder->create<mlir::arith::DivSIOp>(loc, diff2, info.stepValue); 1085 } 1086 info.tripVariable = builder->createTemporary(loc, tripCount.getType()); 1087 builder->create<fir::StoreOp>(loc, tripCount, info.tripVariable); 1088 builder->create<fir::StoreOp>(loc, lowerValue, info.loopVariable); 1089 1090 // Unstructured loop header - generate loop condition and mask. 1091 startBlock(info.headerBlock); 1092 tripCount = builder->create<fir::LoadOp>(loc, info.tripVariable); 1093 mlir::Value zero = 1094 builder->createIntegerConstant(loc, tripCount.getType(), 0); 1095 auto cond = builder->create<mlir::arith::CmpIOp>( 1096 loc, mlir::arith::CmpIPredicate::sgt, tripCount, zero); 1097 // TODO: mask expression 1098 genFIRConditionalBranch(cond, info.bodyBlock, info.exitBlock); 1099 if (&info != &incrementLoopNestInfo.back()) // not innermost 1100 startBlock(info.bodyBlock); // preheader block of enclosed dimension 1101 } 1102 } 1103 1104 /// Generate FIR to end a structured or unstructured increment loop nest. 1105 void genFIRIncrementLoopEnd(IncrementLoopNestInfo &incrementLoopNestInfo) { 1106 assert(!incrementLoopNestInfo.empty() && "empty loop nest"); 1107 mlir::Location loc = toLocation(); 1108 for (auto it = incrementLoopNestInfo.rbegin(), 1109 rend = incrementLoopNestInfo.rend(); 1110 it != rend; ++it) { 1111 IncrementLoopInfo &info = *it; 1112 if (info.isStructured()) { 1113 // End fir.do_loop. 1114 if (!info.isUnordered) { 1115 builder->setInsertionPointToEnd(info.doLoop.getBody()); 1116 mlir::Value result = builder->create<mlir::arith::AddIOp>( 1117 loc, info.doLoop.getInductionVar(), info.doLoop.getStep()); 1118 builder->create<fir::ResultOp>(loc, result); 1119 } 1120 builder->setInsertionPointAfter(info.doLoop); 1121 if (info.isUnordered) 1122 continue; 1123 // The loop control variable may be used after loop execution. 1124 mlir::Value lcv = builder->createConvert( 1125 loc, info.getLoopVariableType(), info.doLoop.getResult(0)); 1126 builder->create<fir::StoreOp>(loc, lcv, info.loopVariable); 1127 continue; 1128 } 1129 1130 // Unstructured loop - decrement tripVariable and step loopVariable. 1131 mlir::Value tripCount = 1132 builder->create<fir::LoadOp>(loc, info.tripVariable); 1133 mlir::Value one = 1134 builder->createIntegerConstant(loc, tripCount.getType(), 1); 1135 tripCount = builder->create<mlir::arith::SubIOp>(loc, tripCount, one); 1136 builder->create<fir::StoreOp>(loc, tripCount, info.tripVariable); 1137 mlir::Value value = builder->create<fir::LoadOp>(loc, info.loopVariable); 1138 if (info.hasRealControl) 1139 value = 1140 builder->create<mlir::arith::AddFOp>(loc, value, info.stepValue); 1141 else 1142 value = 1143 builder->create<mlir::arith::AddIOp>(loc, value, info.stepValue); 1144 builder->create<fir::StoreOp>(loc, value, info.loopVariable); 1145 1146 genFIRBranch(info.headerBlock); 1147 if (&info != &incrementLoopNestInfo.front()) // not outermost 1148 startBlock(info.exitBlock); // latch block of enclosing dimension 1149 } 1150 } 1151 1152 /// Generate structured or unstructured FIR for an IF construct. 1153 /// The initial statement may be either an IfStmt or an IfThenStmt. 1154 void genFIR(const Fortran::parser::IfConstruct &) { 1155 mlir::Location loc = toLocation(); 1156 Fortran::lower::pft::Evaluation &eval = getEval(); 1157 if (eval.lowerAsStructured()) { 1158 // Structured fir.if nest. 1159 fir::IfOp topIfOp, currentIfOp; 1160 for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) { 1161 auto genIfOp = [&](mlir::Value cond) { 1162 auto ifOp = builder->create<fir::IfOp>(loc, cond, /*withElse=*/true); 1163 builder->setInsertionPointToStart(&ifOp.getThenRegion().front()); 1164 return ifOp; 1165 }; 1166 if (auto *s = e.getIf<Fortran::parser::IfThenStmt>()) { 1167 topIfOp = currentIfOp = genIfOp(genIfCondition(s, e.negateCondition)); 1168 } else if (auto *s = e.getIf<Fortran::parser::IfStmt>()) { 1169 topIfOp = currentIfOp = genIfOp(genIfCondition(s, e.negateCondition)); 1170 } else if (auto *s = e.getIf<Fortran::parser::ElseIfStmt>()) { 1171 builder->setInsertionPointToStart( 1172 ¤tIfOp.getElseRegion().front()); 1173 currentIfOp = genIfOp(genIfCondition(s)); 1174 } else if (e.isA<Fortran::parser::ElseStmt>()) { 1175 builder->setInsertionPointToStart( 1176 ¤tIfOp.getElseRegion().front()); 1177 } else if (e.isA<Fortran::parser::EndIfStmt>()) { 1178 builder->setInsertionPointAfter(topIfOp); 1179 } else { 1180 genFIR(e, /*unstructuredContext=*/false); 1181 } 1182 } 1183 return; 1184 } 1185 1186 // Unstructured branch sequence. 1187 for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) { 1188 auto genIfBranch = [&](mlir::Value cond) { 1189 if (e.lexicalSuccessor == e.controlSuccessor) // empty block -> exit 1190 genFIRConditionalBranch(cond, e.parentConstruct->constructExit, 1191 e.controlSuccessor); 1192 else // non-empty block 1193 genFIRConditionalBranch(cond, e.lexicalSuccessor, e.controlSuccessor); 1194 }; 1195 if (auto *s = e.getIf<Fortran::parser::IfThenStmt>()) { 1196 maybeStartBlock(e.block); 1197 genIfBranch(genIfCondition(s, e.negateCondition)); 1198 } else if (auto *s = e.getIf<Fortran::parser::IfStmt>()) { 1199 maybeStartBlock(e.block); 1200 genIfBranch(genIfCondition(s, e.negateCondition)); 1201 } else if (auto *s = e.getIf<Fortran::parser::ElseIfStmt>()) { 1202 startBlock(e.block); 1203 genIfBranch(genIfCondition(s)); 1204 } else { 1205 genFIR(e); 1206 } 1207 } 1208 } 1209 1210 void genFIR(const Fortran::parser::CaseConstruct &) { 1211 for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations()) 1212 genFIR(e); 1213 } 1214 1215 template <typename A> 1216 void genNestedStatement(const Fortran::parser::Statement<A> &stmt) { 1217 setCurrentPosition(stmt.source); 1218 genFIR(stmt.statement); 1219 } 1220 1221 /// Force the binding of an explicit symbol. This is used to bind and re-bind 1222 /// a concurrent control symbol to its value. 1223 void forceControlVariableBinding(const Fortran::semantics::Symbol *sym, 1224 mlir::Value inducVar) { 1225 mlir::Location loc = toLocation(); 1226 assert(sym && "There must be a symbol to bind"); 1227 mlir::Type toTy = genType(*sym); 1228 // FIXME: this should be a "per iteration" temporary. 1229 mlir::Value tmp = builder->createTemporary( 1230 loc, toTy, toStringRef(sym->name()), 1231 llvm::ArrayRef<mlir::NamedAttribute>{ 1232 Fortran::lower::getAdaptToByRefAttr(*builder)}); 1233 mlir::Value cast = builder->createConvert(loc, toTy, inducVar); 1234 builder->create<fir::StoreOp>(loc, cast, tmp); 1235 localSymbols.addSymbol(*sym, tmp, /*force=*/true); 1236 } 1237 1238 /// Process a concurrent header for a FORALL. (Concurrent headers for DO 1239 /// CONCURRENT loops are lowered elsewhere.) 1240 void genFIR(const Fortran::parser::ConcurrentHeader &header) { 1241 llvm::SmallVector<mlir::Value> lows; 1242 llvm::SmallVector<mlir::Value> highs; 1243 llvm::SmallVector<mlir::Value> steps; 1244 if (explicitIterSpace.isOutermostForall()) { 1245 // For the outermost forall, we evaluate the bounds expressions once. 1246 // Contrastingly, if this forall is nested, the bounds expressions are 1247 // assumed to be pure, possibly dependent on outer concurrent control 1248 // variables, possibly variant with respect to arguments, and will be 1249 // re-evaluated. 1250 mlir::Location loc = toLocation(); 1251 mlir::Type idxTy = builder->getIndexType(); 1252 Fortran::lower::StatementContext &stmtCtx = 1253 explicitIterSpace.stmtContext(); 1254 auto lowerExpr = [&](auto &e) { 1255 return fir::getBase(genExprValue(e, stmtCtx)); 1256 }; 1257 for (const Fortran::parser::ConcurrentControl &ctrl : 1258 std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) { 1259 const Fortran::lower::SomeExpr *lo = 1260 Fortran::semantics::GetExpr(std::get<1>(ctrl.t)); 1261 const Fortran::lower::SomeExpr *hi = 1262 Fortran::semantics::GetExpr(std::get<2>(ctrl.t)); 1263 auto &optStep = 1264 std::get<std::optional<Fortran::parser::ScalarIntExpr>>(ctrl.t); 1265 lows.push_back(builder->createConvert(loc, idxTy, lowerExpr(*lo))); 1266 highs.push_back(builder->createConvert(loc, idxTy, lowerExpr(*hi))); 1267 steps.push_back( 1268 optStep.has_value() 1269 ? builder->createConvert( 1270 loc, idxTy, 1271 lowerExpr(*Fortran::semantics::GetExpr(*optStep))) 1272 : builder->createIntegerConstant(loc, idxTy, 1)); 1273 } 1274 } 1275 auto lambda = [&, lows, highs, steps]() { 1276 // Create our iteration space from the header spec. 1277 mlir::Location loc = toLocation(); 1278 mlir::Type idxTy = builder->getIndexType(); 1279 llvm::SmallVector<fir::DoLoopOp> loops; 1280 Fortran::lower::StatementContext &stmtCtx = 1281 explicitIterSpace.stmtContext(); 1282 auto lowerExpr = [&](auto &e) { 1283 return fir::getBase(genExprValue(e, stmtCtx)); 1284 }; 1285 const bool outermost = !lows.empty(); 1286 std::size_t headerIndex = 0; 1287 for (const Fortran::parser::ConcurrentControl &ctrl : 1288 std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) { 1289 const Fortran::semantics::Symbol *ctrlVar = 1290 std::get<Fortran::parser::Name>(ctrl.t).symbol; 1291 mlir::Value lb; 1292 mlir::Value ub; 1293 mlir::Value by; 1294 if (outermost) { 1295 assert(headerIndex < lows.size()); 1296 if (headerIndex == 0) 1297 explicitIterSpace.resetInnerArgs(); 1298 lb = lows[headerIndex]; 1299 ub = highs[headerIndex]; 1300 by = steps[headerIndex++]; 1301 } else { 1302 const Fortran::lower::SomeExpr *lo = 1303 Fortran::semantics::GetExpr(std::get<1>(ctrl.t)); 1304 const Fortran::lower::SomeExpr *hi = 1305 Fortran::semantics::GetExpr(std::get<2>(ctrl.t)); 1306 auto &optStep = 1307 std::get<std::optional<Fortran::parser::ScalarIntExpr>>(ctrl.t); 1308 lb = builder->createConvert(loc, idxTy, lowerExpr(*lo)); 1309 ub = builder->createConvert(loc, idxTy, lowerExpr(*hi)); 1310 by = optStep.has_value() 1311 ? builder->createConvert( 1312 loc, idxTy, 1313 lowerExpr(*Fortran::semantics::GetExpr(*optStep))) 1314 : builder->createIntegerConstant(loc, idxTy, 1); 1315 } 1316 auto lp = builder->create<fir::DoLoopOp>( 1317 loc, lb, ub, by, /*unordered=*/true, 1318 /*finalCount=*/false, explicitIterSpace.getInnerArgs()); 1319 if (!loops.empty() || !outermost) 1320 builder->create<fir::ResultOp>(loc, lp.getResults()); 1321 explicitIterSpace.setInnerArgs(lp.getRegionIterArgs()); 1322 builder->setInsertionPointToStart(lp.getBody()); 1323 forceControlVariableBinding(ctrlVar, lp.getInductionVar()); 1324 loops.push_back(lp); 1325 } 1326 if (outermost) 1327 explicitIterSpace.setOuterLoop(loops[0]); 1328 explicitIterSpace.appendLoops(loops); 1329 if (const auto &mask = 1330 std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>( 1331 header.t); 1332 mask.has_value()) { 1333 mlir::Type i1Ty = builder->getI1Type(); 1334 fir::ExtendedValue maskExv = 1335 genExprValue(*Fortran::semantics::GetExpr(mask.value()), stmtCtx); 1336 mlir::Value cond = 1337 builder->createConvert(loc, i1Ty, fir::getBase(maskExv)); 1338 auto ifOp = builder->create<fir::IfOp>( 1339 loc, explicitIterSpace.innerArgTypes(), cond, 1340 /*withElseRegion=*/true); 1341 builder->create<fir::ResultOp>(loc, ifOp.getResults()); 1342 builder->setInsertionPointToStart(&ifOp.getElseRegion().front()); 1343 builder->create<fir::ResultOp>(loc, explicitIterSpace.getInnerArgs()); 1344 builder->setInsertionPointToStart(&ifOp.getThenRegion().front()); 1345 } 1346 }; 1347 // Push the lambda to gen the loop nest context. 1348 explicitIterSpace.pushLoopNest(lambda); 1349 } 1350 1351 void genFIR(const Fortran::parser::ForallAssignmentStmt &stmt) { 1352 std::visit([&](const auto &x) { genFIR(x); }, stmt.u); 1353 } 1354 1355 void genFIR(const Fortran::parser::EndForallStmt &) { 1356 cleanupExplicitSpace(); 1357 } 1358 1359 template <typename A> 1360 void prepareExplicitSpace(const A &forall) { 1361 if (!explicitIterSpace.isActive()) 1362 analyzeExplicitSpace(forall); 1363 localSymbols.pushScope(); 1364 explicitIterSpace.enter(); 1365 } 1366 1367 /// Cleanup all the FORALL context information when we exit. 1368 void cleanupExplicitSpace() { 1369 explicitIterSpace.leave(); 1370 localSymbols.popScope(); 1371 } 1372 1373 /// Generate FIR for a FORALL statement. 1374 void genFIR(const Fortran::parser::ForallStmt &stmt) { 1375 prepareExplicitSpace(stmt); 1376 genFIR(std::get< 1377 Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>( 1378 stmt.t) 1379 .value()); 1380 genFIR(std::get<Fortran::parser::UnlabeledStatement< 1381 Fortran::parser::ForallAssignmentStmt>>(stmt.t) 1382 .statement); 1383 cleanupExplicitSpace(); 1384 } 1385 1386 /// Generate FIR for a FORALL construct. 1387 void genFIR(const Fortran::parser::ForallConstruct &forall) { 1388 prepareExplicitSpace(forall); 1389 genNestedStatement( 1390 std::get< 1391 Fortran::parser::Statement<Fortran::parser::ForallConstructStmt>>( 1392 forall.t)); 1393 for (const Fortran::parser::ForallBodyConstruct &s : 1394 std::get<std::list<Fortran::parser::ForallBodyConstruct>>(forall.t)) { 1395 std::visit( 1396 Fortran::common::visitors{ 1397 [&](const Fortran::parser::WhereConstruct &b) { genFIR(b); }, 1398 [&](const Fortran::common::Indirection< 1399 Fortran::parser::ForallConstruct> &b) { genFIR(b.value()); }, 1400 [&](const auto &b) { genNestedStatement(b); }}, 1401 s.u); 1402 } 1403 genNestedStatement( 1404 std::get<Fortran::parser::Statement<Fortran::parser::EndForallStmt>>( 1405 forall.t)); 1406 } 1407 1408 /// Lower the concurrent header specification. 1409 void genFIR(const Fortran::parser::ForallConstructStmt &stmt) { 1410 genFIR(std::get< 1411 Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>( 1412 stmt.t) 1413 .value()); 1414 } 1415 1416 void genFIR(const Fortran::parser::CompilerDirective &) { 1417 TODO(toLocation(), "CompilerDirective lowering"); 1418 } 1419 1420 void genFIR(const Fortran::parser::OpenACCConstruct &acc) { 1421 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint(); 1422 genOpenACCConstruct(*this, getEval(), acc); 1423 for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations()) 1424 genFIR(e); 1425 builder->restoreInsertionPoint(insertPt); 1426 } 1427 1428 void genFIR(const Fortran::parser::OpenACCDeclarativeConstruct &accDecl) { 1429 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint(); 1430 genOpenACCDeclarativeConstruct(*this, getEval(), accDecl); 1431 for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations()) 1432 genFIR(e); 1433 builder->restoreInsertionPoint(insertPt); 1434 } 1435 1436 void genFIR(const Fortran::parser::OpenMPConstruct &omp) { 1437 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint(); 1438 localSymbols.pushScope(); 1439 genOpenMPConstruct(*this, getEval(), omp); 1440 1441 const Fortran::parser::OpenMPLoopConstruct *ompLoop = 1442 std::get_if<Fortran::parser::OpenMPLoopConstruct>(&omp.u); 1443 1444 // If loop is part of an OpenMP Construct then the OpenMP dialect 1445 // workshare loop operation has already been created. Only the 1446 // body needs to be created here and the do_loop can be skipped. 1447 // Skip the number of collapsed loops, which is 1 when there is a 1448 // no collapse requested. 1449 1450 Fortran::lower::pft::Evaluation *curEval = &getEval(); 1451 if (ompLoop) { 1452 const auto &wsLoopOpClauseList = std::get<Fortran::parser::OmpClauseList>( 1453 std::get<Fortran::parser::OmpBeginLoopDirective>(ompLoop->t).t); 1454 int64_t collapseValue = 1455 Fortran::lower::getCollapseValue(wsLoopOpClauseList); 1456 1457 curEval = &curEval->getFirstNestedEvaluation(); 1458 for (int64_t i = 1; i < collapseValue; i++) { 1459 curEval = &*std::next(curEval->getNestedEvaluations().begin()); 1460 } 1461 } 1462 1463 for (Fortran::lower::pft::Evaluation &e : curEval->getNestedEvaluations()) 1464 genFIR(e); 1465 localSymbols.popScope(); 1466 builder->restoreInsertionPoint(insertPt); 1467 } 1468 1469 void genFIR(const Fortran::parser::OpenMPDeclarativeConstruct &ompDecl) { 1470 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint(); 1471 genOpenMPDeclarativeConstruct(*this, getEval(), ompDecl); 1472 for (Fortran::lower::pft::Evaluation &e : getEval().getNestedEvaluations()) 1473 genFIR(e); 1474 builder->restoreInsertionPoint(insertPt); 1475 } 1476 1477 /// Generate FIR for a SELECT CASE statement. 1478 /// The type may be CHARACTER, INTEGER, or LOGICAL. 1479 void genFIR(const Fortran::parser::SelectCaseStmt &stmt) { 1480 Fortran::lower::pft::Evaluation &eval = getEval(); 1481 mlir::MLIRContext *context = builder->getContext(); 1482 mlir::Location loc = toLocation(); 1483 Fortran::lower::StatementContext stmtCtx; 1484 const Fortran::lower::SomeExpr *expr = Fortran::semantics::GetExpr( 1485 std::get<Fortran::parser::Scalar<Fortran::parser::Expr>>(stmt.t)); 1486 bool isCharSelector = isCharacterCategory(expr->GetType()->category()); 1487 bool isLogicalSelector = isLogicalCategory(expr->GetType()->category()); 1488 auto charValue = [&](const Fortran::lower::SomeExpr *expr) { 1489 fir::ExtendedValue exv = genExprAddr(*expr, stmtCtx, &loc); 1490 return exv.match( 1491 [&](const fir::CharBoxValue &cbv) { 1492 return fir::factory::CharacterExprHelper{*builder, loc} 1493 .createEmboxChar(cbv.getAddr(), cbv.getLen()); 1494 }, 1495 [&](auto) { 1496 fir::emitFatalError(loc, "not a character"); 1497 return mlir::Value{}; 1498 }); 1499 }; 1500 mlir::Value selector; 1501 if (isCharSelector) { 1502 selector = charValue(expr); 1503 } else { 1504 selector = createFIRExpr(loc, expr, stmtCtx); 1505 if (isLogicalSelector) 1506 selector = builder->createConvert(loc, builder->getI1Type(), selector); 1507 } 1508 mlir::Type selectType = selector.getType(); 1509 llvm::SmallVector<mlir::Attribute> attrList; 1510 llvm::SmallVector<mlir::Value> valueList; 1511 llvm::SmallVector<mlir::Block *> blockList; 1512 mlir::Block *defaultBlock = eval.parentConstruct->constructExit->block; 1513 using CaseValue = Fortran::parser::Scalar<Fortran::parser::ConstantExpr>; 1514 auto addValue = [&](const CaseValue &caseValue) { 1515 const Fortran::lower::SomeExpr *expr = 1516 Fortran::semantics::GetExpr(caseValue.thing); 1517 if (isCharSelector) 1518 valueList.push_back(charValue(expr)); 1519 else if (isLogicalSelector) 1520 valueList.push_back(builder->createConvert( 1521 loc, selectType, createFIRExpr(toLocation(), expr, stmtCtx))); 1522 else 1523 valueList.push_back(builder->createIntegerConstant( 1524 loc, selectType, *Fortran::evaluate::ToInt64(*expr))); 1525 }; 1526 for (Fortran::lower::pft::Evaluation *e = eval.controlSuccessor; e; 1527 e = e->controlSuccessor) { 1528 const auto &caseStmt = e->getIf<Fortran::parser::CaseStmt>(); 1529 assert(e->block && "missing CaseStmt block"); 1530 const auto &caseSelector = 1531 std::get<Fortran::parser::CaseSelector>(caseStmt->t); 1532 const auto *caseValueRangeList = 1533 std::get_if<std::list<Fortran::parser::CaseValueRange>>( 1534 &caseSelector.u); 1535 if (!caseValueRangeList) { 1536 defaultBlock = e->block; 1537 continue; 1538 } 1539 for (const Fortran::parser::CaseValueRange &caseValueRange : 1540 *caseValueRangeList) { 1541 blockList.push_back(e->block); 1542 if (const auto *caseValue = std::get_if<CaseValue>(&caseValueRange.u)) { 1543 attrList.push_back(fir::PointIntervalAttr::get(context)); 1544 addValue(*caseValue); 1545 continue; 1546 } 1547 const auto &caseRange = 1548 std::get<Fortran::parser::CaseValueRange::Range>(caseValueRange.u); 1549 if (caseRange.lower && caseRange.upper) { 1550 attrList.push_back(fir::ClosedIntervalAttr::get(context)); 1551 addValue(*caseRange.lower); 1552 addValue(*caseRange.upper); 1553 } else if (caseRange.lower) { 1554 attrList.push_back(fir::LowerBoundAttr::get(context)); 1555 addValue(*caseRange.lower); 1556 } else { 1557 attrList.push_back(fir::UpperBoundAttr::get(context)); 1558 addValue(*caseRange.upper); 1559 } 1560 } 1561 } 1562 // Skip a logical default block that can never be referenced. 1563 if (isLogicalSelector && attrList.size() == 2) 1564 defaultBlock = eval.parentConstruct->constructExit->block; 1565 attrList.push_back(mlir::UnitAttr::get(context)); 1566 blockList.push_back(defaultBlock); 1567 1568 // Generate a fir::SelectCaseOp. 1569 // Explicit branch code is better for the LOGICAL type. The CHARACTER type 1570 // does not yet have downstream support, and also uses explicit branch code. 1571 // The -no-structured-fir option can be used to force generation of INTEGER 1572 // type branch code. 1573 if (!isLogicalSelector && !isCharSelector && eval.lowerAsStructured()) { 1574 // Numeric selector is a ssa register, all temps that may have 1575 // been generated while evaluating it can be cleaned-up before the 1576 // fir.select_case. 1577 stmtCtx.finalize(); 1578 builder->create<fir::SelectCaseOp>(loc, selector, attrList, valueList, 1579 blockList); 1580 return; 1581 } 1582 1583 // Generate a sequence of case value comparisons and branches. 1584 auto caseValue = valueList.begin(); 1585 auto caseBlock = blockList.begin(); 1586 for (mlir::Attribute attr : attrList) { 1587 if (attr.isa<mlir::UnitAttr>()) { 1588 genFIRBranch(*caseBlock++); 1589 break; 1590 } 1591 auto genCond = [&](mlir::Value rhs, 1592 mlir::arith::CmpIPredicate pred) -> mlir::Value { 1593 if (!isCharSelector) 1594 return builder->create<mlir::arith::CmpIOp>(loc, pred, selector, rhs); 1595 fir::factory::CharacterExprHelper charHelper{*builder, loc}; 1596 std::pair<mlir::Value, mlir::Value> lhsVal = 1597 charHelper.createUnboxChar(selector); 1598 mlir::Value &lhsAddr = lhsVal.first; 1599 mlir::Value &lhsLen = lhsVal.second; 1600 std::pair<mlir::Value, mlir::Value> rhsVal = 1601 charHelper.createUnboxChar(rhs); 1602 mlir::Value &rhsAddr = rhsVal.first; 1603 mlir::Value &rhsLen = rhsVal.second; 1604 return fir::runtime::genCharCompare(*builder, loc, pred, lhsAddr, 1605 lhsLen, rhsAddr, rhsLen); 1606 }; 1607 mlir::Block *newBlock = insertBlock(*caseBlock); 1608 if (attr.isa<fir::ClosedIntervalAttr>()) { 1609 mlir::Block *newBlock2 = insertBlock(*caseBlock); 1610 mlir::Value cond = 1611 genCond(*caseValue++, mlir::arith::CmpIPredicate::sge); 1612 genFIRConditionalBranch(cond, newBlock, newBlock2); 1613 builder->setInsertionPointToEnd(newBlock); 1614 mlir::Value cond2 = 1615 genCond(*caseValue++, mlir::arith::CmpIPredicate::sle); 1616 genFIRConditionalBranch(cond2, *caseBlock++, newBlock2); 1617 builder->setInsertionPointToEnd(newBlock2); 1618 continue; 1619 } 1620 mlir::arith::CmpIPredicate pred; 1621 if (attr.isa<fir::PointIntervalAttr>()) { 1622 pred = mlir::arith::CmpIPredicate::eq; 1623 } else if (attr.isa<fir::LowerBoundAttr>()) { 1624 pred = mlir::arith::CmpIPredicate::sge; 1625 } else { 1626 assert(attr.isa<fir::UpperBoundAttr>() && "unexpected predicate"); 1627 pred = mlir::arith::CmpIPredicate::sle; 1628 } 1629 mlir::Value cond = genCond(*caseValue++, pred); 1630 genFIRConditionalBranch(cond, *caseBlock++, newBlock); 1631 builder->setInsertionPointToEnd(newBlock); 1632 } 1633 assert(caseValue == valueList.end() && caseBlock == blockList.end() && 1634 "select case list mismatch"); 1635 // Clean-up the selector at the end of the construct if it is a temporary 1636 // (which is possible with characters). 1637 mlir::OpBuilder::InsertPoint insertPt = builder->saveInsertionPoint(); 1638 builder->setInsertionPointToEnd(eval.parentConstruct->constructExit->block); 1639 stmtCtx.finalize(); 1640 builder->restoreInsertionPoint(insertPt); 1641 } 1642 1643 fir::ExtendedValue 1644 genAssociateSelector(const Fortran::lower::SomeExpr &selector, 1645 Fortran::lower::StatementContext &stmtCtx) { 1646 return Fortran::lower::isArraySectionWithoutVectorSubscript(selector) 1647 ? Fortran::lower::createSomeArrayBox(*this, selector, 1648 localSymbols, stmtCtx) 1649 : genExprAddr(selector, stmtCtx); 1650 } 1651 1652 void genFIR(const Fortran::parser::AssociateConstruct &) { 1653 Fortran::lower::StatementContext stmtCtx; 1654 Fortran::lower::pft::Evaluation &eval = getEval(); 1655 for (Fortran::lower::pft::Evaluation &e : eval.getNestedEvaluations()) { 1656 if (auto *stmt = e.getIf<Fortran::parser::AssociateStmt>()) { 1657 if (eval.lowerAsUnstructured()) 1658 maybeStartBlock(e.block); 1659 localSymbols.pushScope(); 1660 for (const Fortran::parser::Association &assoc : 1661 std::get<std::list<Fortran::parser::Association>>(stmt->t)) { 1662 Fortran::semantics::Symbol &sym = 1663 *std::get<Fortran::parser::Name>(assoc.t).symbol; 1664 const Fortran::lower::SomeExpr &selector = 1665 *sym.get<Fortran::semantics::AssocEntityDetails>().expr(); 1666 localSymbols.addSymbol(sym, genAssociateSelector(selector, stmtCtx)); 1667 } 1668 } else if (e.getIf<Fortran::parser::EndAssociateStmt>()) { 1669 if (eval.lowerAsUnstructured()) 1670 maybeStartBlock(e.block); 1671 stmtCtx.finalize(); 1672 localSymbols.popScope(); 1673 } else { 1674 genFIR(e); 1675 } 1676 } 1677 } 1678 1679 void genFIR(const Fortran::parser::BlockConstruct &blockConstruct) { 1680 setCurrentPositionAt(blockConstruct); 1681 TODO(toLocation(), "BlockConstruct lowering"); 1682 } 1683 void genFIR(const Fortran::parser::BlockStmt &) { 1684 TODO(toLocation(), "BlockStmt lowering"); 1685 } 1686 void genFIR(const Fortran::parser::EndBlockStmt &) { 1687 TODO(toLocation(), "EndBlockStmt lowering"); 1688 } 1689 1690 void genFIR(const Fortran::parser::ChangeTeamConstruct &construct) { 1691 TODO(toLocation(), "ChangeTeamConstruct lowering"); 1692 } 1693 void genFIR(const Fortran::parser::ChangeTeamStmt &stmt) { 1694 TODO(toLocation(), "ChangeTeamStmt lowering"); 1695 } 1696 void genFIR(const Fortran::parser::EndChangeTeamStmt &stmt) { 1697 TODO(toLocation(), "EndChangeTeamStmt lowering"); 1698 } 1699 1700 void genFIR(const Fortran::parser::CriticalConstruct &criticalConstruct) { 1701 setCurrentPositionAt(criticalConstruct); 1702 TODO(toLocation(), "CriticalConstruct lowering"); 1703 } 1704 void genFIR(const Fortran::parser::CriticalStmt &) { 1705 TODO(toLocation(), "CriticalStmt lowering"); 1706 } 1707 void genFIR(const Fortran::parser::EndCriticalStmt &) { 1708 TODO(toLocation(), "EndCriticalStmt lowering"); 1709 } 1710 1711 void genFIR(const Fortran::parser::SelectRankConstruct &selectRankConstruct) { 1712 setCurrentPositionAt(selectRankConstruct); 1713 TODO(toLocation(), "SelectRankConstruct lowering"); 1714 } 1715 void genFIR(const Fortran::parser::SelectRankStmt &) { 1716 TODO(toLocation(), "SelectRankStmt lowering"); 1717 } 1718 void genFIR(const Fortran::parser::SelectRankCaseStmt &) { 1719 TODO(toLocation(), "SelectRankCaseStmt lowering"); 1720 } 1721 1722 void genFIR(const Fortran::parser::SelectTypeConstruct &selectTypeConstruct) { 1723 setCurrentPositionAt(selectTypeConstruct); 1724 TODO(toLocation(), "SelectTypeConstruct lowering"); 1725 } 1726 void genFIR(const Fortran::parser::SelectTypeStmt &) { 1727 TODO(toLocation(), "SelectTypeStmt lowering"); 1728 } 1729 void genFIR(const Fortran::parser::TypeGuardStmt &) { 1730 TODO(toLocation(), "TypeGuardStmt lowering"); 1731 } 1732 1733 //===--------------------------------------------------------------------===// 1734 // IO statements (see io.h) 1735 //===--------------------------------------------------------------------===// 1736 1737 void genFIR(const Fortran::parser::BackspaceStmt &stmt) { 1738 mlir::Value iostat = genBackspaceStatement(*this, stmt); 1739 genIoConditionBranches(getEval(), stmt.v, iostat); 1740 } 1741 void genFIR(const Fortran::parser::CloseStmt &stmt) { 1742 mlir::Value iostat = genCloseStatement(*this, stmt); 1743 genIoConditionBranches(getEval(), stmt.v, iostat); 1744 } 1745 void genFIR(const Fortran::parser::EndfileStmt &stmt) { 1746 mlir::Value iostat = genEndfileStatement(*this, stmt); 1747 genIoConditionBranches(getEval(), stmt.v, iostat); 1748 } 1749 void genFIR(const Fortran::parser::FlushStmt &stmt) { 1750 mlir::Value iostat = genFlushStatement(*this, stmt); 1751 genIoConditionBranches(getEval(), stmt.v, iostat); 1752 } 1753 void genFIR(const Fortran::parser::InquireStmt &stmt) { 1754 mlir::Value iostat = genInquireStatement(*this, stmt); 1755 if (const auto *specs = 1756 std::get_if<std::list<Fortran::parser::InquireSpec>>(&stmt.u)) 1757 genIoConditionBranches(getEval(), *specs, iostat); 1758 } 1759 void genFIR(const Fortran::parser::OpenStmt &stmt) { 1760 mlir::Value iostat = genOpenStatement(*this, stmt); 1761 genIoConditionBranches(getEval(), stmt.v, iostat); 1762 } 1763 void genFIR(const Fortran::parser::PrintStmt &stmt) { 1764 genPrintStatement(*this, stmt); 1765 } 1766 void genFIR(const Fortran::parser::ReadStmt &stmt) { 1767 mlir::Value iostat = genReadStatement(*this, stmt); 1768 genIoConditionBranches(getEval(), stmt.controls, iostat); 1769 } 1770 void genFIR(const Fortran::parser::RewindStmt &stmt) { 1771 mlir::Value iostat = genRewindStatement(*this, stmt); 1772 genIoConditionBranches(getEval(), stmt.v, iostat); 1773 } 1774 void genFIR(const Fortran::parser::WaitStmt &stmt) { 1775 mlir::Value iostat = genWaitStatement(*this, stmt); 1776 genIoConditionBranches(getEval(), stmt.v, iostat); 1777 } 1778 void genFIR(const Fortran::parser::WriteStmt &stmt) { 1779 mlir::Value iostat = genWriteStatement(*this, stmt); 1780 genIoConditionBranches(getEval(), stmt.controls, iostat); 1781 } 1782 1783 template <typename A> 1784 void genIoConditionBranches(Fortran::lower::pft::Evaluation &eval, 1785 const A &specList, mlir::Value iostat) { 1786 if (!iostat) 1787 return; 1788 1789 mlir::Block *endBlock = nullptr; 1790 mlir::Block *eorBlock = nullptr; 1791 mlir::Block *errBlock = nullptr; 1792 for (const auto &spec : specList) { 1793 std::visit(Fortran::common::visitors{ 1794 [&](const Fortran::parser::EndLabel &label) { 1795 endBlock = blockOfLabel(eval, label.v); 1796 }, 1797 [&](const Fortran::parser::EorLabel &label) { 1798 eorBlock = blockOfLabel(eval, label.v); 1799 }, 1800 [&](const Fortran::parser::ErrLabel &label) { 1801 errBlock = blockOfLabel(eval, label.v); 1802 }, 1803 [](const auto &) {}}, 1804 spec.u); 1805 } 1806 if (!endBlock && !eorBlock && !errBlock) 1807 return; 1808 1809 mlir::Location loc = toLocation(); 1810 mlir::Type indexType = builder->getIndexType(); 1811 mlir::Value selector = builder->createConvert(loc, indexType, iostat); 1812 llvm::SmallVector<int64_t> indexList; 1813 llvm::SmallVector<mlir::Block *> blockList; 1814 if (eorBlock) { 1815 indexList.push_back(Fortran::runtime::io::IostatEor); 1816 blockList.push_back(eorBlock); 1817 } 1818 if (endBlock) { 1819 indexList.push_back(Fortran::runtime::io::IostatEnd); 1820 blockList.push_back(endBlock); 1821 } 1822 if (errBlock) { 1823 indexList.push_back(0); 1824 blockList.push_back(eval.nonNopSuccessor().block); 1825 // ERR label statement is the default successor. 1826 blockList.push_back(errBlock); 1827 } else { 1828 // Fallthrough successor statement is the default successor. 1829 blockList.push_back(eval.nonNopSuccessor().block); 1830 } 1831 builder->create<fir::SelectOp>(loc, selector, indexList, blockList); 1832 } 1833 1834 //===--------------------------------------------------------------------===// 1835 // Memory allocation and deallocation 1836 //===--------------------------------------------------------------------===// 1837 1838 void genFIR(const Fortran::parser::AllocateStmt &stmt) { 1839 Fortran::lower::genAllocateStmt(*this, stmt, toLocation()); 1840 } 1841 1842 void genFIR(const Fortran::parser::DeallocateStmt &stmt) { 1843 Fortran::lower::genDeallocateStmt(*this, stmt, toLocation()); 1844 } 1845 1846 /// Nullify pointer object list 1847 /// 1848 /// For each pointer object, reset the pointer to a disassociated status. 1849 /// We do this by setting each pointer to null. 1850 void genFIR(const Fortran::parser::NullifyStmt &stmt) { 1851 mlir::Location loc = toLocation(); 1852 for (auto &pointerObject : stmt.v) { 1853 const Fortran::lower::SomeExpr *expr = 1854 Fortran::semantics::GetExpr(pointerObject); 1855 assert(expr); 1856 fir::MutableBoxValue box = genExprMutableBox(loc, *expr); 1857 fir::factory::disassociateMutableBox(*builder, loc, box); 1858 } 1859 } 1860 1861 //===--------------------------------------------------------------------===// 1862 1863 void genFIR(const Fortran::parser::EventPostStmt &stmt) { 1864 genEventPostStatement(*this, stmt); 1865 } 1866 1867 void genFIR(const Fortran::parser::EventWaitStmt &stmt) { 1868 genEventWaitStatement(*this, stmt); 1869 } 1870 1871 void genFIR(const Fortran::parser::FormTeamStmt &stmt) { 1872 genFormTeamStatement(*this, getEval(), stmt); 1873 } 1874 1875 void genFIR(const Fortran::parser::LockStmt &stmt) { 1876 genLockStatement(*this, stmt); 1877 } 1878 1879 fir::ExtendedValue 1880 genInitializerExprValue(const Fortran::lower::SomeExpr &expr, 1881 Fortran::lower::StatementContext &stmtCtx) { 1882 return Fortran::lower::createSomeInitializerExpression( 1883 toLocation(), *this, expr, localSymbols, stmtCtx); 1884 } 1885 1886 /// Return true if the current context is a conditionalized and implied 1887 /// iteration space. 1888 bool implicitIterationSpace() { return !implicitIterSpace.empty(); } 1889 1890 /// Return true if context is currently an explicit iteration space. A scalar 1891 /// assignment expression may be contextually within a user-defined iteration 1892 /// space, transforming it into an array expression. 1893 bool explicitIterationSpace() { return explicitIterSpace.isActive(); } 1894 1895 /// Generate an array assignment. 1896 /// This is an assignment expression with rank > 0. The assignment may or may 1897 /// not be in a WHERE and/or FORALL context. 1898 /// In a FORALL context, the assignment may be a pointer assignment and the \p 1899 /// lbounds and \p ubounds parameters should only be used in such a pointer 1900 /// assignment case. (If both are None then the array assignment cannot be a 1901 /// pointer assignment.) 1902 void genArrayAssignment( 1903 const Fortran::evaluate::Assignment &assign, 1904 Fortran::lower::StatementContext &stmtCtx, 1905 llvm::Optional<llvm::SmallVector<mlir::Value>> lbounds = llvm::None, 1906 llvm::Optional<llvm::SmallVector<mlir::Value>> ubounds = llvm::None) { 1907 if (Fortran::lower::isWholeAllocatable(assign.lhs)) { 1908 // Assignment to allocatables may require the lhs to be 1909 // deallocated/reallocated. See Fortran 2018 10.2.1.3 p3 1910 Fortran::lower::createAllocatableArrayAssignment( 1911 *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace, 1912 localSymbols, stmtCtx); 1913 return; 1914 } 1915 1916 if (lbounds.hasValue()) { 1917 // Array of POINTER entities, with elemental assignment. 1918 if (!Fortran::lower::isWholePointer(assign.lhs)) 1919 fir::emitFatalError(toLocation(), "pointer assignment to non-pointer"); 1920 1921 Fortran::lower::createArrayOfPointerAssignment( 1922 *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace, 1923 lbounds.getValue(), ubounds, localSymbols, stmtCtx); 1924 return; 1925 } 1926 1927 if (!implicitIterationSpace() && !explicitIterationSpace()) { 1928 // No masks and the iteration space is implied by the array, so create a 1929 // simple array assignment. 1930 Fortran::lower::createSomeArrayAssignment(*this, assign.lhs, assign.rhs, 1931 localSymbols, stmtCtx); 1932 return; 1933 } 1934 1935 // If there is an explicit iteration space, generate an array assignment 1936 // with a user-specified iteration space and possibly with masks. These 1937 // assignments may *appear* to be scalar expressions, but the scalar 1938 // expression is evaluated at all points in the user-defined space much like 1939 // an ordinary array assignment. More specifically, the semantics inside the 1940 // FORALL much more closely resembles that of WHERE than a scalar 1941 // assignment. 1942 // Otherwise, generate a masked array assignment. The iteration space is 1943 // implied by the lhs array expression. 1944 Fortran::lower::createAnyMaskedArrayAssignment( 1945 *this, assign.lhs, assign.rhs, explicitIterSpace, implicitIterSpace, 1946 localSymbols, 1947 explicitIterationSpace() ? explicitIterSpace.stmtContext() 1948 : implicitIterSpace.stmtContext()); 1949 } 1950 1951 #if !defined(NDEBUG) 1952 static bool isFuncResultDesignator(const Fortran::lower::SomeExpr &expr) { 1953 const Fortran::semantics::Symbol *sym = 1954 Fortran::evaluate::GetFirstSymbol(expr); 1955 return sym && sym->IsFuncResult(); 1956 } 1957 #endif 1958 1959 inline fir::MutableBoxValue 1960 genExprMutableBox(mlir::Location loc, 1961 const Fortran::lower::SomeExpr &expr) override final { 1962 return Fortran::lower::createMutableBox(loc, *this, expr, localSymbols); 1963 } 1964 1965 /// Shared for both assignments and pointer assignments. 1966 void genAssignment(const Fortran::evaluate::Assignment &assign) { 1967 Fortran::lower::StatementContext stmtCtx; 1968 mlir::Location loc = toLocation(); 1969 if (explicitIterationSpace()) { 1970 Fortran::lower::createArrayLoads(*this, explicitIterSpace, localSymbols); 1971 explicitIterSpace.genLoopNest(); 1972 } 1973 std::visit( 1974 Fortran::common::visitors{ 1975 // [1] Plain old assignment. 1976 [&](const Fortran::evaluate::Assignment::Intrinsic &) { 1977 const Fortran::semantics::Symbol *sym = 1978 Fortran::evaluate::GetLastSymbol(assign.lhs); 1979 1980 if (!sym) 1981 TODO(loc, "assignment to pointer result of function reference"); 1982 1983 std::optional<Fortran::evaluate::DynamicType> lhsType = 1984 assign.lhs.GetType(); 1985 assert(lhsType && "lhs cannot be typeless"); 1986 // Assignment to polymorphic allocatables may require changing the 1987 // variable dynamic type (See Fortran 2018 10.2.1.3 p3). 1988 if (lhsType->IsPolymorphic() && 1989 Fortran::lower::isWholeAllocatable(assign.lhs)) 1990 TODO(loc, "assignment to polymorphic allocatable"); 1991 1992 // Note: No ad-hoc handling for pointers is required here. The 1993 // target will be assigned as per 2018 10.2.1.3 p2. genExprAddr 1994 // on a pointer returns the target address and not the address of 1995 // the pointer variable. 1996 1997 if (assign.lhs.Rank() > 0 || explicitIterationSpace()) { 1998 // Array assignment 1999 // See Fortran 2018 10.2.1.3 p5, p6, and p7 2000 genArrayAssignment(assign, stmtCtx); 2001 return; 2002 } 2003 2004 // Scalar assignment 2005 const bool isNumericScalar = 2006 isNumericScalarCategory(lhsType->category()); 2007 fir::ExtendedValue rhs = isNumericScalar 2008 ? genExprValue(assign.rhs, stmtCtx) 2009 : genExprAddr(assign.rhs, stmtCtx); 2010 const bool lhsIsWholeAllocatable = 2011 Fortran::lower::isWholeAllocatable(assign.lhs); 2012 llvm::Optional<fir::factory::MutableBoxReallocation> lhsRealloc; 2013 llvm::Optional<fir::MutableBoxValue> lhsMutableBox; 2014 auto lhs = [&]() -> fir::ExtendedValue { 2015 if (lhsIsWholeAllocatable) { 2016 lhsMutableBox = genExprMutableBox(loc, assign.lhs); 2017 llvm::SmallVector<mlir::Value> lengthParams; 2018 if (const fir::CharBoxValue *charBox = rhs.getCharBox()) 2019 lengthParams.push_back(charBox->getLen()); 2020 else if (fir::isDerivedWithLenParameters(rhs)) 2021 TODO(loc, "assignment to derived type allocatable with " 2022 "length parameters"); 2023 lhsRealloc = fir::factory::genReallocIfNeeded( 2024 *builder, loc, *lhsMutableBox, 2025 /*shape=*/llvm::None, lengthParams); 2026 return lhsRealloc->newValue; 2027 } 2028 return genExprAddr(assign.lhs, stmtCtx); 2029 }(); 2030 2031 if (isNumericScalar) { 2032 // Fortran 2018 10.2.1.3 p8 and p9 2033 // Conversions should have been inserted by semantic analysis, 2034 // but they can be incorrect between the rhs and lhs. Correct 2035 // that here. 2036 mlir::Value addr = fir::getBase(lhs); 2037 mlir::Value val = fir::getBase(rhs); 2038 // A function with multiple entry points returning different 2039 // types tags all result variables with one of the largest 2040 // types to allow them to share the same storage. Assignment 2041 // to a result variable of one of the other types requires 2042 // conversion to the actual type. 2043 mlir::Type toTy = genType(assign.lhs); 2044 mlir::Value cast = 2045 builder->convertWithSemantics(loc, toTy, val); 2046 if (fir::dyn_cast_ptrEleTy(addr.getType()) != toTy) { 2047 assert(isFuncResultDesignator(assign.lhs) && "type mismatch"); 2048 addr = builder->createConvert( 2049 toLocation(), builder->getRefType(toTy), addr); 2050 } 2051 builder->create<fir::StoreOp>(loc, cast, addr); 2052 } else if (isCharacterCategory(lhsType->category())) { 2053 // Fortran 2018 10.2.1.3 p10 and p11 2054 fir::factory::CharacterExprHelper{*builder, loc}.createAssign( 2055 lhs, rhs); 2056 } else if (isDerivedCategory(lhsType->category())) { 2057 // Fortran 2018 10.2.1.3 p13 and p14 2058 // Recursively gen an assignment on each element pair. 2059 fir::factory::genRecordAssignment(*builder, loc, lhs, rhs); 2060 } else { 2061 llvm_unreachable("unknown category"); 2062 } 2063 if (lhsIsWholeAllocatable) 2064 fir::factory::finalizeRealloc( 2065 *builder, loc, lhsMutableBox.getValue(), 2066 /*lbounds=*/llvm::None, /*takeLboundsIfRealloc=*/false, 2067 lhsRealloc.getValue()); 2068 }, 2069 2070 // [2] User defined assignment. If the context is a scalar 2071 // expression then call the procedure. 2072 [&](const Fortran::evaluate::ProcedureRef &procRef) { 2073 Fortran::lower::StatementContext &ctx = 2074 explicitIterationSpace() ? explicitIterSpace.stmtContext() 2075 : stmtCtx; 2076 Fortran::lower::createSubroutineCall( 2077 *this, procRef, explicitIterSpace, implicitIterSpace, 2078 localSymbols, ctx, /*isUserDefAssignment=*/true); 2079 }, 2080 2081 // [3] Pointer assignment with possibly empty bounds-spec. R1035: a 2082 // bounds-spec is a lower bound value. 2083 [&](const Fortran::evaluate::Assignment::BoundsSpec &lbExprs) { 2084 if (Fortran::evaluate::IsProcedure(assign.rhs)) 2085 TODO(loc, "procedure pointer assignment"); 2086 std::optional<Fortran::evaluate::DynamicType> lhsType = 2087 assign.lhs.GetType(); 2088 std::optional<Fortran::evaluate::DynamicType> rhsType = 2089 assign.rhs.GetType(); 2090 // Polymorphic lhs/rhs may need more care. See F2018 10.2.2.3. 2091 if ((lhsType && lhsType->IsPolymorphic()) || 2092 (rhsType && rhsType->IsPolymorphic())) 2093 TODO(loc, "pointer assignment involving polymorphic entity"); 2094 2095 llvm::SmallVector<mlir::Value> lbounds; 2096 for (const Fortran::evaluate::ExtentExpr &lbExpr : lbExprs) 2097 lbounds.push_back( 2098 fir::getBase(genExprValue(toEvExpr(lbExpr), stmtCtx))); 2099 if (explicitIterationSpace()) { 2100 // Pointer assignment in FORALL context. Copy the rhs box value 2101 // into the lhs box variable. 2102 genArrayAssignment(assign, stmtCtx, lbounds); 2103 return; 2104 } 2105 fir::MutableBoxValue lhs = genExprMutableBox(loc, assign.lhs); 2106 Fortran::lower::associateMutableBox(*this, loc, lhs, assign.rhs, 2107 lbounds, stmtCtx); 2108 }, 2109 2110 // [4] Pointer assignment with bounds-remapping. R1036: a 2111 // bounds-remapping is a pair, lower bound and upper bound. 2112 [&](const Fortran::evaluate::Assignment::BoundsRemapping 2113 &boundExprs) { 2114 std::optional<Fortran::evaluate::DynamicType> lhsType = 2115 assign.lhs.GetType(); 2116 std::optional<Fortran::evaluate::DynamicType> rhsType = 2117 assign.rhs.GetType(); 2118 // Polymorphic lhs/rhs may need more care. See F2018 10.2.2.3. 2119 if ((lhsType && lhsType->IsPolymorphic()) || 2120 (rhsType && rhsType->IsPolymorphic())) 2121 TODO(loc, "pointer assignment involving polymorphic entity"); 2122 2123 llvm::SmallVector<mlir::Value> lbounds; 2124 llvm::SmallVector<mlir::Value> ubounds; 2125 for (const std::pair<Fortran::evaluate::ExtentExpr, 2126 Fortran::evaluate::ExtentExpr> &pair : 2127 boundExprs) { 2128 const Fortran::evaluate::ExtentExpr &lbExpr = pair.first; 2129 const Fortran::evaluate::ExtentExpr &ubExpr = pair.second; 2130 lbounds.push_back( 2131 fir::getBase(genExprValue(toEvExpr(lbExpr), stmtCtx))); 2132 ubounds.push_back( 2133 fir::getBase(genExprValue(toEvExpr(ubExpr), stmtCtx))); 2134 } 2135 if (explicitIterationSpace()) { 2136 // Pointer assignment in FORALL context. Copy the rhs box value 2137 // into the lhs box variable. 2138 genArrayAssignment(assign, stmtCtx, lbounds, ubounds); 2139 return; 2140 } 2141 fir::MutableBoxValue lhs = genExprMutableBox(loc, assign.lhs); 2142 if (Fortran::evaluate::UnwrapExpr<Fortran::evaluate::NullPointer>( 2143 assign.rhs)) { 2144 fir::factory::disassociateMutableBox(*builder, loc, lhs); 2145 return; 2146 } 2147 // Do not generate a temp in case rhs is an array section. 2148 fir::ExtendedValue rhs = 2149 Fortran::lower::isArraySectionWithoutVectorSubscript( 2150 assign.rhs) 2151 ? Fortran::lower::createSomeArrayBox( 2152 *this, assign.rhs, localSymbols, stmtCtx) 2153 : genExprAddr(assign.rhs, stmtCtx); 2154 fir::factory::associateMutableBoxWithRemap(*builder, loc, lhs, 2155 rhs, lbounds, ubounds); 2156 if (explicitIterationSpace()) { 2157 mlir::ValueRange inners = explicitIterSpace.getInnerArgs(); 2158 if (!inners.empty()) 2159 builder->create<fir::ResultOp>(loc, inners); 2160 } 2161 }, 2162 }, 2163 assign.u); 2164 if (explicitIterationSpace()) 2165 Fortran::lower::createArrayMergeStores(*this, explicitIterSpace); 2166 } 2167 2168 void genFIR(const Fortran::parser::WhereConstruct &c) { 2169 implicitIterSpace.growStack(); 2170 genNestedStatement( 2171 std::get< 2172 Fortran::parser::Statement<Fortran::parser::WhereConstructStmt>>( 2173 c.t)); 2174 for (const auto &body : 2175 std::get<std::list<Fortran::parser::WhereBodyConstruct>>(c.t)) 2176 genFIR(body); 2177 for (const auto &e : 2178 std::get<std::list<Fortran::parser::WhereConstruct::MaskedElsewhere>>( 2179 c.t)) 2180 genFIR(e); 2181 if (const auto &e = 2182 std::get<std::optional<Fortran::parser::WhereConstruct::Elsewhere>>( 2183 c.t); 2184 e.has_value()) 2185 genFIR(*e); 2186 genNestedStatement( 2187 std::get<Fortran::parser::Statement<Fortran::parser::EndWhereStmt>>( 2188 c.t)); 2189 } 2190 void genFIR(const Fortran::parser::WhereBodyConstruct &body) { 2191 std::visit( 2192 Fortran::common::visitors{ 2193 [&](const Fortran::parser::Statement< 2194 Fortran::parser::AssignmentStmt> &stmt) { 2195 genNestedStatement(stmt); 2196 }, 2197 [&](const Fortran::parser::Statement<Fortran::parser::WhereStmt> 2198 &stmt) { genNestedStatement(stmt); }, 2199 [&](const Fortran::common::Indirection< 2200 Fortran::parser::WhereConstruct> &c) { genFIR(c.value()); }, 2201 }, 2202 body.u); 2203 } 2204 void genFIR(const Fortran::parser::WhereConstructStmt &stmt) { 2205 implicitIterSpace.append(Fortran::semantics::GetExpr( 2206 std::get<Fortran::parser::LogicalExpr>(stmt.t))); 2207 } 2208 void genFIR(const Fortran::parser::WhereConstruct::MaskedElsewhere &ew) { 2209 genNestedStatement( 2210 std::get< 2211 Fortran::parser::Statement<Fortran::parser::MaskedElsewhereStmt>>( 2212 ew.t)); 2213 for (const auto &body : 2214 std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t)) 2215 genFIR(body); 2216 } 2217 void genFIR(const Fortran::parser::MaskedElsewhereStmt &stmt) { 2218 implicitIterSpace.append(Fortran::semantics::GetExpr( 2219 std::get<Fortran::parser::LogicalExpr>(stmt.t))); 2220 } 2221 void genFIR(const Fortran::parser::WhereConstruct::Elsewhere &ew) { 2222 genNestedStatement( 2223 std::get<Fortran::parser::Statement<Fortran::parser::ElsewhereStmt>>( 2224 ew.t)); 2225 for (const auto &body : 2226 std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t)) 2227 genFIR(body); 2228 } 2229 void genFIR(const Fortran::parser::ElsewhereStmt &stmt) { 2230 implicitIterSpace.append(nullptr); 2231 } 2232 void genFIR(const Fortran::parser::EndWhereStmt &) { 2233 implicitIterSpace.shrinkStack(); 2234 } 2235 2236 void genFIR(const Fortran::parser::WhereStmt &stmt) { 2237 Fortran::lower::StatementContext stmtCtx; 2238 const auto &assign = std::get<Fortran::parser::AssignmentStmt>(stmt.t); 2239 implicitIterSpace.growStack(); 2240 implicitIterSpace.append(Fortran::semantics::GetExpr( 2241 std::get<Fortran::parser::LogicalExpr>(stmt.t))); 2242 genAssignment(*assign.typedAssignment->v); 2243 implicitIterSpace.shrinkStack(); 2244 } 2245 2246 void genFIR(const Fortran::parser::PointerAssignmentStmt &stmt) { 2247 genAssignment(*stmt.typedAssignment->v); 2248 } 2249 2250 void genFIR(const Fortran::parser::AssignmentStmt &stmt) { 2251 genAssignment(*stmt.typedAssignment->v); 2252 } 2253 2254 void genFIR(const Fortran::parser::SyncAllStmt &stmt) { 2255 genSyncAllStatement(*this, stmt); 2256 } 2257 2258 void genFIR(const Fortran::parser::SyncImagesStmt &stmt) { 2259 genSyncImagesStatement(*this, stmt); 2260 } 2261 2262 void genFIR(const Fortran::parser::SyncMemoryStmt &stmt) { 2263 genSyncMemoryStatement(*this, stmt); 2264 } 2265 2266 void genFIR(const Fortran::parser::SyncTeamStmt &stmt) { 2267 genSyncTeamStatement(*this, stmt); 2268 } 2269 2270 void genFIR(const Fortran::parser::UnlockStmt &stmt) { 2271 genUnlockStatement(*this, stmt); 2272 } 2273 2274 void genFIR(const Fortran::parser::AssignStmt &stmt) { 2275 const Fortran::semantics::Symbol &symbol = 2276 *std::get<Fortran::parser::Name>(stmt.t).symbol; 2277 mlir::Location loc = toLocation(); 2278 mlir::Value labelValue = builder->createIntegerConstant( 2279 loc, genType(symbol), std::get<Fortran::parser::Label>(stmt.t)); 2280 builder->create<fir::StoreOp>(loc, labelValue, getSymbolAddress(symbol)); 2281 } 2282 2283 void genFIR(const Fortran::parser::FormatStmt &) { 2284 // do nothing. 2285 2286 // FORMAT statements have no semantics. They may be lowered if used by a 2287 // data transfer statement. 2288 } 2289 2290 void genFIR(const Fortran::parser::PauseStmt &stmt) { 2291 genPauseStatement(*this, stmt); 2292 } 2293 2294 // call FAIL IMAGE in runtime 2295 void genFIR(const Fortran::parser::FailImageStmt &stmt) { 2296 genFailImageStatement(*this); 2297 } 2298 2299 // call STOP, ERROR STOP in runtime 2300 void genFIR(const Fortran::parser::StopStmt &stmt) { 2301 genStopStatement(*this, stmt); 2302 } 2303 2304 void genFIR(const Fortran::parser::ReturnStmt &stmt) { 2305 Fortran::lower::pft::FunctionLikeUnit *funit = 2306 getEval().getOwningProcedure(); 2307 assert(funit && "not inside main program, function or subroutine"); 2308 if (funit->isMainProgram()) { 2309 genExitRoutine(); 2310 return; 2311 } 2312 mlir::Location loc = toLocation(); 2313 if (stmt.v) { 2314 // Alternate return statement - If this is a subroutine where some 2315 // alternate entries have alternate returns, but the active entry point 2316 // does not, ignore the alternate return value. Otherwise, assign it 2317 // to the compiler-generated result variable. 2318 const Fortran::semantics::Symbol &symbol = funit->getSubprogramSymbol(); 2319 if (Fortran::semantics::HasAlternateReturns(symbol)) { 2320 Fortran::lower::StatementContext stmtCtx; 2321 const Fortran::lower::SomeExpr *expr = 2322 Fortran::semantics::GetExpr(*stmt.v); 2323 assert(expr && "missing alternate return expression"); 2324 mlir::Value altReturnIndex = builder->createConvert( 2325 loc, builder->getIndexType(), createFIRExpr(loc, expr, stmtCtx)); 2326 builder->create<fir::StoreOp>(loc, altReturnIndex, 2327 getAltReturnResult(symbol)); 2328 } 2329 } 2330 // Branch to the last block of the SUBROUTINE, which has the actual return. 2331 if (!funit->finalBlock) { 2332 mlir::OpBuilder::InsertPoint insPt = builder->saveInsertionPoint(); 2333 funit->finalBlock = builder->createBlock(&builder->getRegion()); 2334 builder->restoreInsertionPoint(insPt); 2335 } 2336 builder->create<mlir::cf::BranchOp>(loc, funit->finalBlock); 2337 } 2338 2339 void genFIR(const Fortran::parser::CycleStmt &) { 2340 genFIRBranch(getEval().controlSuccessor->block); 2341 } 2342 void genFIR(const Fortran::parser::ExitStmt &) { 2343 genFIRBranch(getEval().controlSuccessor->block); 2344 } 2345 void genFIR(const Fortran::parser::GotoStmt &) { 2346 genFIRBranch(getEval().controlSuccessor->block); 2347 } 2348 2349 // Nop statements - No code, or code is generated at the construct level. 2350 void genFIR(const Fortran::parser::AssociateStmt &) {} // nop 2351 void genFIR(const Fortran::parser::CaseStmt &) {} // nop 2352 void genFIR(const Fortran::parser::ContinueStmt &) {} // nop 2353 void genFIR(const Fortran::parser::ElseIfStmt &) {} // nop 2354 void genFIR(const Fortran::parser::ElseStmt &) {} // nop 2355 void genFIR(const Fortran::parser::EndAssociateStmt &) {} // nop 2356 void genFIR(const Fortran::parser::EndDoStmt &) {} // nop 2357 void genFIR(const Fortran::parser::EndFunctionStmt &) {} // nop 2358 void genFIR(const Fortran::parser::EndIfStmt &) {} // nop 2359 void genFIR(const Fortran::parser::EndMpSubprogramStmt &) {} // nop 2360 void genFIR(const Fortran::parser::EndSelectStmt &) {} // nop 2361 void genFIR(const Fortran::parser::EndSubroutineStmt &) {} // nop 2362 void genFIR(const Fortran::parser::EntryStmt &) {} // nop 2363 void genFIR(const Fortran::parser::IfStmt &) {} // nop 2364 void genFIR(const Fortran::parser::IfThenStmt &) {} // nop 2365 void genFIR(const Fortran::parser::NonLabelDoStmt &) {} // nop 2366 void genFIR(const Fortran::parser::OmpEndLoopDirective &) {} // nop 2367 2368 void genFIR(const Fortran::parser::NamelistStmt &) { 2369 TODO(toLocation(), "NamelistStmt lowering"); 2370 } 2371 2372 /// Generate FIR for the Evaluation `eval`. 2373 void genFIR(Fortran::lower::pft::Evaluation &eval, 2374 bool unstructuredContext = true) { 2375 if (unstructuredContext) { 2376 // When transitioning from unstructured to structured code, 2377 // the structured code could be a target that starts a new block. 2378 maybeStartBlock(eval.isConstruct() && eval.lowerAsStructured() 2379 ? eval.getFirstNestedEvaluation().block 2380 : eval.block); 2381 } 2382 2383 setCurrentEval(eval); 2384 setCurrentPosition(eval.position); 2385 eval.visit([&](const auto &stmt) { genFIR(stmt); }); 2386 2387 if (unstructuredContext && blockIsUnterminated()) { 2388 // Exit from an unstructured IF or SELECT construct block. 2389 Fortran::lower::pft::Evaluation *successor{}; 2390 if (eval.isActionStmt()) 2391 successor = eval.controlSuccessor; 2392 else if (eval.isConstruct() && 2393 eval.getLastNestedEvaluation() 2394 .lexicalSuccessor->isIntermediateConstructStmt()) 2395 successor = eval.constructExit; 2396 if (successor && successor->block) 2397 genFIRBranch(successor->block); 2398 } 2399 } 2400 2401 /// Map mlir function block arguments to the corresponding Fortran dummy 2402 /// variables. When the result is passed as a hidden argument, the Fortran 2403 /// result is also mapped. The symbol map is used to hold this mapping. 2404 void mapDummiesAndResults(Fortran::lower::pft::FunctionLikeUnit &funit, 2405 const Fortran::lower::CalleeInterface &callee) { 2406 assert(builder && "require a builder object at this point"); 2407 using PassBy = Fortran::lower::CalleeInterface::PassEntityBy; 2408 auto mapPassedEntity = [&](const auto arg) { 2409 if (arg.passBy == PassBy::AddressAndLength) { 2410 // TODO: now that fir call has some attributes regarding character 2411 // return, PassBy::AddressAndLength should be retired. 2412 mlir::Location loc = toLocation(); 2413 fir::factory::CharacterExprHelper charHelp{*builder, loc}; 2414 mlir::Value box = 2415 charHelp.createEmboxChar(arg.firArgument, arg.firLength); 2416 addSymbol(arg.entity->get(), box); 2417 } else { 2418 if (arg.entity.has_value()) { 2419 addSymbol(arg.entity->get(), arg.firArgument); 2420 } else { 2421 assert(funit.parentHasHostAssoc()); 2422 funit.parentHostAssoc().internalProcedureBindings(*this, 2423 localSymbols); 2424 } 2425 } 2426 }; 2427 for (const Fortran::lower::CalleeInterface::PassedEntity &arg : 2428 callee.getPassedArguments()) 2429 mapPassedEntity(arg); 2430 if (std::optional<Fortran::lower::CalleeInterface::PassedEntity> 2431 passedResult = callee.getPassedResult()) { 2432 mapPassedEntity(*passedResult); 2433 // FIXME: need to make sure things are OK here. addSymbol may not be OK 2434 if (funit.primaryResult && 2435 passedResult->entity->get() != *funit.primaryResult) 2436 addSymbol(*funit.primaryResult, 2437 getSymbolAddress(passedResult->entity->get())); 2438 } 2439 } 2440 2441 /// Instantiate variable \p var and add it to the symbol map. 2442 /// See ConvertVariable.cpp. 2443 void instantiateVar(const Fortran::lower::pft::Variable &var, 2444 Fortran::lower::AggregateStoreMap &storeMap) { 2445 Fortran::lower::instantiateVariable(*this, var, localSymbols, storeMap); 2446 } 2447 2448 /// Prepare to translate a new function 2449 void startNewFunction(Fortran::lower::pft::FunctionLikeUnit &funit) { 2450 assert(!builder && "expected nullptr"); 2451 Fortran::lower::CalleeInterface callee(funit, *this); 2452 mlir::func::FuncOp func = callee.addEntryBlockAndMapArguments(); 2453 builder = new fir::FirOpBuilder(func, bridge.getKindMap()); 2454 assert(builder && "FirOpBuilder did not instantiate"); 2455 builder->setInsertionPointToStart(&func.front()); 2456 func.setVisibility(mlir::SymbolTable::Visibility::Public); 2457 2458 mapDummiesAndResults(funit, callee); 2459 2460 // Note: not storing Variable references because getOrderedSymbolTable 2461 // below returns a temporary. 2462 llvm::SmallVector<Fortran::lower::pft::Variable> deferredFuncResultList; 2463 2464 // Backup actual argument for entry character results 2465 // with different lengths. It needs to be added to the non 2466 // primary results symbol before mapSymbolAttributes is called. 2467 Fortran::lower::SymbolBox resultArg; 2468 if (std::optional<Fortran::lower::CalleeInterface::PassedEntity> 2469 passedResult = callee.getPassedResult()) 2470 resultArg = lookupSymbol(passedResult->entity->get()); 2471 2472 Fortran::lower::AggregateStoreMap storeMap; 2473 // The front-end is currently not adding module variables referenced 2474 // in a module procedure as host associated. As a result we need to 2475 // instantiate all module variables here if this is a module procedure. 2476 // It is likely that the front-end behavior should change here. 2477 // This also applies to internal procedures inside module procedures. 2478 if (auto *module = Fortran::lower::pft::getAncestor< 2479 Fortran::lower::pft::ModuleLikeUnit>(funit)) 2480 for (const Fortran::lower::pft::Variable &var : 2481 module->getOrderedSymbolTable()) 2482 instantiateVar(var, storeMap); 2483 2484 mlir::Value primaryFuncResultStorage; 2485 for (const Fortran::lower::pft::Variable &var : 2486 funit.getOrderedSymbolTable()) { 2487 // Always instantiate aggregate storage blocks. 2488 if (var.isAggregateStore()) { 2489 instantiateVar(var, storeMap); 2490 continue; 2491 } 2492 const Fortran::semantics::Symbol &sym = var.getSymbol(); 2493 if (funit.parentHasHostAssoc()) { 2494 // Never instantitate host associated variables, as they are already 2495 // instantiated from an argument tuple. Instead, just bind the symbol to 2496 // the reference to the host variable, which must be in the map. 2497 const Fortran::semantics::Symbol &ultimate = sym.GetUltimate(); 2498 if (funit.parentHostAssoc().isAssociated(ultimate)) { 2499 Fortran::lower::SymbolBox hostBox = 2500 localSymbols.lookupSymbol(ultimate); 2501 assert(hostBox && "host association is not in map"); 2502 localSymbols.addSymbol(sym, hostBox.toExtendedValue()); 2503 continue; 2504 } 2505 } 2506 if (!sym.IsFuncResult() || !funit.primaryResult) { 2507 instantiateVar(var, storeMap); 2508 } else if (&sym == funit.primaryResult) { 2509 instantiateVar(var, storeMap); 2510 primaryFuncResultStorage = getSymbolAddress(sym); 2511 } else { 2512 deferredFuncResultList.push_back(var); 2513 } 2514 } 2515 2516 // TODO: should use same mechanism as equivalence? 2517 // One blocking point is character entry returns that need special handling 2518 // since they are not locally allocated but come as argument. CHARACTER(*) 2519 // is not something that fits well with equivalence lowering. 2520 for (const Fortran::lower::pft::Variable &altResult : 2521 deferredFuncResultList) { 2522 if (std::optional<Fortran::lower::CalleeInterface::PassedEntity> 2523 passedResult = callee.getPassedResult()) 2524 addSymbol(altResult.getSymbol(), resultArg.getAddr()); 2525 Fortran::lower::StatementContext stmtCtx; 2526 Fortran::lower::mapSymbolAttributes(*this, altResult, localSymbols, 2527 stmtCtx, primaryFuncResultStorage); 2528 } 2529 2530 // If this is a host procedure with host associations, then create the tuple 2531 // of pointers for passing to the internal procedures. 2532 if (!funit.getHostAssoc().empty()) 2533 funit.getHostAssoc().hostProcedureBindings(*this, localSymbols); 2534 2535 // Create most function blocks in advance. 2536 createEmptyBlocks(funit.evaluationList); 2537 2538 // Reinstate entry block as the current insertion point. 2539 builder->setInsertionPointToEnd(&func.front()); 2540 2541 if (callee.hasAlternateReturns()) { 2542 // Create a local temp to hold the alternate return index. 2543 // Give it an integer index type and the subroutine name (for dumps). 2544 // Attach it to the subroutine symbol in the localSymbols map. 2545 // Initialize it to zero, the "fallthrough" alternate return value. 2546 const Fortran::semantics::Symbol &symbol = funit.getSubprogramSymbol(); 2547 mlir::Location loc = toLocation(); 2548 mlir::Type idxTy = builder->getIndexType(); 2549 mlir::Value altResult = 2550 builder->createTemporary(loc, idxTy, toStringRef(symbol.name())); 2551 addSymbol(symbol, altResult); 2552 mlir::Value zero = builder->createIntegerConstant(loc, idxTy, 0); 2553 builder->create<fir::StoreOp>(loc, zero, altResult); 2554 } 2555 2556 if (Fortran::lower::pft::Evaluation *alternateEntryEval = 2557 funit.getEntryEval()) 2558 genFIRBranch(alternateEntryEval->lexicalSuccessor->block); 2559 } 2560 2561 /// Create global blocks for the current function. This eliminates the 2562 /// distinction between forward and backward targets when generating 2563 /// branches. A block is "global" if it can be the target of a GOTO or 2564 /// other source code branch. A block that can only be targeted by a 2565 /// compiler generated branch is "local". For example, a DO loop preheader 2566 /// block containing loop initialization code is global. A loop header 2567 /// block, which is the target of the loop back edge, is local. Blocks 2568 /// belong to a region. Any block within a nested region must be replaced 2569 /// with a block belonging to that region. Branches may not cross region 2570 /// boundaries. 2571 void createEmptyBlocks( 2572 std::list<Fortran::lower::pft::Evaluation> &evaluationList) { 2573 mlir::Region *region = &builder->getRegion(); 2574 for (Fortran::lower::pft::Evaluation &eval : evaluationList) { 2575 if (eval.isNewBlock) 2576 eval.block = builder->createBlock(region); 2577 if (eval.isConstruct() || eval.isDirective()) { 2578 if (eval.lowerAsUnstructured()) { 2579 createEmptyBlocks(eval.getNestedEvaluations()); 2580 } else if (eval.hasNestedEvaluations()) { 2581 // A structured construct that is a target starts a new block. 2582 Fortran::lower::pft::Evaluation &constructStmt = 2583 eval.getFirstNestedEvaluation(); 2584 if (constructStmt.isNewBlock) 2585 constructStmt.block = builder->createBlock(region); 2586 } 2587 } 2588 } 2589 } 2590 2591 /// Return the predicate: "current block does not have a terminator branch". 2592 bool blockIsUnterminated() { 2593 mlir::Block *currentBlock = builder->getBlock(); 2594 return currentBlock->empty() || 2595 !currentBlock->back().hasTrait<mlir::OpTrait::IsTerminator>(); 2596 } 2597 2598 /// Unconditionally switch code insertion to a new block. 2599 void startBlock(mlir::Block *newBlock) { 2600 assert(newBlock && "missing block"); 2601 // Default termination for the current block is a fallthrough branch to 2602 // the new block. 2603 if (blockIsUnterminated()) 2604 genFIRBranch(newBlock); 2605 // Some blocks may be re/started more than once, and might not be empty. 2606 // If the new block already has (only) a terminator, set the insertion 2607 // point to the start of the block. Otherwise set it to the end. 2608 builder->setInsertionPointToStart(newBlock); 2609 if (blockIsUnterminated()) 2610 builder->setInsertionPointToEnd(newBlock); 2611 } 2612 2613 /// Conditionally switch code insertion to a new block. 2614 void maybeStartBlock(mlir::Block *newBlock) { 2615 if (newBlock) 2616 startBlock(newBlock); 2617 } 2618 2619 /// Emit return and cleanup after the function has been translated. 2620 void endNewFunction(Fortran::lower::pft::FunctionLikeUnit &funit) { 2621 setCurrentPosition(Fortran::lower::pft::stmtSourceLoc(funit.endStmt)); 2622 if (funit.isMainProgram()) 2623 genExitRoutine(); 2624 else 2625 genFIRProcedureExit(funit, funit.getSubprogramSymbol()); 2626 funit.finalBlock = nullptr; 2627 LLVM_DEBUG(llvm::dbgs() << "*** Lowering result:\n\n" 2628 << *builder->getFunction() << '\n'); 2629 // FIXME: Simplification should happen in a normal pass, not here. 2630 mlir::IRRewriter rewriter(*builder); 2631 (void)mlir::simplifyRegions(rewriter, 2632 {builder->getRegion()}); // remove dead code 2633 delete builder; 2634 builder = nullptr; 2635 hostAssocTuple = mlir::Value{}; 2636 localSymbols.clear(); 2637 } 2638 2639 /// Helper to generate GlobalOps when the builder is not positioned in any 2640 /// region block. This is required because the FirOpBuilder assumes it is 2641 /// always positioned inside a region block when creating globals, the easiest 2642 /// way comply is to create a dummy function and to throw it afterwards. 2643 void createGlobalOutsideOfFunctionLowering( 2644 const std::function<void()> &createGlobals) { 2645 // FIXME: get rid of the bogus function context and instantiate the 2646 // globals directly into the module. 2647 mlir::MLIRContext *context = &getMLIRContext(); 2648 mlir::func::FuncOp func = fir::FirOpBuilder::createFunction( 2649 mlir::UnknownLoc::get(context), getModuleOp(), 2650 fir::NameUniquer::doGenerated("Sham"), 2651 mlir::FunctionType::get(context, llvm::None, llvm::None)); 2652 func.addEntryBlock(); 2653 builder = new fir::FirOpBuilder(func, bridge.getKindMap()); 2654 createGlobals(); 2655 if (mlir::Region *region = func.getCallableRegion()) 2656 region->dropAllReferences(); 2657 func.erase(); 2658 delete builder; 2659 builder = nullptr; 2660 localSymbols.clear(); 2661 } 2662 /// Instantiate the data from a BLOCK DATA unit. 2663 void lowerBlockData(Fortran::lower::pft::BlockDataUnit &bdunit) { 2664 createGlobalOutsideOfFunctionLowering([&]() { 2665 Fortran::lower::AggregateStoreMap fakeMap; 2666 for (const auto &[_, sym] : bdunit.symTab) { 2667 if (sym->has<Fortran::semantics::ObjectEntityDetails>()) { 2668 Fortran::lower::pft::Variable var(*sym, true); 2669 instantiateVar(var, fakeMap); 2670 } 2671 } 2672 }); 2673 } 2674 2675 /// Create fir::Global for all the common blocks that appear in the program. 2676 void 2677 lowerCommonBlocks(const Fortran::semantics::CommonBlockList &commonBlocks) { 2678 createGlobalOutsideOfFunctionLowering( 2679 [&]() { Fortran::lower::defineCommonBlocks(*this, commonBlocks); }); 2680 } 2681 2682 /// Lower a procedure (nest). 2683 void lowerFunc(Fortran::lower::pft::FunctionLikeUnit &funit) { 2684 if (!funit.isMainProgram()) { 2685 const Fortran::semantics::Symbol &procSymbol = 2686 funit.getSubprogramSymbol(); 2687 if (procSymbol.owner().IsSubmodule()) { 2688 TODO(toLocation(), "support submodules"); 2689 return; 2690 } 2691 } 2692 setCurrentPosition(funit.getStartingSourceLoc()); 2693 for (int entryIndex = 0, last = funit.entryPointList.size(); 2694 entryIndex < last; ++entryIndex) { 2695 funit.setActiveEntry(entryIndex); 2696 startNewFunction(funit); // the entry point for lowering this procedure 2697 for (Fortran::lower::pft::Evaluation &eval : funit.evaluationList) 2698 genFIR(eval); 2699 endNewFunction(funit); 2700 } 2701 funit.setActiveEntry(0); 2702 for (Fortran::lower::pft::FunctionLikeUnit &f : funit.nestedFunctions) 2703 lowerFunc(f); // internal procedure 2704 } 2705 2706 /// Lower module variable definitions to fir::globalOp and OpenMP/OpenACC 2707 /// declarative construct. 2708 void lowerModuleDeclScope(Fortran::lower::pft::ModuleLikeUnit &mod) { 2709 setCurrentPosition(mod.getStartingSourceLoc()); 2710 createGlobalOutsideOfFunctionLowering([&]() { 2711 for (const Fortran::lower::pft::Variable &var : 2712 mod.getOrderedSymbolTable()) { 2713 // Only define the variables owned by this module. 2714 const Fortran::semantics::Scope *owningScope = var.getOwningScope(); 2715 if (!owningScope || mod.getScope() == *owningScope) 2716 Fortran::lower::defineModuleVariable(*this, var); 2717 } 2718 for (auto &eval : mod.evaluationList) 2719 genFIR(eval); 2720 }); 2721 } 2722 2723 /// Lower functions contained in a module. 2724 void lowerMod(Fortran::lower::pft::ModuleLikeUnit &mod) { 2725 for (Fortran::lower::pft::FunctionLikeUnit &f : mod.nestedFunctions) 2726 lowerFunc(f); 2727 } 2728 2729 void setCurrentPosition(const Fortran::parser::CharBlock &position) { 2730 if (position != Fortran::parser::CharBlock{}) 2731 currentPosition = position; 2732 } 2733 2734 /// Set current position at the location of \p parseTreeNode. Note that the 2735 /// position is updated automatically when visiting statements, but not when 2736 /// entering higher level nodes like constructs or procedures. This helper is 2737 /// intended to cover the latter cases. 2738 template <typename A> 2739 void setCurrentPositionAt(const A &parseTreeNode) { 2740 setCurrentPosition(Fortran::parser::FindSourceLocation(parseTreeNode)); 2741 } 2742 2743 //===--------------------------------------------------------------------===// 2744 // Utility methods 2745 //===--------------------------------------------------------------------===// 2746 2747 /// Convert a parser CharBlock to a Location 2748 mlir::Location toLocation(const Fortran::parser::CharBlock &cb) { 2749 return genLocation(cb); 2750 } 2751 2752 mlir::Location toLocation() { return toLocation(currentPosition); } 2753 void setCurrentEval(Fortran::lower::pft::Evaluation &eval) { 2754 evalPtr = &eval; 2755 } 2756 Fortran::lower::pft::Evaluation &getEval() { 2757 assert(evalPtr); 2758 return *evalPtr; 2759 } 2760 2761 std::optional<Fortran::evaluate::Shape> 2762 getShape(const Fortran::lower::SomeExpr &expr) { 2763 return Fortran::evaluate::GetShape(foldingContext, expr); 2764 } 2765 2766 //===--------------------------------------------------------------------===// 2767 // Analysis on a nested explicit iteration space. 2768 //===--------------------------------------------------------------------===// 2769 2770 void analyzeExplicitSpace(const Fortran::parser::ConcurrentHeader &header) { 2771 explicitIterSpace.pushLevel(); 2772 for (const Fortran::parser::ConcurrentControl &ctrl : 2773 std::get<std::list<Fortran::parser::ConcurrentControl>>(header.t)) { 2774 const Fortran::semantics::Symbol *ctrlVar = 2775 std::get<Fortran::parser::Name>(ctrl.t).symbol; 2776 explicitIterSpace.addSymbol(ctrlVar); 2777 } 2778 if (const auto &mask = 2779 std::get<std::optional<Fortran::parser::ScalarLogicalExpr>>( 2780 header.t); 2781 mask.has_value()) 2782 analyzeExplicitSpace(*Fortran::semantics::GetExpr(*mask)); 2783 } 2784 template <bool LHS = false, typename A> 2785 void analyzeExplicitSpace(const Fortran::evaluate::Expr<A> &e) { 2786 explicitIterSpace.exprBase(&e, LHS); 2787 } 2788 void analyzeExplicitSpace(const Fortran::evaluate::Assignment *assign) { 2789 auto analyzeAssign = [&](const Fortran::lower::SomeExpr &lhs, 2790 const Fortran::lower::SomeExpr &rhs) { 2791 analyzeExplicitSpace</*LHS=*/true>(lhs); 2792 analyzeExplicitSpace(rhs); 2793 }; 2794 std::visit( 2795 Fortran::common::visitors{ 2796 [&](const Fortran::evaluate::ProcedureRef &procRef) { 2797 // Ensure the procRef expressions are the one being visited. 2798 assert(procRef.arguments().size() == 2); 2799 const Fortran::lower::SomeExpr *lhs = 2800 procRef.arguments()[0].value().UnwrapExpr(); 2801 const Fortran::lower::SomeExpr *rhs = 2802 procRef.arguments()[1].value().UnwrapExpr(); 2803 assert(lhs && rhs && 2804 "user defined assignment arguments must be expressions"); 2805 analyzeAssign(*lhs, *rhs); 2806 }, 2807 [&](const auto &) { analyzeAssign(assign->lhs, assign->rhs); }}, 2808 assign->u); 2809 explicitIterSpace.endAssign(); 2810 } 2811 void analyzeExplicitSpace(const Fortran::parser::ForallAssignmentStmt &stmt) { 2812 std::visit([&](const auto &s) { analyzeExplicitSpace(s); }, stmt.u); 2813 } 2814 void analyzeExplicitSpace(const Fortran::parser::AssignmentStmt &s) { 2815 analyzeExplicitSpace(s.typedAssignment->v.operator->()); 2816 } 2817 void analyzeExplicitSpace(const Fortran::parser::PointerAssignmentStmt &s) { 2818 analyzeExplicitSpace(s.typedAssignment->v.operator->()); 2819 } 2820 void analyzeExplicitSpace(const Fortran::parser::WhereConstruct &c) { 2821 analyzeExplicitSpace( 2822 std::get< 2823 Fortran::parser::Statement<Fortran::parser::WhereConstructStmt>>( 2824 c.t) 2825 .statement); 2826 for (const Fortran::parser::WhereBodyConstruct &body : 2827 std::get<std::list<Fortran::parser::WhereBodyConstruct>>(c.t)) 2828 analyzeExplicitSpace(body); 2829 for (const Fortran::parser::WhereConstruct::MaskedElsewhere &e : 2830 std::get<std::list<Fortran::parser::WhereConstruct::MaskedElsewhere>>( 2831 c.t)) 2832 analyzeExplicitSpace(e); 2833 if (const auto &e = 2834 std::get<std::optional<Fortran::parser::WhereConstruct::Elsewhere>>( 2835 c.t); 2836 e.has_value()) 2837 analyzeExplicitSpace(e.operator->()); 2838 } 2839 void analyzeExplicitSpace(const Fortran::parser::WhereConstructStmt &ws) { 2840 const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr( 2841 std::get<Fortran::parser::LogicalExpr>(ws.t)); 2842 addMaskVariable(exp); 2843 analyzeExplicitSpace(*exp); 2844 } 2845 void analyzeExplicitSpace( 2846 const Fortran::parser::WhereConstruct::MaskedElsewhere &ew) { 2847 analyzeExplicitSpace( 2848 std::get< 2849 Fortran::parser::Statement<Fortran::parser::MaskedElsewhereStmt>>( 2850 ew.t) 2851 .statement); 2852 for (const Fortran::parser::WhereBodyConstruct &e : 2853 std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew.t)) 2854 analyzeExplicitSpace(e); 2855 } 2856 void analyzeExplicitSpace(const Fortran::parser::WhereBodyConstruct &body) { 2857 std::visit(Fortran::common::visitors{ 2858 [&](const Fortran::common::Indirection< 2859 Fortran::parser::WhereConstruct> &wc) { 2860 analyzeExplicitSpace(wc.value()); 2861 }, 2862 [&](const auto &s) { analyzeExplicitSpace(s.statement); }}, 2863 body.u); 2864 } 2865 void analyzeExplicitSpace(const Fortran::parser::MaskedElsewhereStmt &stmt) { 2866 const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr( 2867 std::get<Fortran::parser::LogicalExpr>(stmt.t)); 2868 addMaskVariable(exp); 2869 analyzeExplicitSpace(*exp); 2870 } 2871 void 2872 analyzeExplicitSpace(const Fortran::parser::WhereConstruct::Elsewhere *ew) { 2873 for (const Fortran::parser::WhereBodyConstruct &e : 2874 std::get<std::list<Fortran::parser::WhereBodyConstruct>>(ew->t)) 2875 analyzeExplicitSpace(e); 2876 } 2877 void analyzeExplicitSpace(const Fortran::parser::WhereStmt &stmt) { 2878 const Fortran::lower::SomeExpr *exp = Fortran::semantics::GetExpr( 2879 std::get<Fortran::parser::LogicalExpr>(stmt.t)); 2880 addMaskVariable(exp); 2881 analyzeExplicitSpace(*exp); 2882 const std::optional<Fortran::evaluate::Assignment> &assign = 2883 std::get<Fortran::parser::AssignmentStmt>(stmt.t).typedAssignment->v; 2884 assert(assign.has_value() && "WHERE has no statement"); 2885 analyzeExplicitSpace(assign.operator->()); 2886 } 2887 void analyzeExplicitSpace(const Fortran::parser::ForallStmt &forall) { 2888 analyzeExplicitSpace( 2889 std::get< 2890 Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>( 2891 forall.t) 2892 .value()); 2893 analyzeExplicitSpace(std::get<Fortran::parser::UnlabeledStatement< 2894 Fortran::parser::ForallAssignmentStmt>>(forall.t) 2895 .statement); 2896 analyzeExplicitSpacePop(); 2897 } 2898 void 2899 analyzeExplicitSpace(const Fortran::parser::ForallConstructStmt &forall) { 2900 analyzeExplicitSpace( 2901 std::get< 2902 Fortran::common::Indirection<Fortran::parser::ConcurrentHeader>>( 2903 forall.t) 2904 .value()); 2905 } 2906 void analyzeExplicitSpace(const Fortran::parser::ForallConstruct &forall) { 2907 analyzeExplicitSpace( 2908 std::get< 2909 Fortran::parser::Statement<Fortran::parser::ForallConstructStmt>>( 2910 forall.t) 2911 .statement); 2912 for (const Fortran::parser::ForallBodyConstruct &s : 2913 std::get<std::list<Fortran::parser::ForallBodyConstruct>>(forall.t)) { 2914 std::visit(Fortran::common::visitors{ 2915 [&](const Fortran::common::Indirection< 2916 Fortran::parser::ForallConstruct> &b) { 2917 analyzeExplicitSpace(b.value()); 2918 }, 2919 [&](const Fortran::parser::WhereConstruct &w) { 2920 analyzeExplicitSpace(w); 2921 }, 2922 [&](const auto &b) { analyzeExplicitSpace(b.statement); }}, 2923 s.u); 2924 } 2925 analyzeExplicitSpacePop(); 2926 } 2927 2928 void analyzeExplicitSpacePop() { explicitIterSpace.popLevel(); } 2929 2930 void addMaskVariable(Fortran::lower::FrontEndExpr exp) { 2931 // Note: use i8 to store bool values. This avoids round-down behavior found 2932 // with sequences of i1. That is, an array of i1 will be truncated in size 2933 // and be too small. For example, a buffer of type fir.array<7xi1> will have 2934 // 0 size. 2935 mlir::Type i64Ty = builder->getIntegerType(64); 2936 mlir::TupleType ty = fir::factory::getRaggedArrayHeaderType(*builder); 2937 mlir::Type buffTy = ty.getType(1); 2938 mlir::Type shTy = ty.getType(2); 2939 mlir::Location loc = toLocation(); 2940 mlir::Value hdr = builder->createTemporary(loc, ty); 2941 // FIXME: Is there a way to create a `zeroinitializer` in LLVM-IR dialect? 2942 // For now, explicitly set lazy ragged header to all zeros. 2943 // auto nilTup = builder->createNullConstant(loc, ty); 2944 // builder->create<fir::StoreOp>(loc, nilTup, hdr); 2945 mlir::Type i32Ty = builder->getIntegerType(32); 2946 mlir::Value zero = builder->createIntegerConstant(loc, i32Ty, 0); 2947 mlir::Value zero64 = builder->createIntegerConstant(loc, i64Ty, 0); 2948 mlir::Value flags = builder->create<fir::CoordinateOp>( 2949 loc, builder->getRefType(i64Ty), hdr, zero); 2950 builder->create<fir::StoreOp>(loc, zero64, flags); 2951 mlir::Value one = builder->createIntegerConstant(loc, i32Ty, 1); 2952 mlir::Value nullPtr1 = builder->createNullConstant(loc, buffTy); 2953 mlir::Value var = builder->create<fir::CoordinateOp>( 2954 loc, builder->getRefType(buffTy), hdr, one); 2955 builder->create<fir::StoreOp>(loc, nullPtr1, var); 2956 mlir::Value two = builder->createIntegerConstant(loc, i32Ty, 2); 2957 mlir::Value nullPtr2 = builder->createNullConstant(loc, shTy); 2958 mlir::Value shape = builder->create<fir::CoordinateOp>( 2959 loc, builder->getRefType(shTy), hdr, two); 2960 builder->create<fir::StoreOp>(loc, nullPtr2, shape); 2961 implicitIterSpace.addMaskVariable(exp, var, shape, hdr); 2962 explicitIterSpace.outermostContext().attachCleanup( 2963 [builder = this->builder, hdr, loc]() { 2964 fir::runtime::genRaggedArrayDeallocate(loc, *builder, hdr); 2965 }); 2966 } 2967 2968 void createRuntimeTypeInfoGlobals() {} 2969 2970 //===--------------------------------------------------------------------===// 2971 2972 Fortran::lower::LoweringBridge &bridge; 2973 Fortran::evaluate::FoldingContext foldingContext; 2974 fir::FirOpBuilder *builder = nullptr; 2975 Fortran::lower::pft::Evaluation *evalPtr = nullptr; 2976 Fortran::lower::SymMap localSymbols; 2977 Fortran::parser::CharBlock currentPosition; 2978 RuntimeTypeInfoConverter runtimeTypeInfoConverter; 2979 2980 /// WHERE statement/construct mask expression stack. 2981 Fortran::lower::ImplicitIterSpace implicitIterSpace; 2982 2983 /// FORALL context 2984 Fortran::lower::ExplicitIterSpace explicitIterSpace; 2985 2986 /// Tuple of host assoicated variables. 2987 mlir::Value hostAssocTuple; 2988 }; 2989 2990 } // namespace 2991 2992 Fortran::evaluate::FoldingContext 2993 Fortran::lower::LoweringBridge::createFoldingContext() const { 2994 return {getDefaultKinds(), getIntrinsicTable()}; 2995 } 2996 2997 void Fortran::lower::LoweringBridge::lower( 2998 const Fortran::parser::Program &prg, 2999 const Fortran::semantics::SemanticsContext &semanticsContext) { 3000 std::unique_ptr<Fortran::lower::pft::Program> pft = 3001 Fortran::lower::createPFT(prg, semanticsContext); 3002 if (dumpBeforeFir) 3003 Fortran::lower::dumpPFT(llvm::errs(), *pft); 3004 FirConverter converter{*this}; 3005 converter.run(*pft); 3006 } 3007 3008 void Fortran::lower::LoweringBridge::parseSourceFile(llvm::SourceMgr &srcMgr) { 3009 mlir::OwningOpRef<mlir::ModuleOp> owningRef = 3010 mlir::parseSourceFile<mlir::ModuleOp>(srcMgr, &context); 3011 module.reset(new mlir::ModuleOp(owningRef.get().getOperation())); 3012 owningRef.release(); 3013 } 3014 3015 Fortran::lower::LoweringBridge::LoweringBridge( 3016 mlir::MLIRContext &context, 3017 const Fortran::common::IntrinsicTypeDefaultKinds &defaultKinds, 3018 const Fortran::evaluate::IntrinsicProcTable &intrinsics, 3019 const Fortran::parser::AllCookedSources &cooked, llvm::StringRef triple, 3020 fir::KindMapping &kindMap) 3021 : defaultKinds{defaultKinds}, intrinsics{intrinsics}, cooked{&cooked}, 3022 context{context}, kindMap{kindMap} { 3023 // Register the diagnostic handler. 3024 context.getDiagEngine().registerHandler([](mlir::Diagnostic &diag) { 3025 llvm::raw_ostream &os = llvm::errs(); 3026 switch (diag.getSeverity()) { 3027 case mlir::DiagnosticSeverity::Error: 3028 os << "error: "; 3029 break; 3030 case mlir::DiagnosticSeverity::Remark: 3031 os << "info: "; 3032 break; 3033 case mlir::DiagnosticSeverity::Warning: 3034 os << "warning: "; 3035 break; 3036 default: 3037 break; 3038 } 3039 if (!diag.getLocation().isa<mlir::UnknownLoc>()) 3040 os << diag.getLocation() << ": "; 3041 os << diag << '\n'; 3042 os.flush(); 3043 return mlir::success(); 3044 }); 3045 3046 // Create the module and attach the attributes. 3047 module = std::make_unique<mlir::ModuleOp>( 3048 mlir::ModuleOp::create(mlir::UnknownLoc::get(&context))); 3049 assert(module.get() && "module was not created"); 3050 fir::setTargetTriple(*module.get(), triple); 3051 fir::setKindMapping(*module.get(), kindMap); 3052 } 3053