xref: /llvm-project/flang/lib/Frontend/CompilerInvocation.cpp (revision 9dadb1f62bb8086a53ba39d188665c4fe3a9c6ec)
1 //===- CompilerInvocation.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/CompilerInvocation.h"
14 #include "flang/Common/Fortran-features.h"
15 #include "flang/Common/OpenMP-features.h"
16 #include "flang/Common/Version.h"
17 #include "flang/Frontend/CodeGenOptions.h"
18 #include "flang/Frontend/PreprocessorOptions.h"
19 #include "flang/Frontend/TargetOptions.h"
20 #include "flang/Semantics/semantics.h"
21 #include "flang/Tools/TargetSetup.h"
22 #include "flang/Version.inc"
23 #include "clang/Basic/AllDiagnostics.h"
24 #include "clang/Basic/DiagnosticDriver.h"
25 #include "clang/Basic/DiagnosticOptions.h"
26 #include "clang/Driver/DriverDiagnostic.h"
27 #include "clang/Driver/OptionUtils.h"
28 #include "clang/Driver/Options.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/Frontend/Debug/Options.h"
32 #include "llvm/Option/Arg.h"
33 #include "llvm/Option/ArgList.h"
34 #include "llvm/Option/OptTable.h"
35 #include "llvm/Support/CodeGen.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/FileUtilities.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/Process.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/TargetParser/Host.h"
42 #include "llvm/TargetParser/Triple.h"
43 #include <cstdlib>
44 #include <memory>
45 #include <optional>
46 
47 using namespace Fortran::frontend;
48 
49 //===----------------------------------------------------------------------===//
50 // Initialization.
51 //===----------------------------------------------------------------------===//
52 CompilerInvocationBase::CompilerInvocationBase()
53     : diagnosticOpts(new clang::DiagnosticOptions()),
54       preprocessorOpts(new PreprocessorOptions()) {}
55 
56 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x)
57     : diagnosticOpts(new clang::DiagnosticOptions(x.getDiagnosticOpts())),
58       preprocessorOpts(new PreprocessorOptions(x.getPreprocessorOpts())) {}
59 
60 CompilerInvocationBase::~CompilerInvocationBase() = default;
61 
62 //===----------------------------------------------------------------------===//
63 // Deserialization (from args)
64 //===----------------------------------------------------------------------===//
65 static bool parseShowColorsArgs(const llvm::opt::ArgList &args,
66                                 bool defaultColor = true) {
67   // Color diagnostics default to auto ("on" if terminal supports) in the
68   // compiler driver `flang-new` but default to off in the frontend driver
69   // `flang-new -fc1`, needing an explicit OPT_fdiagnostics_color.
70   // Support both clang's -f[no-]color-diagnostics and gcc's
71   // -f[no-]diagnostics-colors[=never|always|auto].
72   enum {
73     Colors_On,
74     Colors_Off,
75     Colors_Auto
76   } showColors = defaultColor ? Colors_Auto : Colors_Off;
77 
78   for (auto *a : args) {
79     const llvm::opt::Option &opt = a->getOption();
80     if (opt.matches(clang::driver::options::OPT_fcolor_diagnostics)) {
81       showColors = Colors_On;
82     } else if (opt.matches(clang::driver::options::OPT_fno_color_diagnostics)) {
83       showColors = Colors_Off;
84     } else if (opt.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) {
85       llvm::StringRef value(a->getValue());
86       if (value == "always")
87         showColors = Colors_On;
88       else if (value == "never")
89         showColors = Colors_Off;
90       else if (value == "auto")
91         showColors = Colors_Auto;
92     }
93   }
94 
95   return showColors == Colors_On ||
96          (showColors == Colors_Auto &&
97           llvm::sys::Process::StandardErrHasColors());
98 }
99 
100 /// Extracts the optimisation level from \a args.
101 static unsigned getOptimizationLevel(llvm::opt::ArgList &args,
102                                      clang::DiagnosticsEngine &diags) {
103   unsigned defaultOpt = 0;
104 
105   if (llvm::opt::Arg *a =
106           args.getLastArg(clang::driver::options::OPT_O_Group)) {
107     if (a->getOption().matches(clang::driver::options::OPT_O0))
108       return 0;
109 
110     assert(a->getOption().matches(clang::driver::options::OPT_O));
111 
112     return getLastArgIntValue(args, clang::driver::options::OPT_O, defaultOpt,
113                               diags);
114   }
115 
116   return defaultOpt;
117 }
118 
119 bool Fortran::frontend::parseDiagnosticArgs(clang::DiagnosticOptions &opts,
120                                             llvm::opt::ArgList &args) {
121   opts.ShowColors = parseShowColorsArgs(args);
122 
123   return true;
124 }
125 
126 static bool parseDebugArgs(Fortran::frontend::CodeGenOptions &opts,
127                            llvm::opt::ArgList &args,
128                            clang::DiagnosticsEngine &diags) {
129   using DebugInfoKind = llvm::codegenoptions::DebugInfoKind;
130   if (llvm::opt::Arg *arg =
131           args.getLastArg(clang::driver::options::OPT_debug_info_kind_EQ)) {
132     std::optional<DebugInfoKind> val =
133         llvm::StringSwitch<std::optional<DebugInfoKind>>(arg->getValue())
134             .Case("line-tables-only", llvm::codegenoptions::DebugLineTablesOnly)
135             .Case("line-directives-only",
136                   llvm::codegenoptions::DebugDirectivesOnly)
137             .Case("constructor", llvm::codegenoptions::DebugInfoConstructor)
138             .Case("limited", llvm::codegenoptions::LimitedDebugInfo)
139             .Case("standalone", llvm::codegenoptions::FullDebugInfo)
140             .Case("unused-types", llvm::codegenoptions::UnusedTypeInfo)
141             .Default(std::nullopt);
142     if (!val.has_value()) {
143       diags.Report(clang::diag::err_drv_invalid_value)
144           << arg->getAsString(args) << arg->getValue();
145       return false;
146     }
147     opts.setDebugInfo(val.value());
148     if (val != llvm::codegenoptions::DebugLineTablesOnly &&
149         val != llvm::codegenoptions::FullDebugInfo &&
150         val != llvm::codegenoptions::NoDebugInfo) {
151       const auto debugWarning = diags.getCustomDiagID(
152           clang::DiagnosticsEngine::Warning, "Unsupported debug option: %0");
153       diags.Report(debugWarning) << arg->getValue();
154     }
155   }
156   return true;
157 }
158 
159 static bool parseVectorLibArg(Fortran::frontend::CodeGenOptions &opts,
160                               llvm::opt::ArgList &args,
161                               clang::DiagnosticsEngine &diags) {
162   llvm::opt::Arg *arg = args.getLastArg(clang::driver::options::OPT_fveclib);
163   if (!arg)
164     return true;
165 
166   using VectorLibrary = llvm::driver::VectorLibrary;
167   std::optional<VectorLibrary> val =
168       llvm::StringSwitch<std::optional<VectorLibrary>>(arg->getValue())
169           .Case("Accelerate", VectorLibrary::Accelerate)
170           .Case("LIBMVEC", VectorLibrary::LIBMVEC)
171           .Case("MASSV", VectorLibrary::MASSV)
172           .Case("SVML", VectorLibrary::SVML)
173           .Case("SLEEF", VectorLibrary::SLEEF)
174           .Case("Darwin_libsystem_m", VectorLibrary::Darwin_libsystem_m)
175           .Case("ArmPL", VectorLibrary::ArmPL)
176           .Case("NoLibrary", VectorLibrary::NoLibrary)
177           .Default(std::nullopt);
178   if (!val.has_value()) {
179     diags.Report(clang::diag::err_drv_invalid_value)
180         << arg->getAsString(args) << arg->getValue();
181     return false;
182   }
183   opts.setVecLib(val.value());
184   return true;
185 }
186 
187 // Generate an OptRemark object containing info on if the -Rgroup
188 // specified is enabled or not.
189 static CodeGenOptions::OptRemark
190 parseOptimizationRemark(clang::DiagnosticsEngine &diags,
191                         llvm::opt::ArgList &args, llvm::opt::OptSpecifier optEq,
192                         llvm::StringRef remarkOptName) {
193   assert((remarkOptName == "pass" || remarkOptName == "pass-missed" ||
194           remarkOptName == "pass-analysis") &&
195          "Unsupported remark option name provided.");
196   CodeGenOptions::OptRemark result;
197 
198   for (llvm::opt::Arg *a : args) {
199     if (a->getOption().matches(clang::driver::options::OPT_R_Joined)) {
200       llvm::StringRef value = a->getValue();
201 
202       if (value == remarkOptName) {
203         result.Kind = CodeGenOptions::RemarkKind::RK_Enabled;
204         // Enable everything
205         result.Pattern = ".*";
206         result.Regex = std::make_shared<llvm::Regex>(result.Pattern);
207 
208       } else if (value.split('-') ==
209                  std::make_pair(llvm::StringRef("no"), remarkOptName)) {
210         result.Kind = CodeGenOptions::RemarkKind::RK_Disabled;
211         // Disable everything
212         result.Pattern = "";
213         result.Regex = nullptr;
214       }
215     } else if (a->getOption().matches(optEq)) {
216       result.Kind = CodeGenOptions::RemarkKind::RK_WithPattern;
217       result.Pattern = a->getValue();
218       result.Regex = std::make_shared<llvm::Regex>(result.Pattern);
219       std::string regexError;
220 
221       if (!result.Regex->isValid(regexError)) {
222         diags.Report(clang::diag::err_drv_optimization_remark_pattern)
223             << regexError << a->getAsString(args);
224         return CodeGenOptions::OptRemark();
225       }
226     }
227   }
228   return result;
229 }
230 
231 static void parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts,
232                              llvm::opt::ArgList &args,
233                              clang::DiagnosticsEngine &diags) {
234   opts.OptimizationLevel = getOptimizationLevel(args, diags);
235 
236   if (args.hasFlag(clang::driver::options::OPT_fdebug_pass_manager,
237                    clang::driver::options::OPT_fno_debug_pass_manager, false))
238     opts.DebugPassManager = 1;
239 
240   if (args.hasFlag(clang::driver::options::OPT_fstack_arrays,
241                    clang::driver::options::OPT_fno_stack_arrays, false))
242     opts.StackArrays = 1;
243 
244   if (args.hasFlag(clang::driver::options::OPT_floop_versioning,
245                    clang::driver::options::OPT_fno_loop_versioning, false))
246     opts.LoopVersioning = 1;
247 
248   opts.AliasAnalysis = opts.OptimizationLevel > 0;
249 
250   // -mframe-pointer=none/non-leaf/all option.
251   if (const llvm::opt::Arg *a =
252           args.getLastArg(clang::driver::options::OPT_mframe_pointer_EQ)) {
253     std::optional<llvm::FramePointerKind> val =
254         llvm::StringSwitch<std::optional<llvm::FramePointerKind>>(a->getValue())
255             .Case("none", llvm::FramePointerKind::None)
256             .Case("non-leaf", llvm::FramePointerKind::NonLeaf)
257             .Case("all", llvm::FramePointerKind::All)
258             .Default(std::nullopt);
259 
260     if (!val.has_value()) {
261       diags.Report(clang::diag::err_drv_invalid_value)
262           << a->getAsString(args) << a->getValue();
263     } else
264       opts.setFramePointer(val.value());
265   }
266 
267   for (auto *a : args.filtered(clang::driver::options::OPT_fpass_plugin_EQ))
268     opts.LLVMPassPlugins.push_back(a->getValue());
269 
270   // -fembed-offload-object option
271   for (auto *a :
272        args.filtered(clang::driver::options::OPT_fembed_offload_object_EQ))
273     opts.OffloadObjects.push_back(a->getValue());
274 
275   // -flto=full/thin option.
276   if (const llvm::opt::Arg *a =
277           args.getLastArg(clang::driver::options::OPT_flto_EQ)) {
278     llvm::StringRef s = a->getValue();
279     assert((s == "full" || s == "thin") && "Unknown LTO mode.");
280     if (s == "full")
281       opts.PrepareForFullLTO = true;
282     else
283       opts.PrepareForThinLTO = true;
284   }
285 
286   if (const llvm::opt::Arg *a = args.getLastArg(
287           clang::driver::options::OPT_mcode_object_version_EQ)) {
288     llvm::StringRef s = a->getValue();
289     if (s == "6")
290       opts.CodeObjectVersion = llvm::CodeObjectVersionKind::COV_6;
291     if (s == "5")
292       opts.CodeObjectVersion = llvm::CodeObjectVersionKind::COV_5;
293     if (s == "4")
294       opts.CodeObjectVersion = llvm::CodeObjectVersionKind::COV_4;
295     if (s == "none")
296       opts.CodeObjectVersion = llvm::CodeObjectVersionKind::COV_None;
297   }
298 
299   // -f[no-]save-optimization-record[=<format>]
300   if (const llvm::opt::Arg *a =
301           args.getLastArg(clang::driver::options::OPT_opt_record_file))
302     opts.OptRecordFile = a->getValue();
303 
304   // Optimization file format. Defaults to yaml
305   if (const llvm::opt::Arg *a =
306           args.getLastArg(clang::driver::options::OPT_opt_record_format))
307     opts.OptRecordFormat = a->getValue();
308 
309   // Specifies, using a regex, which successful optimization passes(middle and
310   // backend), to include in the final optimization record file generated. If
311   // not provided -fsave-optimization-record will include all passes.
312   if (const llvm::opt::Arg *a =
313           args.getLastArg(clang::driver::options::OPT_opt_record_passes))
314     opts.OptRecordPasses = a->getValue();
315 
316   // Create OptRemark that allows printing of all successful optimization
317   // passes applied.
318   opts.OptimizationRemark =
319       parseOptimizationRemark(diags, args, clang::driver::options::OPT_Rpass_EQ,
320                               /*remarkOptName=*/"pass");
321 
322   // Create OptRemark that allows all missed optimization passes to be printed.
323   opts.OptimizationRemarkMissed = parseOptimizationRemark(
324       diags, args, clang::driver::options::OPT_Rpass_missed_EQ,
325       /*remarkOptName=*/"pass-missed");
326 
327   // Create OptRemark that allows all optimization decisions made by LLVM
328   // to be printed.
329   opts.OptimizationRemarkAnalysis = parseOptimizationRemark(
330       diags, args, clang::driver::options::OPT_Rpass_analysis_EQ,
331       /*remarkOptName=*/"pass-analysis");
332 
333   if (opts.getDebugInfo() == llvm::codegenoptions::NoDebugInfo) {
334     // If the user requested a flag that requires source locations available in
335     // the backend, make sure that the backend tracks source location
336     // information.
337     bool needLocTracking = !opts.OptRecordFile.empty() ||
338                            !opts.OptRecordPasses.empty() ||
339                            !opts.OptRecordFormat.empty() ||
340                            opts.OptimizationRemark.hasValidPattern() ||
341                            opts.OptimizationRemarkMissed.hasValidPattern() ||
342                            opts.OptimizationRemarkAnalysis.hasValidPattern();
343 
344     if (needLocTracking)
345       opts.setDebugInfo(llvm::codegenoptions::LocTrackingOnly);
346   }
347 
348   if (auto *a = args.getLastArg(clang::driver::options::OPT_save_temps_EQ))
349     opts.SaveTempsDir = a->getValue();
350 
351   // -mlink-builtin-bitcode
352   for (auto *a :
353        args.filtered(clang::driver::options::OPT_mlink_builtin_bitcode))
354     opts.BuiltinBCLibs.push_back(a->getValue());
355 
356   // -mrelocation-model option.
357   if (const llvm::opt::Arg *a =
358           args.getLastArg(clang::driver::options::OPT_mrelocation_model)) {
359     llvm::StringRef modelName = a->getValue();
360     auto relocModel =
361         llvm::StringSwitch<std::optional<llvm::Reloc::Model>>(modelName)
362             .Case("static", llvm::Reloc::Static)
363             .Case("pic", llvm::Reloc::PIC_)
364             .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC)
365             .Case("ropi", llvm::Reloc::ROPI)
366             .Case("rwpi", llvm::Reloc::RWPI)
367             .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
368             .Default(std::nullopt);
369     if (relocModel.has_value())
370       opts.setRelocationModel(*relocModel);
371     else
372       diags.Report(clang::diag::err_drv_invalid_value)
373           << a->getAsString(args) << modelName;
374   }
375 
376   // -pic-level and -pic-is-pie option.
377   if (int picLevel = getLastArgIntValue(
378           args, clang::driver::options::OPT_pic_level, 0, diags)) {
379     if (picLevel > 2)
380       diags.Report(clang::diag::err_drv_invalid_value)
381           << args.getLastArg(clang::driver::options::OPT_pic_level)
382                  ->getAsString(args)
383           << picLevel;
384 
385     opts.PICLevel = picLevel;
386     if (args.hasArg(clang::driver::options::OPT_pic_is_pie))
387       opts.IsPIE = 1;
388   }
389 
390   // -mcmodel option.
391   if (const llvm::opt::Arg *a =
392           args.getLastArg(clang::driver::options::OPT_mcmodel_EQ)) {
393     llvm::StringRef modelName = a->getValue();
394     std::optional<llvm::CodeModel::Model> codeModel = getCodeModel(modelName);
395 
396     if (codeModel.has_value())
397       opts.CodeModel = modelName;
398     else
399       diags.Report(clang::diag::err_drv_invalid_value)
400           << a->getAsString(args) << modelName;
401   }
402 
403   if (const llvm::opt::Arg *arg = args.getLastArg(
404           clang::driver::options::OPT_mlarge_data_threshold_EQ)) {
405     uint64_t LDT;
406     if (llvm::StringRef(arg->getValue()).getAsInteger(/*Radix=*/10, LDT)) {
407       diags.Report(clang::diag::err_drv_invalid_value)
408           << arg->getSpelling() << arg->getValue();
409     }
410     opts.LargeDataThreshold = LDT;
411   }
412 
413   // This option is compatible with -f[no-]underscoring in gfortran.
414   if (args.hasFlag(clang::driver::options::OPT_fno_underscoring,
415                    clang::driver::options::OPT_funderscoring, false)) {
416     opts.Underscoring = 0;
417   }
418 }
419 
420 /// Parses all target input arguments and populates the target
421 /// options accordingly.
422 ///
423 /// \param [in] opts The target options instance to update
424 /// \param [in] args The list of input arguments (from the compiler invocation)
425 static void parseTargetArgs(TargetOptions &opts, llvm::opt::ArgList &args) {
426   if (const llvm::opt::Arg *a =
427           args.getLastArg(clang::driver::options::OPT_triple))
428     opts.triple = a->getValue();
429 
430   if (const llvm::opt::Arg *a =
431           args.getLastArg(clang::driver::options::OPT_target_cpu))
432     opts.cpu = a->getValue();
433 
434   if (const llvm::opt::Arg *a =
435           args.getLastArg(clang::driver::options::OPT_tune_cpu))
436     opts.cpuToTuneFor = a->getValue();
437 
438   for (const llvm::opt::Arg *currentArg :
439        args.filtered(clang::driver::options::OPT_target_feature))
440     opts.featuresAsWritten.emplace_back(currentArg->getValue());
441 }
442 
443 // Tweak the frontend configuration based on the frontend action
444 static void setUpFrontendBasedOnAction(FrontendOptions &opts) {
445   if (opts.programAction == DebugDumpParsingLog)
446     opts.instrumentedParse = true;
447 
448   if (opts.programAction == DebugDumpProvenance ||
449       opts.programAction == Fortran::frontend::GetDefinition)
450     opts.needProvenanceRangeToCharBlockMappings = true;
451 }
452 
453 /// Parse the argument specified for the -fconvert=<value> option
454 static std::optional<const char *> parseConvertArg(const char *s) {
455   return llvm::StringSwitch<std::optional<const char *>>(s)
456       .Case("unknown", "UNKNOWN")
457       .Case("native", "NATIVE")
458       .Case("little-endian", "LITTLE_ENDIAN")
459       .Case("big-endian", "BIG_ENDIAN")
460       .Case("swap", "SWAP")
461       .Default(std::nullopt);
462 }
463 
464 static bool parseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args,
465                               clang::DiagnosticsEngine &diags) {
466   unsigned numErrorsBefore = diags.getNumErrors();
467 
468   // By default the frontend driver creates a ParseSyntaxOnly action.
469   opts.programAction = ParseSyntaxOnly;
470 
471   // Treat multiple action options as an invocation error. Note that `clang
472   // -cc1` does accept multiple action options, but will only consider the
473   // rightmost one.
474   if (args.hasMultipleArgs(clang::driver::options::OPT_Action_Group)) {
475     const unsigned diagID = diags.getCustomDiagID(
476         clang::DiagnosticsEngine::Error, "Only one action option is allowed");
477     diags.Report(diagID);
478     return false;
479   }
480 
481   // Identify the action (i.e. opts.ProgramAction)
482   if (const llvm::opt::Arg *a =
483           args.getLastArg(clang::driver::options::OPT_Action_Group)) {
484     switch (a->getOption().getID()) {
485     default: {
486       llvm_unreachable("Invalid option in group!");
487     }
488     case clang::driver::options::OPT_test_io:
489       opts.programAction = InputOutputTest;
490       break;
491     case clang::driver::options::OPT_E:
492       opts.programAction = PrintPreprocessedInput;
493       break;
494     case clang::driver::options::OPT_fsyntax_only:
495       opts.programAction = ParseSyntaxOnly;
496       break;
497     case clang::driver::options::OPT_emit_fir:
498       opts.programAction = EmitFIR;
499       break;
500     case clang::driver::options::OPT_emit_hlfir:
501       opts.programAction = EmitHLFIR;
502       break;
503     case clang::driver::options::OPT_emit_llvm:
504       opts.programAction = EmitLLVM;
505       break;
506     case clang::driver::options::OPT_emit_llvm_bc:
507       opts.programAction = EmitLLVMBitcode;
508       break;
509     case clang::driver::options::OPT_emit_obj:
510       opts.programAction = EmitObj;
511       break;
512     case clang::driver::options::OPT_S:
513       opts.programAction = EmitAssembly;
514       break;
515     case clang::driver::options::OPT_fdebug_unparse:
516       opts.programAction = DebugUnparse;
517       break;
518     case clang::driver::options::OPT_fdebug_unparse_no_sema:
519       opts.programAction = DebugUnparseNoSema;
520       break;
521     case clang::driver::options::OPT_fdebug_unparse_with_symbols:
522       opts.programAction = DebugUnparseWithSymbols;
523       break;
524     case clang::driver::options::OPT_fdebug_unparse_with_modules:
525       opts.programAction = DebugUnparseWithModules;
526       break;
527     case clang::driver::options::OPT_fdebug_dump_symbols:
528       opts.programAction = DebugDumpSymbols;
529       break;
530     case clang::driver::options::OPT_fdebug_dump_parse_tree:
531       opts.programAction = DebugDumpParseTree;
532       break;
533     case clang::driver::options::OPT_fdebug_dump_pft:
534       opts.programAction = DebugDumpPFT;
535       break;
536     case clang::driver::options::OPT_fdebug_dump_all:
537       opts.programAction = DebugDumpAll;
538       break;
539     case clang::driver::options::OPT_fdebug_dump_parse_tree_no_sema:
540       opts.programAction = DebugDumpParseTreeNoSema;
541       break;
542     case clang::driver::options::OPT_fdebug_dump_provenance:
543       opts.programAction = DebugDumpProvenance;
544       break;
545     case clang::driver::options::OPT_fdebug_dump_parsing_log:
546       opts.programAction = DebugDumpParsingLog;
547       break;
548     case clang::driver::options::OPT_fdebug_measure_parse_tree:
549       opts.programAction = DebugMeasureParseTree;
550       break;
551     case clang::driver::options::OPT_fdebug_pre_fir_tree:
552       opts.programAction = DebugPreFIRTree;
553       break;
554     case clang::driver::options::OPT_fget_symbols_sources:
555       opts.programAction = GetSymbolsSources;
556       break;
557     case clang::driver::options::OPT_fget_definition:
558       opts.programAction = GetDefinition;
559       break;
560     case clang::driver::options::OPT_init_only:
561       opts.programAction = InitOnly;
562       break;
563 
564       // TODO:
565       // case clang::driver::options::OPT_emit_llvm:
566       // case clang::driver::options::OPT_emit_llvm_only:
567       // case clang::driver::options::OPT_emit_codegen_only:
568       // case clang::driver::options::OPT_emit_module:
569       // (...)
570     }
571 
572     // Parse the values provided with `-fget-definition` (there should be 3
573     // integers)
574     if (llvm::opt::OptSpecifier(a->getOption().getID()) ==
575         clang::driver::options::OPT_fget_definition) {
576       unsigned optVals[3] = {0, 0, 0};
577 
578       for (unsigned i = 0; i < 3; i++) {
579         llvm::StringRef val = a->getValue(i);
580 
581         if (val.getAsInteger(10, optVals[i])) {
582           // A non-integer was encountered - that's an error.
583           diags.Report(clang::diag::err_drv_invalid_value)
584               << a->getOption().getName() << val;
585           break;
586         }
587       }
588       opts.getDefVals.line = optVals[0];
589       opts.getDefVals.startColumn = optVals[1];
590       opts.getDefVals.endColumn = optVals[2];
591     }
592   }
593 
594   // Parsing -load <dsopath> option and storing shared object path
595   if (llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_load)) {
596     opts.plugins.push_back(a->getValue());
597   }
598 
599   // Parsing -plugin <name> option and storing plugin name and setting action
600   if (const llvm::opt::Arg *a =
601           args.getLastArg(clang::driver::options::OPT_plugin)) {
602     opts.programAction = PluginAction;
603     opts.actionName = a->getValue();
604   }
605 
606   opts.outputFile = args.getLastArgValue(clang::driver::options::OPT_o);
607   opts.showHelp = args.hasArg(clang::driver::options::OPT_help);
608   opts.showVersion = args.hasArg(clang::driver::options::OPT_version);
609 
610   // Get the input kind (from the value passed via `-x`)
611   InputKind dashX(Language::Unknown);
612   if (const llvm::opt::Arg *a =
613           args.getLastArg(clang::driver::options::OPT_x)) {
614     llvm::StringRef xValue = a->getValue();
615     // Principal languages.
616     dashX = llvm::StringSwitch<InputKind>(xValue)
617                 // Flang does not differentiate between pre-processed and not
618                 // pre-processed inputs.
619                 .Case("f95", Language::Fortran)
620                 .Case("f95-cpp-input", Language::Fortran)
621                 // CUDA Fortran
622                 .Case("cuda", Language::Fortran)
623                 .Default(Language::Unknown);
624 
625     // Flang's intermediate representations.
626     if (dashX.isUnknown())
627       dashX = llvm::StringSwitch<InputKind>(xValue)
628                   .Case("ir", Language::LLVM_IR)
629                   .Case("fir", Language::MLIR)
630                   .Case("mlir", Language::MLIR)
631                   .Default(Language::Unknown);
632 
633     if (dashX.isUnknown())
634       diags.Report(clang::diag::err_drv_invalid_value)
635           << a->getAsString(args) << a->getValue();
636   }
637 
638   // Collect the input files and save them in our instance of FrontendOptions.
639   std::vector<std::string> inputs =
640       args.getAllArgValues(clang::driver::options::OPT_INPUT);
641   opts.inputs.clear();
642   if (inputs.empty())
643     // '-' is the default input if none is given.
644     inputs.push_back("-");
645   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
646     InputKind ik = dashX;
647     if (ik.isUnknown()) {
648       ik = FrontendOptions::getInputKindForExtension(
649           llvm::StringRef(inputs[i]).rsplit('.').second);
650       if (ik.isUnknown())
651         ik = Language::Unknown;
652       if (i == 0)
653         dashX = ik;
654     }
655 
656     opts.inputs.emplace_back(std::move(inputs[i]), ik);
657   }
658 
659   // Set fortranForm based on options -ffree-form and -ffixed-form.
660   if (const auto *arg =
661           args.getLastArg(clang::driver::options::OPT_ffixed_form,
662                           clang::driver::options::OPT_ffree_form)) {
663     opts.fortranForm =
664         arg->getOption().matches(clang::driver::options::OPT_ffixed_form)
665             ? FortranForm::FixedForm
666             : FortranForm::FreeForm;
667   }
668 
669   // Set fixedFormColumns based on -ffixed-line-length=<value>
670   if (const auto *arg =
671           args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) {
672     llvm::StringRef argValue = llvm::StringRef(arg->getValue());
673     std::int64_t columns = -1;
674     if (argValue == "none") {
675       columns = 0;
676     } else if (argValue.getAsInteger(/*Radix=*/10, columns)) {
677       columns = -1;
678     }
679     if (columns < 0) {
680       diags.Report(clang::diag::err_drv_negative_columns)
681           << arg->getOption().getName() << arg->getValue();
682     } else if (columns == 0) {
683       opts.fixedFormColumns = 1000000;
684     } else if (columns < 7) {
685       diags.Report(clang::diag::err_drv_small_columns)
686           << arg->getOption().getName() << arg->getValue() << "7";
687     } else {
688       opts.fixedFormColumns = columns;
689     }
690   }
691 
692   // Set conversion based on -fconvert=<value>
693   if (const auto *arg =
694           args.getLastArg(clang::driver::options::OPT_fconvert_EQ)) {
695     const char *argValue = arg->getValue();
696     if (auto convert = parseConvertArg(argValue))
697       opts.envDefaults.push_back({"FORT_CONVERT", *convert});
698     else
699       diags.Report(clang::diag::err_drv_invalid_value)
700           << arg->getAsString(args) << argValue;
701   }
702 
703   // -f{no-}implicit-none
704   opts.features.Enable(
705       Fortran::common::LanguageFeature::ImplicitNoneTypeAlways,
706       args.hasFlag(clang::driver::options::OPT_fimplicit_none,
707                    clang::driver::options::OPT_fno_implicit_none, false));
708 
709   // -f{no-}backslash
710   opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes,
711                        args.hasFlag(clang::driver::options::OPT_fbackslash,
712                                     clang::driver::options::OPT_fno_backslash,
713                                     false));
714 
715   // -f{no-}logical-abbreviations
716   opts.features.Enable(
717       Fortran::common::LanguageFeature::LogicalAbbreviations,
718       args.hasFlag(clang::driver::options::OPT_flogical_abbreviations,
719                    clang::driver::options::OPT_fno_logical_abbreviations,
720                    false));
721 
722   // -f{no-}xor-operator
723   opts.features.Enable(
724       Fortran::common::LanguageFeature::XOROperator,
725       args.hasFlag(clang::driver::options::OPT_fxor_operator,
726                    clang::driver::options::OPT_fno_xor_operator, false));
727 
728   // -fno-automatic
729   if (args.hasArg(clang::driver::options::OPT_fno_automatic)) {
730     opts.features.Enable(Fortran::common::LanguageFeature::DefaultSave);
731   }
732 
733   if (args.hasArg(
734           clang::driver::options::OPT_falternative_parameter_statement)) {
735     opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter);
736   }
737   if (const llvm::opt::Arg *arg =
738           args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) {
739     llvm::StringRef argValue = arg->getValue();
740     if (argValue == "utf-8") {
741       opts.encoding = Fortran::parser::Encoding::UTF_8;
742     } else if (argValue == "latin-1") {
743       opts.encoding = Fortran::parser::Encoding::LATIN_1;
744     } else {
745       diags.Report(clang::diag::err_drv_invalid_value)
746           << arg->getAsString(args) << argValue;
747     }
748   }
749 
750   setUpFrontendBasedOnAction(opts);
751   opts.dashX = dashX;
752 
753   return diags.getNumErrors() == numErrorsBefore;
754 }
755 
756 // Generate the path to look for intrinsic modules
757 static std::string getIntrinsicDir(const char *argv) {
758   // TODO: Find a system independent API
759   llvm::SmallString<128> driverPath;
760   driverPath.assign(llvm::sys::fs::getMainExecutable(argv, nullptr));
761   llvm::sys::path::remove_filename(driverPath);
762   driverPath.append("/../include/flang/");
763   return std::string(driverPath);
764 }
765 
766 // Generate the path to look for OpenMP headers
767 static std::string getOpenMPHeadersDir(const char *argv) {
768   llvm::SmallString<128> includePath;
769   includePath.assign(llvm::sys::fs::getMainExecutable(argv, nullptr));
770   llvm::sys::path::remove_filename(includePath);
771   includePath.append("/../include/flang/OpenMP/");
772   return std::string(includePath);
773 }
774 
775 /// Parses all preprocessor input arguments and populates the preprocessor
776 /// options accordingly.
777 ///
778 /// \param [in] opts The preprocessor options instance
779 /// \param [out] args The list of input arguments
780 static void parsePreprocessorArgs(Fortran::frontend::PreprocessorOptions &opts,
781                                   llvm::opt::ArgList &args) {
782   // Add macros from the command line.
783   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_D,
784                                               clang::driver::options::OPT_U)) {
785     if (currentArg->getOption().matches(clang::driver::options::OPT_D)) {
786       opts.addMacroDef(currentArg->getValue());
787     } else {
788       opts.addMacroUndef(currentArg->getValue());
789     }
790   }
791 
792   // Add the ordered list of -I's.
793   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I))
794     opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue());
795 
796   // Prepend the ordered list of -intrinsic-modules-path
797   // to the default location to search.
798   for (const auto *currentArg :
799        args.filtered(clang::driver::options::OPT_fintrinsic_modules_path))
800     opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue());
801 
802   // -cpp/-nocpp
803   if (const auto *currentArg = args.getLastArg(
804           clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp))
805     opts.macrosFlag =
806         (currentArg->getOption().matches(clang::driver::options::OPT_cpp))
807             ? PPMacrosFlag::Include
808             : PPMacrosFlag::Exclude;
809 
810   opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat);
811   opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P);
812   opts.showMacros = args.hasArg(clang::driver::options::OPT_dM);
813 }
814 
815 /// Parses all semantic related arguments and populates the variables
816 /// options accordingly. Returns false if new errors are generated.
817 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
818                           clang::DiagnosticsEngine &diags) {
819   unsigned numErrorsBefore = diags.getNumErrors();
820 
821   // -J/module-dir option
822   auto moduleDirList =
823       args.getAllArgValues(clang::driver::options::OPT_module_dir);
824   // User can only specify -J/-module-dir once
825   // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html
826   if (moduleDirList.size() > 1) {
827     const unsigned diagID =
828         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
829                               "Only one '-module-dir/-J' option allowed");
830     diags.Report(diagID);
831   }
832   if (moduleDirList.size() == 1)
833     res.setModuleDir(moduleDirList[0]);
834 
835   // -fdebug-module-writer option
836   if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) {
837     res.setDebugModuleDir(true);
838   }
839 
840   // -fhermetic-module-files option
841   if (args.hasArg(clang::driver::options::OPT_fhermetic_module_files)) {
842     res.setHermeticModuleFileOutput(true);
843   }
844 
845   // -module-suffix
846   if (const auto *moduleSuffix =
847           args.getLastArg(clang::driver::options::OPT_module_suffix)) {
848     res.setModuleFileSuffix(moduleSuffix->getValue());
849   }
850 
851   // -f{no-}analyzed-objects-for-unparse
852   res.setUseAnalyzedObjectsForUnparse(args.hasFlag(
853       clang::driver::options::OPT_fanalyzed_objects_for_unparse,
854       clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true));
855 
856   return diags.getNumErrors() == numErrorsBefore;
857 }
858 
859 /// Parses all diagnostics related arguments and populates the variables
860 /// options accordingly. Returns false if new errors are generated.
861 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
862                           clang::DiagnosticsEngine &diags) {
863   unsigned numErrorsBefore = diags.getNumErrors();
864 
865   // -Werror option
866   // TODO: Currently throws a Diagnostic for anything other than -W<error>,
867   // this has to change when other -W<opt>'s are supported.
868   if (args.hasArg(clang::driver::options::OPT_W_Joined)) {
869     const auto &wArgs =
870         args.getAllArgValues(clang::driver::options::OPT_W_Joined);
871     for (const auto &wArg : wArgs) {
872       if (wArg == "error") {
873         res.setWarnAsErr(true);
874       } else {
875         const unsigned diagID =
876             diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
877                                   "Only `-Werror` is supported currently.");
878         diags.Report(diagID);
879       }
880     }
881   }
882 
883   // Default to off for `flang-new -fc1`.
884   res.getFrontendOpts().showColors =
885       parseShowColorsArgs(args, /*defaultDiagColor=*/false);
886 
887   // Honor color diagnostics.
888   res.getDiagnosticOpts().ShowColors = res.getFrontendOpts().showColors;
889 
890   return diags.getNumErrors() == numErrorsBefore;
891 }
892 
893 /// Parses all Dialect related arguments and populates the variables
894 /// options accordingly. Returns false if new errors are generated.
895 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
896                              clang::DiagnosticsEngine &diags) {
897   unsigned numErrorsBefore = diags.getNumErrors();
898 
899   // -fdefault* family
900   if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
901     res.getDefaultKinds().set_defaultRealKind(8);
902     res.getDefaultKinds().set_doublePrecisionKind(16);
903   }
904   if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) {
905     res.getDefaultKinds().set_defaultIntegerKind(8);
906     res.getDefaultKinds().set_subscriptIntegerKind(8);
907     res.getDefaultKinds().set_sizeIntegerKind(8);
908     res.getDefaultKinds().set_defaultLogicalKind(8);
909   }
910   if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) {
911     if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
912       // -fdefault-double-8 has to be used with -fdefault-real-8
913       // to be compatible with gfortran
914       const unsigned diagID = diags.getCustomDiagID(
915           clang::DiagnosticsEngine::Error,
916           "Use of `-fdefault-double-8` requires `-fdefault-real-8`");
917       diags.Report(diagID);
918     }
919     // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html
920     res.getDefaultKinds().set_doublePrecisionKind(8);
921   }
922   if (args.hasArg(clang::driver::options::OPT_flarge_sizes))
923     res.getDefaultKinds().set_sizeIntegerKind(8);
924 
925   // -x cuda
926   auto language = args.getLastArgValue(clang::driver::options::OPT_x);
927   if (language == "cuda") {
928     res.getFrontendOpts().features.Enable(
929         Fortran::common::LanguageFeature::CUDA);
930   }
931 
932   // -fopenacc
933   if (args.hasArg(clang::driver::options::OPT_fopenacc)) {
934     res.getFrontendOpts().features.Enable(
935         Fortran::common::LanguageFeature::OpenACC);
936   }
937 
938   // -pedantic
939   if (args.hasArg(clang::driver::options::OPT_pedantic)) {
940     res.setEnableConformanceChecks();
941     res.setEnableUsageChecks();
942   }
943 
944   // -w
945   if (args.hasArg(clang::driver::options::OPT_w))
946     res.setDisableWarnings();
947 
948   // -std=f2018
949   // TODO: Set proper options when more fortran standards
950   // are supported.
951   if (args.hasArg(clang::driver::options::OPT_std_EQ)) {
952     auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ);
953     // We only allow f2018 as the given standard
954     if (standard == "f2018") {
955       res.setEnableConformanceChecks();
956     } else {
957       const unsigned diagID =
958           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
959                                 "Only -std=f2018 is allowed currently.");
960       diags.Report(diagID);
961     }
962   }
963   return diags.getNumErrors() == numErrorsBefore;
964 }
965 
966 /// Parses all OpenMP related arguments if the -fopenmp option is present,
967 /// populating the \c res object accordingly. Returns false if new errors are
968 /// generated.
969 static bool parseOpenMPArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
970                             clang::DiagnosticsEngine &diags) {
971   if (!args.hasArg(clang::driver::options::OPT_fopenmp))
972     return true;
973 
974   unsigned numErrorsBefore = diags.getNumErrors();
975   llvm::Triple t(res.getTargetOpts().triple);
976 
977   // By default OpenMP is set to 1.1 version
978   res.getLangOpts().OpenMPVersion = 11;
979   res.getFrontendOpts().features.Enable(
980       Fortran::common::LanguageFeature::OpenMP);
981   if (int Version = getLastArgIntValue(
982           args, clang::driver::options::OPT_fopenmp_version_EQ,
983           res.getLangOpts().OpenMPVersion, diags)) {
984     res.getLangOpts().OpenMPVersion = Version;
985   }
986   if (args.hasArg(clang::driver::options::OPT_fopenmp_force_usm)) {
987     res.getLangOpts().OpenMPForceUSM = 1;
988   }
989   if (args.hasArg(clang::driver::options::OPT_fopenmp_is_target_device)) {
990     res.getLangOpts().OpenMPIsTargetDevice = 1;
991 
992     // Get OpenMP host file path if any and report if a non existent file is
993     // found
994     if (auto *arg = args.getLastArg(
995             clang::driver::options::OPT_fopenmp_host_ir_file_path)) {
996       res.getLangOpts().OMPHostIRFile = arg->getValue();
997       if (!llvm::sys::fs::exists(res.getLangOpts().OMPHostIRFile))
998         diags.Report(clang::diag::err_drv_omp_host_ir_file_not_found)
999             << res.getLangOpts().OMPHostIRFile;
1000     }
1001 
1002     if (args.hasFlag(
1003             clang::driver::options::OPT_fopenmp_assume_teams_oversubscription,
1004             clang::driver::options::
1005                 OPT_fno_openmp_assume_teams_oversubscription,
1006             /*Default=*/false))
1007       res.getLangOpts().OpenMPTeamSubscription = true;
1008 
1009     if (args.hasArg(clang::driver::options::OPT_fopenmp_assume_no_thread_state))
1010       res.getLangOpts().OpenMPNoThreadState = 1;
1011 
1012     if (args.hasArg(
1013             clang::driver::options::OPT_fopenmp_assume_no_nested_parallelism))
1014       res.getLangOpts().OpenMPNoNestedParallelism = 1;
1015 
1016     if (args.hasFlag(
1017             clang::driver::options::OPT_fopenmp_assume_threads_oversubscription,
1018             clang::driver::options::
1019                 OPT_fno_openmp_assume_threads_oversubscription,
1020             /*Default=*/false))
1021       res.getLangOpts().OpenMPThreadSubscription = true;
1022 
1023     if ((args.hasArg(clang::driver::options::OPT_fopenmp_target_debug) ||
1024          args.hasArg(clang::driver::options::OPT_fopenmp_target_debug_EQ))) {
1025       res.getLangOpts().OpenMPTargetDebug = getLastArgIntValue(
1026           args, clang::driver::options::OPT_fopenmp_target_debug_EQ,
1027           res.getLangOpts().OpenMPTargetDebug, diags);
1028 
1029       if (!res.getLangOpts().OpenMPTargetDebug &&
1030           args.hasArg(clang::driver::options::OPT_fopenmp_target_debug))
1031         res.getLangOpts().OpenMPTargetDebug = 1;
1032     }
1033     if (args.hasArg(clang::driver::options::OPT_nogpulib))
1034       res.getLangOpts().NoGPULib = 1;
1035   }
1036 
1037   switch (llvm::Triple(res.getTargetOpts().triple).getArch()) {
1038   case llvm::Triple::nvptx:
1039   case llvm::Triple::nvptx64:
1040   case llvm::Triple::amdgcn:
1041     if (!res.getLangOpts().OpenMPIsTargetDevice) {
1042       const unsigned diagID = diags.getCustomDiagID(
1043           clang::DiagnosticsEngine::Error,
1044           "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
1045       diags.Report(diagID);
1046     }
1047     res.getLangOpts().OpenMPIsGPU = 1;
1048     break;
1049   default:
1050     res.getLangOpts().OpenMPIsGPU = 0;
1051     break;
1052   }
1053 
1054   // Get the OpenMP target triples if any.
1055   if (auto *arg =
1056           args.getLastArg(clang::driver::options::OPT_fopenmp_targets_EQ)) {
1057     enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit };
1058     auto getArchPtrSize = [](const llvm::Triple &triple) {
1059       if (triple.isArch16Bit())
1060         return Arch16Bit;
1061       if (triple.isArch32Bit())
1062         return Arch32Bit;
1063       assert(triple.isArch64Bit() && "Expected 64-bit architecture");
1064       return Arch64Bit;
1065     };
1066 
1067     for (unsigned i = 0; i < arg->getNumValues(); ++i) {
1068       llvm::Triple tt(arg->getValue(i));
1069 
1070       if (tt.getArch() == llvm::Triple::UnknownArch ||
1071           !(tt.getArch() == llvm::Triple::aarch64 || tt.isPPC() ||
1072             tt.getArch() == llvm::Triple::systemz ||
1073             tt.getArch() == llvm::Triple::nvptx ||
1074             tt.getArch() == llvm::Triple::nvptx64 ||
1075             tt.getArch() == llvm::Triple::amdgcn ||
1076             tt.getArch() == llvm::Triple::x86 ||
1077             tt.getArch() == llvm::Triple::x86_64))
1078         diags.Report(clang::diag::err_drv_invalid_omp_target)
1079             << arg->getValue(i);
1080       else if (getArchPtrSize(t) != getArchPtrSize(tt))
1081         diags.Report(clang::diag::err_drv_incompatible_omp_arch)
1082             << arg->getValue(i) << t.str();
1083       else
1084         res.getLangOpts().OMPTargetTriples.push_back(tt);
1085     }
1086   }
1087   return diags.getNumErrors() == numErrorsBefore;
1088 }
1089 
1090 /// Parses all floating point related arguments and populates the
1091 /// CompilerInvocation accordingly.
1092 /// Returns false if new errors are generated.
1093 ///
1094 /// \param [out] invoc Stores the processed arguments
1095 /// \param [in] args The compiler invocation arguments to parse
1096 /// \param [out] diags DiagnosticsEngine to report erros with
1097 static bool parseFloatingPointArgs(CompilerInvocation &invoc,
1098                                    llvm::opt::ArgList &args,
1099                                    clang::DiagnosticsEngine &diags) {
1100   LangOptions &opts = invoc.getLangOpts();
1101 
1102   if (const llvm::opt::Arg *a =
1103           args.getLastArg(clang::driver::options::OPT_ffp_contract)) {
1104     const llvm::StringRef val = a->getValue();
1105     enum LangOptions::FPModeKind fpContractMode;
1106 
1107     if (val == "off")
1108       fpContractMode = LangOptions::FPM_Off;
1109     else if (val == "fast")
1110       fpContractMode = LangOptions::FPM_Fast;
1111     else {
1112       diags.Report(clang::diag::err_drv_unsupported_option_argument)
1113           << a->getSpelling() << val;
1114       return false;
1115     }
1116 
1117     opts.setFPContractMode(fpContractMode);
1118   }
1119 
1120   if (args.getLastArg(clang::driver::options::OPT_menable_no_infs)) {
1121     opts.NoHonorInfs = true;
1122   }
1123 
1124   if (args.getLastArg(clang::driver::options::OPT_menable_no_nans)) {
1125     opts.NoHonorNaNs = true;
1126   }
1127 
1128   if (args.getLastArg(clang::driver::options::OPT_fapprox_func)) {
1129     opts.ApproxFunc = true;
1130   }
1131 
1132   if (args.getLastArg(clang::driver::options::OPT_fno_signed_zeros)) {
1133     opts.NoSignedZeros = true;
1134   }
1135 
1136   if (args.getLastArg(clang::driver::options::OPT_mreassociate)) {
1137     opts.AssociativeMath = true;
1138   }
1139 
1140   if (args.getLastArg(clang::driver::options::OPT_freciprocal_math)) {
1141     opts.ReciprocalMath = true;
1142   }
1143 
1144   if (args.getLastArg(clang::driver::options::OPT_ffast_math)) {
1145     opts.NoHonorInfs = true;
1146     opts.NoHonorNaNs = true;
1147     opts.AssociativeMath = true;
1148     opts.ReciprocalMath = true;
1149     opts.ApproxFunc = true;
1150     opts.NoSignedZeros = true;
1151     opts.setFPContractMode(LangOptions::FPM_Fast);
1152   }
1153 
1154   return true;
1155 }
1156 
1157 /// Parses vscale range options and populates the CompilerInvocation
1158 /// accordingly.
1159 /// Returns false if new errors are generated.
1160 ///
1161 /// \param [out] invoc Stores the processed arguments
1162 /// \param [in] args The compiler invocation arguments to parse
1163 /// \param [out] diags DiagnosticsEngine to report erros with
1164 static bool parseVScaleArgs(CompilerInvocation &invoc, llvm::opt::ArgList &args,
1165                             clang::DiagnosticsEngine &diags) {
1166   const auto *vscaleMin =
1167       args.getLastArg(clang::driver::options::OPT_mvscale_min_EQ);
1168   const auto *vscaleMax =
1169       args.getLastArg(clang::driver::options::OPT_mvscale_max_EQ);
1170 
1171   if (!vscaleMin && !vscaleMax)
1172     return true;
1173 
1174   llvm::Triple triple = llvm::Triple(invoc.getTargetOpts().triple);
1175   if (!triple.isAArch64() && !triple.isRISCV()) {
1176     const unsigned diagID =
1177         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
1178                               "`-mvscale-max` and `-mvscale-min` are not "
1179                               "supported for this architecture: %0");
1180     diags.Report(diagID) << triple.getArchName();
1181     return false;
1182   }
1183 
1184   LangOptions &opts = invoc.getLangOpts();
1185   if (vscaleMin) {
1186     llvm::StringRef argValue = llvm::StringRef(vscaleMin->getValue());
1187     unsigned vscaleMinVal;
1188     if (argValue.getAsInteger(/*Radix=*/10, vscaleMinVal)) {
1189       diags.Report(clang::diag::err_drv_unsupported_option_argument)
1190           << vscaleMax->getSpelling() << argValue;
1191       return false;
1192     }
1193     opts.VScaleMin = vscaleMinVal;
1194   }
1195 
1196   if (vscaleMax) {
1197     llvm::StringRef argValue = llvm::StringRef(vscaleMax->getValue());
1198     unsigned vscaleMaxVal;
1199     if (argValue.getAsInteger(/*Radix=w*/ 10, vscaleMaxVal)) {
1200       diags.Report(clang::diag::err_drv_unsupported_option_argument)
1201           << vscaleMax->getSpelling() << argValue;
1202       return false;
1203     }
1204     opts.VScaleMax = vscaleMaxVal;
1205   }
1206   return true;
1207 }
1208 
1209 static bool parseLinkerOptionsArgs(CompilerInvocation &invoc,
1210                                    llvm::opt::ArgList &args,
1211                                    clang::DiagnosticsEngine &diags) {
1212   llvm::Triple triple = llvm::Triple(invoc.getTargetOpts().triple);
1213 
1214   // TODO: support --dependent-lib on other platforms when MLIR supports
1215   //       !llvm.dependent.lib
1216   if (args.hasArg(clang::driver::options::OPT_dependent_lib) &&
1217       !triple.isOSWindows()) {
1218     const unsigned diagID =
1219         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
1220                               "--dependent-lib is only supported on Windows");
1221     diags.Report(diagID);
1222     return false;
1223   }
1224 
1225   invoc.getCodeGenOpts().DependentLibs =
1226       args.getAllArgValues(clang::driver::options::OPT_dependent_lib);
1227   return true;
1228 }
1229 
1230 bool CompilerInvocation::createFromArgs(
1231     CompilerInvocation &invoc, llvm::ArrayRef<const char *> commandLineArgs,
1232     clang::DiagnosticsEngine &diags, const char *argv0) {
1233 
1234   bool success = true;
1235 
1236   // Set the default triple for this CompilerInvocation. This might be
1237   // overridden by users with `-triple` (see the call to `ParseTargetArgs`
1238   // below).
1239   // NOTE: Like in Clang, it would be nice to use option marshalling
1240   // for this so that the entire logic for setting-up the triple is in one
1241   // place.
1242   invoc.getTargetOpts().triple =
1243       llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple());
1244 
1245   // Parse the arguments
1246   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
1247   llvm::opt::Visibility visibilityMask(clang::driver::options::FC1Option);
1248   unsigned missingArgIndex, missingArgCount;
1249   llvm::opt::InputArgList args = opts.ParseArgs(
1250       commandLineArgs, missingArgIndex, missingArgCount, visibilityMask);
1251 
1252   // Check for missing argument error.
1253   if (missingArgCount) {
1254     diags.Report(clang::diag::err_drv_missing_argument)
1255         << args.getArgString(missingArgIndex) << missingArgCount;
1256     success = false;
1257   }
1258 
1259   // Issue errors on unknown arguments
1260   for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
1261     auto argString = a->getAsString(args);
1262     std::string nearest;
1263     if (opts.findNearest(argString, nearest, visibilityMask) > 1)
1264       diags.Report(clang::diag::err_drv_unknown_argument) << argString;
1265     else
1266       diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
1267           << argString << nearest;
1268     success = false;
1269   }
1270 
1271   // -flang-experimental-hlfir
1272   if (args.hasArg(clang::driver::options::OPT_flang_experimental_hlfir) ||
1273       args.hasArg(clang::driver::options::OPT_emit_hlfir)) {
1274     invoc.loweringOpts.setLowerToHighLevelFIR(true);
1275   }
1276 
1277   // -flang-deprecated-no-hlfir
1278   if (args.hasArg(clang::driver::options::OPT_flang_deprecated_no_hlfir) &&
1279       !args.hasArg(clang::driver::options::OPT_emit_hlfir)) {
1280     if (args.hasArg(clang::driver::options::OPT_flang_experimental_hlfir)) {
1281       const unsigned diagID = diags.getCustomDiagID(
1282           clang::DiagnosticsEngine::Error,
1283           "Options '-flang-experimental-hlfir' and "
1284           "'-flang-deprecated-no-hlfir' cannot be both specified");
1285       diags.Report(diagID);
1286     }
1287     invoc.loweringOpts.setLowerToHighLevelFIR(false);
1288   }
1289 
1290   // -fno-ppc-native-vector-element-order
1291   if (args.hasArg(clang::driver::options::OPT_fno_ppc_native_vec_elem_order)) {
1292     invoc.loweringOpts.setNoPPCNativeVecElemOrder(true);
1293   }
1294 
1295   // -flang-experimental-integer-overflow
1296   if (args.hasArg(
1297           clang::driver::options::OPT_flang_experimental_integer_overflow)) {
1298     invoc.loweringOpts.setNSWOnLoopVarInc(true);
1299   }
1300 
1301   // Preserve all the remark options requested, i.e. -Rpass, -Rpass-missed or
1302   // -Rpass-analysis. This will be used later when processing and outputting the
1303   // remarks generated by LLVM in ExecuteCompilerInvocation.cpp.
1304   for (auto *a : args.filtered(clang::driver::options::OPT_R_Group)) {
1305     if (a->getOption().matches(clang::driver::options::OPT_R_value_Group))
1306       // This is -Rfoo=, where foo is the name of the diagnostic
1307       // group. Add only the remark option name to the diagnostics. e.g. for
1308       // -Rpass= we will add the string "pass".
1309       invoc.getDiagnosticOpts().Remarks.push_back(
1310           std::string(a->getOption().getName().drop_front(1).rtrim("=-")));
1311     else
1312       // If no regex was provided, add the provided value, e.g. for -Rpass add
1313       // the string "pass".
1314       invoc.getDiagnosticOpts().Remarks.push_back(a->getValue());
1315   }
1316 
1317   success &= parseFrontendArgs(invoc.getFrontendOpts(), args, diags);
1318   parseTargetArgs(invoc.getTargetOpts(), args);
1319   parsePreprocessorArgs(invoc.getPreprocessorOpts(), args);
1320   parseCodeGenArgs(invoc.getCodeGenOpts(), args, diags);
1321   success &= parseDebugArgs(invoc.getCodeGenOpts(), args, diags);
1322   success &= parseVectorLibArg(invoc.getCodeGenOpts(), args, diags);
1323   success &= parseSemaArgs(invoc, args, diags);
1324   success &= parseDialectArgs(invoc, args, diags);
1325   success &= parseOpenMPArgs(invoc, args, diags);
1326   success &= parseDiagArgs(invoc, args, diags);
1327 
1328   // Collect LLVM (-mllvm) and MLIR (-mmlir) options.
1329   // NOTE: Try to avoid adding any options directly to `llvmArgs` or
1330   // `mlirArgs`. Instead, you can use
1331   //    * `-mllvm <your-llvm-option>`, or
1332   //    * `-mmlir <your-mlir-option>`.
1333   invoc.frontendOpts.llvmArgs =
1334       args.getAllArgValues(clang::driver::options::OPT_mllvm);
1335   invoc.frontendOpts.mlirArgs =
1336       args.getAllArgValues(clang::driver::options::OPT_mmlir);
1337 
1338   success &= parseFloatingPointArgs(invoc, args, diags);
1339 
1340   success &= parseVScaleArgs(invoc, args, diags);
1341 
1342   success &= parseLinkerOptionsArgs(invoc, args, diags);
1343 
1344   // Set the string to be used as the return value of the COMPILER_OPTIONS
1345   // intrinsic of iso_fortran_env. This is either passed in from the parent
1346   // compiler driver invocation with an environment variable, or failing that
1347   // set to the command line arguments of the frontend driver invocation.
1348   invoc.allCompilerInvocOpts = std::string();
1349   llvm::raw_string_ostream os(invoc.allCompilerInvocOpts);
1350   char *compilerOptsEnv = std::getenv("FLANG_COMPILER_OPTIONS_STRING");
1351   if (compilerOptsEnv != nullptr) {
1352     os << compilerOptsEnv;
1353   } else {
1354     os << argv0 << ' ';
1355     for (auto it = commandLineArgs.begin(), e = commandLineArgs.end(); it != e;
1356          ++it) {
1357       os << ' ' << *it;
1358     }
1359   }
1360 
1361   invoc.setArgv0(argv0);
1362 
1363   return success;
1364 }
1365 
1366 void CompilerInvocation::collectMacroDefinitions() {
1367   auto &ppOpts = this->getPreprocessorOpts();
1368 
1369   for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) {
1370     llvm::StringRef macro = ppOpts.macros[i].first;
1371     bool isUndef = ppOpts.macros[i].second;
1372 
1373     std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('=');
1374     llvm::StringRef macroName = macroPair.first;
1375     llvm::StringRef macroBody = macroPair.second;
1376 
1377     // For an #undef'd macro, we only care about the name.
1378     if (isUndef) {
1379       parserOpts.predefinitions.emplace_back(macroName.str(),
1380                                              std::optional<std::string>{});
1381       continue;
1382     }
1383 
1384     // For a #define'd macro, figure out the actual definition.
1385     if (macroName.size() == macro.size())
1386       macroBody = "1";
1387     else {
1388       // Note: GCC drops anything following an end-of-line character.
1389       llvm::StringRef::size_type end = macroBody.find_first_of("\n\r");
1390       macroBody = macroBody.substr(0, end);
1391     }
1392     parserOpts.predefinitions.emplace_back(
1393         macroName, std::optional<std::string>(macroBody.str()));
1394   }
1395 }
1396 
1397 void CompilerInvocation::setDefaultFortranOpts() {
1398   auto &fortranOptions = getFortranOpts();
1399 
1400   std::vector<std::string> searchDirectories{"."s};
1401   fortranOptions.searchDirectories = searchDirectories;
1402 
1403   // Add the location of omp_lib.h to the search directories. Currently this is
1404   // identical to the modules' directory.
1405   fortranOptions.searchDirectories.emplace_back(
1406       getOpenMPHeadersDir(getArgv0()));
1407 
1408   fortranOptions.isFixedForm = false;
1409 }
1410 
1411 // TODO: When expanding this method, consider creating a dedicated API for
1412 // this. Also at some point we will need to differentiate between different
1413 // targets and add dedicated predefines for each.
1414 void CompilerInvocation::setDefaultPredefinitions() {
1415   auto &fortranOptions = getFortranOpts();
1416   const auto &frontendOptions = getFrontendOpts();
1417   // Populate the macro list with version numbers and other predefinitions.
1418   fortranOptions.predefinitions.emplace_back("__flang__", "1");
1419   fortranOptions.predefinitions.emplace_back("__flang_major__",
1420                                              FLANG_VERSION_MAJOR_STRING);
1421   fortranOptions.predefinitions.emplace_back("__flang_minor__",
1422                                              FLANG_VERSION_MINOR_STRING);
1423   fortranOptions.predefinitions.emplace_back("__flang_patchlevel__",
1424                                              FLANG_VERSION_PATCHLEVEL_STRING);
1425 
1426   // Add predefinitions based on extensions enabled
1427   if (frontendOptions.features.IsEnabled(
1428           Fortran::common::LanguageFeature::OpenACC)) {
1429     fortranOptions.predefinitions.emplace_back("_OPENACC", "202211");
1430   }
1431   if (frontendOptions.features.IsEnabled(
1432           Fortran::common::LanguageFeature::OpenMP)) {
1433     Fortran::common::setOpenMPMacro(getLangOpts().OpenMPVersion,
1434                                     fortranOptions.predefinitions);
1435   }
1436 
1437   llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)};
1438   if (targetTriple.isPPC()) {
1439     // '__powerpc__' is a generic macro for any PowerPC cases. e.g. Max integer
1440     // size.
1441     fortranOptions.predefinitions.emplace_back("__powerpc__", "1");
1442   }
1443   if (targetTriple.isOSLinux()) {
1444     fortranOptions.predefinitions.emplace_back("__linux__", "1");
1445   }
1446 
1447   switch (targetTriple.getArch()) {
1448   default:
1449     break;
1450   case llvm::Triple::ArchType::x86_64:
1451     fortranOptions.predefinitions.emplace_back("__x86_64__", "1");
1452     fortranOptions.predefinitions.emplace_back("__x86_64", "1");
1453     break;
1454   }
1455 }
1456 
1457 void CompilerInvocation::setFortranOpts() {
1458   auto &fortranOptions = getFortranOpts();
1459   const auto &frontendOptions = getFrontendOpts();
1460   const auto &preprocessorOptions = getPreprocessorOpts();
1461   auto &moduleDirJ = getModuleDir();
1462 
1463   if (frontendOptions.fortranForm != FortranForm::Unknown) {
1464     fortranOptions.isFixedForm =
1465         frontendOptions.fortranForm == FortranForm::FixedForm;
1466   }
1467   fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns;
1468 
1469   fortranOptions.features = frontendOptions.features;
1470   fortranOptions.encoding = frontendOptions.encoding;
1471 
1472   // Adding search directories specified by -I
1473   fortranOptions.searchDirectories.insert(
1474       fortranOptions.searchDirectories.end(),
1475       preprocessorOptions.searchDirectoriesFromDashI.begin(),
1476       preprocessorOptions.searchDirectoriesFromDashI.end());
1477 
1478   // Add the ordered list of -intrinsic-modules-path
1479   fortranOptions.searchDirectories.insert(
1480       fortranOptions.searchDirectories.end(),
1481       preprocessorOptions.searchDirectoriesFromIntrModPath.begin(),
1482       preprocessorOptions.searchDirectoriesFromIntrModPath.end());
1483 
1484   //  Add the default intrinsic module directory
1485   fortranOptions.intrinsicModuleDirectories.emplace_back(
1486       getIntrinsicDir(getArgv0()));
1487 
1488   // Add the directory supplied through -J/-module-dir to the list of search
1489   // directories
1490   if (moduleDirJ != ".")
1491     fortranOptions.searchDirectories.emplace_back(moduleDirJ);
1492 
1493   if (frontendOptions.instrumentedParse)
1494     fortranOptions.instrumentedParse = true;
1495 
1496   if (frontendOptions.showColors)
1497     fortranOptions.showColors = true;
1498 
1499   if (frontendOptions.needProvenanceRangeToCharBlockMappings)
1500     fortranOptions.needProvenanceRangeToCharBlockMappings = true;
1501 
1502   if (getEnableConformanceChecks())
1503     fortranOptions.features.WarnOnAllNonstandard();
1504 
1505   if (getEnableUsageChecks())
1506     fortranOptions.features.WarnOnAllUsage();
1507 
1508   if (getDisableWarnings()) {
1509     fortranOptions.features.DisableAllNonstandardWarnings();
1510     fortranOptions.features.DisableAllUsageWarnings();
1511   }
1512 }
1513 
1514 std::unique_ptr<Fortran::semantics::SemanticsContext>
1515 CompilerInvocation::getSemanticsCtx(
1516     Fortran::parser::AllCookedSources &allCookedSources,
1517     const llvm::TargetMachine &targetMachine) {
1518   auto &fortranOptions = getFortranOpts();
1519 
1520   auto semanticsContext = std::make_unique<semantics::SemanticsContext>(
1521       getDefaultKinds(), fortranOptions.features, allCookedSources);
1522 
1523   semanticsContext->set_moduleDirectory(getModuleDir())
1524       .set_searchDirectories(fortranOptions.searchDirectories)
1525       .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories)
1526       .set_warningsAreErrors(getWarnAsErr())
1527       .set_moduleFileSuffix(getModuleFileSuffix())
1528       .set_underscoring(getCodeGenOpts().Underscoring);
1529 
1530   std::string compilerVersion = Fortran::common::getFlangFullVersion();
1531   Fortran::tools::setUpTargetCharacteristics(
1532       semanticsContext->targetCharacteristics(), targetMachine, compilerVersion,
1533       allCompilerInvocOpts);
1534   return semanticsContext;
1535 }
1536 
1537 /// Set \p loweringOptions controlling lowering behavior based
1538 /// on the \p optimizationLevel.
1539 void CompilerInvocation::setLoweringOptions() {
1540   const CodeGenOptions &codegenOpts = getCodeGenOpts();
1541 
1542   // Lower TRANSPOSE as a runtime call under -O0.
1543   loweringOpts.setOptimizeTranspose(codegenOpts.OptimizationLevel > 0);
1544   loweringOpts.setUnderscoring(codegenOpts.Underscoring);
1545 
1546   const LangOptions &langOptions = getLangOpts();
1547   Fortran::common::MathOptionsBase &mathOpts = loweringOpts.getMathOptions();
1548   // TODO: when LangOptions are finalized, we can represent
1549   //       the math related options using Fortran::commmon::MathOptionsBase,
1550   //       so that we can just copy it into LoweringOptions.
1551   mathOpts
1552       .setFPContractEnabled(langOptions.getFPContractMode() ==
1553                             LangOptions::FPM_Fast)
1554       .setNoHonorInfs(langOptions.NoHonorInfs)
1555       .setNoHonorNaNs(langOptions.NoHonorNaNs)
1556       .setApproxFunc(langOptions.ApproxFunc)
1557       .setNoSignedZeros(langOptions.NoSignedZeros)
1558       .setAssociativeMath(langOptions.AssociativeMath)
1559       .setReciprocalMath(langOptions.ReciprocalMath);
1560 }
1561