1 //===--- FrontendActions.cpp ----------------------------------------------===//
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/Frontend/FrontendActions.h"
14 #include "flang/Common/default-kinds.h"
15 #include "flang/Frontend/CompilerInstance.h"
16 #include "flang/Frontend/FrontendOptions.h"
17 #include "flang/Frontend/PreprocessorOptions.h"
18 #include "flang/Lower/Bridge.h"
19 #include "flang/Lower/PFTBuilder.h"
20 #include "flang/Lower/Support/Verifier.h"
21 #include "flang/Optimizer/Support/FIRContext.h"
22 #include "flang/Optimizer/Support/InitFIR.h"
23 #include "flang/Optimizer/Support/KindMapping.h"
24 #include "flang/Optimizer/Support/Utils.h"
25 #include "flang/Parser/dump-parse-tree.h"
26 #include "flang/Parser/parsing.h"
27 #include "flang/Parser/provenance.h"
28 #include "flang/Parser/source.h"
29 #include "flang/Parser/unparse.h"
30 #include "flang/Semantics/runtime-type-info.h"
31 #include "flang/Semantics/semantics.h"
32 #include "flang/Semantics/unparse-with-symbols.h"
33 
34 #include "mlir/IR/Dialect.h"
35 #include "mlir/Parser/Parser.h"
36 #include "mlir/Pass/PassManager.h"
37 #include "mlir/Target/LLVMIR/ModuleTranslation.h"
38 #include "clang/Basic/Diagnostic.h"
39 #include "clang/Basic/DiagnosticFrontend.h"
40 #include "llvm/ADT/StringRef.h"
41 #include "llvm/Analysis/TargetLibraryInfo.h"
42 #include "llvm/Analysis/TargetTransformInfo.h"
43 #include "llvm/Bitcode/BitcodeWriterPass.h"
44 #include "llvm/IR/LegacyPassManager.h"
45 #include "llvm/IR/Verifier.h"
46 #include "llvm/IRReader/IRReader.h"
47 #include "llvm/MC/TargetRegistry.h"
48 #include "llvm/Passes/PassBuilder.h"
49 #include "llvm/Passes/StandardInstrumentations.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/SourceMgr.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include <memory>
54 
55 using namespace Fortran::frontend;
56 
57 //===----------------------------------------------------------------------===//
58 // Custom BeginSourceFileAction
59 //===----------------------------------------------------------------------===//
60 
61 bool PrescanAction::beginSourceFileAction() { return runPrescan(); }
62 
63 bool PrescanAndParseAction::beginSourceFileAction() {
64   return runPrescan() && runParse();
65 }
66 
67 bool PrescanAndSemaAction::beginSourceFileAction() {
68   return runPrescan() && runParse() && runSemanticChecks() &&
69          generateRtTypeTables();
70 }
71 
72 bool PrescanAndSemaDebugAction::beginSourceFileAction() {
73   // This is a "debug" action for development purposes. To facilitate this, the
74   // semantic checks are made to succeed unconditionally to prevent this action
75   // from exiting early (i.e. in the presence of semantic errors). We should
76   // never do this in actions intended for end-users or otherwise regular
77   // compiler workflows!
78   return runPrescan() && runParse() && (runSemanticChecks() || true) &&
79          (generateRtTypeTables() || true);
80 }
81 
82 bool CodeGenAction::beginSourceFileAction() {
83   llvmCtx = std::make_unique<llvm::LLVMContext>();
84   CompilerInstance &ci = this->getInstance();
85 
86   // If the input is an LLVM file, just parse it and return.
87   if (this->getCurrentInput().getKind().getLanguage() == Language::LLVM_IR) {
88     llvm::SMDiagnostic err;
89     llvmModule = llvm::parseIRFile(getCurrentInput().getFile(), err, *llvmCtx);
90     if (!llvmModule || llvm::verifyModule(*llvmModule, &llvm::errs())) {
91       err.print("flang-new", llvm::errs());
92       unsigned diagID = ci.getDiagnostics().getCustomDiagID(
93           clang::DiagnosticsEngine::Error, "Could not parse IR");
94       ci.getDiagnostics().Report(diagID);
95       return false;
96     }
97 
98     return true;
99   }
100 
101   // Load the MLIR dialects required by Flang
102   mlir::DialectRegistry registry;
103   mlirCtx = std::make_unique<mlir::MLIRContext>(registry);
104   fir::support::registerNonCodegenDialects(registry);
105   fir::support::loadNonCodegenDialects(*mlirCtx);
106   fir::support::loadDialects(*mlirCtx);
107   fir::support::registerLLVMTranslation(*mlirCtx);
108 
109   // If the input is an MLIR file, just parse it and return.
110   if (this->getCurrentInput().getKind().getLanguage() == Language::MLIR) {
111     llvm::SourceMgr sourceMgr;
112     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> fileOrErr =
113         llvm::MemoryBuffer::getFileOrSTDIN(getCurrentInput().getFile());
114     sourceMgr.AddNewSourceBuffer(std::move(*fileOrErr), llvm::SMLoc());
115     mlir::OwningOpRef<mlir::ModuleOp> module =
116         mlir::parseSourceFile<mlir::ModuleOp>(sourceMgr, mlirCtx.get());
117 
118     if (!module || mlir::failed(module->verifyInvariants())) {
119       unsigned diagID = ci.getDiagnostics().getCustomDiagID(
120           clang::DiagnosticsEngine::Error, "Could not parse FIR");
121       ci.getDiagnostics().Report(diagID);
122       return false;
123     }
124 
125     mlirModule = std::make_unique<mlir::ModuleOp>(module.release());
126     return true;
127   }
128 
129   // Otherwise, generate an MLIR module from the input Fortran source
130   if (getCurrentInput().getKind().getLanguage() != Language::Fortran) {
131     unsigned diagID = ci.getDiagnostics().getCustomDiagID(
132         clang::DiagnosticsEngine::Error,
133         "Invalid input type - expecting a Fortran file");
134     ci.getDiagnostics().Report(diagID);
135     return false;
136   }
137   bool res = runPrescan() && runParse() && runSemanticChecks() &&
138              generateRtTypeTables();
139   if (!res)
140     return res;
141 
142   // Create a LoweringBridge
143   const common::IntrinsicTypeDefaultKinds &defKinds =
144       ci.getInvocation().getSemanticsContext().defaultKinds();
145   fir::KindMapping kindMap(mlirCtx.get(),
146       llvm::ArrayRef<fir::KindTy>{fir::fromDefaultKinds(defKinds)});
147   lower::LoweringBridge lb = Fortran::lower::LoweringBridge::create(
148       *mlirCtx, defKinds, ci.getInvocation().getSemanticsContext().intrinsics(),
149       ci.getParsing().allCooked(), ci.getInvocation().getTargetOpts().triple,
150       kindMap);
151 
152   // Create a parse tree and lower it to FIR
153   Fortran::parser::Program &parseTree{*ci.getParsing().parseTree()};
154   lb.lower(parseTree, ci.getInvocation().getSemanticsContext());
155   mlirModule = std::make_unique<mlir::ModuleOp>(lb.getModule());
156 
157   // run the default passes.
158   mlir::PassManager pm(mlirCtx.get(), mlir::OpPassManager::Nesting::Implicit);
159   pm.enableVerifier(/*verifyPasses=*/true);
160   pm.addPass(std::make_unique<Fortran::lower::VerifierPass>());
161 
162   if (mlir::failed(pm.run(*mlirModule))) {
163     unsigned diagID = ci.getDiagnostics().getCustomDiagID(
164         clang::DiagnosticsEngine::Error,
165         "verification of lowering to FIR failed");
166     ci.getDiagnostics().Report(diagID);
167     return false;
168   }
169 
170   return true;
171 }
172 
173 //===----------------------------------------------------------------------===//
174 // Custom ExecuteAction
175 //===----------------------------------------------------------------------===//
176 void InputOutputTestAction::executeAction() {
177   CompilerInstance &ci = getInstance();
178 
179   // Create a stream for errors
180   std::string buf;
181   llvm::raw_string_ostream errorStream{buf};
182 
183   // Read the input file
184   Fortran::parser::AllSources &allSources{ci.getAllSources()};
185   std::string path{getCurrentFileOrBufferName()};
186   const Fortran::parser::SourceFile *sf;
187   if (path == "-")
188     sf = allSources.ReadStandardInput(errorStream);
189   else
190     sf = allSources.Open(path, errorStream, std::optional<std::string>{"."s});
191   llvm::ArrayRef<char> fileContent = sf->content();
192 
193   // Output file descriptor to receive the contents of the input file.
194   std::unique_ptr<llvm::raw_ostream> os;
195 
196   // Copy the contents from the input file to the output file
197   if (!ci.isOutputStreamNull()) {
198     // An output stream (outputStream_) was set earlier
199     ci.writeOutputStream(fileContent.data());
200   } else {
201     // No pre-set output stream - create an output file
202     os = ci.createDefaultOutputFile(
203         /*binary=*/true, getCurrentFileOrBufferName(), "txt");
204     if (!os)
205       return;
206     (*os) << fileContent.data();
207   }
208 }
209 
210 void PrintPreprocessedAction::executeAction() {
211   std::string buf;
212   llvm::raw_string_ostream outForPP{buf};
213 
214   // Format or dump the prescanner's output
215   CompilerInstance &ci = this->getInstance();
216   if (ci.getInvocation().getPreprocessorOpts().noReformat) {
217     ci.getParsing().DumpCookedChars(outForPP);
218   } else {
219     ci.getParsing().EmitPreprocessedSource(
220         outForPP, !ci.getInvocation().getPreprocessorOpts().noLineDirectives);
221   }
222 
223   // Print getDiagnostics from the prescanner
224   ci.getParsing().messages().Emit(llvm::errs(), ci.getAllCookedSources());
225 
226   // If a pre-defined output stream exists, dump the preprocessed content there
227   if (!ci.isOutputStreamNull()) {
228     // Send the output to the pre-defined output buffer.
229     ci.writeOutputStream(outForPP.str());
230     return;
231   }
232 
233   // Create a file and save the preprocessed output there
234   std::unique_ptr<llvm::raw_pwrite_stream> os{ci.createDefaultOutputFile(
235       /*Binary=*/true, /*InFile=*/getCurrentFileOrBufferName())};
236   if (!os) {
237     return;
238   }
239 
240   (*os) << outForPP.str();
241 }
242 
243 void DebugDumpProvenanceAction::executeAction() {
244   this->getInstance().getParsing().DumpProvenance(llvm::outs());
245 }
246 
247 void ParseSyntaxOnlyAction::executeAction() {}
248 
249 void DebugUnparseNoSemaAction::executeAction() {
250   auto &invoc = this->getInstance().getInvocation();
251   auto &parseTree{getInstance().getParsing().parseTree()};
252 
253   // TODO: Options should come from CompilerInvocation
254   Unparse(llvm::outs(), *parseTree,
255           /*encoding=*/Fortran::parser::Encoding::UTF_8,
256           /*capitalizeKeywords=*/true, /*backslashEscapes=*/false,
257           /*preStatement=*/nullptr,
258           invoc.getUseAnalyzedObjectsForUnparse() ? &invoc.getAsFortran()
259                                                   : nullptr);
260 }
261 
262 void DebugUnparseAction::executeAction() {
263   auto &invoc = this->getInstance().getInvocation();
264   auto &parseTree{getInstance().getParsing().parseTree()};
265 
266   CompilerInstance &ci = this->getInstance();
267   auto os{ci.createDefaultOutputFile(
268       /*Binary=*/false, /*InFile=*/getCurrentFileOrBufferName())};
269 
270   // TODO: Options should come from CompilerInvocation
271   Unparse(*os, *parseTree,
272           /*encoding=*/Fortran::parser::Encoding::UTF_8,
273           /*capitalizeKeywords=*/true, /*backslashEscapes=*/false,
274           /*preStatement=*/nullptr,
275           invoc.getUseAnalyzedObjectsForUnparse() ? &invoc.getAsFortran()
276                                                   : nullptr);
277 
278   // Report fatal semantic errors
279   reportFatalSemanticErrors();
280 }
281 
282 void DebugUnparseWithSymbolsAction::executeAction() {
283   auto &parseTree{*getInstance().getParsing().parseTree()};
284 
285   Fortran::semantics::UnparseWithSymbols(
286       llvm::outs(), parseTree, /*encoding=*/Fortran::parser::Encoding::UTF_8);
287 
288   // Report fatal semantic errors
289   reportFatalSemanticErrors();
290 }
291 
292 void DebugDumpSymbolsAction::executeAction() {
293   CompilerInstance &ci = this->getInstance();
294 
295   if (!ci.getRtTyTables().schemata) {
296     unsigned diagID = ci.getDiagnostics().getCustomDiagID(
297         clang::DiagnosticsEngine::Error,
298         "could not find module file for __fortran_type_info");
299     ci.getDiagnostics().Report(diagID);
300     llvm::errs() << "\n";
301     return;
302   }
303 
304   // Dump symbols
305   ci.getSemantics().DumpSymbols(llvm::outs());
306 }
307 
308 void DebugDumpAllAction::executeAction() {
309   CompilerInstance &ci = this->getInstance();
310 
311   // Dump parse tree
312   auto &parseTree{getInstance().getParsing().parseTree()};
313   llvm::outs() << "========================";
314   llvm::outs() << " Flang: parse tree dump ";
315   llvm::outs() << "========================\n";
316   Fortran::parser::DumpTree(llvm::outs(), parseTree,
317                             &ci.getInvocation().getAsFortran());
318 
319   if (!ci.getRtTyTables().schemata) {
320     unsigned diagID = ci.getDiagnostics().getCustomDiagID(
321         clang::DiagnosticsEngine::Error,
322         "could not find module file for __fortran_type_info");
323     ci.getDiagnostics().Report(diagID);
324     llvm::errs() << "\n";
325     return;
326   }
327 
328   // Dump symbols
329   llvm::outs() << "=====================";
330   llvm::outs() << " Flang: symbols dump ";
331   llvm::outs() << "=====================\n";
332   ci.getSemantics().DumpSymbols(llvm::outs());
333 }
334 
335 void DebugDumpParseTreeNoSemaAction::executeAction() {
336   auto &parseTree{getInstance().getParsing().parseTree()};
337 
338   // Dump parse tree
339   Fortran::parser::DumpTree(
340       llvm::outs(), parseTree,
341       &this->getInstance().getInvocation().getAsFortran());
342 }
343 
344 void DebugDumpParseTreeAction::executeAction() {
345   auto &parseTree{getInstance().getParsing().parseTree()};
346 
347   // Dump parse tree
348   Fortran::parser::DumpTree(
349       llvm::outs(), parseTree,
350       &this->getInstance().getInvocation().getAsFortran());
351 
352   // Report fatal semantic errors
353   reportFatalSemanticErrors();
354 }
355 
356 void DebugMeasureParseTreeAction::executeAction() {
357   CompilerInstance &ci = this->getInstance();
358 
359   // Parse. In case of failure, report and return.
360   ci.getParsing().Parse(llvm::outs());
361 
362   if (!ci.getParsing().messages().empty() &&
363       (ci.getInvocation().getWarnAsErr() ||
364        ci.getParsing().messages().AnyFatalError())) {
365     unsigned diagID = ci.getDiagnostics().getCustomDiagID(
366         clang::DiagnosticsEngine::Error, "Could not parse %0");
367     ci.getDiagnostics().Report(diagID) << getCurrentFileOrBufferName();
368 
369     ci.getParsing().messages().Emit(llvm::errs(),
370                                     this->getInstance().getAllCookedSources());
371     return;
372   }
373 
374   // Report the getDiagnostics from parsing
375   ci.getParsing().messages().Emit(llvm::errs(), ci.getAllCookedSources());
376 
377   auto &parseTree{*ci.getParsing().parseTree()};
378 
379   // Measure the parse tree
380   MeasurementVisitor visitor;
381   Fortran::parser::Walk(parseTree, visitor);
382   llvm::outs() << "Parse tree comprises " << visitor.objects
383                << " objects and occupies " << visitor.bytes
384                << " total bytes.\n";
385 }
386 
387 void DebugPreFIRTreeAction::executeAction() {
388   CompilerInstance &ci = this->getInstance();
389   // Report and exit if fatal semantic errors are present
390   if (reportFatalSemanticErrors()) {
391     return;
392   }
393 
394   auto &parseTree{*ci.getParsing().parseTree()};
395 
396   // Dump pre-FIR tree
397   if (auto ast{Fortran::lower::createPFT(
398           parseTree, ci.getInvocation().getSemanticsContext())}) {
399     Fortran::lower::dumpPFT(llvm::outs(), *ast);
400   } else {
401     unsigned diagID = ci.getDiagnostics().getCustomDiagID(
402         clang::DiagnosticsEngine::Error, "Pre FIR Tree is NULL.");
403     ci.getDiagnostics().Report(diagID);
404   }
405 }
406 
407 void DebugDumpParsingLogAction::executeAction() {
408   CompilerInstance &ci = this->getInstance();
409 
410   ci.getParsing().Parse(llvm::errs());
411   ci.getParsing().DumpParsingLog(llvm::outs());
412 }
413 
414 void GetDefinitionAction::executeAction() {
415   CompilerInstance &ci = this->getInstance();
416 
417   // Report and exit if fatal semantic errors are present
418   if (reportFatalSemanticErrors()) {
419     return;
420   }
421 
422   parser::AllCookedSources &cs = ci.getAllCookedSources();
423   unsigned diagID = ci.getDiagnostics().getCustomDiagID(
424       clang::DiagnosticsEngine::Error, "Symbol not found");
425 
426   auto gdv = ci.getInvocation().getFrontendOpts().getDefVals;
427   auto charBlock{cs.GetCharBlockFromLineAndColumns(
428       gdv.line, gdv.startColumn, gdv.endColumn)};
429   if (!charBlock) {
430     ci.getDiagnostics().Report(diagID);
431     return;
432   }
433 
434   llvm::outs() << "String range: >" << charBlock->ToString() << "<\n";
435 
436   auto *symbol{ci.getInvocation()
437                    .getSemanticsContext()
438                    .FindScope(*charBlock)
439                    .FindSymbol(*charBlock)};
440   if (!symbol) {
441     ci.getDiagnostics().Report(diagID);
442     return;
443   }
444 
445   llvm::outs() << "Found symbol name: " << symbol->name().ToString() << "\n";
446 
447   auto sourceInfo{cs.GetSourcePositionRange(symbol->name())};
448   if (!sourceInfo) {
449     llvm_unreachable(
450         "Failed to obtain SourcePosition."
451         "TODO: Please, write a test and replace this with a diagnostic!");
452     return;
453   }
454 
455   llvm::outs() << "Found symbol name: " << symbol->name().ToString() << "\n";
456   llvm::outs() << symbol->name().ToString() << ": "
457                << sourceInfo->first.file.path() << ", "
458                << sourceInfo->first.line << ", " << sourceInfo->first.column
459                << "-" << sourceInfo->second.column << "\n";
460 }
461 
462 void GetSymbolsSourcesAction::executeAction() {
463   CompilerInstance &ci = this->getInstance();
464 
465   // Report and exit if fatal semantic errors are present
466   if (reportFatalSemanticErrors()) {
467     return;
468   }
469 
470   ci.getSemantics().DumpSymbolsSources(llvm::outs());
471 }
472 
473 //===----------------------------------------------------------------------===//
474 // CodeGenActions
475 //===----------------------------------------------------------------------===//
476 
477 CodeGenAction::~CodeGenAction() = default;
478 
479 #include "flang/Tools/CLOptions.inc"
480 
481 // Lower the previously generated MLIR module into an LLVM IR module
482 void CodeGenAction::generateLLVMIR() {
483   assert(mlirModule && "The MLIR module has not been generated yet.");
484 
485   CompilerInstance &ci = this->getInstance();
486 
487   fir::support::loadDialects(*mlirCtx);
488   fir::support::registerLLVMTranslation(*mlirCtx);
489 
490   // Set-up the MLIR pass manager
491   mlir::PassManager pm(mlirCtx.get(), mlir::OpPassManager::Nesting::Implicit);
492 
493   pm.addPass(std::make_unique<Fortran::lower::VerifierPass>());
494   pm.enableVerifier(/*verifyPasses=*/true);
495 
496   // Create the pass pipeline
497   fir::createMLIRToLLVMPassPipeline(pm);
498   mlir::applyPassManagerCLOptions(pm);
499 
500   // run the pass manager
501   if (!mlir::succeeded(pm.run(*mlirModule))) {
502     unsigned diagID = ci.getDiagnostics().getCustomDiagID(
503         clang::DiagnosticsEngine::Error, "Lowering to LLVM IR failed");
504     ci.getDiagnostics().Report(diagID);
505   }
506 
507   // Translate to LLVM IR
508   llvm::Optional<llvm::StringRef> moduleName = mlirModule->getName();
509   llvmModule = mlir::translateModuleToLLVMIR(
510       *mlirModule, *llvmCtx, moduleName ? *moduleName : "FIRModule");
511 
512   if (!llvmModule) {
513     unsigned diagID = ci.getDiagnostics().getCustomDiagID(
514         clang::DiagnosticsEngine::Error, "failed to create the LLVM module");
515     ci.getDiagnostics().Report(diagID);
516     return;
517   }
518 }
519 
520 void CodeGenAction::setUpTargetMachine() {
521   CompilerInstance &ci = this->getInstance();
522 
523   // Set the triple based on the CompilerInvocation set-up
524   const std::string &theTriple = ci.getInvocation().getTargetOpts().triple;
525   if (llvmModule->getTargetTriple() != theTriple) {
526     ci.getDiagnostics().Report(clang::diag::warn_fe_override_module)
527         << theTriple;
528     llvmModule->setTargetTriple(theTriple);
529   }
530 
531   // Create `Target`
532   std::string error;
533   const llvm::Target *theTarget =
534       llvm::TargetRegistry::lookupTarget(theTriple, error);
535   assert(theTarget && "Failed to create Target");
536 
537   // Create `TargetMachine`
538   tm.reset(theTarget->createTargetMachine(theTriple, /*CPU=*/"",
539                                           /*Features=*/"",
540                                           llvm::TargetOptions(), llvm::None));
541   assert(tm && "Failed to create TargetMachine");
542 }
543 
544 static std::unique_ptr<llvm::raw_pwrite_stream>
545 getOutputStream(CompilerInstance &ci, llvm::StringRef inFile,
546                 BackendActionTy action) {
547   switch (action) {
548   case BackendActionTy::Backend_EmitAssembly:
549     return ci.createDefaultOutputFile(
550         /*Binary=*/false, inFile, /*extension=*/"s");
551   case BackendActionTy::Backend_EmitLL:
552     return ci.createDefaultOutputFile(
553         /*Binary=*/false, inFile, /*extension=*/"ll");
554   case BackendActionTy::Backend_EmitMLIR:
555     return ci.createDefaultOutputFile(
556         /*Binary=*/false, inFile, /*extension=*/"mlir");
557   case BackendActionTy::Backend_EmitBC:
558     return ci.createDefaultOutputFile(
559         /*Binary=*/true, inFile, /*extension=*/"bc");
560   case BackendActionTy::Backend_EmitObj:
561     return ci.createDefaultOutputFile(
562         /*Binary=*/true, inFile, /*extension=*/"o");
563   }
564 
565   llvm_unreachable("Invalid action!");
566 }
567 
568 /// Generate target-specific machine-code or assembly file from the input LLVM
569 /// module.
570 ///
571 /// \param [in] diags Diagnostics engine for reporting errors
572 /// \param [in] tm Target machine to aid the code-gen pipeline set-up
573 /// \param [in] act Backend act to run (assembly vs machine-code generation)
574 /// \param [in] llvmModule LLVM module to lower to assembly/machine-code
575 /// \param [out] os Output stream to emit the generated code to
576 static void generateMachineCodeOrAssemblyImpl(clang::DiagnosticsEngine &diags,
577                                               llvm::TargetMachine &tm,
578                                               BackendActionTy act,
579                                               llvm::Module &llvmModule,
580                                               llvm::raw_pwrite_stream &os) {
581   assert(((act == BackendActionTy::Backend_EmitObj) ||
582           (act == BackendActionTy::Backend_EmitAssembly)) &&
583          "Unsupported action");
584 
585   // Set-up the pass manager, i.e create an LLVM code-gen pass pipeline.
586   // Currently only the legacy pass manager is supported.
587   // TODO: Switch to the new PM once it's available in the backend.
588   llvm::legacy::PassManager codeGenPasses;
589   codeGenPasses.add(
590       createTargetTransformInfoWrapperPass(tm.getTargetIRAnalysis()));
591 
592   llvm::Triple triple(llvmModule.getTargetTriple());
593   std::unique_ptr<llvm::TargetLibraryInfoImpl> tlii =
594       std::make_unique<llvm::TargetLibraryInfoImpl>(triple);
595   assert(tlii && "Failed to create TargetLibraryInfo");
596   codeGenPasses.add(new llvm::TargetLibraryInfoWrapperPass(*tlii));
597 
598   llvm::CodeGenFileType cgft = (act == BackendActionTy::Backend_EmitAssembly)
599                                    ? llvm::CodeGenFileType::CGFT_AssemblyFile
600                                    : llvm::CodeGenFileType::CGFT_ObjectFile;
601   if (tm.addPassesToEmitFile(codeGenPasses, os, nullptr, cgft)) {
602     unsigned diagID =
603         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
604                               "emission of this file type is not supported");
605     diags.Report(diagID);
606     return;
607   }
608 
609   // Run the passes
610   codeGenPasses.run(llvmModule);
611 }
612 
613 static llvm::OptimizationLevel
614 mapToLevel(const Fortran::frontend::CodeGenOptions &opts) {
615   switch (opts.OptimizationLevel) {
616   default:
617     llvm_unreachable("Invalid optimization level!");
618   case 0:
619     return llvm::OptimizationLevel::O0;
620   case 1:
621     return llvm::OptimizationLevel::O1;
622   case 2:
623     return llvm::OptimizationLevel::O2;
624   case 3:
625     return llvm::OptimizationLevel::O3;
626   }
627 }
628 
629 void CodeGenAction::runOptimizationPipeline(llvm::raw_pwrite_stream &os) {
630   auto opts = getInstance().getInvocation().getCodeGenOpts();
631   llvm::OptimizationLevel level = mapToLevel(opts);
632 
633   // Create the analysis managers.
634   llvm::LoopAnalysisManager lam;
635   llvm::FunctionAnalysisManager fam;
636   llvm::CGSCCAnalysisManager cgam;
637   llvm::ModuleAnalysisManager mam;
638 
639   // Create the pass manager builder.
640   llvm::PassInstrumentationCallbacks pic;
641   llvm::PipelineTuningOptions pto;
642   llvm::Optional<llvm::PGOOptions> pgoOpt;
643   llvm::StandardInstrumentations si(opts.DebugPassManager);
644   si.registerCallbacks(pic, &fam);
645   llvm::PassBuilder pb(tm.get(), pto, pgoOpt, &pic);
646 
647   // Register all the basic analyses with the managers.
648   pb.registerModuleAnalyses(mam);
649   pb.registerCGSCCAnalyses(cgam);
650   pb.registerFunctionAnalyses(fam);
651   pb.registerLoopAnalyses(lam);
652   pb.crossRegisterProxies(lam, fam, cgam, mam);
653 
654   // Create the pass manager.
655   llvm::ModulePassManager mpm;
656   if (opts.OptimizationLevel == 0)
657     mpm = pb.buildO0DefaultPipeline(level, false);
658   else
659     mpm = pb.buildPerModuleDefaultPipeline(level);
660 
661   if (action == BackendActionTy::Backend_EmitBC)
662     mpm.addPass(llvm::BitcodeWriterPass(os));
663 
664   // Run the passes.
665   mpm.run(*llvmModule, mam);
666 }
667 
668 void CodeGenAction::executeAction() {
669   CompilerInstance &ci = this->getInstance();
670 
671   // If the output stream is a file, generate it and define the corresponding
672   // output stream. If a pre-defined output stream is available, we will use
673   // that instead.
674   //
675   // NOTE: `os` is a smart pointer that will be destroyed at the end of this
676   // method. However, it won't be written to until `codeGenPasses` is
677   // destroyed. By defining `os` before `codeGenPasses`, we make sure that the
678   // output stream won't be destroyed before it is written to. This only
679   // applies when an output file is used (i.e. there is no pre-defined output
680   // stream).
681   // TODO: Revisit once the new PM is ready (i.e. when `codeGenPasses` is
682   // updated to use it).
683   std::unique_ptr<llvm::raw_pwrite_stream> os;
684   if (ci.isOutputStreamNull()) {
685     os = getOutputStream(ci, getCurrentFileOrBufferName(), action);
686 
687     if (!os) {
688       unsigned diagID = ci.getDiagnostics().getCustomDiagID(
689           clang::DiagnosticsEngine::Error, "failed to create the output file");
690       ci.getDiagnostics().Report(diagID);
691       return;
692     }
693   }
694 
695   if (action == BackendActionTy::Backend_EmitMLIR) {
696     mlirModule->print(ci.isOutputStreamNull() ? *os : ci.getOutputStream());
697     return;
698   }
699 
700   // Generate an LLVM module if it's not already present (it will already be
701   // present if the input file is an LLVM IR/BC file).
702   if (!llvmModule)
703     generateLLVMIR();
704 
705   // Run LLVM's middle-end (i.e. the optimizer).
706   runOptimizationPipeline(*os);
707 
708   if (action == BackendActionTy::Backend_EmitLL) {
709     llvmModule->print(ci.isOutputStreamNull() ? *os : ci.getOutputStream(),
710                       /*AssemblyAnnotationWriter=*/nullptr);
711     return;
712   }
713 
714   setUpTargetMachine();
715   llvmModule->setDataLayout(tm->createDataLayout());
716 
717   if (action == BackendActionTy::Backend_EmitBC) {
718     // This action has effectively been completed in runOptimizationPipeline.
719     return;
720   }
721 
722   // Run LLVM's backend and generate either assembly or machine code
723   if (action == BackendActionTy::Backend_EmitAssembly ||
724       action == BackendActionTy::Backend_EmitObj) {
725     generateMachineCodeOrAssemblyImpl(
726         ci.getDiagnostics(), *tm, action, *llvmModule,
727         ci.isOutputStreamNull() ? *os : ci.getOutputStream());
728     return;
729   }
730 }
731 
732 void InitOnlyAction::executeAction() {
733   CompilerInstance &ci = this->getInstance();
734   unsigned diagID = ci.getDiagnostics().getCustomDiagID(
735       clang::DiagnosticsEngine::Warning,
736       "Use `-init-only` for testing purposes only");
737   ci.getDiagnostics().Report(diagID);
738 }
739 
740 void PluginParseTreeAction::executeAction() {}
741 
742 void DebugDumpPFTAction::executeAction() {
743   CompilerInstance &ci = this->getInstance();
744 
745   if (auto ast = Fortran::lower::createPFT(*ci.getParsing().parseTree(),
746                                            ci.getSemantics().context())) {
747     Fortran::lower::dumpPFT(llvm::outs(), *ast);
748     return;
749   }
750 
751   unsigned diagID = ci.getDiagnostics().getCustomDiagID(
752       clang::DiagnosticsEngine::Error, "Pre FIR Tree is NULL.");
753   ci.getDiagnostics().Report(diagID);
754 }
755 
756 Fortran::parser::Parsing &PluginParseTreeAction::getParsing() {
757   return getInstance().getParsing();
758 }
759 
760 std::unique_ptr<llvm::raw_pwrite_stream>
761 PluginParseTreeAction::createOutputFile(llvm::StringRef extension = "") {
762 
763   std::unique_ptr<llvm::raw_pwrite_stream> os{
764       getInstance().createDefaultOutputFile(
765           /*Binary=*/false, /*InFile=*/getCurrentFileOrBufferName(),
766           extension)};
767   return os;
768 }
769