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