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