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