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