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