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