xref: /llvm-project/flang/lib/Frontend/CompilerInvocation.cpp (revision d768bf994f508d7eaf9541a568be3d71096febf5)
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/Frontend/CodeGenOptions.h"
16 #include "flang/Frontend/PreprocessorOptions.h"
17 #include "flang/Frontend/TargetOptions.h"
18 #include "flang/Semantics/semantics.h"
19 #include "flang/Version.inc"
20 #include "clang/Basic/AllDiagnostics.h"
21 #include "clang/Basic/DiagnosticDriver.h"
22 #include "clang/Basic/DiagnosticOptions.h"
23 #include "clang/Driver/DriverDiagnostic.h"
24 #include "clang/Driver/OptionUtils.h"
25 #include "clang/Driver/Options.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/Option/Arg.h"
29 #include "llvm/Option/ArgList.h"
30 #include "llvm/Option/OptTable.h"
31 #include "llvm/Support/FileSystem.h"
32 #include "llvm/Support/FileUtilities.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/Process.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/TargetParser/Host.h"
37 #include "llvm/TargetParser/Triple.h"
38 #include <memory>
39 #include <optional>
40 
41 using namespace Fortran::frontend;
42 
43 //===----------------------------------------------------------------------===//
44 // Initialization.
45 //===----------------------------------------------------------------------===//
46 CompilerInvocationBase::CompilerInvocationBase()
47     : diagnosticOpts(new clang::DiagnosticOptions()),
48       preprocessorOpts(new PreprocessorOptions()) {}
49 
50 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x)
51     : diagnosticOpts(new clang::DiagnosticOptions(x.getDiagnosticOpts())),
52       preprocessorOpts(new PreprocessorOptions(x.getPreprocessorOpts())) {}
53 
54 CompilerInvocationBase::~CompilerInvocationBase() = default;
55 
56 //===----------------------------------------------------------------------===//
57 // Deserialization (from args)
58 //===----------------------------------------------------------------------===//
59 static bool parseShowColorsArgs(const llvm::opt::ArgList &args,
60                                 bool defaultColor = true) {
61   // Color diagnostics default to auto ("on" if terminal supports) in the
62   // compiler driver `flang-new` but default to off in the frontend driver
63   // `flang-new -fc1`, needing an explicit OPT_fdiagnostics_color.
64   // Support both clang's -f[no-]color-diagnostics and gcc's
65   // -f[no-]diagnostics-colors[=never|always|auto].
66   enum {
67     Colors_On,
68     Colors_Off,
69     Colors_Auto
70   } showColors = defaultColor ? Colors_Auto : Colors_Off;
71 
72   for (auto *a : args) {
73     const llvm::opt::Option &opt = a->getOption();
74     if (opt.matches(clang::driver::options::OPT_fcolor_diagnostics)) {
75       showColors = Colors_On;
76     } else if (opt.matches(clang::driver::options::OPT_fno_color_diagnostics)) {
77       showColors = Colors_Off;
78     } else if (opt.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) {
79       llvm::StringRef value(a->getValue());
80       if (value == "always")
81         showColors = Colors_On;
82       else if (value == "never")
83         showColors = Colors_Off;
84       else if (value == "auto")
85         showColors = Colors_Auto;
86     }
87   }
88 
89   return showColors == Colors_On ||
90          (showColors == Colors_Auto &&
91           llvm::sys::Process::StandardErrHasColors());
92 }
93 
94 /// Extracts the optimisation level from \a args.
95 static unsigned getOptimizationLevel(llvm::opt::ArgList &args,
96                                      clang::DiagnosticsEngine &diags) {
97   unsigned defaultOpt = llvm::CodeGenOpt::None;
98 
99   if (llvm::opt::Arg *a =
100           args.getLastArg(clang::driver::options::OPT_O_Group)) {
101     if (a->getOption().matches(clang::driver::options::OPT_O0))
102       return llvm::CodeGenOpt::None;
103 
104     assert(a->getOption().matches(clang::driver::options::OPT_O));
105 
106     return getLastArgIntValue(args, clang::driver::options::OPT_O, defaultOpt,
107                               diags);
108   }
109 
110   return defaultOpt;
111 }
112 
113 bool Fortran::frontend::parseDiagnosticArgs(clang::DiagnosticOptions &opts,
114                                             llvm::opt::ArgList &args) {
115   opts.ShowColors = parseShowColorsArgs(args);
116 
117   return true;
118 }
119 
120 static void parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts,
121                              llvm::opt::ArgList &args,
122                              clang::DiagnosticsEngine &diags) {
123   opts.OptimizationLevel = getOptimizationLevel(args, diags);
124 
125   if (args.hasFlag(clang::driver::options::OPT_fdebug_pass_manager,
126                    clang::driver::options::OPT_fno_debug_pass_manager, false))
127     opts.DebugPassManager = 1;
128 
129   if (args.hasFlag(clang::driver::options::OPT_fstack_arrays,
130                    clang::driver::options::OPT_fno_stack_arrays, false)) {
131     opts.StackArrays = 1;
132   }
133 
134   for (auto *a : args.filtered(clang::driver::options::OPT_fpass_plugin_EQ))
135     opts.LLVMPassPlugins.push_back(a->getValue());
136 
137   // -fembed-offload-object option
138   for (auto *a :
139        args.filtered(clang::driver::options::OPT_fembed_offload_object_EQ))
140     opts.OffloadObjects.push_back(a->getValue());
141 
142   // -mrelocation-model option.
143   if (const llvm::opt::Arg *A =
144           args.getLastArg(clang::driver::options::OPT_mrelocation_model)) {
145     llvm::StringRef ModelName = A->getValue();
146     auto RM = llvm::StringSwitch<std::optional<llvm::Reloc::Model>>(ModelName)
147                   .Case("static", llvm::Reloc::Static)
148                   .Case("pic", llvm::Reloc::PIC_)
149                   .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC)
150                   .Case("ropi", llvm::Reloc::ROPI)
151                   .Case("rwpi", llvm::Reloc::RWPI)
152                   .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
153                   .Default(std::nullopt);
154     if (RM.has_value())
155       opts.setRelocationModel(*RM);
156     else
157       diags.Report(clang::diag::err_drv_invalid_value)
158           << A->getAsString(args) << ModelName;
159   }
160 
161   // -pic-level and -pic-is-pie option.
162   if (int PICLevel = getLastArgIntValue(
163           args, clang::driver::options::OPT_pic_level, 0, diags)) {
164     if (PICLevel > 2)
165       diags.Report(clang::diag::err_drv_invalid_value)
166           << args.getLastArg(clang::driver::options::OPT_pic_level)
167                  ->getAsString(args)
168           << PICLevel;
169 
170     opts.PICLevel = PICLevel;
171     if (args.hasArg(clang::driver::options::OPT_pic_is_pie))
172       opts.IsPIE = 1;
173   }
174 }
175 
176 /// Parses all target input arguments and populates the target
177 /// options accordingly.
178 ///
179 /// \param [in] opts The target options instance to update
180 /// \param [in] args The list of input arguments (from the compiler invocation)
181 static void parseTargetArgs(TargetOptions &opts, llvm::opt::ArgList &args) {
182   if (const llvm::opt::Arg *a =
183           args.getLastArg(clang::driver::options::OPT_triple))
184     opts.triple = a->getValue();
185 
186   if (const llvm::opt::Arg *a =
187           args.getLastArg(clang::driver::options::OPT_target_cpu))
188     opts.cpu = a->getValue();
189 
190   for (const llvm::opt::Arg *currentArg :
191        args.filtered(clang::driver::options::OPT_target_feature))
192     opts.featuresAsWritten.emplace_back(currentArg->getValue());
193 }
194 
195 // Tweak the frontend configuration based on the frontend action
196 static void setUpFrontendBasedOnAction(FrontendOptions &opts) {
197   if (opts.programAction == DebugDumpParsingLog)
198     opts.instrumentedParse = true;
199 
200   if (opts.programAction == DebugDumpProvenance ||
201       opts.programAction == Fortran::frontend::GetDefinition)
202     opts.needProvenanceRangeToCharBlockMappings = true;
203 }
204 
205 /// Parse the argument specified for the -fconvert=<value> option
206 static std::optional<const char *> parseConvertArg(const char *s) {
207   return llvm::StringSwitch<std::optional<const char *>>(s)
208       .Case("unknown", "UNKNOWN")
209       .Case("native", "NATIVE")
210       .Case("little-endian", "LITTLE_ENDIAN")
211       .Case("big-endian", "BIG_ENDIAN")
212       .Case("swap", "SWAP")
213       .Default(std::nullopt);
214 }
215 
216 static bool parseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args,
217                               clang::DiagnosticsEngine &diags) {
218   unsigned numErrorsBefore = diags.getNumErrors();
219 
220   // By default the frontend driver creates a ParseSyntaxOnly action.
221   opts.programAction = ParseSyntaxOnly;
222 
223   // Treat multiple action options as an invocation error. Note that `clang
224   // -cc1` does accept multiple action options, but will only consider the
225   // rightmost one.
226   if (args.hasMultipleArgs(clang::driver::options::OPT_Action_Group)) {
227     const unsigned diagID = diags.getCustomDiagID(
228         clang::DiagnosticsEngine::Error, "Only one action option is allowed");
229     diags.Report(diagID);
230     return false;
231   }
232 
233   // Identify the action (i.e. opts.ProgramAction)
234   if (const llvm::opt::Arg *a =
235           args.getLastArg(clang::driver::options::OPT_Action_Group)) {
236     switch (a->getOption().getID()) {
237     default: {
238       llvm_unreachable("Invalid option in group!");
239     }
240     case clang::driver::options::OPT_test_io:
241       opts.programAction = InputOutputTest;
242       break;
243     case clang::driver::options::OPT_E:
244       opts.programAction = PrintPreprocessedInput;
245       break;
246     case clang::driver::options::OPT_fsyntax_only:
247       opts.programAction = ParseSyntaxOnly;
248       break;
249     case clang::driver::options::OPT_emit_mlir:
250       opts.programAction = EmitMLIR;
251       break;
252     case clang::driver::options::OPT_emit_llvm:
253       opts.programAction = EmitLLVM;
254       break;
255     case clang::driver::options::OPT_emit_llvm_bc:
256       opts.programAction = EmitLLVMBitcode;
257       break;
258     case clang::driver::options::OPT_emit_obj:
259       opts.programAction = EmitObj;
260       break;
261     case clang::driver::options::OPT_S:
262       opts.programAction = EmitAssembly;
263       break;
264     case clang::driver::options::OPT_fdebug_unparse:
265       opts.programAction = DebugUnparse;
266       break;
267     case clang::driver::options::OPT_fdebug_unparse_no_sema:
268       opts.programAction = DebugUnparseNoSema;
269       break;
270     case clang::driver::options::OPT_fdebug_unparse_with_symbols:
271       opts.programAction = DebugUnparseWithSymbols;
272       break;
273     case clang::driver::options::OPT_fdebug_dump_symbols:
274       opts.programAction = DebugDumpSymbols;
275       break;
276     case clang::driver::options::OPT_fdebug_dump_parse_tree:
277       opts.programAction = DebugDumpParseTree;
278       break;
279     case clang::driver::options::OPT_fdebug_dump_pft:
280       opts.programAction = DebugDumpPFT;
281       break;
282     case clang::driver::options::OPT_fdebug_dump_all:
283       opts.programAction = DebugDumpAll;
284       break;
285     case clang::driver::options::OPT_fdebug_dump_parse_tree_no_sema:
286       opts.programAction = DebugDumpParseTreeNoSema;
287       break;
288     case clang::driver::options::OPT_fdebug_dump_provenance:
289       opts.programAction = DebugDumpProvenance;
290       break;
291     case clang::driver::options::OPT_fdebug_dump_parsing_log:
292       opts.programAction = DebugDumpParsingLog;
293       break;
294     case clang::driver::options::OPT_fdebug_measure_parse_tree:
295       opts.programAction = DebugMeasureParseTree;
296       break;
297     case clang::driver::options::OPT_fdebug_pre_fir_tree:
298       opts.programAction = DebugPreFIRTree;
299       break;
300     case clang::driver::options::OPT_fget_symbols_sources:
301       opts.programAction = GetSymbolsSources;
302       break;
303     case clang::driver::options::OPT_fget_definition:
304       opts.programAction = GetDefinition;
305       break;
306     case clang::driver::options::OPT_init_only:
307       opts.programAction = InitOnly;
308       break;
309 
310       // TODO:
311       // case clang::driver::options::OPT_emit_llvm:
312       // case clang::driver::options::OPT_emit_llvm_only:
313       // case clang::driver::options::OPT_emit_codegen_only:
314       // case clang::driver::options::OPT_emit_module:
315       // (...)
316     }
317 
318     // Parse the values provided with `-fget-definition` (there should be 3
319     // integers)
320     if (llvm::opt::OptSpecifier(a->getOption().getID()) ==
321         clang::driver::options::OPT_fget_definition) {
322       unsigned optVals[3] = {0, 0, 0};
323 
324       for (unsigned i = 0; i < 3; i++) {
325         llvm::StringRef val = a->getValue(i);
326 
327         if (val.getAsInteger(10, optVals[i])) {
328           // A non-integer was encountered - that's an error.
329           diags.Report(clang::diag::err_drv_invalid_value)
330               << a->getOption().getName() << val;
331           break;
332         }
333       }
334       opts.getDefVals.line = optVals[0];
335       opts.getDefVals.startColumn = optVals[1];
336       opts.getDefVals.endColumn = optVals[2];
337     }
338   }
339 
340   // Parsing -load <dsopath> option and storing shared object path
341   if (llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_load)) {
342     opts.plugins.push_back(a->getValue());
343   }
344 
345   // Parsing -plugin <name> option and storing plugin name and setting action
346   if (const llvm::opt::Arg *a =
347           args.getLastArg(clang::driver::options::OPT_plugin)) {
348     opts.programAction = PluginAction;
349     opts.actionName = a->getValue();
350   }
351 
352   opts.outputFile = args.getLastArgValue(clang::driver::options::OPT_o);
353   opts.showHelp = args.hasArg(clang::driver::options::OPT_help);
354   opts.showVersion = args.hasArg(clang::driver::options::OPT_version);
355 
356   // Get the input kind (from the value passed via `-x`)
357   InputKind dashX(Language::Unknown);
358   if (const llvm::opt::Arg *a =
359           args.getLastArg(clang::driver::options::OPT_x)) {
360     llvm::StringRef xValue = a->getValue();
361     // Principal languages.
362     dashX = llvm::StringSwitch<InputKind>(xValue)
363                 // Flang does not differentiate between pre-processed and not
364                 // pre-processed inputs.
365                 .Case("f95", Language::Fortran)
366                 .Case("f95-cpp-input", Language::Fortran)
367                 .Default(Language::Unknown);
368 
369     // Flang's intermediate representations.
370     if (dashX.isUnknown())
371       dashX = llvm::StringSwitch<InputKind>(xValue)
372                   .Case("ir", Language::LLVM_IR)
373                   .Case("fir", Language::MLIR)
374                   .Case("mlir", Language::MLIR)
375                   .Default(Language::Unknown);
376 
377     if (dashX.isUnknown())
378       diags.Report(clang::diag::err_drv_invalid_value)
379           << a->getAsString(args) << a->getValue();
380   }
381 
382   // Collect the input files and save them in our instance of FrontendOptions.
383   std::vector<std::string> inputs =
384       args.getAllArgValues(clang::driver::options::OPT_INPUT);
385   opts.inputs.clear();
386   if (inputs.empty())
387     // '-' is the default input if none is given.
388     inputs.push_back("-");
389   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
390     InputKind ik = dashX;
391     if (ik.isUnknown()) {
392       ik = FrontendOptions::getInputKindForExtension(
393           llvm::StringRef(inputs[i]).rsplit('.').second);
394       if (ik.isUnknown())
395         ik = Language::Unknown;
396       if (i == 0)
397         dashX = ik;
398     }
399 
400     opts.inputs.emplace_back(std::move(inputs[i]), ik);
401   }
402 
403   // Set fortranForm based on options -ffree-form and -ffixed-form.
404   if (const auto *arg =
405           args.getLastArg(clang::driver::options::OPT_ffixed_form,
406                           clang::driver::options::OPT_ffree_form)) {
407     opts.fortranForm =
408         arg->getOption().matches(clang::driver::options::OPT_ffixed_form)
409             ? FortranForm::FixedForm
410             : FortranForm::FreeForm;
411   }
412 
413   // Set fixedFormColumns based on -ffixed-line-length=<value>
414   if (const auto *arg =
415           args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) {
416     llvm::StringRef argValue = llvm::StringRef(arg->getValue());
417     std::int64_t columns = -1;
418     if (argValue == "none") {
419       columns = 0;
420     } else if (argValue.getAsInteger(/*Radix=*/10, columns)) {
421       columns = -1;
422     }
423     if (columns < 0) {
424       diags.Report(clang::diag::err_drv_negative_columns)
425           << arg->getOption().getName() << arg->getValue();
426     } else if (columns == 0) {
427       opts.fixedFormColumns = 1000000;
428     } else if (columns < 7) {
429       diags.Report(clang::diag::err_drv_small_columns)
430           << arg->getOption().getName() << arg->getValue() << "7";
431     } else {
432       opts.fixedFormColumns = columns;
433     }
434   }
435 
436   // Set conversion based on -fconvert=<value>
437   if (const auto *arg =
438           args.getLastArg(clang::driver::options::OPT_fconvert_EQ)) {
439     const char *argValue = arg->getValue();
440     if (auto convert = parseConvertArg(argValue))
441       opts.envDefaults.push_back({"FORT_CONVERT", *convert});
442     else
443       diags.Report(clang::diag::err_drv_invalid_value)
444           << arg->getAsString(args) << argValue;
445   }
446 
447   // -f{no-}implicit-none
448   opts.features.Enable(
449       Fortran::common::LanguageFeature::ImplicitNoneTypeAlways,
450       args.hasFlag(clang::driver::options::OPT_fimplicit_none,
451                    clang::driver::options::OPT_fno_implicit_none, false));
452 
453   // -f{no-}backslash
454   opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes,
455                        args.hasFlag(clang::driver::options::OPT_fbackslash,
456                                     clang::driver::options::OPT_fno_backslash,
457                                     false));
458 
459   // -f{no-}logical-abbreviations
460   opts.features.Enable(
461       Fortran::common::LanguageFeature::LogicalAbbreviations,
462       args.hasFlag(clang::driver::options::OPT_flogical_abbreviations,
463                    clang::driver::options::OPT_fno_logical_abbreviations,
464                    false));
465 
466   // -f{no-}xor-operator
467   opts.features.Enable(
468       Fortran::common::LanguageFeature::XOROperator,
469       args.hasFlag(clang::driver::options::OPT_fxor_operator,
470                    clang::driver::options::OPT_fno_xor_operator, false));
471 
472   // -fno-automatic
473   if (args.hasArg(clang::driver::options::OPT_fno_automatic)) {
474     opts.features.Enable(Fortran::common::LanguageFeature::DefaultSave);
475   }
476 
477   if (args.hasArg(
478           clang::driver::options::OPT_falternative_parameter_statement)) {
479     opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter);
480   }
481   if (const llvm::opt::Arg *arg =
482           args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) {
483     llvm::StringRef argValue = arg->getValue();
484     if (argValue == "utf-8") {
485       opts.encoding = Fortran::parser::Encoding::UTF_8;
486     } else if (argValue == "latin-1") {
487       opts.encoding = Fortran::parser::Encoding::LATIN_1;
488     } else {
489       diags.Report(clang::diag::err_drv_invalid_value)
490           << arg->getAsString(args) << argValue;
491     }
492   }
493 
494   setUpFrontendBasedOnAction(opts);
495   opts.dashX = dashX;
496 
497   return diags.getNumErrors() == numErrorsBefore;
498 }
499 
500 // Generate the path to look for intrinsic modules
501 static std::string getIntrinsicDir() {
502   // TODO: Find a system independent API
503   llvm::SmallString<128> driverPath;
504   driverPath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr));
505   llvm::sys::path::remove_filename(driverPath);
506   driverPath.append("/../include/flang/");
507   return std::string(driverPath);
508 }
509 
510 // Generate the path to look for OpenMP headers
511 static std::string getOpenMPHeadersDir() {
512   llvm::SmallString<128> includePath;
513   includePath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr));
514   llvm::sys::path::remove_filename(includePath);
515   includePath.append("/../include/flang/OpenMP/");
516   return std::string(includePath);
517 }
518 
519 /// Parses all preprocessor input arguments and populates the preprocessor
520 /// options accordingly.
521 ///
522 /// \param [in] opts The preprocessor options instance
523 /// \param [out] args The list of input arguments
524 static void parsePreprocessorArgs(Fortran::frontend::PreprocessorOptions &opts,
525                                   llvm::opt::ArgList &args) {
526   // Add macros from the command line.
527   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_D,
528                                               clang::driver::options::OPT_U)) {
529     if (currentArg->getOption().matches(clang::driver::options::OPT_D)) {
530       opts.addMacroDef(currentArg->getValue());
531     } else {
532       opts.addMacroUndef(currentArg->getValue());
533     }
534   }
535 
536   // Add the ordered list of -I's.
537   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I))
538     opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue());
539 
540   // Prepend the ordered list of -intrinsic-modules-path
541   // to the default location to search.
542   for (const auto *currentArg :
543        args.filtered(clang::driver::options::OPT_fintrinsic_modules_path))
544     opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue());
545 
546   // -cpp/-nocpp
547   if (const auto *currentArg = args.getLastArg(
548           clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp))
549     opts.macrosFlag =
550         (currentArg->getOption().matches(clang::driver::options::OPT_cpp))
551             ? PPMacrosFlag::Include
552             : PPMacrosFlag::Exclude;
553 
554   opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat);
555   opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P);
556 }
557 
558 /// Parses all semantic related arguments and populates the variables
559 /// options accordingly. Returns false if new errors are generated.
560 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
561                           clang::DiagnosticsEngine &diags) {
562   unsigned numErrorsBefore = diags.getNumErrors();
563 
564   // -J/module-dir option
565   auto moduleDirList =
566       args.getAllArgValues(clang::driver::options::OPT_module_dir);
567   // User can only specify -J/-module-dir once
568   // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html
569   if (moduleDirList.size() > 1) {
570     const unsigned diagID =
571         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
572                               "Only one '-module-dir/-J' option allowed");
573     diags.Report(diagID);
574   }
575   if (moduleDirList.size() == 1)
576     res.setModuleDir(moduleDirList[0]);
577 
578   // -fdebug-module-writer option
579   if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) {
580     res.setDebugModuleDir(true);
581   }
582 
583   // -module-suffix
584   if (const auto *moduleSuffix =
585           args.getLastArg(clang::driver::options::OPT_module_suffix)) {
586     res.setModuleFileSuffix(moduleSuffix->getValue());
587   }
588 
589   // -f{no-}analyzed-objects-for-unparse
590   res.setUseAnalyzedObjectsForUnparse(args.hasFlag(
591       clang::driver::options::OPT_fanalyzed_objects_for_unparse,
592       clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true));
593 
594   return diags.getNumErrors() == numErrorsBefore;
595 }
596 
597 /// Parses all diagnostics related arguments and populates the variables
598 /// options accordingly. Returns false if new errors are generated.
599 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
600                           clang::DiagnosticsEngine &diags) {
601   unsigned numErrorsBefore = diags.getNumErrors();
602 
603   // -Werror option
604   // TODO: Currently throws a Diagnostic for anything other than -W<error>,
605   // this has to change when other -W<opt>'s are supported.
606   if (args.hasArg(clang::driver::options::OPT_W_Joined)) {
607     if (args.getLastArgValue(clang::driver::options::OPT_W_Joined)
608             .equals("error")) {
609       res.setWarnAsErr(true);
610     } else {
611       const unsigned diagID =
612           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
613                                 "Only `-Werror` is supported currently.");
614       diags.Report(diagID);
615     }
616   }
617 
618   // Default to off for `flang-new -fc1`.
619   res.getFrontendOpts().showColors =
620       parseShowColorsArgs(args, /*defaultDiagColor=*/false);
621 
622   return diags.getNumErrors() == numErrorsBefore;
623 }
624 
625 /// Parses all Dialect related arguments and populates the variables
626 /// options accordingly. Returns false if new errors are generated.
627 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
628                              clang::DiagnosticsEngine &diags) {
629   unsigned numErrorsBefore = diags.getNumErrors();
630 
631   // -fdefault* family
632   if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
633     res.getDefaultKinds().set_defaultRealKind(8);
634     res.getDefaultKinds().set_doublePrecisionKind(16);
635   }
636   if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) {
637     res.getDefaultKinds().set_defaultIntegerKind(8);
638     res.getDefaultKinds().set_subscriptIntegerKind(8);
639     res.getDefaultKinds().set_sizeIntegerKind(8);
640   }
641   if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) {
642     if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
643       // -fdefault-double-8 has to be used with -fdefault-real-8
644       // to be compatible with gfortran
645       const unsigned diagID = diags.getCustomDiagID(
646           clang::DiagnosticsEngine::Error,
647           "Use of `-fdefault-double-8` requires `-fdefault-real-8`");
648       diags.Report(diagID);
649     }
650     // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html
651     res.getDefaultKinds().set_doublePrecisionKind(8);
652   }
653   if (args.hasArg(clang::driver::options::OPT_flarge_sizes))
654     res.getDefaultKinds().set_sizeIntegerKind(8);
655 
656   // -fopenmp and -fopenacc
657   if (args.hasArg(clang::driver::options::OPT_fopenacc)) {
658     res.getFrontendOpts().features.Enable(
659         Fortran::common::LanguageFeature::OpenACC);
660   }
661   if (args.hasArg(clang::driver::options::OPT_fopenmp)) {
662     res.getFrontendOpts().features.Enable(
663         Fortran::common::LanguageFeature::OpenMP);
664   }
665 
666   // -pedantic
667   if (args.hasArg(clang::driver::options::OPT_pedantic)) {
668     res.setEnableConformanceChecks();
669   }
670   // -std=f2018 (currently this implies -pedantic)
671   // TODO: Set proper options when more fortran standards
672   // are supported.
673   if (args.hasArg(clang::driver::options::OPT_std_EQ)) {
674     auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ);
675     // We only allow f2018 as the given standard
676     if (standard.equals("f2018")) {
677       res.setEnableConformanceChecks();
678     } else {
679       const unsigned diagID =
680           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
681                                 "Only -std=f2018 is allowed currently.");
682       diags.Report(diagID);
683     }
684   }
685   return diags.getNumErrors() == numErrorsBefore;
686 }
687 
688 /// Parses all floating point related arguments and populates the
689 /// CompilerInvocation accordingly.
690 /// Returns false if new errors are generated.
691 ///
692 /// \param [out] invoc Stores the processed arguments
693 /// \param [in] args The compiler invocation arguments to parse
694 /// \param [out] diags DiagnosticsEngine to report erros with
695 static bool parseFloatingPointArgs(CompilerInvocation &invoc,
696                                    llvm::opt::ArgList &args,
697                                    clang::DiagnosticsEngine &diags) {
698   LangOptions &opts = invoc.getLangOpts();
699 
700   if (const llvm::opt::Arg *a =
701           args.getLastArg(clang::driver::options::OPT_ffp_contract)) {
702     const llvm::StringRef val = a->getValue();
703     enum LangOptions::FPModeKind fpContractMode;
704 
705     if (val == "off")
706       fpContractMode = LangOptions::FPM_Off;
707     else if (val == "fast")
708       fpContractMode = LangOptions::FPM_Fast;
709     else {
710       diags.Report(clang::diag::err_drv_unsupported_option_argument)
711           << a->getSpelling() << val;
712       return false;
713     }
714 
715     opts.setFPContractMode(fpContractMode);
716   }
717 
718   if (args.getLastArg(clang::driver::options::OPT_menable_no_infinities)) {
719     opts.NoHonorInfs = true;
720   }
721 
722   if (args.getLastArg(clang::driver::options::OPT_menable_no_nans)) {
723     opts.NoHonorNaNs = true;
724   }
725 
726   if (args.getLastArg(clang::driver::options::OPT_fapprox_func)) {
727     opts.ApproxFunc = true;
728   }
729 
730   if (args.getLastArg(clang::driver::options::OPT_fno_signed_zeros)) {
731     opts.NoSignedZeros = true;
732   }
733 
734   if (args.getLastArg(clang::driver::options::OPT_mreassociate)) {
735     opts.AssociativeMath = true;
736   }
737 
738   if (args.getLastArg(clang::driver::options::OPT_freciprocal_math)) {
739     opts.ReciprocalMath = true;
740   }
741 
742   if (args.getLastArg(clang::driver::options::OPT_ffast_math)) {
743     opts.NoHonorInfs = true;
744     opts.NoHonorNaNs = true;
745     opts.AssociativeMath = true;
746     opts.ReciprocalMath = true;
747     opts.ApproxFunc = true;
748     opts.NoSignedZeros = true;
749     opts.setFPContractMode(LangOptions::FPM_Fast);
750   }
751 
752   return true;
753 }
754 
755 bool CompilerInvocation::createFromArgs(
756     CompilerInvocation &res, llvm::ArrayRef<const char *> commandLineArgs,
757     clang::DiagnosticsEngine &diags) {
758 
759   bool success = true;
760 
761   // Set the default triple for this CompilerInvocation. This might be
762   // overridden by users with `-triple` (see the call to `ParseTargetArgs`
763   // below).
764   // NOTE: Like in Clang, it would be nice to use option marshalling
765   // for this so that the entire logic for setting-up the triple is in one
766   // place.
767   res.getTargetOpts().triple =
768       llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple());
769 
770   // Parse the arguments
771   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
772   const unsigned includedFlagsBitmask = clang::driver::options::FC1Option;
773   unsigned missingArgIndex, missingArgCount;
774   llvm::opt::InputArgList args = opts.ParseArgs(
775       commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask);
776 
777   // Check for missing argument error.
778   if (missingArgCount) {
779     diags.Report(clang::diag::err_drv_missing_argument)
780         << args.getArgString(missingArgIndex) << missingArgCount;
781     success = false;
782   }
783 
784   // Issue errors on unknown arguments
785   for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
786     auto argString = a->getAsString(args);
787     std::string nearest;
788     if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1)
789       diags.Report(clang::diag::err_drv_unknown_argument) << argString;
790     else
791       diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
792           << argString << nearest;
793     success = false;
794   }
795 
796   success &= parseFrontendArgs(res.getFrontendOpts(), args, diags);
797   parseTargetArgs(res.getTargetOpts(), args);
798   parsePreprocessorArgs(res.getPreprocessorOpts(), args);
799   parseCodeGenArgs(res.getCodeGenOpts(), args, diags);
800   success &= parseSemaArgs(res, args, diags);
801   success &= parseDialectArgs(res, args, diags);
802   success &= parseDiagArgs(res, args, diags);
803   res.frontendOpts.llvmArgs =
804       args.getAllArgValues(clang::driver::options::OPT_mllvm);
805 
806   res.frontendOpts.mlirArgs =
807       args.getAllArgValues(clang::driver::options::OPT_mmlir);
808 
809   success &= parseFloatingPointArgs(res, args, diags);
810 
811   return success;
812 }
813 
814 void CompilerInvocation::collectMacroDefinitions() {
815   auto &ppOpts = this->getPreprocessorOpts();
816 
817   for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) {
818     llvm::StringRef macro = ppOpts.macros[i].first;
819     bool isUndef = ppOpts.macros[i].second;
820 
821     std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('=');
822     llvm::StringRef macroName = macroPair.first;
823     llvm::StringRef macroBody = macroPair.second;
824 
825     // For an #undef'd macro, we only care about the name.
826     if (isUndef) {
827       parserOpts.predefinitions.emplace_back(macroName.str(),
828                                              std::optional<std::string>{});
829       continue;
830     }
831 
832     // For a #define'd macro, figure out the actual definition.
833     if (macroName.size() == macro.size())
834       macroBody = "1";
835     else {
836       // Note: GCC drops anything following an end-of-line character.
837       llvm::StringRef::size_type end = macroBody.find_first_of("\n\r");
838       macroBody = macroBody.substr(0, end);
839     }
840     parserOpts.predefinitions.emplace_back(
841         macroName, std::optional<std::string>(macroBody.str()));
842   }
843 }
844 
845 void CompilerInvocation::setDefaultFortranOpts() {
846   auto &fortranOptions = getFortranOpts();
847 
848   std::vector<std::string> searchDirectories{"."s};
849   fortranOptions.searchDirectories = searchDirectories;
850 
851   // Add the location of omp_lib.h to the search directories. Currently this is
852   // identical to the modules' directory.
853   fortranOptions.searchDirectories.emplace_back(getOpenMPHeadersDir());
854 
855   fortranOptions.isFixedForm = false;
856 }
857 
858 // TODO: When expanding this method, consider creating a dedicated API for
859 // this. Also at some point we will need to differentiate between different
860 // targets and add dedicated predefines for each.
861 void CompilerInvocation::setDefaultPredefinitions() {
862   auto &fortranOptions = getFortranOpts();
863   const auto &frontendOptions = getFrontendOpts();
864 
865   // Populate the macro list with version numbers and other predefinitions.
866   fortranOptions.predefinitions.emplace_back("__flang__", "1");
867   fortranOptions.predefinitions.emplace_back("__flang_major__",
868                                              FLANG_VERSION_MAJOR_STRING);
869   fortranOptions.predefinitions.emplace_back("__flang_minor__",
870                                              FLANG_VERSION_MINOR_STRING);
871   fortranOptions.predefinitions.emplace_back("__flang_patchlevel__",
872                                              FLANG_VERSION_PATCHLEVEL_STRING);
873 
874   // Add predefinitions based on extensions enabled
875   if (frontendOptions.features.IsEnabled(
876           Fortran::common::LanguageFeature::OpenACC)) {
877     fortranOptions.predefinitions.emplace_back("_OPENACC", "202011");
878   }
879   if (frontendOptions.features.IsEnabled(
880           Fortran::common::LanguageFeature::OpenMP)) {
881     fortranOptions.predefinitions.emplace_back("_OPENMP", "201511");
882   }
883   llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)};
884   if (targetTriple.getArch() == llvm::Triple::ArchType::x86_64) {
885     fortranOptions.predefinitions.emplace_back("__x86_64__", "1");
886     fortranOptions.predefinitions.emplace_back("__x86_64", "1");
887   }
888 }
889 
890 void CompilerInvocation::setFortranOpts() {
891   auto &fortranOptions = getFortranOpts();
892   const auto &frontendOptions = getFrontendOpts();
893   const auto &preprocessorOptions = getPreprocessorOpts();
894   auto &moduleDirJ = getModuleDir();
895 
896   if (frontendOptions.fortranForm != FortranForm::Unknown) {
897     fortranOptions.isFixedForm =
898         frontendOptions.fortranForm == FortranForm::FixedForm;
899   }
900   fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns;
901 
902   fortranOptions.features = frontendOptions.features;
903   fortranOptions.encoding = frontendOptions.encoding;
904 
905   // Adding search directories specified by -I
906   fortranOptions.searchDirectories.insert(
907       fortranOptions.searchDirectories.end(),
908       preprocessorOptions.searchDirectoriesFromDashI.begin(),
909       preprocessorOptions.searchDirectoriesFromDashI.end());
910 
911   // Add the ordered list of -intrinsic-modules-path
912   fortranOptions.searchDirectories.insert(
913       fortranOptions.searchDirectories.end(),
914       preprocessorOptions.searchDirectoriesFromIntrModPath.begin(),
915       preprocessorOptions.searchDirectoriesFromIntrModPath.end());
916 
917   //  Add the default intrinsic module directory
918   fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir());
919 
920   // Add the directory supplied through -J/-module-dir to the list of search
921   // directories
922   if (moduleDirJ != ".")
923     fortranOptions.searchDirectories.emplace_back(moduleDirJ);
924 
925   if (frontendOptions.instrumentedParse)
926     fortranOptions.instrumentedParse = true;
927 
928   if (frontendOptions.showColors)
929     fortranOptions.showColors = true;
930 
931   if (frontendOptions.needProvenanceRangeToCharBlockMappings)
932     fortranOptions.needProvenanceRangeToCharBlockMappings = true;
933 
934   if (getEnableConformanceChecks()) {
935     fortranOptions.features.WarnOnAllNonstandard();
936   }
937 }
938 
939 void CompilerInvocation::setSemanticsOpts(
940     Fortran::parser::AllCookedSources &allCookedSources) {
941   auto &fortranOptions = getFortranOpts();
942 
943   semanticsContext = std::make_unique<semantics::SemanticsContext>(
944       getDefaultKinds(), fortranOptions.features, allCookedSources);
945 
946   semanticsContext->set_moduleDirectory(getModuleDir())
947       .set_searchDirectories(fortranOptions.searchDirectories)
948       .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories)
949       .set_warnOnNonstandardUsage(getEnableConformanceChecks())
950       .set_warningsAreErrors(getWarnAsErr())
951       .set_moduleFileSuffix(getModuleFileSuffix());
952 
953   llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)};
954   // FIXME: Handle real(3) ?
955   if (targetTriple.getArch() != llvm::Triple::ArchType::x86_64) {
956     semanticsContext->targetCharacteristics().DisableType(
957         Fortran::common::TypeCategory::Real, /*kind=*/10);
958   }
959 }
960 
961 /// Set \p loweringOptions controlling lowering behavior based
962 /// on the \p optimizationLevel.
963 void CompilerInvocation::setLoweringOptions() {
964   const CodeGenOptions &codegenOpts = getCodeGenOpts();
965 
966   // Lower TRANSPOSE as a runtime call under -O0.
967   loweringOpts.setOptimizeTranspose(codegenOpts.OptimizationLevel > 0);
968 
969   const LangOptions &langOptions = getLangOpts();
970   Fortran::common::MathOptionsBase &mathOpts = loweringOpts.getMathOptions();
971   // TODO: when LangOptions are finalized, we can represent
972   //       the math related options using Fortran::commmon::MathOptionsBase,
973   //       so that we can just copy it into LoweringOptions.
974   mathOpts
975       .setFPContractEnabled(langOptions.getFPContractMode() ==
976                             LangOptions::FPM_Fast)
977       .setNoHonorInfs(langOptions.NoHonorInfs)
978       .setNoHonorNaNs(langOptions.NoHonorNaNs)
979       .setApproxFunc(langOptions.ApproxFunc)
980       .setNoSignedZeros(langOptions.NoSignedZeros)
981       .setAssociativeMath(langOptions.AssociativeMath)
982       .setReciprocalMath(langOptions.ReciprocalMath);
983 }
984