xref: /llvm-project/flang/lib/Frontend/CompilerInvocation.cpp (revision fc97d2e68b03bc2979395e84b645e5b3ba35aecd)
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/Tools/TargetSetup.h"
22 #include "flang/Version.inc"
23 #include "clang/Basic/AllDiagnostics.h"
24 #include "clang/Basic/DiagnosticDriver.h"
25 #include "clang/Basic/DiagnosticOptions.h"
26 #include "clang/Driver/DriverDiagnostic.h"
27 #include "clang/Driver/OptionUtils.h"
28 #include "clang/Driver/Options.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/Frontend/Debug/Options.h"
32 #include "llvm/Option/Arg.h"
33 #include "llvm/Option/ArgList.h"
34 #include "llvm/Option/OptTable.h"
35 #include "llvm/Support/CodeGen.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/FileUtilities.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/Process.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/TargetParser/Host.h"
42 #include "llvm/TargetParser/Triple.h"
43 #include <algorithm>
44 #include <cstdlib>
45 #include <memory>
46 #include <optional>
47 
48 using namespace Fortran::frontend;
49 
50 //===----------------------------------------------------------------------===//
51 // Initialization.
52 //===----------------------------------------------------------------------===//
53 CompilerInvocationBase::CompilerInvocationBase()
54     : diagnosticOpts(new clang::DiagnosticOptions()),
55       preprocessorOpts(new PreprocessorOptions()) {}
56 
57 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x)
58     : diagnosticOpts(new clang::DiagnosticOptions(x.getDiagnosticOpts())),
59       preprocessorOpts(new PreprocessorOptions(x.getPreprocessorOpts())) {}
60 
61 CompilerInvocationBase::~CompilerInvocationBase() = default;
62 
63 //===----------------------------------------------------------------------===//
64 // Deserialization (from args)
65 //===----------------------------------------------------------------------===//
66 static bool parseShowColorsArgs(const llvm::opt::ArgList &args,
67                                 bool defaultColor = true) {
68   // Color diagnostics default to auto ("on" if terminal supports) in the
69   // compiler driver `flang` but default to off in the frontend driver
70   // `flang -fc1`, needing an explicit OPT_fdiagnostics_color.
71   // Support both clang's -f[no-]color-diagnostics and gcc's
72   // -f[no-]diagnostics-colors[=never|always|auto].
73   enum {
74     Colors_On,
75     Colors_Off,
76     Colors_Auto
77   } showColors = defaultColor ? Colors_Auto : Colors_Off;
78 
79   for (auto *a : args) {
80     const llvm::opt::Option &opt = a->getOption();
81     if (opt.matches(clang::driver::options::OPT_fcolor_diagnostics)) {
82       showColors = Colors_On;
83     } else if (opt.matches(clang::driver::options::OPT_fno_color_diagnostics)) {
84       showColors = Colors_Off;
85     } else if (opt.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) {
86       llvm::StringRef value(a->getValue());
87       if (value == "always")
88         showColors = Colors_On;
89       else if (value == "never")
90         showColors = Colors_Off;
91       else if (value == "auto")
92         showColors = Colors_Auto;
93     }
94   }
95 
96   return showColors == Colors_On ||
97          (showColors == Colors_Auto &&
98           llvm::sys::Process::StandardErrHasColors());
99 }
100 
101 /// Extracts the optimisation level from \a args.
102 static unsigned getOptimizationLevel(llvm::opt::ArgList &args,
103                                      clang::DiagnosticsEngine &diags) {
104   unsigned defaultOpt = 0;
105 
106   if (llvm::opt::Arg *a =
107           args.getLastArg(clang::driver::options::OPT_O_Group)) {
108     if (a->getOption().matches(clang::driver::options::OPT_O0))
109       return 0;
110 
111     assert(a->getOption().matches(clang::driver::options::OPT_O));
112 
113     return getLastArgIntValue(args, clang::driver::options::OPT_O, defaultOpt,
114                               diags);
115   }
116 
117   return defaultOpt;
118 }
119 
120 bool Fortran::frontend::parseDiagnosticArgs(clang::DiagnosticOptions &opts,
121                                             llvm::opt::ArgList &args) {
122   opts.ShowColors = parseShowColorsArgs(args);
123 
124   return true;
125 }
126 
127 static bool parseDebugArgs(Fortran::frontend::CodeGenOptions &opts,
128                            llvm::opt::ArgList &args,
129                            clang::DiagnosticsEngine &diags) {
130   using DebugInfoKind = llvm::codegenoptions::DebugInfoKind;
131   if (llvm::opt::Arg *arg =
132           args.getLastArg(clang::driver::options::OPT_debug_info_kind_EQ)) {
133     std::optional<DebugInfoKind> val =
134         llvm::StringSwitch<std::optional<DebugInfoKind>>(arg->getValue())
135             .Case("line-tables-only", llvm::codegenoptions::DebugLineTablesOnly)
136             .Case("line-directives-only",
137                   llvm::codegenoptions::DebugDirectivesOnly)
138             .Case("constructor", llvm::codegenoptions::DebugInfoConstructor)
139             .Case("limited", llvm::codegenoptions::LimitedDebugInfo)
140             .Case("standalone", llvm::codegenoptions::FullDebugInfo)
141             .Case("unused-types", llvm::codegenoptions::UnusedTypeInfo)
142             .Default(std::nullopt);
143     if (!val.has_value()) {
144       diags.Report(clang::diag::err_drv_invalid_value)
145           << arg->getAsString(args) << arg->getValue();
146       return false;
147     }
148     opts.setDebugInfo(val.value());
149     if (val != llvm::codegenoptions::DebugLineTablesOnly &&
150         val != llvm::codegenoptions::FullDebugInfo &&
151         val != llvm::codegenoptions::NoDebugInfo) {
152       const auto debugWarning = diags.getCustomDiagID(
153           clang::DiagnosticsEngine::Warning, "Unsupported debug option: %0");
154       diags.Report(debugWarning) << arg->getValue();
155     }
156   }
157   return true;
158 }
159 
160 static bool parseVectorLibArg(Fortran::frontend::CodeGenOptions &opts,
161                               llvm::opt::ArgList &args,
162                               clang::DiagnosticsEngine &diags) {
163   llvm::opt::Arg *arg = args.getLastArg(clang::driver::options::OPT_fveclib);
164   if (!arg)
165     return true;
166 
167   using VectorLibrary = llvm::driver::VectorLibrary;
168   std::optional<VectorLibrary> val =
169       llvm::StringSwitch<std::optional<VectorLibrary>>(arg->getValue())
170           .Case("Accelerate", VectorLibrary::Accelerate)
171           .Case("LIBMVEC", VectorLibrary::LIBMVEC)
172           .Case("MASSV", VectorLibrary::MASSV)
173           .Case("SVML", VectorLibrary::SVML)
174           .Case("SLEEF", VectorLibrary::SLEEF)
175           .Case("Darwin_libsystem_m", VectorLibrary::Darwin_libsystem_m)
176           .Case("ArmPL", VectorLibrary::ArmPL)
177           .Case("NoLibrary", VectorLibrary::NoLibrary)
178           .Default(std::nullopt);
179   if (!val.has_value()) {
180     diags.Report(clang::diag::err_drv_invalid_value)
181         << arg->getAsString(args) << arg->getValue();
182     return false;
183   }
184   opts.setVecLib(val.value());
185   return true;
186 }
187 
188 // Generate an OptRemark object containing info on if the -Rgroup
189 // specified is enabled or not.
190 static CodeGenOptions::OptRemark
191 parseOptimizationRemark(clang::DiagnosticsEngine &diags,
192                         llvm::opt::ArgList &args, llvm::opt::OptSpecifier optEq,
193                         llvm::StringRef remarkOptName) {
194   assert((remarkOptName == "pass" || remarkOptName == "pass-missed" ||
195           remarkOptName == "pass-analysis") &&
196          "Unsupported remark option name provided.");
197   CodeGenOptions::OptRemark result;
198 
199   for (llvm::opt::Arg *a : args) {
200     if (a->getOption().matches(clang::driver::options::OPT_R_Joined)) {
201       llvm::StringRef value = a->getValue();
202 
203       if (value == remarkOptName) {
204         result.Kind = CodeGenOptions::RemarkKind::RK_Enabled;
205         // Enable everything
206         result.Pattern = ".*";
207         result.Regex = std::make_shared<llvm::Regex>(result.Pattern);
208 
209       } else if (value.split('-') ==
210                  std::make_pair(llvm::StringRef("no"), remarkOptName)) {
211         result.Kind = CodeGenOptions::RemarkKind::RK_Disabled;
212         // Disable everything
213         result.Pattern = "";
214         result.Regex = nullptr;
215       }
216     } else if (a->getOption().matches(optEq)) {
217       result.Kind = CodeGenOptions::RemarkKind::RK_WithPattern;
218       result.Pattern = a->getValue();
219       result.Regex = std::make_shared<llvm::Regex>(result.Pattern);
220       std::string regexError;
221 
222       if (!result.Regex->isValid(regexError)) {
223         diags.Report(clang::diag::err_drv_optimization_remark_pattern)
224             << regexError << a->getAsString(args);
225         return CodeGenOptions::OptRemark();
226       }
227     }
228   }
229   return result;
230 }
231 
232 static void parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts,
233                              llvm::opt::ArgList &args,
234                              clang::DiagnosticsEngine &diags) {
235   opts.OptimizationLevel = getOptimizationLevel(args, diags);
236 
237   if (args.hasFlag(clang::driver::options::OPT_fdebug_pass_manager,
238                    clang::driver::options::OPT_fno_debug_pass_manager, false))
239     opts.DebugPassManager = 1;
240 
241   if (args.hasFlag(clang::driver::options::OPT_fstack_arrays,
242                    clang::driver::options::OPT_fno_stack_arrays, false))
243     opts.StackArrays = 1;
244 
245   if (args.hasFlag(clang::driver::options::OPT_floop_versioning,
246                    clang::driver::options::OPT_fno_loop_versioning, false))
247     opts.LoopVersioning = 1;
248 
249   opts.AliasAnalysis = opts.OptimizationLevel > 0;
250 
251   // -mframe-pointer=none/non-leaf/all option.
252   if (const llvm::opt::Arg *a =
253           args.getLastArg(clang::driver::options::OPT_mframe_pointer_EQ)) {
254     std::optional<llvm::FramePointerKind> val =
255         llvm::StringSwitch<std::optional<llvm::FramePointerKind>>(a->getValue())
256             .Case("none", llvm::FramePointerKind::None)
257             .Case("non-leaf", llvm::FramePointerKind::NonLeaf)
258             .Case("all", llvm::FramePointerKind::All)
259             .Default(std::nullopt);
260 
261     if (!val.has_value()) {
262       diags.Report(clang::diag::err_drv_invalid_value)
263           << a->getAsString(args) << a->getValue();
264     } else
265       opts.setFramePointer(val.value());
266   }
267 
268   for (auto *a : args.filtered(clang::driver::options::OPT_fpass_plugin_EQ))
269     opts.LLVMPassPlugins.push_back(a->getValue());
270 
271   // -fembed-offload-object option
272   for (auto *a :
273        args.filtered(clang::driver::options::OPT_fembed_offload_object_EQ))
274     opts.OffloadObjects.push_back(a->getValue());
275 
276   // -flto=full/thin option.
277   if (const llvm::opt::Arg *a =
278           args.getLastArg(clang::driver::options::OPT_flto_EQ)) {
279     llvm::StringRef s = a->getValue();
280     assert((s == "full" || s == "thin") && "Unknown LTO mode.");
281     if (s == "full")
282       opts.PrepareForFullLTO = true;
283     else
284       opts.PrepareForThinLTO = true;
285   }
286 
287   if (const llvm::opt::Arg *a = args.getLastArg(
288           clang::driver::options::OPT_mcode_object_version_EQ)) {
289     llvm::StringRef s = a->getValue();
290     if (s == "6")
291       opts.CodeObjectVersion = llvm::CodeObjectVersionKind::COV_6;
292     if (s == "5")
293       opts.CodeObjectVersion = llvm::CodeObjectVersionKind::COV_5;
294     if (s == "4")
295       opts.CodeObjectVersion = llvm::CodeObjectVersionKind::COV_4;
296     if (s == "none")
297       opts.CodeObjectVersion = llvm::CodeObjectVersionKind::COV_None;
298   }
299 
300   // -f[no-]save-optimization-record[=<format>]
301   if (const llvm::opt::Arg *a =
302           args.getLastArg(clang::driver::options::OPT_opt_record_file))
303     opts.OptRecordFile = a->getValue();
304 
305   // Optimization file format. Defaults to yaml
306   if (const llvm::opt::Arg *a =
307           args.getLastArg(clang::driver::options::OPT_opt_record_format))
308     opts.OptRecordFormat = a->getValue();
309 
310   // Specifies, using a regex, which successful optimization passes(middle and
311   // backend), to include in the final optimization record file generated. If
312   // not provided -fsave-optimization-record will include all passes.
313   if (const llvm::opt::Arg *a =
314           args.getLastArg(clang::driver::options::OPT_opt_record_passes))
315     opts.OptRecordPasses = a->getValue();
316 
317   // Create OptRemark that allows printing of all successful optimization
318   // passes applied.
319   opts.OptimizationRemark =
320       parseOptimizationRemark(diags, args, clang::driver::options::OPT_Rpass_EQ,
321                               /*remarkOptName=*/"pass");
322 
323   // Create OptRemark that allows all missed optimization passes to be printed.
324   opts.OptimizationRemarkMissed = parseOptimizationRemark(
325       diags, args, clang::driver::options::OPT_Rpass_missed_EQ,
326       /*remarkOptName=*/"pass-missed");
327 
328   // Create OptRemark that allows all optimization decisions made by LLVM
329   // to be printed.
330   opts.OptimizationRemarkAnalysis = parseOptimizationRemark(
331       diags, args, clang::driver::options::OPT_Rpass_analysis_EQ,
332       /*remarkOptName=*/"pass-analysis");
333 
334   if (opts.getDebugInfo() == llvm::codegenoptions::NoDebugInfo) {
335     // If the user requested a flag that requires source locations available in
336     // the backend, make sure that the backend tracks source location
337     // information.
338     bool needLocTracking = !opts.OptRecordFile.empty() ||
339                            !opts.OptRecordPasses.empty() ||
340                            !opts.OptRecordFormat.empty() ||
341                            opts.OptimizationRemark.hasValidPattern() ||
342                            opts.OptimizationRemarkMissed.hasValidPattern() ||
343                            opts.OptimizationRemarkAnalysis.hasValidPattern();
344 
345     if (needLocTracking)
346       opts.setDebugInfo(llvm::codegenoptions::LocTrackingOnly);
347   }
348 
349   if (auto *a = args.getLastArg(clang::driver::options::OPT_save_temps_EQ))
350     opts.SaveTempsDir = a->getValue();
351 
352   // -record-command-line option.
353   if (const llvm::opt::Arg *a =
354           args.getLastArg(clang::driver::options::OPT_record_command_line)) {
355     opts.RecordCommandLine = a->getValue();
356   }
357 
358   // -mlink-builtin-bitcode
359   for (auto *a :
360        args.filtered(clang::driver::options::OPT_mlink_builtin_bitcode))
361     opts.BuiltinBCLibs.push_back(a->getValue());
362 
363   // -mrelocation-model option.
364   if (const llvm::opt::Arg *a =
365           args.getLastArg(clang::driver::options::OPT_mrelocation_model)) {
366     llvm::StringRef modelName = a->getValue();
367     auto relocModel =
368         llvm::StringSwitch<std::optional<llvm::Reloc::Model>>(modelName)
369             .Case("static", llvm::Reloc::Static)
370             .Case("pic", llvm::Reloc::PIC_)
371             .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC)
372             .Case("ropi", llvm::Reloc::ROPI)
373             .Case("rwpi", llvm::Reloc::RWPI)
374             .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI)
375             .Default(std::nullopt);
376     if (relocModel.has_value())
377       opts.setRelocationModel(*relocModel);
378     else
379       diags.Report(clang::diag::err_drv_invalid_value)
380           << a->getAsString(args) << modelName;
381   }
382 
383   // -pic-level and -pic-is-pie option.
384   if (int picLevel = getLastArgIntValue(
385           args, clang::driver::options::OPT_pic_level, 0, diags)) {
386     if (picLevel > 2)
387       diags.Report(clang::diag::err_drv_invalid_value)
388           << args.getLastArg(clang::driver::options::OPT_pic_level)
389                  ->getAsString(args)
390           << picLevel;
391 
392     opts.PICLevel = picLevel;
393     if (args.hasArg(clang::driver::options::OPT_pic_is_pie))
394       opts.IsPIE = 1;
395   }
396 
397   // -mcmodel option.
398   if (const llvm::opt::Arg *a =
399           args.getLastArg(clang::driver::options::OPT_mcmodel_EQ)) {
400     llvm::StringRef modelName = a->getValue();
401     std::optional<llvm::CodeModel::Model> codeModel = getCodeModel(modelName);
402 
403     if (codeModel.has_value())
404       opts.CodeModel = modelName;
405     else
406       diags.Report(clang::diag::err_drv_invalid_value)
407           << a->getAsString(args) << modelName;
408   }
409 
410   if (const llvm::opt::Arg *arg = args.getLastArg(
411           clang::driver::options::OPT_mlarge_data_threshold_EQ)) {
412     uint64_t LDT;
413     if (llvm::StringRef(arg->getValue()).getAsInteger(/*Radix=*/10, LDT)) {
414       diags.Report(clang::diag::err_drv_invalid_value)
415           << arg->getSpelling() << arg->getValue();
416     }
417     opts.LargeDataThreshold = LDT;
418   }
419 
420   // This option is compatible with -f[no-]underscoring in gfortran.
421   if (args.hasFlag(clang::driver::options::OPT_fno_underscoring,
422                    clang::driver::options::OPT_funderscoring, false)) {
423     opts.Underscoring = 0;
424   }
425 }
426 
427 /// Parses all target input arguments and populates the target
428 /// options accordingly.
429 ///
430 /// \param [in] opts The target options instance to update
431 /// \param [in] args The list of input arguments (from the compiler invocation)
432 static void parseTargetArgs(TargetOptions &opts, llvm::opt::ArgList &args) {
433   if (const llvm::opt::Arg *a =
434           args.getLastArg(clang::driver::options::OPT_triple))
435     opts.triple = a->getValue();
436 
437   if (const llvm::opt::Arg *a =
438           args.getLastArg(clang::driver::options::OPT_target_cpu))
439     opts.cpu = a->getValue();
440 
441   if (const llvm::opt::Arg *a =
442           args.getLastArg(clang::driver::options::OPT_tune_cpu))
443     opts.cpuToTuneFor = a->getValue();
444 
445   for (const llvm::opt::Arg *currentArg :
446        args.filtered(clang::driver::options::OPT_target_feature))
447     opts.featuresAsWritten.emplace_back(currentArg->getValue());
448 
449   if (args.hasArg(clang::driver::options::OPT_fdisable_real_10))
450     opts.disabledRealKinds.push_back(10);
451 
452   if (args.hasArg(clang::driver::options::OPT_fdisable_real_3))
453     opts.disabledRealKinds.push_back(3);
454 
455   if (args.hasArg(clang::driver::options::OPT_fdisable_integer_2))
456     opts.disabledIntegerKinds.push_back(2);
457 
458   if (args.hasArg(clang::driver::options::OPT_fdisable_integer_16))
459     opts.disabledIntegerKinds.push_back(16);
460 
461   if (const llvm::opt::Arg *a =
462           args.getLastArg(clang::driver::options::OPT_mabi_EQ)) {
463     llvm::StringRef V = a->getValue();
464     if (V == "vec-extabi") {
465       opts.EnableAIXExtendedAltivecABI = true;
466     } else if (V == "vec-default") {
467       opts.EnableAIXExtendedAltivecABI = false;
468     }
469   }
470 }
471 // Tweak the frontend configuration based on the frontend action
472 static void setUpFrontendBasedOnAction(FrontendOptions &opts) {
473   if (opts.programAction == DebugDumpParsingLog)
474     opts.instrumentedParse = true;
475 
476   if (opts.programAction == DebugDumpProvenance ||
477       opts.programAction == Fortran::frontend::GetDefinition)
478     opts.needProvenanceRangeToCharBlockMappings = true;
479 }
480 
481 /// Parse the argument specified for the -fconvert=<value> option
482 static std::optional<const char *> parseConvertArg(const char *s) {
483   return llvm::StringSwitch<std::optional<const char *>>(s)
484       .Case("unknown", "UNKNOWN")
485       .Case("native", "NATIVE")
486       .Case("little-endian", "LITTLE_ENDIAN")
487       .Case("big-endian", "BIG_ENDIAN")
488       .Case("swap", "SWAP")
489       .Default(std::nullopt);
490 }
491 
492 static bool parseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args,
493                               clang::DiagnosticsEngine &diags) {
494   unsigned numErrorsBefore = diags.getNumErrors();
495 
496   // By default the frontend driver creates a ParseSyntaxOnly action.
497   opts.programAction = ParseSyntaxOnly;
498 
499   // Treat multiple action options as an invocation error. Note that `clang
500   // -cc1` does accept multiple action options, but will only consider the
501   // rightmost one.
502   if (args.hasMultipleArgs(clang::driver::options::OPT_Action_Group)) {
503     const unsigned diagID = diags.getCustomDiagID(
504         clang::DiagnosticsEngine::Error, "Only one action option is allowed");
505     diags.Report(diagID);
506     return false;
507   }
508 
509   // Identify the action (i.e. opts.ProgramAction)
510   if (const llvm::opt::Arg *a =
511           args.getLastArg(clang::driver::options::OPT_Action_Group)) {
512     switch (a->getOption().getID()) {
513     default: {
514       llvm_unreachable("Invalid option in group!");
515     }
516     case clang::driver::options::OPT_test_io:
517       opts.programAction = InputOutputTest;
518       break;
519     case clang::driver::options::OPT_E:
520       opts.programAction = PrintPreprocessedInput;
521       break;
522     case clang::driver::options::OPT_fsyntax_only:
523       opts.programAction = ParseSyntaxOnly;
524       break;
525     case clang::driver::options::OPT_emit_fir:
526       opts.programAction = EmitFIR;
527       break;
528     case clang::driver::options::OPT_emit_hlfir:
529       opts.programAction = EmitHLFIR;
530       break;
531     case clang::driver::options::OPT_emit_llvm:
532       opts.programAction = EmitLLVM;
533       break;
534     case clang::driver::options::OPT_emit_llvm_bc:
535       opts.programAction = EmitLLVMBitcode;
536       break;
537     case clang::driver::options::OPT_emit_obj:
538       opts.programAction = EmitObj;
539       break;
540     case clang::driver::options::OPT_S:
541       opts.programAction = EmitAssembly;
542       break;
543     case clang::driver::options::OPT_fdebug_unparse:
544       opts.programAction = DebugUnparse;
545       break;
546     case clang::driver::options::OPT_fdebug_unparse_no_sema:
547       opts.programAction = DebugUnparseNoSema;
548       break;
549     case clang::driver::options::OPT_fdebug_unparse_with_symbols:
550       opts.programAction = DebugUnparseWithSymbols;
551       break;
552     case clang::driver::options::OPT_fdebug_unparse_with_modules:
553       opts.programAction = DebugUnparseWithModules;
554       break;
555     case clang::driver::options::OPT_fdebug_dump_symbols:
556       opts.programAction = DebugDumpSymbols;
557       break;
558     case clang::driver::options::OPT_fdebug_dump_parse_tree:
559       opts.programAction = DebugDumpParseTree;
560       break;
561     case clang::driver::options::OPT_fdebug_dump_pft:
562       opts.programAction = DebugDumpPFT;
563       break;
564     case clang::driver::options::OPT_fdebug_dump_all:
565       opts.programAction = DebugDumpAll;
566       break;
567     case clang::driver::options::OPT_fdebug_dump_parse_tree_no_sema:
568       opts.programAction = DebugDumpParseTreeNoSema;
569       break;
570     case clang::driver::options::OPT_fdebug_dump_provenance:
571       opts.programAction = DebugDumpProvenance;
572       break;
573     case clang::driver::options::OPT_fdebug_dump_parsing_log:
574       opts.programAction = DebugDumpParsingLog;
575       break;
576     case clang::driver::options::OPT_fdebug_measure_parse_tree:
577       opts.programAction = DebugMeasureParseTree;
578       break;
579     case clang::driver::options::OPT_fdebug_pre_fir_tree:
580       opts.programAction = DebugPreFIRTree;
581       break;
582     case clang::driver::options::OPT_fget_symbols_sources:
583       opts.programAction = GetSymbolsSources;
584       break;
585     case clang::driver::options::OPT_fget_definition:
586       opts.programAction = GetDefinition;
587       break;
588     case clang::driver::options::OPT_init_only:
589       opts.programAction = InitOnly;
590       break;
591 
592       // TODO:
593       // case clang::driver::options::OPT_emit_llvm:
594       // case clang::driver::options::OPT_emit_llvm_only:
595       // case clang::driver::options::OPT_emit_codegen_only:
596       // case clang::driver::options::OPT_emit_module:
597       // (...)
598     }
599 
600     // Parse the values provided with `-fget-definition` (there should be 3
601     // integers)
602     if (llvm::opt::OptSpecifier(a->getOption().getID()) ==
603         clang::driver::options::OPT_fget_definition) {
604       unsigned optVals[3] = {0, 0, 0};
605 
606       for (unsigned i = 0; i < 3; i++) {
607         llvm::StringRef val = a->getValue(i);
608 
609         if (val.getAsInteger(10, optVals[i])) {
610           // A non-integer was encountered - that's an error.
611           diags.Report(clang::diag::err_drv_invalid_value)
612               << a->getOption().getName() << val;
613           break;
614         }
615       }
616       opts.getDefVals.line = optVals[0];
617       opts.getDefVals.startColumn = optVals[1];
618       opts.getDefVals.endColumn = optVals[2];
619     }
620   }
621 
622   // Parsing -load <dsopath> option and storing shared object path
623   if (llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_load)) {
624     opts.plugins.push_back(a->getValue());
625   }
626 
627   // Parsing -plugin <name> option and storing plugin name and setting action
628   if (const llvm::opt::Arg *a =
629           args.getLastArg(clang::driver::options::OPT_plugin)) {
630     opts.programAction = PluginAction;
631     opts.actionName = a->getValue();
632   }
633 
634   opts.outputFile = args.getLastArgValue(clang::driver::options::OPT_o);
635   opts.showHelp = args.hasArg(clang::driver::options::OPT_help);
636   opts.showVersion = args.hasArg(clang::driver::options::OPT_version);
637   opts.printSupportedCPUs =
638       args.hasArg(clang::driver::options::OPT_print_supported_cpus);
639 
640   // Get the input kind (from the value passed via `-x`)
641   InputKind dashX(Language::Unknown);
642   if (const llvm::opt::Arg *a =
643           args.getLastArg(clang::driver::options::OPT_x)) {
644     llvm::StringRef xValue = a->getValue();
645     // Principal languages.
646     dashX = llvm::StringSwitch<InputKind>(xValue)
647                 // Flang does not differentiate between pre-processed and not
648                 // pre-processed inputs.
649                 .Case("f95", Language::Fortran)
650                 .Case("f95-cpp-input", Language::Fortran)
651                 // CUDA Fortran
652                 .Case("cuda", Language::Fortran)
653                 .Default(Language::Unknown);
654 
655     // Flang's intermediate representations.
656     if (dashX.isUnknown())
657       dashX = llvm::StringSwitch<InputKind>(xValue)
658                   .Case("ir", Language::LLVM_IR)
659                   .Case("fir", Language::MLIR)
660                   .Case("mlir", Language::MLIR)
661                   .Default(Language::Unknown);
662 
663     if (dashX.isUnknown())
664       diags.Report(clang::diag::err_drv_invalid_value)
665           << a->getAsString(args) << a->getValue();
666   }
667 
668   // Collect the input files and save them in our instance of FrontendOptions.
669   std::vector<std::string> inputs =
670       args.getAllArgValues(clang::driver::options::OPT_INPUT);
671   opts.inputs.clear();
672   if (inputs.empty())
673     // '-' is the default input if none is given.
674     inputs.push_back("-");
675   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
676     InputKind ik = dashX;
677     if (ik.isUnknown()) {
678       ik = FrontendOptions::getInputKindForExtension(
679           llvm::StringRef(inputs[i]).rsplit('.').second);
680       if (ik.isUnknown())
681         ik = Language::Unknown;
682       if (i == 0)
683         dashX = ik;
684     }
685 
686     opts.inputs.emplace_back(std::move(inputs[i]), ik);
687   }
688 
689   // Set fortranForm based on options -ffree-form and -ffixed-form.
690   if (const auto *arg =
691           args.getLastArg(clang::driver::options::OPT_ffixed_form,
692                           clang::driver::options::OPT_ffree_form)) {
693     opts.fortranForm =
694         arg->getOption().matches(clang::driver::options::OPT_ffixed_form)
695             ? FortranForm::FixedForm
696             : FortranForm::FreeForm;
697   }
698 
699   // Set fixedFormColumns based on -ffixed-line-length=<value>
700   if (const auto *arg =
701           args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) {
702     llvm::StringRef argValue = llvm::StringRef(arg->getValue());
703     std::int64_t columns = -1;
704     if (argValue == "none") {
705       columns = 0;
706     } else if (argValue.getAsInteger(/*Radix=*/10, columns)) {
707       columns = -1;
708     }
709     if (columns < 0) {
710       diags.Report(clang::diag::err_drv_negative_columns)
711           << arg->getOption().getName() << arg->getValue();
712     } else if (columns == 0) {
713       opts.fixedFormColumns = 1000000;
714     } else if (columns < 7) {
715       diags.Report(clang::diag::err_drv_small_columns)
716           << arg->getOption().getName() << arg->getValue() << "7";
717     } else {
718       opts.fixedFormColumns = columns;
719     }
720   }
721 
722   // Set conversion based on -fconvert=<value>
723   if (const auto *arg =
724           args.getLastArg(clang::driver::options::OPT_fconvert_EQ)) {
725     const char *argValue = arg->getValue();
726     if (auto convert = parseConvertArg(argValue))
727       opts.envDefaults.push_back({"FORT_CONVERT", *convert});
728     else
729       diags.Report(clang::diag::err_drv_invalid_value)
730           << arg->getAsString(args) << argValue;
731   }
732 
733   // -f{no-}implicit-none
734   opts.features.Enable(
735       Fortran::common::LanguageFeature::ImplicitNoneTypeAlways,
736       args.hasFlag(clang::driver::options::OPT_fimplicit_none,
737                    clang::driver::options::OPT_fno_implicit_none, false));
738 
739   // -f{no-}backslash
740   opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes,
741                        args.hasFlag(clang::driver::options::OPT_fbackslash,
742                                     clang::driver::options::OPT_fno_backslash,
743                                     false));
744 
745   // -f{no-}logical-abbreviations
746   opts.features.Enable(
747       Fortran::common::LanguageFeature::LogicalAbbreviations,
748       args.hasFlag(clang::driver::options::OPT_flogical_abbreviations,
749                    clang::driver::options::OPT_fno_logical_abbreviations,
750                    false));
751 
752   // -f{no-}unsigned
753   opts.features.Enable(Fortran::common::LanguageFeature::Unsigned,
754                        args.hasFlag(clang::driver::options::OPT_funsigned,
755                                     clang::driver::options::OPT_fno_unsigned,
756                                     false));
757 
758   // -f{no-}xor-operator
759   opts.features.Enable(
760       Fortran::common::LanguageFeature::XOROperator,
761       args.hasFlag(clang::driver::options::OPT_fxor_operator,
762                    clang::driver::options::OPT_fno_xor_operator, false));
763 
764   // -fno-automatic
765   if (args.hasArg(clang::driver::options::OPT_fno_automatic)) {
766     opts.features.Enable(Fortran::common::LanguageFeature::DefaultSave);
767   }
768 
769   if (args.hasArg(
770           clang::driver::options::OPT_falternative_parameter_statement)) {
771     opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter);
772   }
773   if (const llvm::opt::Arg *arg =
774           args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) {
775     llvm::StringRef argValue = arg->getValue();
776     if (argValue == "utf-8") {
777       opts.encoding = Fortran::parser::Encoding::UTF_8;
778     } else if (argValue == "latin-1") {
779       opts.encoding = Fortran::parser::Encoding::LATIN_1;
780     } else {
781       diags.Report(clang::diag::err_drv_invalid_value)
782           << arg->getAsString(args) << argValue;
783     }
784   }
785 
786   setUpFrontendBasedOnAction(opts);
787   opts.dashX = dashX;
788 
789   return diags.getNumErrors() == numErrorsBefore;
790 }
791 
792 // Generate the path to look for intrinsic modules
793 static std::string getIntrinsicDir(const char *argv) {
794   // TODO: Find a system independent API
795   llvm::SmallString<128> driverPath;
796   driverPath.assign(llvm::sys::fs::getMainExecutable(argv, nullptr));
797   llvm::sys::path::remove_filename(driverPath);
798   driverPath.append("/../include/flang/");
799   return std::string(driverPath);
800 }
801 
802 // Generate the path to look for OpenMP headers
803 static std::string getOpenMPHeadersDir(const char *argv) {
804   llvm::SmallString<128> includePath;
805   includePath.assign(llvm::sys::fs::getMainExecutable(argv, nullptr));
806   llvm::sys::path::remove_filename(includePath);
807   includePath.append("/../include/flang/OpenMP/");
808   return std::string(includePath);
809 }
810 
811 /// Parses all preprocessor input arguments and populates the preprocessor
812 /// options accordingly.
813 ///
814 /// \param [in] opts The preprocessor options instance
815 /// \param [out] args The list of input arguments
816 static void parsePreprocessorArgs(Fortran::frontend::PreprocessorOptions &opts,
817                                   llvm::opt::ArgList &args) {
818   // Add macros from the command line.
819   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_D,
820                                               clang::driver::options::OPT_U)) {
821     if (currentArg->getOption().matches(clang::driver::options::OPT_D)) {
822       opts.addMacroDef(currentArg->getValue());
823     } else {
824       opts.addMacroUndef(currentArg->getValue());
825     }
826   }
827 
828   // Add the ordered list of -I's.
829   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I))
830     opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue());
831 
832   // Prepend the ordered list of -intrinsic-modules-path
833   // to the default location to search.
834   for (const auto *currentArg :
835        args.filtered(clang::driver::options::OPT_fintrinsic_modules_path))
836     opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue());
837 
838   // -cpp/-nocpp
839   if (const auto *currentArg = args.getLastArg(
840           clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp))
841     opts.macrosFlag =
842         (currentArg->getOption().matches(clang::driver::options::OPT_cpp))
843             ? PPMacrosFlag::Include
844             : PPMacrosFlag::Exclude;
845 
846   opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat);
847   opts.preprocessIncludeLines =
848       args.hasArg(clang::driver::options::OPT_fpreprocess_include_lines);
849   opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P);
850   opts.showMacros = args.hasArg(clang::driver::options::OPT_dM);
851 }
852 
853 /// Parses all semantic related arguments and populates the variables
854 /// options accordingly. Returns false if new errors are generated.
855 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
856                           clang::DiagnosticsEngine &diags) {
857   unsigned numErrorsBefore = diags.getNumErrors();
858 
859   // -J/module-dir option
860   std::vector<std::string> moduleDirList =
861       args.getAllArgValues(clang::driver::options::OPT_module_dir);
862   // User can only specify one -J/-module-dir directory, but may repeat
863   // -J/-module-dir as long as the directory is the same each time.
864   // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html
865   std::sort(moduleDirList.begin(), moduleDirList.end());
866   moduleDirList.erase(std::unique(moduleDirList.begin(), moduleDirList.end()),
867                       moduleDirList.end());
868   if (moduleDirList.size() > 1) {
869     const unsigned diagID =
870         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
871                               "Only one '-module-dir/-J' directory allowed. "
872                               "'-module-dir/-J' may be given multiple times "
873                               "but the directory must be the same each time.");
874     diags.Report(diagID);
875   }
876   if (moduleDirList.size() == 1)
877     res.setModuleDir(moduleDirList[0]);
878 
879   // -fdebug-module-writer option
880   if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) {
881     res.setDebugModuleDir(true);
882   }
883 
884   // -fhermetic-module-files option
885   if (args.hasArg(clang::driver::options::OPT_fhermetic_module_files)) {
886     res.setHermeticModuleFileOutput(true);
887   }
888 
889   // -module-suffix
890   if (const auto *moduleSuffix =
891           args.getLastArg(clang::driver::options::OPT_module_suffix)) {
892     res.setModuleFileSuffix(moduleSuffix->getValue());
893   }
894 
895   // -f{no-}analyzed-objects-for-unparse
896   res.setUseAnalyzedObjectsForUnparse(args.hasFlag(
897       clang::driver::options::OPT_fanalyzed_objects_for_unparse,
898       clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true));
899 
900   return diags.getNumErrors() == numErrorsBefore;
901 }
902 
903 /// Parses all diagnostics related arguments and populates the variables
904 /// options accordingly. Returns false if new errors are generated.
905 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
906                           clang::DiagnosticsEngine &diags) {
907   unsigned numErrorsBefore = diags.getNumErrors();
908 
909   // -Werror option
910   // TODO: Currently throws a Diagnostic for anything other than -W<error>,
911   // this has to change when other -W<opt>'s are supported.
912   if (args.hasArg(clang::driver::options::OPT_W_Joined)) {
913     const auto &wArgs =
914         args.getAllArgValues(clang::driver::options::OPT_W_Joined);
915     for (const auto &wArg : wArgs) {
916       if (wArg == "error") {
917         res.setWarnAsErr(true);
918       } else {
919         const unsigned diagID =
920             diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
921                                   "Only `-Werror` is supported currently.");
922         diags.Report(diagID);
923       }
924     }
925   }
926 
927   // Default to off for `flang -fc1`.
928   res.getFrontendOpts().showColors =
929       parseShowColorsArgs(args, /*defaultDiagColor=*/false);
930 
931   // Honor color diagnostics.
932   res.getDiagnosticOpts().ShowColors = res.getFrontendOpts().showColors;
933 
934   return diags.getNumErrors() == numErrorsBefore;
935 }
936 
937 /// Parses all Dialect related arguments and populates the variables
938 /// options accordingly. Returns false if new errors are generated.
939 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
940                              clang::DiagnosticsEngine &diags) {
941   unsigned numErrorsBefore = diags.getNumErrors();
942 
943   // -fdefault* family
944   if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
945     res.getDefaultKinds().set_defaultRealKind(8);
946     res.getDefaultKinds().set_doublePrecisionKind(16);
947   }
948   if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) {
949     res.getDefaultKinds().set_defaultIntegerKind(8);
950     res.getDefaultKinds().set_subscriptIntegerKind(8);
951     res.getDefaultKinds().set_sizeIntegerKind(8);
952     res.getDefaultKinds().set_defaultLogicalKind(8);
953   }
954   if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) {
955     if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
956       // -fdefault-double-8 has to be used with -fdefault-real-8
957       // to be compatible with gfortran
958       const unsigned diagID = diags.getCustomDiagID(
959           clang::DiagnosticsEngine::Error,
960           "Use of `-fdefault-double-8` requires `-fdefault-real-8`");
961       diags.Report(diagID);
962     }
963     // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html
964     res.getDefaultKinds().set_doublePrecisionKind(8);
965   }
966   if (args.hasArg(clang::driver::options::OPT_flarge_sizes))
967     res.getDefaultKinds().set_sizeIntegerKind(8);
968 
969   // -x cuda
970   auto language = args.getLastArgValue(clang::driver::options::OPT_x);
971   if (language == "cuda") {
972     res.getFrontendOpts().features.Enable(
973         Fortran::common::LanguageFeature::CUDA);
974   }
975 
976   // -fopenacc
977   if (args.hasArg(clang::driver::options::OPT_fopenacc)) {
978     res.getFrontendOpts().features.Enable(
979         Fortran::common::LanguageFeature::OpenACC);
980   }
981 
982   // -pedantic
983   if (args.hasArg(clang::driver::options::OPT_pedantic)) {
984     res.setEnableConformanceChecks();
985     res.setEnableUsageChecks();
986   }
987 
988   // -w
989   if (args.hasArg(clang::driver::options::OPT_w))
990     res.setDisableWarnings();
991 
992   // -std=f2018
993   // TODO: Set proper options when more fortran standards
994   // are supported.
995   if (args.hasArg(clang::driver::options::OPT_std_EQ)) {
996     auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ);
997     // We only allow f2018 as the given standard
998     if (standard == "f2018") {
999       res.setEnableConformanceChecks();
1000     } else {
1001       const unsigned diagID =
1002           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
1003                                 "Only -std=f2018 is allowed currently.");
1004       diags.Report(diagID);
1005     }
1006   }
1007   return diags.getNumErrors() == numErrorsBefore;
1008 }
1009 
1010 /// Parses all OpenMP related arguments if the -fopenmp option is present,
1011 /// populating the \c res object accordingly. Returns false if new errors are
1012 /// generated.
1013 static bool parseOpenMPArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
1014                             clang::DiagnosticsEngine &diags) {
1015   llvm::opt::Arg *arg = args.getLastArg(clang::driver::options::OPT_fopenmp,
1016                                         clang::driver::options::OPT_fno_openmp);
1017   if (!arg || arg->getOption().matches(clang::driver::options::OPT_fno_openmp))
1018     return true;
1019 
1020   unsigned numErrorsBefore = diags.getNumErrors();
1021   llvm::Triple t(res.getTargetOpts().triple);
1022 
1023   // By default OpenMP is set to 1.1 version
1024   res.getLangOpts().OpenMPVersion = 11;
1025   res.getFrontendOpts().features.Enable(
1026       Fortran::common::LanguageFeature::OpenMP);
1027   if (int Version = getLastArgIntValue(
1028           args, clang::driver::options::OPT_fopenmp_version_EQ,
1029           res.getLangOpts().OpenMPVersion, diags)) {
1030     res.getLangOpts().OpenMPVersion = Version;
1031   }
1032   if (args.hasArg(clang::driver::options::OPT_fopenmp_force_usm)) {
1033     res.getLangOpts().OpenMPForceUSM = 1;
1034   }
1035   if (args.hasArg(clang::driver::options::OPT_fopenmp_is_target_device)) {
1036     res.getLangOpts().OpenMPIsTargetDevice = 1;
1037 
1038     // Get OpenMP host file path if any and report if a non existent file is
1039     // found
1040     if (auto *arg = args.getLastArg(
1041             clang::driver::options::OPT_fopenmp_host_ir_file_path)) {
1042       res.getLangOpts().OMPHostIRFile = arg->getValue();
1043       if (!llvm::sys::fs::exists(res.getLangOpts().OMPHostIRFile))
1044         diags.Report(clang::diag::err_drv_omp_host_ir_file_not_found)
1045             << res.getLangOpts().OMPHostIRFile;
1046     }
1047 
1048     if (args.hasFlag(
1049             clang::driver::options::OPT_fopenmp_assume_teams_oversubscription,
1050             clang::driver::options::
1051                 OPT_fno_openmp_assume_teams_oversubscription,
1052             /*Default=*/false))
1053       res.getLangOpts().OpenMPTeamSubscription = true;
1054 
1055     if (args.hasArg(clang::driver::options::OPT_fopenmp_assume_no_thread_state))
1056       res.getLangOpts().OpenMPNoThreadState = 1;
1057 
1058     if (args.hasArg(
1059             clang::driver::options::OPT_fopenmp_assume_no_nested_parallelism))
1060       res.getLangOpts().OpenMPNoNestedParallelism = 1;
1061 
1062     if (args.hasFlag(
1063             clang::driver::options::OPT_fopenmp_assume_threads_oversubscription,
1064             clang::driver::options::
1065                 OPT_fno_openmp_assume_threads_oversubscription,
1066             /*Default=*/false))
1067       res.getLangOpts().OpenMPThreadSubscription = true;
1068 
1069     if ((args.hasArg(clang::driver::options::OPT_fopenmp_target_debug) ||
1070          args.hasArg(clang::driver::options::OPT_fopenmp_target_debug_EQ))) {
1071       res.getLangOpts().OpenMPTargetDebug = getLastArgIntValue(
1072           args, clang::driver::options::OPT_fopenmp_target_debug_EQ,
1073           res.getLangOpts().OpenMPTargetDebug, diags);
1074 
1075       if (!res.getLangOpts().OpenMPTargetDebug &&
1076           args.hasArg(clang::driver::options::OPT_fopenmp_target_debug))
1077         res.getLangOpts().OpenMPTargetDebug = 1;
1078     }
1079     if (args.hasArg(clang::driver::options::OPT_nogpulib))
1080       res.getLangOpts().NoGPULib = 1;
1081   }
1082 
1083   switch (llvm::Triple(res.getTargetOpts().triple).getArch()) {
1084   case llvm::Triple::nvptx:
1085   case llvm::Triple::nvptx64:
1086   case llvm::Triple::amdgcn:
1087     if (!res.getLangOpts().OpenMPIsTargetDevice) {
1088       const unsigned diagID = diags.getCustomDiagID(
1089           clang::DiagnosticsEngine::Error,
1090           "OpenMP AMDGPU/NVPTX is only prepared to deal with device code.");
1091       diags.Report(diagID);
1092     }
1093     res.getLangOpts().OpenMPIsGPU = 1;
1094     break;
1095   default:
1096     res.getLangOpts().OpenMPIsGPU = 0;
1097     break;
1098   }
1099 
1100   // Get the OpenMP target triples if any.
1101   if (auto *arg =
1102           args.getLastArg(clang::driver::options::OPT_fopenmp_targets_EQ)) {
1103     enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit };
1104     auto getArchPtrSize = [](const llvm::Triple &triple) {
1105       if (triple.isArch16Bit())
1106         return Arch16Bit;
1107       if (triple.isArch32Bit())
1108         return Arch32Bit;
1109       assert(triple.isArch64Bit() && "Expected 64-bit architecture");
1110       return Arch64Bit;
1111     };
1112 
1113     for (unsigned i = 0; i < arg->getNumValues(); ++i) {
1114       llvm::Triple tt(arg->getValue(i));
1115 
1116       if (tt.getArch() == llvm::Triple::UnknownArch ||
1117           !(tt.getArch() == llvm::Triple::aarch64 || tt.isPPC() ||
1118             tt.getArch() == llvm::Triple::systemz ||
1119             tt.getArch() == llvm::Triple::nvptx ||
1120             tt.getArch() == llvm::Triple::nvptx64 ||
1121             tt.getArch() == llvm::Triple::amdgcn ||
1122             tt.getArch() == llvm::Triple::x86 ||
1123             tt.getArch() == llvm::Triple::x86_64))
1124         diags.Report(clang::diag::err_drv_invalid_omp_target)
1125             << arg->getValue(i);
1126       else if (getArchPtrSize(t) != getArchPtrSize(tt))
1127         diags.Report(clang::diag::err_drv_incompatible_omp_arch)
1128             << arg->getValue(i) << t.str();
1129       else
1130         res.getLangOpts().OMPTargetTriples.push_back(tt);
1131     }
1132   }
1133   return diags.getNumErrors() == numErrorsBefore;
1134 }
1135 
1136 /// Parses signed integer overflow options and populates the
1137 /// CompilerInvocation accordingly.
1138 /// Returns false if new errors are generated.
1139 ///
1140 /// \param [out] invoc Stores the processed arguments
1141 /// \param [in] args The compiler invocation arguments to parse
1142 /// \param [out] diags DiagnosticsEngine to report erros with
1143 static bool parseIntegerOverflowArgs(CompilerInvocation &invoc,
1144                                      llvm::opt::ArgList &args,
1145                                      clang::DiagnosticsEngine &diags) {
1146   Fortran::common::LangOptions &opts = invoc.getLangOpts();
1147 
1148   if (args.getLastArg(clang::driver::options::OPT_fwrapv))
1149     opts.setSignedOverflowBehavior(Fortran::common::LangOptions::SOB_Defined);
1150 
1151   return true;
1152 }
1153 
1154 /// Parses all floating point related arguments and populates the
1155 /// CompilerInvocation accordingly.
1156 /// Returns false if new errors are generated.
1157 ///
1158 /// \param [out] invoc Stores the processed arguments
1159 /// \param [in] args The compiler invocation arguments to parse
1160 /// \param [out] diags DiagnosticsEngine to report erros with
1161 static bool parseFloatingPointArgs(CompilerInvocation &invoc,
1162                                    llvm::opt::ArgList &args,
1163                                    clang::DiagnosticsEngine &diags) {
1164   Fortran::common::LangOptions &opts = invoc.getLangOpts();
1165 
1166   if (const llvm::opt::Arg *a =
1167           args.getLastArg(clang::driver::options::OPT_ffp_contract)) {
1168     const llvm::StringRef val = a->getValue();
1169     enum Fortran::common::LangOptions::FPModeKind fpContractMode;
1170 
1171     if (val == "off")
1172       fpContractMode = Fortran::common::LangOptions::FPM_Off;
1173     else if (val == "fast")
1174       fpContractMode = Fortran::common::LangOptions::FPM_Fast;
1175     else {
1176       diags.Report(clang::diag::err_drv_unsupported_option_argument)
1177           << a->getSpelling() << val;
1178       return false;
1179     }
1180 
1181     opts.setFPContractMode(fpContractMode);
1182   }
1183 
1184   if (args.getLastArg(clang::driver::options::OPT_menable_no_infs)) {
1185     opts.NoHonorInfs = true;
1186   }
1187 
1188   if (args.getLastArg(clang::driver::options::OPT_menable_no_nans)) {
1189     opts.NoHonorNaNs = true;
1190   }
1191 
1192   if (args.getLastArg(clang::driver::options::OPT_fapprox_func)) {
1193     opts.ApproxFunc = true;
1194   }
1195 
1196   if (args.getLastArg(clang::driver::options::OPT_fno_signed_zeros)) {
1197     opts.NoSignedZeros = true;
1198   }
1199 
1200   if (args.getLastArg(clang::driver::options::OPT_mreassociate)) {
1201     opts.AssociativeMath = true;
1202   }
1203 
1204   if (args.getLastArg(clang::driver::options::OPT_freciprocal_math)) {
1205     opts.ReciprocalMath = true;
1206   }
1207 
1208   if (args.getLastArg(clang::driver::options::OPT_ffast_math)) {
1209     opts.NoHonorInfs = true;
1210     opts.NoHonorNaNs = true;
1211     opts.AssociativeMath = true;
1212     opts.ReciprocalMath = true;
1213     opts.ApproxFunc = true;
1214     opts.NoSignedZeros = true;
1215     opts.setFPContractMode(Fortran::common::LangOptions::FPM_Fast);
1216   }
1217 
1218   return true;
1219 }
1220 
1221 /// Parses vscale range options and populates the CompilerInvocation
1222 /// accordingly.
1223 /// Returns false if new errors are generated.
1224 ///
1225 /// \param [out] invoc Stores the processed arguments
1226 /// \param [in] args The compiler invocation arguments to parse
1227 /// \param [out] diags DiagnosticsEngine to report erros with
1228 static bool parseVScaleArgs(CompilerInvocation &invoc, llvm::opt::ArgList &args,
1229                             clang::DiagnosticsEngine &diags) {
1230   const auto *vscaleMin =
1231       args.getLastArg(clang::driver::options::OPT_mvscale_min_EQ);
1232   const auto *vscaleMax =
1233       args.getLastArg(clang::driver::options::OPT_mvscale_max_EQ);
1234 
1235   if (!vscaleMin && !vscaleMax)
1236     return true;
1237 
1238   llvm::Triple triple = llvm::Triple(invoc.getTargetOpts().triple);
1239   if (!triple.isAArch64() && !triple.isRISCV()) {
1240     const unsigned diagID =
1241         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
1242                               "`-mvscale-max` and `-mvscale-min` are not "
1243                               "supported for this architecture: %0");
1244     diags.Report(diagID) << triple.getArchName();
1245     return false;
1246   }
1247 
1248   Fortran::common::LangOptions &opts = invoc.getLangOpts();
1249   if (vscaleMin) {
1250     llvm::StringRef argValue = llvm::StringRef(vscaleMin->getValue());
1251     unsigned vscaleMinVal;
1252     if (argValue.getAsInteger(/*Radix=*/10, vscaleMinVal)) {
1253       diags.Report(clang::diag::err_drv_unsupported_option_argument)
1254           << vscaleMax->getSpelling() << argValue;
1255       return false;
1256     }
1257     opts.VScaleMin = vscaleMinVal;
1258   }
1259 
1260   if (vscaleMax) {
1261     llvm::StringRef argValue = llvm::StringRef(vscaleMax->getValue());
1262     unsigned vscaleMaxVal;
1263     if (argValue.getAsInteger(/*Radix=w*/ 10, vscaleMaxVal)) {
1264       diags.Report(clang::diag::err_drv_unsupported_option_argument)
1265           << vscaleMax->getSpelling() << argValue;
1266       return false;
1267     }
1268     opts.VScaleMax = vscaleMaxVal;
1269   }
1270   return true;
1271 }
1272 
1273 static bool parseLinkerOptionsArgs(CompilerInvocation &invoc,
1274                                    llvm::opt::ArgList &args,
1275                                    clang::DiagnosticsEngine &diags) {
1276   llvm::Triple triple = llvm::Triple(invoc.getTargetOpts().triple);
1277 
1278   // TODO: support --dependent-lib on other platforms when MLIR supports
1279   //       !llvm.dependent.lib
1280   if (args.hasArg(clang::driver::options::OPT_dependent_lib) &&
1281       !triple.isOSWindows()) {
1282     const unsigned diagID =
1283         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
1284                               "--dependent-lib is only supported on Windows");
1285     diags.Report(diagID);
1286     return false;
1287   }
1288 
1289   invoc.getCodeGenOpts().DependentLibs =
1290       args.getAllArgValues(clang::driver::options::OPT_dependent_lib);
1291   return true;
1292 }
1293 
1294 static bool parseLangOptionsArgs(CompilerInvocation &invoc,
1295                                  llvm::opt::ArgList &args,
1296                                  clang::DiagnosticsEngine &diags) {
1297   bool success = true;
1298 
1299   success &= parseIntegerOverflowArgs(invoc, args, diags);
1300   success &= parseFloatingPointArgs(invoc, args, diags);
1301   success &= parseVScaleArgs(invoc, args, diags);
1302 
1303   return success;
1304 }
1305 
1306 bool CompilerInvocation::createFromArgs(
1307     CompilerInvocation &invoc, llvm::ArrayRef<const char *> commandLineArgs,
1308     clang::DiagnosticsEngine &diags, const char *argv0) {
1309 
1310   bool success = true;
1311 
1312   // Set the default triple for this CompilerInvocation. This might be
1313   // overridden by users with `-triple` (see the call to `ParseTargetArgs`
1314   // below).
1315   // NOTE: Like in Clang, it would be nice to use option marshalling
1316   // for this so that the entire logic for setting-up the triple is in one
1317   // place.
1318   invoc.getTargetOpts().triple =
1319       llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple());
1320 
1321   // Parse the arguments
1322   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
1323   llvm::opt::Visibility visibilityMask(clang::driver::options::FC1Option);
1324   unsigned missingArgIndex, missingArgCount;
1325   llvm::opt::InputArgList args = opts.ParseArgs(
1326       commandLineArgs, missingArgIndex, missingArgCount, visibilityMask);
1327 
1328   // Check for missing argument error.
1329   if (missingArgCount) {
1330     diags.Report(clang::diag::err_drv_missing_argument)
1331         << args.getArgString(missingArgIndex) << missingArgCount;
1332     success = false;
1333   }
1334 
1335   // Issue errors on unknown arguments
1336   for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
1337     auto argString = a->getAsString(args);
1338     std::string nearest;
1339     if (opts.findNearest(argString, nearest, visibilityMask) > 1)
1340       diags.Report(clang::diag::err_drv_unknown_argument) << argString;
1341     else
1342       diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
1343           << argString << nearest;
1344     success = false;
1345   }
1346 
1347   // -flang-experimental-hlfir
1348   if (args.hasArg(clang::driver::options::OPT_flang_experimental_hlfir) ||
1349       args.hasArg(clang::driver::options::OPT_emit_hlfir)) {
1350     invoc.loweringOpts.setLowerToHighLevelFIR(true);
1351   }
1352 
1353   // -flang-deprecated-no-hlfir
1354   if (args.hasArg(clang::driver::options::OPT_flang_deprecated_no_hlfir) &&
1355       !args.hasArg(clang::driver::options::OPT_emit_hlfir)) {
1356     if (args.hasArg(clang::driver::options::OPT_flang_experimental_hlfir)) {
1357       const unsigned diagID = diags.getCustomDiagID(
1358           clang::DiagnosticsEngine::Error,
1359           "Options '-flang-experimental-hlfir' and "
1360           "'-flang-deprecated-no-hlfir' cannot be both specified");
1361       diags.Report(diagID);
1362     }
1363     invoc.loweringOpts.setLowerToHighLevelFIR(false);
1364   }
1365 
1366   // -fno-ppc-native-vector-element-order
1367   if (args.hasArg(clang::driver::options::OPT_fno_ppc_native_vec_elem_order)) {
1368     invoc.loweringOpts.setNoPPCNativeVecElemOrder(true);
1369   }
1370 
1371   // Preserve all the remark options requested, i.e. -Rpass, -Rpass-missed or
1372   // -Rpass-analysis. This will be used later when processing and outputting the
1373   // remarks generated by LLVM in ExecuteCompilerInvocation.cpp.
1374   for (auto *a : args.filtered(clang::driver::options::OPT_R_Group)) {
1375     if (a->getOption().matches(clang::driver::options::OPT_R_value_Group))
1376       // This is -Rfoo=, where foo is the name of the diagnostic
1377       // group. Add only the remark option name to the diagnostics. e.g. for
1378       // -Rpass= we will add the string "pass".
1379       invoc.getDiagnosticOpts().Remarks.push_back(
1380           std::string(a->getOption().getName().drop_front(1).rtrim("=-")));
1381     else
1382       // If no regex was provided, add the provided value, e.g. for -Rpass add
1383       // the string "pass".
1384       invoc.getDiagnosticOpts().Remarks.push_back(a->getValue());
1385   }
1386 
1387   // -frealloc-lhs is the default.
1388   if (!args.hasFlag(clang::driver::options::OPT_frealloc_lhs,
1389                     clang::driver::options::OPT_fno_realloc_lhs, true))
1390     invoc.loweringOpts.setReallocateLHS(false);
1391 
1392   success &= parseFrontendArgs(invoc.getFrontendOpts(), args, diags);
1393   parseTargetArgs(invoc.getTargetOpts(), args);
1394   parsePreprocessorArgs(invoc.getPreprocessorOpts(), args);
1395   parseCodeGenArgs(invoc.getCodeGenOpts(), args, diags);
1396   success &= parseDebugArgs(invoc.getCodeGenOpts(), args, diags);
1397   success &= parseVectorLibArg(invoc.getCodeGenOpts(), args, diags);
1398   success &= parseSemaArgs(invoc, args, diags);
1399   success &= parseDialectArgs(invoc, args, diags);
1400   success &= parseOpenMPArgs(invoc, args, diags);
1401   success &= parseDiagArgs(invoc, args, diags);
1402 
1403   // Collect LLVM (-mllvm) and MLIR (-mmlir) options.
1404   // NOTE: Try to avoid adding any options directly to `llvmArgs` or
1405   // `mlirArgs`. Instead, you can use
1406   //    * `-mllvm <your-llvm-option>`, or
1407   //    * `-mmlir <your-mlir-option>`.
1408   invoc.frontendOpts.llvmArgs =
1409       args.getAllArgValues(clang::driver::options::OPT_mllvm);
1410   invoc.frontendOpts.mlirArgs =
1411       args.getAllArgValues(clang::driver::options::OPT_mmlir);
1412 
1413   success &= parseLangOptionsArgs(invoc, args, diags);
1414 
1415   success &= parseLinkerOptionsArgs(invoc, args, diags);
1416 
1417   // Set the string to be used as the return value of the COMPILER_OPTIONS
1418   // intrinsic of iso_fortran_env. This is either passed in from the parent
1419   // compiler driver invocation with an environment variable, or failing that
1420   // set to the command line arguments of the frontend driver invocation.
1421   invoc.allCompilerInvocOpts = std::string();
1422   llvm::raw_string_ostream os(invoc.allCompilerInvocOpts);
1423   char *compilerOptsEnv = std::getenv("FLANG_COMPILER_OPTIONS_STRING");
1424   if (compilerOptsEnv != nullptr) {
1425     os << compilerOptsEnv;
1426   } else {
1427     os << argv0 << ' ';
1428     for (auto it = commandLineArgs.begin(), e = commandLineArgs.end(); it != e;
1429          ++it) {
1430       os << ' ' << *it;
1431     }
1432   }
1433 
1434   invoc.setArgv0(argv0);
1435 
1436   return success;
1437 }
1438 
1439 void CompilerInvocation::collectMacroDefinitions() {
1440   auto &ppOpts = this->getPreprocessorOpts();
1441 
1442   for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) {
1443     llvm::StringRef macro = ppOpts.macros[i].first;
1444     bool isUndef = ppOpts.macros[i].second;
1445 
1446     std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('=');
1447     llvm::StringRef macroName = macroPair.first;
1448     llvm::StringRef macroBody = macroPair.second;
1449 
1450     // For an #undef'd macro, we only care about the name.
1451     if (isUndef) {
1452       parserOpts.predefinitions.emplace_back(macroName.str(),
1453                                              std::optional<std::string>{});
1454       continue;
1455     }
1456 
1457     // For a #define'd macro, figure out the actual definition.
1458     if (macroName.size() == macro.size())
1459       macroBody = "1";
1460     else {
1461       // Note: GCC drops anything following an end-of-line character.
1462       llvm::StringRef::size_type end = macroBody.find_first_of("\n\r");
1463       macroBody = macroBody.substr(0, end);
1464     }
1465     parserOpts.predefinitions.emplace_back(
1466         macroName, std::optional<std::string>(macroBody.str()));
1467   }
1468 }
1469 
1470 void CompilerInvocation::setDefaultFortranOpts() {
1471   auto &fortranOptions = getFortranOpts();
1472 
1473   std::vector<std::string> searchDirectories{"."s};
1474   fortranOptions.searchDirectories = searchDirectories;
1475 
1476   // Add the location of omp_lib.h to the search directories. Currently this is
1477   // identical to the modules' directory.
1478   fortranOptions.searchDirectories.emplace_back(
1479       getOpenMPHeadersDir(getArgv0()));
1480 
1481   fortranOptions.isFixedForm = false;
1482 }
1483 
1484 // TODO: When expanding this method, consider creating a dedicated API for
1485 // this. Also at some point we will need to differentiate between different
1486 // targets and add dedicated predefines for each.
1487 void CompilerInvocation::setDefaultPredefinitions() {
1488   auto &fortranOptions = getFortranOpts();
1489   const auto &frontendOptions = getFrontendOpts();
1490   // Populate the macro list with version numbers and other predefinitions.
1491   fortranOptions.predefinitions.emplace_back("__flang__", "1");
1492   fortranOptions.predefinitions.emplace_back("__flang_major__",
1493                                              FLANG_VERSION_MAJOR_STRING);
1494   fortranOptions.predefinitions.emplace_back("__flang_minor__",
1495                                              FLANG_VERSION_MINOR_STRING);
1496   fortranOptions.predefinitions.emplace_back("__flang_patchlevel__",
1497                                              FLANG_VERSION_PATCHLEVEL_STRING);
1498 
1499   // Add predefinitions based on extensions enabled
1500   if (frontendOptions.features.IsEnabled(
1501           Fortran::common::LanguageFeature::OpenACC)) {
1502     fortranOptions.predefinitions.emplace_back("_OPENACC", "202211");
1503   }
1504   if (frontendOptions.features.IsEnabled(
1505           Fortran::common::LanguageFeature::OpenMP)) {
1506     Fortran::common::setOpenMPMacro(getLangOpts().OpenMPVersion,
1507                                     fortranOptions.predefinitions);
1508   }
1509 
1510   llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)};
1511   if (targetTriple.isPPC()) {
1512     // '__powerpc__' is a generic macro for any PowerPC cases. e.g. Max integer
1513     // size.
1514     fortranOptions.predefinitions.emplace_back("__powerpc__", "1");
1515   }
1516   if (targetTriple.isOSLinux()) {
1517     fortranOptions.predefinitions.emplace_back("__linux__", "1");
1518   }
1519 
1520   switch (targetTriple.getArch()) {
1521   default:
1522     break;
1523   case llvm::Triple::ArchType::x86_64:
1524     fortranOptions.predefinitions.emplace_back("__x86_64__", "1");
1525     fortranOptions.predefinitions.emplace_back("__x86_64", "1");
1526     break;
1527   }
1528 }
1529 
1530 void CompilerInvocation::setFortranOpts() {
1531   auto &fortranOptions = getFortranOpts();
1532   const auto &frontendOptions = getFrontendOpts();
1533   const auto &preprocessorOptions = getPreprocessorOpts();
1534   auto &moduleDirJ = getModuleDir();
1535 
1536   if (frontendOptions.fortranForm != FortranForm::Unknown) {
1537     fortranOptions.isFixedForm =
1538         frontendOptions.fortranForm == FortranForm::FixedForm;
1539   }
1540   fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns;
1541 
1542   // -E
1543   fortranOptions.prescanAndReformat =
1544       frontendOptions.programAction == PrintPreprocessedInput;
1545 
1546   fortranOptions.features = frontendOptions.features;
1547   fortranOptions.encoding = frontendOptions.encoding;
1548 
1549   // Adding search directories specified by -I
1550   fortranOptions.searchDirectories.insert(
1551       fortranOptions.searchDirectories.end(),
1552       preprocessorOptions.searchDirectoriesFromDashI.begin(),
1553       preprocessorOptions.searchDirectoriesFromDashI.end());
1554 
1555   // Add the ordered list of -intrinsic-modules-path
1556   fortranOptions.searchDirectories.insert(
1557       fortranOptions.searchDirectories.end(),
1558       preprocessorOptions.searchDirectoriesFromIntrModPath.begin(),
1559       preprocessorOptions.searchDirectoriesFromIntrModPath.end());
1560 
1561   //  Add the default intrinsic module directory
1562   fortranOptions.intrinsicModuleDirectories.emplace_back(
1563       getIntrinsicDir(getArgv0()));
1564 
1565   // Add the directory supplied through -J/-module-dir to the list of search
1566   // directories
1567   if (moduleDirJ != ".")
1568     fortranOptions.searchDirectories.emplace_back(moduleDirJ);
1569 
1570   if (frontendOptions.instrumentedParse)
1571     fortranOptions.instrumentedParse = true;
1572 
1573   if (frontendOptions.showColors)
1574     fortranOptions.showColors = true;
1575 
1576   if (frontendOptions.needProvenanceRangeToCharBlockMappings)
1577     fortranOptions.needProvenanceRangeToCharBlockMappings = true;
1578 
1579   if (getEnableConformanceChecks())
1580     fortranOptions.features.WarnOnAllNonstandard();
1581 
1582   if (getEnableUsageChecks())
1583     fortranOptions.features.WarnOnAllUsage();
1584 
1585   if (getDisableWarnings()) {
1586     fortranOptions.features.DisableAllNonstandardWarnings();
1587     fortranOptions.features.DisableAllUsageWarnings();
1588   }
1589 }
1590 
1591 std::unique_ptr<Fortran::semantics::SemanticsContext>
1592 CompilerInvocation::getSemanticsCtx(
1593     Fortran::parser::AllCookedSources &allCookedSources,
1594     const llvm::TargetMachine &targetMachine) {
1595   auto &fortranOptions = getFortranOpts();
1596 
1597   auto semanticsContext = std::make_unique<semantics::SemanticsContext>(
1598       getDefaultKinds(), fortranOptions.features, getLangOpts(),
1599       allCookedSources);
1600 
1601   semanticsContext->set_moduleDirectory(getModuleDir())
1602       .set_searchDirectories(fortranOptions.searchDirectories)
1603       .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories)
1604       .set_warningsAreErrors(getWarnAsErr())
1605       .set_moduleFileSuffix(getModuleFileSuffix())
1606       .set_underscoring(getCodeGenOpts().Underscoring);
1607 
1608   std::string compilerVersion = Fortran::common::getFlangFullVersion();
1609   Fortran::tools::setUpTargetCharacteristics(
1610       semanticsContext->targetCharacteristics(), targetMachine, getTargetOpts(),
1611       compilerVersion, allCompilerInvocOpts);
1612   return semanticsContext;
1613 }
1614 
1615 /// Set \p loweringOptions controlling lowering behavior based
1616 /// on the \p optimizationLevel.
1617 void CompilerInvocation::setLoweringOptions() {
1618   const CodeGenOptions &codegenOpts = getCodeGenOpts();
1619 
1620   // Lower TRANSPOSE as a runtime call under -O0.
1621   loweringOpts.setOptimizeTranspose(codegenOpts.OptimizationLevel > 0);
1622   loweringOpts.setUnderscoring(codegenOpts.Underscoring);
1623 
1624   const Fortran::common::LangOptions &langOptions = getLangOpts();
1625   loweringOpts.setIntegerWrapAround(langOptions.getSignedOverflowBehavior() ==
1626                                     Fortran::common::LangOptions::SOB_Defined);
1627   Fortran::common::MathOptionsBase &mathOpts = loweringOpts.getMathOptions();
1628   // TODO: when LangOptions are finalized, we can represent
1629   //       the math related options using Fortran::commmon::MathOptionsBase,
1630   //       so that we can just copy it into LoweringOptions.
1631   mathOpts
1632       .setFPContractEnabled(langOptions.getFPContractMode() ==
1633                             Fortran::common::LangOptions::FPM_Fast)
1634       .setNoHonorInfs(langOptions.NoHonorInfs)
1635       .setNoHonorNaNs(langOptions.NoHonorNaNs)
1636       .setApproxFunc(langOptions.ApproxFunc)
1637       .setNoSignedZeros(langOptions.NoSignedZeros)
1638       .setAssociativeMath(langOptions.AssociativeMath)
1639       .setReciprocalMath(langOptions.ReciprocalMath);
1640 }
1641