xref: /llvm-project/flang/lib/Frontend/CompilerInvocation.cpp (revision 53152f12a47bf6e97f1f2f2d6b71e7b4d4e3740a)
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       if (args.hasFlag(
726               clang::driver::options::OPT_fopenmp_assume_teams_oversubscription,
727               clang::driver::options::
728                   OPT_fno_openmp_assume_teams_oversubscription,
729               /*Default=*/false))
730         res.getLangOpts().OpenMPTeamSubscription = true;
731 
732       if (args.hasArg(
733               clang::driver::options::OPT_fopenmp_assume_no_thread_state))
734         res.getLangOpts().OpenMPNoThreadState = 1;
735 
736       if (args.hasArg(
737               clang::driver::options::OPT_fopenmp_assume_no_nested_parallelism))
738         res.getLangOpts().OpenMPNoNestedParallelism = 1;
739 
740       if (args.hasFlag(clang::driver::options::
741                            OPT_fopenmp_assume_threads_oversubscription,
742                        clang::driver::options::
743                            OPT_fno_openmp_assume_threads_oversubscription,
744                        /*Default=*/false))
745         res.getLangOpts().OpenMPThreadSubscription = true;
746 
747       if ((args.hasArg(clang::driver::options::OPT_fopenmp_target_debug) ||
748            args.hasArg(clang::driver::options::OPT_fopenmp_target_debug_EQ))) {
749         res.getLangOpts().OpenMPTargetDebug = getLastArgIntValue(
750             args, clang::driver::options::OPT_fopenmp_target_debug_EQ,
751             res.getLangOpts().OpenMPTargetDebug, diags);
752 
753         if (!res.getLangOpts().OpenMPTargetDebug &&
754             args.hasArg(clang::driver::options::OPT_fopenmp_target_debug))
755           res.getLangOpts().OpenMPTargetDebug = 1;
756       }
757     }
758   }
759 
760   // -pedantic
761   if (args.hasArg(clang::driver::options::OPT_pedantic)) {
762     res.setEnableConformanceChecks();
763   }
764   // -std=f2018 (currently this implies -pedantic)
765   // TODO: Set proper options when more fortran standards
766   // are supported.
767   if (args.hasArg(clang::driver::options::OPT_std_EQ)) {
768     auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ);
769     // We only allow f2018 as the given standard
770     if (standard.equals("f2018")) {
771       res.setEnableConformanceChecks();
772     } else {
773       const unsigned diagID =
774           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
775                                 "Only -std=f2018 is allowed currently.");
776       diags.Report(diagID);
777     }
778   }
779   return diags.getNumErrors() == numErrorsBefore;
780 }
781 
782 /// Parses all floating point related arguments and populates the
783 /// CompilerInvocation accordingly.
784 /// Returns false if new errors are generated.
785 ///
786 /// \param [out] invoc Stores the processed arguments
787 /// \param [in] args The compiler invocation arguments to parse
788 /// \param [out] diags DiagnosticsEngine to report erros with
789 static bool parseFloatingPointArgs(CompilerInvocation &invoc,
790                                    llvm::opt::ArgList &args,
791                                    clang::DiagnosticsEngine &diags) {
792   LangOptions &opts = invoc.getLangOpts();
793 
794   if (const llvm::opt::Arg *a =
795           args.getLastArg(clang::driver::options::OPT_ffp_contract)) {
796     const llvm::StringRef val = a->getValue();
797     enum LangOptions::FPModeKind fpContractMode;
798 
799     if (val == "off")
800       fpContractMode = LangOptions::FPM_Off;
801     else if (val == "fast")
802       fpContractMode = LangOptions::FPM_Fast;
803     else {
804       diags.Report(clang::diag::err_drv_unsupported_option_argument)
805           << a->getSpelling() << val;
806       return false;
807     }
808 
809     opts.setFPContractMode(fpContractMode);
810   }
811 
812   if (args.getLastArg(clang::driver::options::OPT_menable_no_infinities)) {
813     opts.NoHonorInfs = true;
814   }
815 
816   if (args.getLastArg(clang::driver::options::OPT_menable_no_nans)) {
817     opts.NoHonorNaNs = true;
818   }
819 
820   if (args.getLastArg(clang::driver::options::OPT_fapprox_func)) {
821     opts.ApproxFunc = true;
822   }
823 
824   if (args.getLastArg(clang::driver::options::OPT_fno_signed_zeros)) {
825     opts.NoSignedZeros = true;
826   }
827 
828   if (args.getLastArg(clang::driver::options::OPT_mreassociate)) {
829     opts.AssociativeMath = true;
830   }
831 
832   if (args.getLastArg(clang::driver::options::OPT_freciprocal_math)) {
833     opts.ReciprocalMath = true;
834   }
835 
836   if (args.getLastArg(clang::driver::options::OPT_ffast_math)) {
837     opts.NoHonorInfs = true;
838     opts.NoHonorNaNs = true;
839     opts.AssociativeMath = true;
840     opts.ReciprocalMath = true;
841     opts.ApproxFunc = true;
842     opts.NoSignedZeros = true;
843     opts.setFPContractMode(LangOptions::FPM_Fast);
844   }
845 
846   return true;
847 }
848 
849 bool CompilerInvocation::createFromArgs(
850     CompilerInvocation &res, llvm::ArrayRef<const char *> commandLineArgs,
851     clang::DiagnosticsEngine &diags) {
852 
853   bool success = true;
854 
855   // Set the default triple for this CompilerInvocation. This might be
856   // overridden by users with `-triple` (see the call to `ParseTargetArgs`
857   // below).
858   // NOTE: Like in Clang, it would be nice to use option marshalling
859   // for this so that the entire logic for setting-up the triple is in one
860   // place.
861   res.getTargetOpts().triple =
862       llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple());
863 
864   // Parse the arguments
865   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
866   const unsigned includedFlagsBitmask = clang::driver::options::FC1Option;
867   unsigned missingArgIndex, missingArgCount;
868   llvm::opt::InputArgList args = opts.ParseArgs(
869       commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask);
870 
871   // Check for missing argument error.
872   if (missingArgCount) {
873     diags.Report(clang::diag::err_drv_missing_argument)
874         << args.getArgString(missingArgIndex) << missingArgCount;
875     success = false;
876   }
877 
878   // Issue errors on unknown arguments
879   for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
880     auto argString = a->getAsString(args);
881     std::string nearest;
882     if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1)
883       diags.Report(clang::diag::err_drv_unknown_argument) << argString;
884     else
885       diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
886           << argString << nearest;
887     success = false;
888   }
889 
890   // -flang-experimental-hlfir
891   if (args.hasArg(clang::driver::options::OPT_flang_experimental_hlfir)) {
892     res.loweringOpts.setLowerToHighLevelFIR(true);
893   }
894 
895   success &= parseFrontendArgs(res.getFrontendOpts(), args, diags);
896   parseTargetArgs(res.getTargetOpts(), args);
897   parsePreprocessorArgs(res.getPreprocessorOpts(), args);
898   parseCodeGenArgs(res.getCodeGenOpts(), args, diags);
899   success &= parseDebugArgs(res.getCodeGenOpts(), args, diags);
900   success &= parseSemaArgs(res, args, diags);
901   success &= parseDialectArgs(res, args, diags);
902   success &= parseDiagArgs(res, args, diags);
903   res.frontendOpts.llvmArgs =
904       args.getAllArgValues(clang::driver::options::OPT_mllvm);
905 
906   res.frontendOpts.mlirArgs =
907       args.getAllArgValues(clang::driver::options::OPT_mmlir);
908 
909   success &= parseFloatingPointArgs(res, args, diags);
910 
911   return success;
912 }
913 
914 void CompilerInvocation::collectMacroDefinitions() {
915   auto &ppOpts = this->getPreprocessorOpts();
916 
917   for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) {
918     llvm::StringRef macro = ppOpts.macros[i].first;
919     bool isUndef = ppOpts.macros[i].second;
920 
921     std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('=');
922     llvm::StringRef macroName = macroPair.first;
923     llvm::StringRef macroBody = macroPair.second;
924 
925     // For an #undef'd macro, we only care about the name.
926     if (isUndef) {
927       parserOpts.predefinitions.emplace_back(macroName.str(),
928                                              std::optional<std::string>{});
929       continue;
930     }
931 
932     // For a #define'd macro, figure out the actual definition.
933     if (macroName.size() == macro.size())
934       macroBody = "1";
935     else {
936       // Note: GCC drops anything following an end-of-line character.
937       llvm::StringRef::size_type end = macroBody.find_first_of("\n\r");
938       macroBody = macroBody.substr(0, end);
939     }
940     parserOpts.predefinitions.emplace_back(
941         macroName, std::optional<std::string>(macroBody.str()));
942   }
943 }
944 
945 void CompilerInvocation::setDefaultFortranOpts() {
946   auto &fortranOptions = getFortranOpts();
947 
948   std::vector<std::string> searchDirectories{"."s};
949   fortranOptions.searchDirectories = searchDirectories;
950 
951   // Add the location of omp_lib.h to the search directories. Currently this is
952   // identical to the modules' directory.
953   fortranOptions.searchDirectories.emplace_back(getOpenMPHeadersDir());
954 
955   fortranOptions.isFixedForm = false;
956 }
957 
958 // TODO: When expanding this method, consider creating a dedicated API for
959 // this. Also at some point we will need to differentiate between different
960 // targets and add dedicated predefines for each.
961 void CompilerInvocation::setDefaultPredefinitions() {
962   auto &fortranOptions = getFortranOpts();
963   const auto &frontendOptions = getFrontendOpts();
964 
965   // Populate the macro list with version numbers and other predefinitions.
966   fortranOptions.predefinitions.emplace_back("__flang__", "1");
967   fortranOptions.predefinitions.emplace_back("__flang_major__",
968                                              FLANG_VERSION_MAJOR_STRING);
969   fortranOptions.predefinitions.emplace_back("__flang_minor__",
970                                              FLANG_VERSION_MINOR_STRING);
971   fortranOptions.predefinitions.emplace_back("__flang_patchlevel__",
972                                              FLANG_VERSION_PATCHLEVEL_STRING);
973 
974   // Add predefinitions based on extensions enabled
975   if (frontendOptions.features.IsEnabled(
976           Fortran::common::LanguageFeature::OpenACC)) {
977     fortranOptions.predefinitions.emplace_back("_OPENACC", "202011");
978   }
979   if (frontendOptions.features.IsEnabled(
980           Fortran::common::LanguageFeature::OpenMP)) {
981     fortranOptions.predefinitions.emplace_back("_OPENMP", "201511");
982   }
983   llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)};
984   if (targetTriple.getArch() == llvm::Triple::ArchType::x86_64) {
985     fortranOptions.predefinitions.emplace_back("__x86_64__", "1");
986     fortranOptions.predefinitions.emplace_back("__x86_64", "1");
987   }
988 }
989 
990 void CompilerInvocation::setFortranOpts() {
991   auto &fortranOptions = getFortranOpts();
992   const auto &frontendOptions = getFrontendOpts();
993   const auto &preprocessorOptions = getPreprocessorOpts();
994   auto &moduleDirJ = getModuleDir();
995 
996   if (frontendOptions.fortranForm != FortranForm::Unknown) {
997     fortranOptions.isFixedForm =
998         frontendOptions.fortranForm == FortranForm::FixedForm;
999   }
1000   fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns;
1001 
1002   fortranOptions.features = frontendOptions.features;
1003   fortranOptions.encoding = frontendOptions.encoding;
1004 
1005   // Adding search directories specified by -I
1006   fortranOptions.searchDirectories.insert(
1007       fortranOptions.searchDirectories.end(),
1008       preprocessorOptions.searchDirectoriesFromDashI.begin(),
1009       preprocessorOptions.searchDirectoriesFromDashI.end());
1010 
1011   // Add the ordered list of -intrinsic-modules-path
1012   fortranOptions.searchDirectories.insert(
1013       fortranOptions.searchDirectories.end(),
1014       preprocessorOptions.searchDirectoriesFromIntrModPath.begin(),
1015       preprocessorOptions.searchDirectoriesFromIntrModPath.end());
1016 
1017   //  Add the default intrinsic module directory
1018   fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir());
1019 
1020   // Add the directory supplied through -J/-module-dir to the list of search
1021   // directories
1022   if (moduleDirJ != ".")
1023     fortranOptions.searchDirectories.emplace_back(moduleDirJ);
1024 
1025   if (frontendOptions.instrumentedParse)
1026     fortranOptions.instrumentedParse = true;
1027 
1028   if (frontendOptions.showColors)
1029     fortranOptions.showColors = true;
1030 
1031   if (frontendOptions.needProvenanceRangeToCharBlockMappings)
1032     fortranOptions.needProvenanceRangeToCharBlockMappings = true;
1033 
1034   if (getEnableConformanceChecks()) {
1035     fortranOptions.features.WarnOnAllNonstandard();
1036   }
1037 }
1038 
1039 void CompilerInvocation::setSemanticsOpts(
1040     Fortran::parser::AllCookedSources &allCookedSources) {
1041   auto &fortranOptions = getFortranOpts();
1042 
1043   semanticsContext = std::make_unique<semantics::SemanticsContext>(
1044       getDefaultKinds(), fortranOptions.features, allCookedSources);
1045 
1046   semanticsContext->set_moduleDirectory(getModuleDir())
1047       .set_searchDirectories(fortranOptions.searchDirectories)
1048       .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories)
1049       .set_warnOnNonstandardUsage(getEnableConformanceChecks())
1050       .set_warningsAreErrors(getWarnAsErr())
1051       .set_moduleFileSuffix(getModuleFileSuffix());
1052 
1053   llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)};
1054   // FIXME: Handle real(3) ?
1055   if (targetTriple.getArch() != llvm::Triple::ArchType::x86_64) {
1056     semanticsContext->targetCharacteristics().DisableType(
1057         Fortran::common::TypeCategory::Real, /*kind=*/10);
1058   }
1059 }
1060 
1061 /// Set \p loweringOptions controlling lowering behavior based
1062 /// on the \p optimizationLevel.
1063 void CompilerInvocation::setLoweringOptions() {
1064   const CodeGenOptions &codegenOpts = getCodeGenOpts();
1065 
1066   // Lower TRANSPOSE as a runtime call under -O0.
1067   loweringOpts.setOptimizeTranspose(codegenOpts.OptimizationLevel > 0);
1068 
1069   const LangOptions &langOptions = getLangOpts();
1070   Fortran::common::MathOptionsBase &mathOpts = loweringOpts.getMathOptions();
1071   // TODO: when LangOptions are finalized, we can represent
1072   //       the math related options using Fortran::commmon::MathOptionsBase,
1073   //       so that we can just copy it into LoweringOptions.
1074   mathOpts
1075       .setFPContractEnabled(langOptions.getFPContractMode() ==
1076                             LangOptions::FPM_Fast)
1077       .setNoHonorInfs(langOptions.NoHonorInfs)
1078       .setNoHonorNaNs(langOptions.NoHonorNaNs)
1079       .setApproxFunc(langOptions.ApproxFunc)
1080       .setNoSignedZeros(langOptions.NoSignedZeros)
1081       .setAssociativeMath(langOptions.AssociativeMath)
1082       .setReciprocalMath(langOptions.ReciprocalMath);
1083 }
1084