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