xref: /llvm-project/flang/lib/Frontend/CompilerInvocation.cpp (revision 1e462fafdf8be70137c8eaf856f4eb886f8b4d4c)
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/PreprocessorOptions.h"
16 #include "flang/Frontend/TargetOptions.h"
17 #include "flang/Semantics/semantics.h"
18 #include "flang/Version.inc"
19 #include "clang/Basic/AllDiagnostics.h"
20 #include "clang/Basic/DiagnosticDriver.h"
21 #include "clang/Basic/DiagnosticOptions.h"
22 #include "clang/Driver/DriverDiagnostic.h"
23 #include "clang/Driver/Options.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/Triple.h"
27 #include "llvm/Option/Arg.h"
28 #include "llvm/Option/ArgList.h"
29 #include "llvm/Option/OptTable.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/FileUtilities.h"
32 #include "llvm/Support/Host.h"
33 #include "llvm/Support/Path.h"
34 #include "llvm/Support/Process.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <memory>
37 
38 using namespace Fortran::frontend;
39 
40 //===----------------------------------------------------------------------===//
41 // Initialization.
42 //===----------------------------------------------------------------------===//
43 CompilerInvocationBase::CompilerInvocationBase()
44     : diagnosticOpts(new clang::DiagnosticOptions()),
45       preprocessorOpts(new PreprocessorOptions()) {}
46 
47 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x)
48     : diagnosticOpts(new clang::DiagnosticOptions(x.getDiagnosticOpts())),
49       preprocessorOpts(new PreprocessorOptions(x.getPreprocessorOpts())) {}
50 
51 CompilerInvocationBase::~CompilerInvocationBase() = default;
52 
53 //===----------------------------------------------------------------------===//
54 // Deserialization (from args)
55 //===----------------------------------------------------------------------===//
56 static bool parseShowColorsArgs(
57     const llvm::opt::ArgList &args, bool defaultColor) {
58   // Color diagnostics default to auto ("on" if terminal supports) in the driver
59   // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
60   // Support both clang's -f[no-]color-diagnostics and gcc's
61   // -f[no-]diagnostics-colors[=never|always|auto].
62   enum {
63     Colors_On,
64     Colors_Off,
65     Colors_Auto
66   } showColors = defaultColor ? Colors_Auto : Colors_Off;
67 
68   for (auto *a : args) {
69     const llvm::opt::Option &opt = a->getOption();
70     if (opt.matches(clang::driver::options::OPT_fcolor_diagnostics)) {
71       showColors = Colors_On;
72     } else if (opt.matches(clang::driver::options::OPT_fno_color_diagnostics)) {
73       showColors = Colors_Off;
74     } else if (opt.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) {
75       llvm::StringRef value(a->getValue());
76       if (value == "always")
77         showColors = Colors_On;
78       else if (value == "never")
79         showColors = Colors_Off;
80       else if (value == "auto")
81         showColors = Colors_Auto;
82     }
83   }
84 
85   return showColors == Colors_On ||
86          (showColors == Colors_Auto &&
87           llvm::sys::Process::StandardErrHasColors());
88 }
89 
90 bool Fortran::frontend::parseDiagnosticArgs(clang::DiagnosticOptions &opts,
91                                             llvm::opt::ArgList &args,
92                                             bool defaultDiagColor) {
93   opts.ShowColors = parseShowColorsArgs(args, defaultDiagColor);
94 
95   return true;
96 }
97 
98 /// Parses all target input arguments and populates the target
99 /// options accordingly.
100 ///
101 /// \param [in] opts The target options instance to update
102 /// \param [in] args The list of input arguments (from the compiler invocation)
103 static void parseTargetArgs(TargetOptions &opts, llvm::opt::ArgList &args) {
104   if (const llvm::opt::Arg *a =
105           args.getLastArg(clang::driver::options::OPT_triple))
106     opts.triple = a->getValue();
107 }
108 
109 // Tweak the frontend configuration based on the frontend action
110 static void setUpFrontendBasedOnAction(FrontendOptions &opts) {
111   if (opts.programAction == DebugDumpParsingLog)
112     opts.instrumentedParse = true;
113 
114   if (opts.programAction == DebugDumpProvenance ||
115       opts.programAction == Fortran::frontend::GetDefinition)
116     opts.needProvenanceRangeToCharBlockMappings = true;
117 }
118 
119 static bool parseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args,
120                               clang::DiagnosticsEngine &diags) {
121   unsigned numErrorsBefore = diags.getNumErrors();
122 
123   // By default the frontend driver creates a ParseSyntaxOnly action.
124   opts.programAction = ParseSyntaxOnly;
125 
126   // Treat multiple action options as an invocation error. Note that `clang
127   // -cc1` does accept multiple action options, but will only consider the
128   // rightmost one.
129   if (args.hasMultipleArgs(clang::driver::options::OPT_Action_Group)) {
130     const unsigned diagID = diags.getCustomDiagID(
131         clang::DiagnosticsEngine::Error, "Only one action option is allowed");
132     diags.Report(diagID);
133     return false;
134   }
135 
136   // Identify the action (i.e. opts.ProgramAction)
137   if (const llvm::opt::Arg *a =
138           args.getLastArg(clang::driver::options::OPT_Action_Group)) {
139     switch (a->getOption().getID()) {
140     default: {
141       llvm_unreachable("Invalid option in group!");
142     }
143     case clang::driver::options::OPT_test_io:
144       opts.programAction = InputOutputTest;
145       break;
146     case clang::driver::options::OPT_E:
147       opts.programAction = PrintPreprocessedInput;
148       break;
149     case clang::driver::options::OPT_fsyntax_only:
150       opts.programAction = ParseSyntaxOnly;
151       break;
152     case clang::driver::options::OPT_emit_mlir:
153       opts.programAction = EmitMLIR;
154       break;
155     case clang::driver::options::OPT_emit_llvm:
156       opts.programAction = EmitLLVM;
157       break;
158     case clang::driver::options::OPT_emit_llvm_bc:
159       opts.programAction = EmitLLVMBitcode;
160       break;
161     case clang::driver::options::OPT_emit_obj:
162       opts.programAction = EmitObj;
163       break;
164     case clang::driver::options::OPT_S:
165       opts.programAction = EmitAssembly;
166       break;
167     case clang::driver::options::OPT_fdebug_unparse:
168       opts.programAction = DebugUnparse;
169       break;
170     case clang::driver::options::OPT_fdebug_unparse_no_sema:
171       opts.programAction = DebugUnparseNoSema;
172       break;
173     case clang::driver::options::OPT_fdebug_unparse_with_symbols:
174       opts.programAction = DebugUnparseWithSymbols;
175       break;
176     case clang::driver::options::OPT_fdebug_dump_symbols:
177       opts.programAction = DebugDumpSymbols;
178       break;
179     case clang::driver::options::OPT_fdebug_dump_parse_tree:
180       opts.programAction = DebugDumpParseTree;
181       break;
182     case clang::driver::options::OPT_fdebug_dump_pft:
183       opts.programAction = DebugDumpPFT;
184       break;
185     case clang::driver::options::OPT_fdebug_dump_all:
186       opts.programAction = DebugDumpAll;
187       break;
188     case clang::driver::options::OPT_fdebug_dump_parse_tree_no_sema:
189       opts.programAction = DebugDumpParseTreeNoSema;
190       break;
191     case clang::driver::options::OPT_fdebug_dump_provenance:
192       opts.programAction = DebugDumpProvenance;
193       break;
194     case clang::driver::options::OPT_fdebug_dump_parsing_log:
195       opts.programAction = DebugDumpParsingLog;
196       break;
197     case clang::driver::options::OPT_fdebug_measure_parse_tree:
198       opts.programAction = DebugMeasureParseTree;
199       break;
200     case clang::driver::options::OPT_fdebug_pre_fir_tree:
201       opts.programAction = DebugPreFIRTree;
202       break;
203     case clang::driver::options::OPT_fget_symbols_sources:
204       opts.programAction = GetSymbolsSources;
205       break;
206     case clang::driver::options::OPT_fget_definition:
207       opts.programAction = GetDefinition;
208       break;
209     case clang::driver::options::OPT_init_only:
210       opts.programAction = InitOnly;
211       break;
212 
213       // TODO:
214       // case clang::driver::options::OPT_emit_llvm:
215       // case clang::driver::options::OPT_emit_llvm_only:
216       // case clang::driver::options::OPT_emit_codegen_only:
217       // case clang::driver::options::OPT_emit_module:
218       // (...)
219     }
220 
221     // Parse the values provided with `-fget-definition` (there should be 3
222     // integers)
223     if (llvm::opt::OptSpecifier(a->getOption().getID()) ==
224         clang::driver::options::OPT_fget_definition) {
225       unsigned optVals[3] = {0, 0, 0};
226 
227       for (unsigned i = 0; i < 3; i++) {
228         llvm::StringRef val = a->getValue(i);
229 
230         if (val.getAsInteger(10, optVals[i])) {
231           // A non-integer was encountered - that's an error.
232           diags.Report(clang::diag::err_drv_invalid_value)
233               << a->getOption().getName() << val;
234           break;
235         }
236       }
237       opts.getDefVals.line = optVals[0];
238       opts.getDefVals.startColumn = optVals[1];
239       opts.getDefVals.endColumn = optVals[2];
240     }
241   }
242 
243   // Parsing -load <dsopath> option and storing shared object path
244   if (llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_load)) {
245     opts.plugins.push_back(a->getValue());
246   }
247 
248   // Parsing -plugin <name> option and storing plugin name and setting action
249   if (const llvm::opt::Arg *a =
250           args.getLastArg(clang::driver::options::OPT_plugin)) {
251     opts.programAction = PluginAction;
252     opts.actionName = a->getValue();
253   }
254 
255   opts.outputFile = args.getLastArgValue(clang::driver::options::OPT_o);
256   opts.showHelp = args.hasArg(clang::driver::options::OPT_help);
257   opts.showVersion = args.hasArg(clang::driver::options::OPT_version);
258 
259   // Get the input kind (from the value passed via `-x`)
260   InputKind dashX(Language::Unknown);
261   if (const llvm::opt::Arg *a =
262           args.getLastArg(clang::driver::options::OPT_x)) {
263     llvm::StringRef xValue = a->getValue();
264     // Principal languages.
265     dashX = llvm::StringSwitch<InputKind>(xValue)
266                 .Case("f90", Language::Fortran)
267                 .Default(Language::Unknown);
268 
269     // Some special cases cannot be combined with suffixes.
270     if (dashX.isUnknown())
271       dashX = llvm::StringSwitch<InputKind>(xValue)
272                   .Case("ir", Language::LLVM_IR)
273                   .Default(Language::Unknown);
274 
275     if (dashX.isUnknown())
276       diags.Report(clang::diag::err_drv_invalid_value)
277           << a->getAsString(args) << a->getValue();
278   }
279 
280   // Collect the input files and save them in our instance of FrontendOptions.
281   std::vector<std::string> inputs =
282       args.getAllArgValues(clang::driver::options::OPT_INPUT);
283   opts.inputs.clear();
284   if (inputs.empty())
285     // '-' is the default input if none is given.
286     inputs.push_back("-");
287   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
288     InputKind ik = dashX;
289     if (ik.isUnknown()) {
290       ik = FrontendOptions::getInputKindForExtension(
291           llvm::StringRef(inputs[i]).rsplit('.').second);
292       if (ik.isUnknown())
293         ik = Language::Unknown;
294       if (i == 0)
295         dashX = ik;
296     }
297 
298     opts.inputs.emplace_back(std::move(inputs[i]), ik);
299   }
300 
301   // Set fortranForm based on options -ffree-form and -ffixed-form.
302   if (const auto *arg = args.getLastArg(clang::driver::options::OPT_ffixed_form,
303           clang::driver::options::OPT_ffree_form)) {
304     opts.fortranForm =
305         arg->getOption().matches(clang::driver::options::OPT_ffixed_form)
306         ? FortranForm::FixedForm
307         : FortranForm::FreeForm;
308   }
309 
310   // Set fixedFormColumns based on -ffixed-line-length=<value>
311   if (const auto *arg =
312           args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) {
313     llvm::StringRef argValue = llvm::StringRef(arg->getValue());
314     std::int64_t columns = -1;
315     if (argValue == "none") {
316       columns = 0;
317     } else if (argValue.getAsInteger(/*Radix=*/10, columns)) {
318       columns = -1;
319     }
320     if (columns < 0) {
321       diags.Report(clang::diag::err_drv_negative_columns)
322           << arg->getOption().getName() << arg->getValue();
323     } else if (columns == 0) {
324       opts.fixedFormColumns = 1000000;
325     } else if (columns < 7) {
326       diags.Report(clang::diag::err_drv_small_columns)
327           << arg->getOption().getName() << arg->getValue() << "7";
328     } else {
329       opts.fixedFormColumns = columns;
330     }
331   }
332 
333   // -f{no-}implicit-none
334   opts.features.Enable(
335       Fortran::common::LanguageFeature::ImplicitNoneTypeAlways,
336       args.hasFlag(clang::driver::options::OPT_fimplicit_none,
337           clang::driver::options::OPT_fno_implicit_none, false));
338 
339   // -f{no-}backslash
340   opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes,
341       args.hasFlag(clang::driver::options::OPT_fbackslash,
342           clang::driver::options::OPT_fno_backslash, false));
343 
344   // -f{no-}logical-abbreviations
345   opts.features.Enable(Fortran::common::LanguageFeature::LogicalAbbreviations,
346       args.hasFlag(clang::driver::options::OPT_flogical_abbreviations,
347           clang::driver::options::OPT_fno_logical_abbreviations, false));
348 
349   // -f{no-}xor-operator
350   opts.features.Enable(Fortran::common::LanguageFeature::XOROperator,
351       args.hasFlag(clang::driver::options::OPT_fxor_operator,
352           clang::driver::options::OPT_fno_xor_operator, false));
353 
354   // -fno-automatic
355   if (args.hasArg(clang::driver::options::OPT_fno_automatic)) {
356     opts.features.Enable(Fortran::common::LanguageFeature::DefaultSave);
357   }
358 
359   if (args.hasArg(
360           clang::driver::options::OPT_falternative_parameter_statement)) {
361     opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter);
362   }
363   if (const llvm::opt::Arg *arg =
364           args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) {
365     llvm::StringRef argValue = arg->getValue();
366     if (argValue == "utf-8") {
367       opts.encoding = Fortran::parser::Encoding::UTF_8;
368     } else if (argValue == "latin-1") {
369       opts.encoding = Fortran::parser::Encoding::LATIN_1;
370     } else {
371       diags.Report(clang::diag::err_drv_invalid_value)
372           << arg->getAsString(args) << argValue;
373     }
374   }
375 
376   setUpFrontendBasedOnAction(opts);
377   opts.dashX = dashX;
378 
379   return diags.getNumErrors() == numErrorsBefore;
380 }
381 
382 // Generate the path to look for intrinsic modules
383 static std::string getIntrinsicDir() {
384   // TODO: Find a system independent API
385   llvm::SmallString<128> driverPath;
386   driverPath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr));
387   llvm::sys::path::remove_filename(driverPath);
388   driverPath.append("/../include/flang/");
389   return std::string(driverPath);
390 }
391 
392 // Generate the path to look for OpenMP headers
393 static std::string getOpenMPHeadersDir() {
394   llvm::SmallString<128> includePath;
395   includePath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr));
396   llvm::sys::path::remove_filename(includePath);
397   includePath.append("/../include/flang/OpenMP/");
398   return std::string(includePath);
399 }
400 
401 /// Parses all preprocessor input arguments and populates the preprocessor
402 /// options accordingly.
403 ///
404 /// \param [in] opts The preprocessor options instance
405 /// \param [out] args The list of input arguments
406 static void parsePreprocessorArgs(
407     Fortran::frontend::PreprocessorOptions &opts, llvm::opt::ArgList &args) {
408   // Add macros from the command line.
409   for (const auto *currentArg : args.filtered(
410            clang::driver::options::OPT_D, clang::driver::options::OPT_U)) {
411     if (currentArg->getOption().matches(clang::driver::options::OPT_D)) {
412       opts.addMacroDef(currentArg->getValue());
413     } else {
414       opts.addMacroUndef(currentArg->getValue());
415     }
416   }
417 
418   // Add the ordered list of -I's.
419   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I))
420     opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue());
421 
422   // Prepend the ordered list of -intrinsic-modules-path
423   // to the default location to search.
424   for (const auto *currentArg :
425       args.filtered(clang::driver::options::OPT_fintrinsic_modules_path))
426     opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue());
427 
428   // -cpp/-nocpp
429   if (const auto *currentArg = args.getLastArg(
430           clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp))
431     opts.macrosFlag =
432         (currentArg->getOption().matches(clang::driver::options::OPT_cpp))
433         ? PPMacrosFlag::Include
434         : PPMacrosFlag::Exclude;
435 
436   opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat);
437   opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P);
438 }
439 
440 /// Parses all semantic related arguments and populates the variables
441 /// options accordingly. Returns false if new errors are generated.
442 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
443     clang::DiagnosticsEngine &diags) {
444   unsigned numErrorsBefore = diags.getNumErrors();
445 
446   // -J/module-dir option
447   auto moduleDirList =
448       args.getAllArgValues(clang::driver::options::OPT_module_dir);
449   // User can only specify -J/-module-dir once
450   // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html
451   if (moduleDirList.size() > 1) {
452     const unsigned diagID =
453         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
454             "Only one '-module-dir/-J' option allowed");
455     diags.Report(diagID);
456   }
457   if (moduleDirList.size() == 1)
458     res.setModuleDir(moduleDirList[0]);
459 
460   // -fdebug-module-writer option
461   if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) {
462     res.setDebugModuleDir(true);
463   }
464 
465   // -module-suffix
466   if (const auto *moduleSuffix =
467           args.getLastArg(clang::driver::options::OPT_module_suffix)) {
468     res.setModuleFileSuffix(moduleSuffix->getValue());
469   }
470 
471   // -f{no-}analyzed-objects-for-unparse
472   res.setUseAnalyzedObjectsForUnparse(args.hasFlag(
473       clang::driver::options::OPT_fanalyzed_objects_for_unparse,
474       clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true));
475 
476   return diags.getNumErrors() == numErrorsBefore;
477 }
478 
479 /// Parses all diagnostics related arguments and populates the variables
480 /// options accordingly. Returns false if new errors are generated.
481 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
482     clang::DiagnosticsEngine &diags) {
483   unsigned numErrorsBefore = diags.getNumErrors();
484 
485   // -Werror option
486   // TODO: Currently throws a Diagnostic for anything other than -W<error>,
487   // this has to change when other -W<opt>'s are supported.
488   if (args.hasArg(clang::driver::options::OPT_W_Joined)) {
489     if (args.getLastArgValue(clang::driver::options::OPT_W_Joined)
490             .equals("error")) {
491       res.setWarnAsErr(true);
492     } else {
493       const unsigned diagID =
494           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
495               "Only `-Werror` is supported currently.");
496       diags.Report(diagID);
497     }
498   }
499 
500   return diags.getNumErrors() == numErrorsBefore;
501 }
502 
503 /// Parses all Dialect related arguments and populates the variables
504 /// options accordingly. Returns false if new errors are generated.
505 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
506     clang::DiagnosticsEngine &diags) {
507   unsigned numErrorsBefore = diags.getNumErrors();
508 
509   // -fdefault* family
510   if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
511     res.getDefaultKinds().set_defaultRealKind(8);
512     res.getDefaultKinds().set_doublePrecisionKind(16);
513   }
514   if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) {
515     res.getDefaultKinds().set_defaultIntegerKind(8);
516     res.getDefaultKinds().set_subscriptIntegerKind(8);
517     res.getDefaultKinds().set_sizeIntegerKind(8);
518   }
519   if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) {
520     if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
521       // -fdefault-double-8 has to be used with -fdefault-real-8
522       // to be compatible with gfortran
523       const unsigned diagID =
524           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
525               "Use of `-fdefault-double-8` requires `-fdefault-real-8`");
526       diags.Report(diagID);
527     }
528     // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html
529     res.getDefaultKinds().set_doublePrecisionKind(8);
530   }
531   if (args.hasArg(clang::driver::options::OPT_flarge_sizes))
532     res.getDefaultKinds().set_sizeIntegerKind(8);
533 
534   // -fopenmp and -fopenacc
535   if (args.hasArg(clang::driver::options::OPT_fopenacc)) {
536     res.getFrontendOpts().features.Enable(
537         Fortran::common::LanguageFeature::OpenACC);
538   }
539   if (args.hasArg(clang::driver::options::OPT_fopenmp)) {
540     res.getFrontendOpts().features.Enable(
541         Fortran::common::LanguageFeature::OpenMP);
542   }
543 
544   // -pedantic
545   if (args.hasArg(clang::driver::options::OPT_pedantic)) {
546     res.setEnableConformanceChecks();
547   }
548   // -std=f2018 (currently this implies -pedantic)
549   // TODO: Set proper options when more fortran standards
550   // are supported.
551   if (args.hasArg(clang::driver::options::OPT_std_EQ)) {
552     auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ);
553     // We only allow f2018 as the given standard
554     if (standard.equals("f2018")) {
555       res.setEnableConformanceChecks();
556     } else {
557       const unsigned diagID =
558           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
559               "Only -std=f2018 is allowed currently.");
560       diags.Report(diagID);
561     }
562   }
563   return diags.getNumErrors() == numErrorsBefore;
564 }
565 
566 bool CompilerInvocation::createFromArgs(
567     CompilerInvocation &res, llvm::ArrayRef<const char *> commandLineArgs,
568     clang::DiagnosticsEngine &diags) {
569 
570   bool success = true;
571 
572   // Set the default triple for this CompilerInvocation. This might be
573   // overridden by users with `-triple` (see the call to `ParseTargetArgs`
574   // below).
575   // NOTE: Like in Clang, it would be nice to use option marshalling
576   // for this so that the entire logic for setting-up the triple is in one
577   // place.
578   res.getTargetOpts().triple =
579       llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple());
580 
581   // Parse the arguments
582   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
583   const unsigned includedFlagsBitmask = clang::driver::options::FC1Option;
584   unsigned missingArgIndex, missingArgCount;
585   llvm::opt::InputArgList args = opts.ParseArgs(
586       commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask);
587 
588   // Check for missing argument error.
589   if (missingArgCount) {
590     diags.Report(clang::diag::err_drv_missing_argument)
591         << args.getArgString(missingArgIndex) << missingArgCount;
592     success = false;
593   }
594 
595   // Issue errors on unknown arguments
596   for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
597     auto argString = a->getAsString(args);
598     std::string nearest;
599     if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1)
600       diags.Report(clang::diag::err_drv_unknown_argument) << argString;
601     else
602       diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
603           << argString << nearest;
604     success = false;
605   }
606 
607   success &= parseFrontendArgs(res.getFrontendOpts(), args, diags);
608   parseTargetArgs(res.getTargetOpts(), args);
609   parsePreprocessorArgs(res.getPreprocessorOpts(), args);
610   success &= parseSemaArgs(res, args, diags);
611   success &= parseDialectArgs(res, args, diags);
612   success &= parseDiagArgs(res, args, diags);
613   res.frontendOpts.llvmArgs =
614       args.getAllArgValues(clang::driver::options::OPT_mllvm);
615 
616   res.frontendOpts.mlirArgs =
617       args.getAllArgValues(clang::driver::options::OPT_mmlir);
618 
619   return success;
620 }
621 
622 void CompilerInvocation::collectMacroDefinitions() {
623   auto &ppOpts = this->getPreprocessorOpts();
624 
625   for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) {
626     llvm::StringRef macro = ppOpts.macros[i].first;
627     bool isUndef = ppOpts.macros[i].second;
628 
629     std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('=');
630     llvm::StringRef macroName = macroPair.first;
631     llvm::StringRef macroBody = macroPair.second;
632 
633     // For an #undef'd macro, we only care about the name.
634     if (isUndef) {
635       parserOpts.predefinitions.emplace_back(macroName.str(),
636                                              std::optional<std::string>{});
637       continue;
638     }
639 
640     // For a #define'd macro, figure out the actual definition.
641     if (macroName.size() == macro.size())
642       macroBody = "1";
643     else {
644       // Note: GCC drops anything following an end-of-line character.
645       llvm::StringRef::size_type end = macroBody.find_first_of("\n\r");
646       macroBody = macroBody.substr(0, end);
647     }
648     parserOpts.predefinitions.emplace_back(
649         macroName, std::optional<std::string>(macroBody.str()));
650   }
651 }
652 
653 void CompilerInvocation::setDefaultFortranOpts() {
654   auto &fortranOptions = getFortranOpts();
655 
656   std::vector<std::string> searchDirectories{"."s};
657   fortranOptions.searchDirectories = searchDirectories;
658 
659   // Add the location of omp_lib.h to the search directories. Currently this is
660   // identical to the modules' directory.
661   fortranOptions.searchDirectories.emplace_back(getOpenMPHeadersDir());
662 
663   fortranOptions.isFixedForm = false;
664 }
665 
666 // TODO: When expanding this method, consider creating a dedicated API for
667 // this. Also at some point we will need to differentiate between different
668 // targets and add dedicated predefines for each.
669 void CompilerInvocation::setDefaultPredefinitions() {
670   auto &fortranOptions = getFortranOpts();
671   const auto &frontendOptions = getFrontendOpts();
672 
673   // Populate the macro list with version numbers and other predefinitions.
674   fortranOptions.predefinitions.emplace_back("__flang__", "1");
675   fortranOptions.predefinitions.emplace_back(
676       "__flang_major__", FLANG_VERSION_MAJOR_STRING);
677   fortranOptions.predefinitions.emplace_back(
678       "__flang_minor__", FLANG_VERSION_MINOR_STRING);
679   fortranOptions.predefinitions.emplace_back(
680       "__flang_patchlevel__", FLANG_VERSION_PATCHLEVEL_STRING);
681 
682   // Add predefinitions based on extensions enabled
683   if (frontendOptions.features.IsEnabled(
684           Fortran::common::LanguageFeature::OpenACC)) {
685     fortranOptions.predefinitions.emplace_back("_OPENACC", "202011");
686   }
687   if (frontendOptions.features.IsEnabled(
688           Fortran::common::LanguageFeature::OpenMP)) {
689     fortranOptions.predefinitions.emplace_back("_OPENMP", "201511");
690   }
691 }
692 
693 void CompilerInvocation::setFortranOpts() {
694   auto &fortranOptions = getFortranOpts();
695   const auto &frontendOptions = getFrontendOpts();
696   const auto &preprocessorOptions = getPreprocessorOpts();
697   auto &moduleDirJ = getModuleDir();
698 
699   if (frontendOptions.fortranForm != FortranForm::Unknown) {
700     fortranOptions.isFixedForm =
701         frontendOptions.fortranForm == FortranForm::FixedForm;
702   }
703   fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns;
704 
705   fortranOptions.features = frontendOptions.features;
706   fortranOptions.encoding = frontendOptions.encoding;
707 
708   // Adding search directories specified by -I
709   fortranOptions.searchDirectories.insert(
710       fortranOptions.searchDirectories.end(),
711       preprocessorOptions.searchDirectoriesFromDashI.begin(),
712       preprocessorOptions.searchDirectoriesFromDashI.end());
713 
714   // Add the ordered list of -intrinsic-modules-path
715   fortranOptions.searchDirectories.insert(
716       fortranOptions.searchDirectories.end(),
717       preprocessorOptions.searchDirectoriesFromIntrModPath.begin(),
718       preprocessorOptions.searchDirectoriesFromIntrModPath.end());
719 
720   //  Add the default intrinsic module directory
721   fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir());
722 
723   // Add the directory supplied through -J/-module-dir to the list of search
724   // directories
725   if (moduleDirJ.compare(".") != 0)
726     fortranOptions.searchDirectories.emplace_back(moduleDirJ);
727 
728   if (frontendOptions.instrumentedParse)
729     fortranOptions.instrumentedParse = true;
730 
731   if (frontendOptions.needProvenanceRangeToCharBlockMappings)
732     fortranOptions.needProvenanceRangeToCharBlockMappings = true;
733 
734   if (getEnableConformanceChecks()) {
735     fortranOptions.features.WarnOnAllNonstandard();
736   }
737 }
738 
739 void CompilerInvocation::setSemanticsOpts(
740     Fortran::parser::AllCookedSources &allCookedSources) {
741   const auto &fortranOptions = getFortranOpts();
742 
743   semanticsContext = std::make_unique<semantics::SemanticsContext>(
744       getDefaultKinds(), fortranOptions.features, allCookedSources);
745 
746   semanticsContext->set_moduleDirectory(getModuleDir())
747       .set_searchDirectories(fortranOptions.searchDirectories)
748       .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories)
749       .set_warnOnNonstandardUsage(getEnableConformanceChecks())
750       .set_warningsAreErrors(getWarnAsErr())
751       .set_moduleFileSuffix(getModuleFileSuffix());
752 }
753