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