clang 24.0.0git
Flang.cpp
Go to the documentation of this file.
1//===-- Flang.cpp - Flang+LLVM ToolChain Implementations --------*- C++ -*-===//
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#include "Flang.h"
10#include "Arch/RISCV.h"
11#include "Cuda.h"
12
18#include "llvm/Frontend/Debug/Options.h"
19#include "llvm/Support/Path.h"
20#include "llvm/TargetParser/Host.h"
21#include "llvm/TargetParser/RISCVISAInfo.h"
22#include "llvm/TargetParser/RISCVTargetParser.h"
23
24#include <cassert>
25
26using namespace clang::driver;
27using namespace clang::driver::tools;
28using namespace clang;
29using namespace llvm::opt;
30
31/// Add -x lang to \p CmdArgs for \p Input.
32static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
33 ArgStringList &CmdArgs) {
34 CmdArgs.push_back("-x");
35 // Map the driver type to the frontend type.
36 CmdArgs.push_back(types::getTypeName(Input.getType()));
37}
38
39// Translate the dependency-file options into the arguments understood by
40// `flang -fc1`. The options handled here:
41// -M Emit only the dependencies and skip code generation. They are
42// written to stdout unless -MF redirects them.
43// -MM Treated identically to -M. The -MM/-M split exists to omit system
44// headers, but Fortran has no notion of system vs user headers, so
45// there is nothing for -MM to exclude.
46// -MD Compile normally and produce the object file, while also writing the
47// dependency file. Its name defaults to the -o value, or the input
48// file name when -o is absent, with the extension replaced by .d.
49// -MMD Treated identically to -MD, for the same reason -MM equals -M.
50// -MF Set the path of the dependency file to write.
51// -MT Set the dependency target name (the part before the colon).
52// -MQ Like -MT, but additionally quotes characters special to Make.
54 const JobAction &JA,
55 const ArgList &Args,
56 const InputInfo &Output,
57 const InputInfoList &Inputs,
58 ArgStringList &CmdArgs) {
59 Arg *ArgM = Args.getLastArg(options::OPT_M, options::OPT_MM);
60 Arg *ArgMD = Args.getLastArg(options::OPT_MD, options::OPT_MMD);
61
62 if (!ArgM && !ArgMD)
63 return;
64
65 // Drop warnings for -M/-MM so they don't mix into the dependency output.
66 if (ArgM)
67 CmdArgs.push_back("-w");
68 else
69 ArgM = ArgMD;
70
71 // Emit "-MT <target>", quoting Make metacharacters when requested.
72 auto addTarget = [&](StringRef Target, bool Quote) {
73 CmdArgs.push_back("-MT");
74 if (Quote) {
75 SmallString<128> Quoted;
77 CmdArgs.push_back(Args.MakeArgString(Quoted));
78 } else {
79 CmdArgs.push_back(Args.MakeArgString(Target));
80 }
81 };
82
83 // Decide where to write the dependency file.
84 const char *DepFile;
85 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
86 // -MF gives the path explicitly.
87 DepFile = MF->getValue();
88 C.addFailureResultFile(DepFile, &JA);
89 } else if (Output.getType() == types::TY_Dependencies) {
90 // Plain -M/-MM: the dependency file is the output, so use its name
91 DepFile = Output.getFilename();
92 } else if (!ArgMD) {
93 // -M/-MM with no -o: write the dependencies to stdout.
94 DepFile = "-";
95 } else {
96 // -MD/-MMD: name it after -o, else the input, with a .d extension.
98 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o))
99 P = OutputOpt->getValue();
100 else
101 P = llvm::sys::path::filename(Inputs[0].getBaseInput());
102 llvm::sys::path::replace_extension(P, "d");
103 DepFile = Args.MakeArgString(P);
104 C.addFailureResultFile(DepFile, &JA);
105 }
106 CmdArgs.push_back("-dependency-file");
107 CmdArgs.push_back(DepFile);
108
109 // Render the explicit target(s). -MT is verbatim, -MQ is Make-quoted.
110 bool HasTarget = false;
111 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
112 HasTarget = true;
113 A->claim();
114 addTarget(A->getValue(), A->getOption().matches(options::OPT_MQ));
115 }
116
117 // With no explicit target, default to the object file. In -M/-MM mode -o
118 // names the dependency file, not the target, so derive <base>.o instead.
119 if (!HasTarget) {
120 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
121 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
122 addTarget(OutputOpt->getValue(), /*Quote=*/true);
123 } else {
124 SmallString<128> P(llvm::sys::path::filename(Inputs[0].getBaseInput()));
125 llvm::sys::path::replace_extension(P, "o");
126 addTarget(P, /*Quote=*/true);
127 }
128 }
129}
130
131void Flang::addFortranDialectOptions(const ArgList &Args,
132 ArgStringList &CmdArgs) const {
133 Args.addAllArgs(CmdArgs,
134 {options::OPT_ffixed_form,
135 options::OPT_ffree_form,
136 options::OPT_ffixed_line_length_EQ,
137 options::OPT_fopenacc,
138 options::OPT_finput_charset_EQ,
139 options::OPT_fimplicit_none,
140 options::OPT_fimplicit_none_ext,
141 options::OPT_fimplicit_module_prefix,
142 options::OPT_fno_implicit_none,
143 options::OPT_fno_implicit_module_prefix,
144 options::OPT_fbackslash,
145 options::OPT_fno_backslash,
146 options::OPT_flogical_abbreviations,
147 options::OPT_fno_logical_abbreviations,
148 options::OPT_fxor_operator,
149 options::OPT_fno_xor_operator,
150 options::OPT_falternative_parameter_statement,
151 options::OPT_fdefault_integer_4,
152 options::OPT_fdefault_real_4,
153 options::OPT_fdefault_real_8,
154 options::OPT_fdefault_integer_8,
155 options::OPT_fdefault_double_8,
156 options::OPT_flarge_sizes,
157 options::OPT_fno_automatic,
158 options::OPT_fhermetic_module_files,
159 options::OPT_frealloc_lhs,
160 options::OPT_fno_realloc_lhs,
161 options::OPT_fsave_main_program,
162 options::OPT_fd_lines_as_code,
163 options::OPT_fd_lines_as_comments,
164 options::OPT_fno_save_main_program,
165 options::OPT_fprefer_intrinsic_module_use_association,
166 options::OPT_fno_prefer_intrinsic_module_use_association});
167}
168
169void Flang::addPreprocessingOptions(const ArgList &Args,
170 ArgStringList &CmdArgs) const {
171 Args.addAllArgs(CmdArgs,
172 {options::OPT_P, options::OPT_D, options::OPT_U,
173 options::OPT_I, options::OPT_cpp, options::OPT_nocpp});
174}
175
176/// @C shouldLoopVersion
177///
178/// Check if a loop versioning pass should be enabled.
179/// We look for the last of one of the following:
180/// -Ofast, -O4, -O<number>, -O0 and the pass's -f[no-]version-loops-for-*
181/// flag.
182/// Loop versioning is disabled if the last option is the -fno- flag or -O0.
183/// Loop versioning is enabled if the last option is one of:
184/// the -f flag
185/// -Ofast
186/// -O4
187/// -O3
188/// For all other cases, loop versioning is disabled.
189///
190/// The gfortran compiler automatically enables the option for -O3 or -Ofast.
191///
192/// @return true if loop-versioning should be enabled, otherwise false.
193static bool shouldLoopVersion(const ArgList &Args, options::ID PosFlag,
194 options::ID NegFlag) {
195 const Arg *LoopVersioningArg =
196 Args.getLastArg(options::OPT_Ofast, options::OPT_O, options::OPT_O4,
197 options::OPT_O0, PosFlag, NegFlag);
198 if (!LoopVersioningArg)
199 return false;
200
201 if (LoopVersioningArg->getOption().matches(NegFlag) ||
202 LoopVersioningArg->getOption().matches(options::OPT_O0))
203 return false;
204
205 if (LoopVersioningArg->getOption().matches(PosFlag))
206 return true;
207
208 if (LoopVersioningArg->getOption().matches(options::OPT_Ofast) ||
209 LoopVersioningArg->getOption().matches(options::OPT_O4))
210 return true;
211
212 if (LoopVersioningArg->getOption().matches(options::OPT_O)) {
213 StringRef S(LoopVersioningArg->getValue());
214 unsigned OptLevel = 0;
215 // Note -Os or Oz woould "fail" here, so return false. Which is the
216 // desiered behavior.
217 if (S.getAsInteger(10, OptLevel))
218 return false;
219
220 return OptLevel > 2;
221 }
222
223 llvm_unreachable("We should not end up here");
224 return false;
225}
226
227/// Return the kind of split DWARF that \p JA generates, or None if it generates
228/// none. Diagnoses a -gsplit-dwarf that cannot be honoured.
229static DwarfFissionKind
230getSplitDWARFKind(const ArgList &Args, const JobAction &JA, const ToolChain &TC,
231 llvm::codegenoptions::DebugInfoKind DebugInfoKind) {
232 const Driver &D = TC.getDriver();
233 if (Args.hasArg(options::OPT_gsplit_dwarf) ||
234 Args.hasArg(options::OPT_gsplit_dwarf_EQ)) {
235 // FIXME: -gsplit-dwarf on AIX is currently unimplemented.
236 if (TC.getTriple().isOSAIX()) {
237 D.Diag(diag::err_drv_unsupported_opt_for_target)
238 << Args.getLastArg(options::OPT_gsplit_dwarf)->getSpelling()
239 << TC.getTriple().str();
241 }
242 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo)
244
245 Arg *SplitDWARFArg;
246 DwarfFissionKind DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
247
248 if (DwarfFission == DwarfFissionKind::None ||
249 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC))
251
252 if (!TC.getTriple().isOSBinFormatELF() &&
253 !TC.getTriple().isOSBinFormatWasm() &&
254 !TC.getTriple().isOSBinFormatCOFF()) {
255 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
256 << SplitDWARFArg->getSpelling() << TC.getTriple().str();
258 }
259
263
264 return DwarfFission;
265 }
267}
268
269void Flang::addDebugOptions(const llvm::opt::ArgList &Args, const JobAction &JA,
270 const InputInfo &Output, const InputInfo &Input,
271 llvm::opt::ArgStringList &CmdArgs) const {
272 const auto &TC = getToolChain();
273 const Driver &D = TC.getDriver();
274 Args.addAllArgs(CmdArgs,
275 {options::OPT_module_dir,
276 options::OPT_fdebug_module_writer,
277 options::OPT_fintrinsic_modules_path,
278 options::OPT_pedantic,
279 options::OPT_std_EQ,
280 options::OPT_W_Joined,
281 options::OPT_fconvert_EQ,
282 options::OPT_fpass_plugin_EQ,
283 options::OPT_funderscoring,
284 options::OPT_fno_underscoring,
285 options::OPT_funsigned,
286 options::OPT_fno_unsigned,
287 options::OPT_fout_of_bounds_subscripts,
288 options::OPT_fno_out_of_bounds_subscripts,
289 options::OPT_fopenacc_default_none_scalars_strict,
290 options::OPT_fno_openacc_default_none_scalars_strict,
291 options::OPT_fopenacc_multiple_names_in_routine,
292 options::OPT_fno_openacc_multiple_names_in_routine,
293 options::OPT_finstrument_functions});
294
295 llvm::codegenoptions::DebugInfoKind DebugInfoKind;
296 bool hasDwarfNArg = getDwarfNArg(Args) != nullptr;
297 if (Args.hasArg(options::OPT_gN_Group)) {
298 Arg *gNArg = Args.getLastArg(options::OPT_gN_Group);
299 DebugInfoKind = debugLevelToInfoKind(*gNArg);
300 } else if (Args.hasArg(options::OPT_g_Flag) || hasDwarfNArg) {
301 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
302 } else {
303 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
304 }
305 addDebugInfoKind(CmdArgs, DebugInfoKind);
306 // Pass on the DWARF version when debug information is being generated, or
307 // when -gdwarf-N names a version. Leaving it out means the version stays
308 // unset and the backend falls back to dwarf::DWARF_VERSION (4) instead of
309 // honouring toolchain default like clang does.
310 //
311 // Note that both conditions are needed to match clang for cases like
312 // "-gdwarf-5 -g0".
313 if (hasDwarfNArg || DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
314 const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
315 CmdArgs.push_back(
316 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
317 }
318
319 DwarfFissionKind DwarfFission =
320 getSplitDWARFKind(Args, JA, TC, DebugInfoKind);
321 if (DwarfFission != DwarfFissionKind::None) {
322 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
323 CmdArgs.push_back("-split-dwarf-file");
324 CmdArgs.push_back(SplitDWARFOut);
325 if (DwarfFission == DwarfFissionKind::Split) {
326 CmdArgs.push_back("-split-dwarf-output");
327 CmdArgs.push_back(SplitDWARFOut);
328 }
329 }
330
331 // Handle name table requests (-gpubnames, -ggnu-pubnames). As in clang,
332 // split DWARF implies -ggnu-pubnames unless one of these says otherwise.
333 // TODO: Clang does not imply it when tuning for LLDB. Add that exception once
334 // flang has debugger tuning options (-glldb, -ggdb).
335 const Arg *PubnamesArg =
336 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
337 options::OPT_gpubnames, options::OPT_gno_pubnames);
338 if (DwarfFission != DwarfFissionKind::None ||
339 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) {
340 if (!PubnamesArg ||
341 PubnamesArg->getOption().matches(options::OPT_ggnu_pubnames))
342 CmdArgs.push_back("-ggnu-pubnames");
343 else if (PubnamesArg->getOption().matches(options::OPT_gpubnames))
344 CmdArgs.push_back("-gpubnames");
345 }
346
347 // Handle compressed debug sections (-gz).
348 renderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
349
350 addDebugInfoForProfilingArgs(D, TC, Args, CmdArgs);
351}
352
353void Flang::addCodegenOptions(const ArgList &Args,
354 ArgStringList &CmdArgs) const {
355 Arg *stackArrays =
356 Args.getLastArg(options::OPT_Ofast, options::OPT_fstack_arrays,
357 options::OPT_fno_stack_arrays);
358 if (stackArrays &&
359 !stackArrays->getOption().matches(options::OPT_fno_stack_arrays))
360 CmdArgs.push_back("-fstack-arrays");
361
362 if (Args.hasFlag(options::OPT_fsafe_trampoline,
363 options::OPT_fno_safe_trampoline, false)) {
364 const llvm::Triple &T = getToolChain().getTriple();
365 if (T.getArch() == llvm::Triple::x86_64 ||
366 T.getArch() == llvm::Triple::aarch64 ||
367 T.getArch() == llvm::Triple::aarch64_be) {
368 CmdArgs.push_back("-fsafe-trampoline");
369 } else {
371 diag::warn_drv_unsupported_option_for_target)
372 << "-fsafe-trampoline" << T.str();
373 }
374 }
375
376 // -fno-protect-parens is the default for -Ofast.
377 if (!Args.hasFlag(options::OPT_fprotect_parens,
378 options::OPT_fno_protect_parens,
379 /*Default=*/!Args.hasArg(options::OPT_Ofast)))
380 CmdArgs.push_back("-fno-protect-parens");
381
382 if (Args.hasFlag(options::OPT_funsafe_cray_pointers,
383 options::OPT_fno_unsafe_cray_pointers, false)) {
384 // TODO: currently passed as MLIR option
385 CmdArgs.push_back("-mmlir");
386 CmdArgs.push_back("-unsafe-cray-pointers");
387 }
388
389 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_loop_fusion,
390 options::OPT_fno_experimental_loop_fusion);
391 Args.AddLastArg(CmdArgs, options::OPT_ffp_sum_reassociation,
392 options::OPT_fno_fp_sum_reassociation);
393
394 Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
395 options::OPT_fno_unique_internal_linkage_names);
396
397 handleInterchangeLoopsArgs(Args, CmdArgs);
398 handleVectorizeLoopsArgs(Args, CmdArgs);
399 handleVectorizeSLPArgs(Args, CmdArgs);
400
401 if (shouldLoopVersion(Args, options::OPT_floop_versioning,
402 options::OPT_fno_loop_versioning))
403 CmdArgs.push_back("-fversion-loops-for-stride");
404 if (shouldLoopVersion(Args, options::OPT_floop_tripcount_versioning,
405 options::OPT_fno_loop_tripcount_versioning))
406 CmdArgs.push_back("-fversion-loops-for-trip-count");
407
408 for (const auto &arg :
409 Args.getAllArgValues(options::OPT_frepack_arrays_contiguity_EQ))
410 if (arg != "whole" && arg != "innermost") {
411 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
412 << "-frepack-arrays-contiguity=" << arg;
413 }
414
415 Args.addAllArgs(
416 CmdArgs,
417 {options::OPT_fdo_concurrent_to_openmp_EQ,
418 options::OPT_fno_ppc_native_vec_elem_order,
419 options::OPT_fppc_native_vec_elem_order, options::OPT_finit_global_zero,
420 options::OPT_fno_init_global_zero, options::OPT_finit_local_EQ,
421 options::OPT_frepack_arrays, options::OPT_fno_repack_arrays,
422 options::OPT_frepack_arrays_contiguity_EQ,
423 options::OPT_fstack_repack_arrays, options::OPT_fno_stack_repack_arrays,
424 options::OPT_ftime_report, options::OPT_ftime_report_EQ,
425 options::OPT_funroll_loops, options::OPT_fno_unroll_loops,
426 options::OPT_relaxed_c_loc});
427
428 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
429 options::OPT_fno_optimize_sibling_calls);
430
431 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
432 // Only ELF x86 and AArch64 use -fno-plt. The default is PLT,
433 // so only an explicit -fno-plt (last flag wins) is forwarded.
434 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
435 Args.addOptOutFlag(CmdArgs, options::OPT_fplt, options::OPT_fno_plt);
436 addSeparateSectionFlags(Triple, Args, CmdArgs);
437
438 if (Args.hasArg(options::OPT_fcoarray))
439 CmdArgs.push_back("-fcoarray");
440}
441
442void Flang::addLTOOptions(const ArgList &Args, ArgStringList &CmdArgs) const {
443 const ToolChain &TC = getToolChain();
444 LTOKind LTOMode = TC.getLTOMode(Args);
445 // LTO mode is parsed by the Clang driver library.
446 assert(LTOMode != LTOK_Unknown && "Unknown LTO mode.");
447 if (LTOMode == LTOK_Full)
448 CmdArgs.push_back("-flto=full");
449 else if (LTOMode == LTOK_Thin)
450 CmdArgs.push_back("-flto=thin");
451
452 if (Args.hasFlag(options::OPT_fsplit_lto_unit,
453 options::OPT_fno_split_lto_unit, /*Default=*/false))
454 CmdArgs.push_back("-fsplit-lto-unit");
455
456 Args.addAllArgs(CmdArgs, {options::OPT_ffat_lto_objects,
457 options::OPT_fno_fat_lto_objects});
458}
459
460void Flang::addPicOptions(const ArgList &Args, ArgStringList &CmdArgs) const {
461 // ParsePICArgs parses -fPIC/-fPIE and their variants and returns a tuple of
462 // (RelocationModel, PICLevel, IsPIE).
463 llvm::Reloc::Model RelocationModel;
464 unsigned PICLevel;
465 bool IsPIE;
466 std::tie(RelocationModel, PICLevel, IsPIE) =
467 ParsePICArgs(getToolChain(), Args);
468
469 if (auto *RMName = RelocationModelName(RelocationModel)) {
470 CmdArgs.push_back("-mrelocation-model");
471 CmdArgs.push_back(RMName);
472 }
473 if (PICLevel > 0) {
474 CmdArgs.push_back("-pic-level");
475 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
476 if (IsPIE)
477 CmdArgs.push_back("-pic-is-pie");
478 }
479}
480
481void Flang::AddAArch64TargetArgs(const ArgList &Args,
482 ArgStringList &CmdArgs) const {
483 // Handle -msve_vector_bits=<bits>
484 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
485 StringRef Val = A->getValue();
486 const Driver &D = getToolChain().getDriver();
487 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
488 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
489 Val == "1024+" || Val == "2048+") {
490 unsigned Bits = 0;
491 if (!Val.consume_back("+")) {
492 [[maybe_unused]] bool Invalid = Val.getAsInteger(10, Bits);
493 assert(!Invalid && "Failed to parse value");
494 CmdArgs.push_back(
495 Args.MakeArgString("-mvscale-max=" + llvm::Twine(Bits / 128)));
496 }
497
498 [[maybe_unused]] bool Invalid = Val.getAsInteger(10, Bits);
499 assert(!Invalid && "Failed to parse value");
500 CmdArgs.push_back(
501 Args.MakeArgString("-mvscale-min=" + llvm::Twine(Bits / 128)));
502 // Silently drop requests for vector-length agnostic code as it's implied.
503 } else if (Val != "scalable")
504 // Handle the unsupported values passed to msve-vector-bits.
505 D.Diag(diag::err_drv_unsupported_option_argument)
506 << A->getSpelling() << Val;
507 }
508}
509
510void Flang::AddLoongArch64TargetArgs(const ArgList &Args,
511 ArgStringList &CmdArgs) const {
512 const Driver &D = getToolChain().getDriver();
513 // Currently, flang only support `-mabi=lp64d` in LoongArch64.
514 if (const Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
515 StringRef V = A->getValue();
516 if (V != "lp64d") {
517 D.Diag(diag::err_drv_argument_not_allowed_with) << "-mabi" << V;
518 }
519 }
520
521 if (const Arg *A = Args.getLastArg(options::OPT_mannotate_tablejump,
522 options::OPT_mno_annotate_tablejump)) {
523 if (A->getOption().matches(options::OPT_mannotate_tablejump)) {
524 CmdArgs.push_back("-mllvm");
525 CmdArgs.push_back("-loongarch-annotate-tablejump");
526 }
527 }
528}
529
530void Flang::AddPPCTargetArgs(const ArgList &Args,
531 ArgStringList &CmdArgs) const {
532 const Driver &D = getToolChain().getDriver();
533 bool VecExtabi = false;
534
535 if (const Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
536 StringRef V = A->getValue();
537 if (V == "vec-extabi")
538 VecExtabi = true;
539 else if (V == "vec-default")
540 VecExtabi = false;
541 else
542 D.Diag(diag::err_drv_unsupported_option_argument)
543 << A->getSpelling() << V;
544 }
545
546 const llvm::Triple &T = getToolChain().getTriple();
547 if (VecExtabi) {
548 if (!T.isOSAIX()) {
549 D.Diag(diag::err_drv_unsupported_opt_for_target)
550 << "-mabi=vec-extabi" << T.str();
551 }
552 CmdArgs.push_back("-mabi=vec-extabi");
553 }
554}
555
556void Flang::AddRISCVTargetArgs(const ArgList &Args,
557 ArgStringList &CmdArgs) const {
558 const Driver &D = getToolChain().getDriver();
559 const llvm::Triple &Triple = getToolChain().getTriple();
560
561 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
562 if (ABIName == "lp64" || ABIName == "lp64f" || ABIName == "lp64d")
563 CmdArgs.push_back(Args.MakeArgString("-mabi=" + ABIName));
564 else
565 D.Diag(diag::err_drv_unsupported_option_argument) << "-mabi=" << ABIName;
566
567 // Handle -mrvv-vector-bits=<bits>
568 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
569 StringRef Val = A->getValue();
570
571 // Get minimum VLen from march.
572 unsigned MinVLen = 0;
573 std::string Arch = riscv::getRISCVArch(Args, Triple);
574 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
575 Arch, /*EnableExperimentalExtensions*/ true);
576 // Ignore parsing error.
577 if (!errorToBool(ISAInfo.takeError()))
578 MinVLen = (*ISAInfo)->getMinVLen();
579
580 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
581 // as integer as long as we have a MinVLen.
582 unsigned Bits = 0;
583 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
584 Bits = MinVLen;
585 } else if (!Val.getAsInteger(10, Bits)) {
586 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
587 // at least MinVLen.
588 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
589 Bits > 65536 || !llvm::isPowerOf2_32(Bits))
590 Bits = 0;
591 }
592
593 // If we got a valid value try to use it.
594 if (Bits != 0) {
595 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
596 CmdArgs.push_back(
597 Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
598 CmdArgs.push_back(
599 Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
600 } else if (Val != "scalable") {
601 // Handle the unsupported values passed to mrvv-vector-bits.
602 D.Diag(diag::err_drv_unsupported_option_argument)
603 << A->getSpelling() << Val;
604 }
605 }
606}
607
608void Flang::AddX86_64TargetArgs(const ArgList &Args,
609 ArgStringList &CmdArgs) const {
610 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
611 StringRef Value = A->getValue();
612 if (Value == "intel" || Value == "att") {
613 CmdArgs.push_back(Args.MakeArgString("-mllvm"));
614 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
615 } else {
616 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
617 << A->getSpelling() << Value;
618 }
619 }
620}
621
622static void addVSDefines(const ToolChain &TC, const ArgList &Args,
623 ArgStringList &CmdArgs) {
624
625 unsigned ver = 0;
626 const VersionTuple vt = TC.computeMSVCVersion(nullptr, Args);
627 ver = vt.getMajor() * 10000000 + vt.getMinor().value_or(0) * 100000 +
628 vt.getSubminor().value_or(0);
629 CmdArgs.push_back(Args.MakeArgString("-D_MSC_VER=" + Twine(ver / 100000)));
630 CmdArgs.push_back(Args.MakeArgString("-D_MSC_FULL_VER=" + Twine(ver)));
631 CmdArgs.push_back(Args.MakeArgString("-D_WIN32"));
632
633 const llvm::Triple &triple = TC.getTriple();
634 if (triple.isAArch64()) {
635 CmdArgs.push_back("-D_M_ARM64=1");
636 } else if (triple.isX86() && triple.isArch32Bit()) {
637 CmdArgs.push_back("-D_M_IX86=600");
638 } else if (triple.isX86() && triple.isArch64Bit()) {
639 CmdArgs.push_back("-D_M_X64=100");
640 } else {
641 llvm_unreachable(
642 "Flang on Windows only supports X86_32, X86_64 and AArch64");
643 }
644}
645
646static void processVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
647 ArgStringList &CmdArgs) {
648 assert(TC.getTriple().isKnownWindowsMSVCEnvironment() &&
649 "can only add VS runtime library on Windows!");
650
651 // Flang/Clang (including clang-cl) -compiled programs targeting the MSVC ABI
652 // should only depend on msv(u)crt. LLVM still emits libgcc/compiler-rt
653 // functions in some cases like 128-bit integer math (__udivti3, __modti3,
654 // __fixsfti, __floattidf, ...) that msvc does not support. We are injecting a
655 // dependency to Compiler-RT's builtin library where these are implemented.
656 CmdArgs.push_back(Args.MakeArgString(
657 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "builtins")));
658
659 unsigned RTOptionID = options::OPT__SLASH_MT;
660 if (auto *rtl = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
661 RTOptionID = llvm::StringSwitch<unsigned>(rtl->getValue())
662 .Case("static", options::OPT__SLASH_MT)
663 .Case("static_dbg", options::OPT__SLASH_MTd)
664 .Case("dll", options::OPT__SLASH_MD)
665 .Case("dll_dbg", options::OPT__SLASH_MDd)
666 .Default(options::OPT__SLASH_MT);
667 }
668 switch (RTOptionID) {
669 case options::OPT__SLASH_MT:
670 CmdArgs.push_back("-D_MT");
671 CmdArgs.push_back("--dependent-lib=libcmt");
672 CmdArgs.push_back("--dependent-lib=flang_rt.runtime.static.lib");
673 break;
674 case options::OPT__SLASH_MTd:
675 CmdArgs.push_back("-D_MT");
676 CmdArgs.push_back("-D_DEBUG");
677 CmdArgs.push_back("--dependent-lib=libcmtd");
678 CmdArgs.push_back("--dependent-lib=flang_rt.runtime.static_dbg.lib");
679 break;
680 case options::OPT__SLASH_MD:
681 CmdArgs.push_back("-D_MT");
682 CmdArgs.push_back("-D_DLL");
683 CmdArgs.push_back("--dependent-lib=msvcrt");
684 CmdArgs.push_back("--dependent-lib=flang_rt.runtime.dynamic.lib");
685 break;
686 case options::OPT__SLASH_MDd:
687 CmdArgs.push_back("-D_MT");
688 CmdArgs.push_back("-D_DEBUG");
689 CmdArgs.push_back("-D_DLL");
690 CmdArgs.push_back("--dependent-lib=msvcrtd");
691 CmdArgs.push_back("--dependent-lib=flang_rt.runtime.dynamic_dbg.lib");
692 break;
693 }
694}
695
696void Flang::AddAMDGPUTargetArgs(const ArgList &Args, ArgStringList &CmdArgs,
697 BoundArch BA,
698 Action::OffloadKind DeviceOffloadKind) const {
699 if (Arg *A = Args.getLastArg(options::OPT_mcode_object_version_EQ)) {
700 StringRef Val = A->getValue();
701 CmdArgs.push_back(Args.MakeArgString("-mcode-object-version=" + Val));
702 CmdArgs.push_back(Args.MakeArgString("-mllvm"));
703 CmdArgs.push_back(
704 Args.MakeArgString("--amdhsa-code-object-version=" + Val));
705 }
706
707 const ToolChain &TC = getToolChain();
708 TC.addClangTargetOptions(Args, CmdArgs, BA, DeviceOffloadKind);
709}
710
711void Flang::AddNVPTXTargetArgs(const ArgList &Args, ArgStringList &CmdArgs,
712 BoundArch BA,
713 Action::OffloadKind DeviceOffloadKind) const {
714 // we cannot use addClangTargetOptions, as it appends unsupported args for
715 // flang: -fcuda-is-device, -fno-threadsafe-statics,
716 // -fcuda-allow-variadic-functions and -target-sdk-version Instead we manually
717 // detect the CUDA installation and link libdevice
718 const ToolChain &TC = getToolChain();
719 const Driver &D = TC.getDriver();
720 const llvm::Triple &Triple = TC.getEffectiveTriple();
721
722 if (!Args.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib, true))
723 return;
724
725 // Detect CUDA installation and link libdevice
726 CudaInstallationDetector CudaInstallation(D, Triple, Args);
727 if (!CudaInstallation.isValid()) {
728 D.Diag(diag::err_drv_no_cuda_installation);
729 return;
730 }
731
732 StringRef GpuArch = Args.getLastArgValue(options::OPT_march_EQ);
733 if (GpuArch.empty()) {
734 D.Diag(diag::err_drv_offload_missing_gpu_arch) << "NVPTX" << "flang";
735 return;
736 }
737
738 std::string LibDeviceFile = CudaInstallation.getLibDeviceFile(GpuArch);
739 if (LibDeviceFile.empty()) {
740 D.Diag(diag::err_drv_no_cuda_libdevice) << GpuArch;
741 return;
742 }
743
744 CmdArgs.push_back("-mlink-builtin-bitcode");
745 CmdArgs.push_back(Args.MakeArgString(LibDeviceFile));
746}
747
748void Flang::addTargetOptions(const ArgList &Args, ArgStringList &CmdArgs,
749 BoundArch BA,
750 Action::OffloadKind DeviceOffloadKind) const {
751 const ToolChain &TC = getToolChain();
752 const llvm::Triple &Triple = TC.getEffectiveTriple();
753 const Driver &D = TC.getDriver();
754
755 std::string CPU = getCPUName(D, Args, Triple);
756 if (!CPU.empty()) {
757 CmdArgs.push_back("-target-cpu");
758 CmdArgs.push_back(Args.MakeArgString(CPU));
759 }
760
761 addOutlineAtomicsArgs(D, getToolChain(), Args, CmdArgs, Triple);
762
763 // Add the target features.
764 switch (TC.getArch()) {
765 default:
766 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
767 break;
768 case llvm::Triple::aarch64:
769 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
770 AddAArch64TargetArgs(Args, CmdArgs);
771 break;
772 case llvm::Triple::amdgpu:
773 case llvm::Triple::r600:
774 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
775 AddAMDGPUTargetArgs(Args, CmdArgs, BA, DeviceOffloadKind);
776 break;
777 case llvm::Triple::nvptx:
778 case llvm::Triple::nvptx64:
779 AddNVPTXTargetArgs(Args, CmdArgs, BA, DeviceOffloadKind);
780 break;
781 case llvm::Triple::riscv64:
782 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
783 AddRISCVTargetArgs(Args, CmdArgs);
784 break;
785 case llvm::Triple::x86_64:
786 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
787 AddX86_64TargetArgs(Args, CmdArgs);
788 break;
789 case llvm::Triple::ppc:
790 case llvm::Triple::ppc64:
791 case llvm::Triple::ppc64le:
792 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
793 AddPPCTargetArgs(Args, CmdArgs);
794 break;
795 case llvm::Triple::loongarch64:
796 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
797 AddLoongArch64TargetArgs(Args, CmdArgs);
798 break;
799 }
800
801 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
802 StringRef Name = A->getValue();
803 if (Name == "SVML") {
804 if (Triple.getArch() != llvm::Triple::x86 &&
805 Triple.getArch() != llvm::Triple::x86_64)
806 D.Diag(diag::err_drv_unsupported_opt_for_target)
807 << Name << Triple.getArchName();
808 } else if (Name == "AMDLIBM") {
809 if (Triple.getArch() != llvm::Triple::x86 &&
810 Triple.getArch() != llvm::Triple::x86_64)
811 D.Diag(diag::err_drv_unsupported_opt_for_target)
812 << Name << Triple.getArchName();
813 } else if (Name == "libmvec") {
814 if (Triple.getArch() != llvm::Triple::x86 &&
815 Triple.getArch() != llvm::Triple::x86_64 &&
816 Triple.getArch() != llvm::Triple::aarch64 &&
817 Triple.getArch() != llvm::Triple::aarch64_be)
818 D.Diag(diag::err_drv_unsupported_opt_for_target)
819 << Name << Triple.getArchName();
820 } else if (Name == "SLEEF" || Name == "ArmPL") {
821 if (Triple.getArch() != llvm::Triple::aarch64 &&
822 Triple.getArch() != llvm::Triple::aarch64_be)
823 D.Diag(diag::err_drv_unsupported_opt_for_target)
824 << Name << Triple.getArchName();
825 }
826
827 if (Triple.isOSDarwin()) {
828 // flang doesn't currently support nostdlib, nodefaultlibs. Adding these
829 // here incase they are added someday
830 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
831 if (A->getValue() == StringRef{"Accelerate"}) {
832 CmdArgs.push_back("-framework");
833 CmdArgs.push_back("Accelerate");
834 }
835 }
836 }
837 A->render(Args, CmdArgs);
838 }
839
840 if (Triple.isKnownWindowsMSVCEnvironment()) {
841 processVSRuntimeLibrary(TC, Args, CmdArgs);
842 addVSDefines(TC, Args, CmdArgs);
843 }
844
845 // TODO: Add target specific flags, ABI, mtune option etc.
846 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
847 CmdArgs.push_back("-tune-cpu");
848 if (A->getValue() == StringRef{"native"})
849 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
850 else
851 CmdArgs.push_back(A->getValue());
852 }
853
854 Args.addAllArgs(CmdArgs,
855 {options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
856 options::OPT_fatomic_ignore_denormal_mode,
857 options::OPT_fno_atomic_ignore_denormal_mode,
858 options::OPT_fatomic_fine_grained_memory,
859 options::OPT_fno_atomic_fine_grained_memory,
860 options::OPT_fatomic_remote_memory,
861 options::OPT_fno_atomic_remote_memory,
862 options::OPT_munsafe_fp_atomics});
863}
864
865void Flang::addOffloadOptions(Compilation &C, const InputInfoList &Inputs,
866 const JobAction &JA, const ArgList &Args,
867 ArgStringList &CmdArgs) const {
868 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
869 bool IsHostOffloadingAction = JA.isHostOffloading(Action::OFK_OpenMP) ||
870 JA.isHostOffloading(C.getActiveOffloadKinds());
871
872 // Tell the frontend when it is compiling for an offloading device, regardless
873 // of offloading programming model.
875 CmdArgs.push_back("-foffload-device");
876
877 // Skips the primary input file, which is the input file that the compilation
878 // proccess will be executed upon (e.g. the host bitcode file) and
879 // adds other secondary input (e.g. device bitcode files for embedding to the
880 // -fembed-offload-object argument or the host IR file for proccessing
881 // during device compilation to the fopenmp-host-ir-file-path argument via
882 // OpenMPDeviceInput). This is condensed logic from the ConstructJob
883 // function inside of the Clang driver for pushing on further input arguments
884 // needed for offloading during various phases of compilation.
885 for (size_t i = 1; i < Inputs.size(); ++i) {
886 if (Inputs[i].getType() == types::TY_Nothing) {
887 // contains nothing, so it's skippable
888 } else if (IsHostOffloadingAction) {
889 CmdArgs.push_back(
890 Args.MakeArgString("-fembed-offload-object=" +
891 getToolChain().getInputFilename(Inputs[i])));
892 } else if (IsOpenMPDevice) {
893 if (Inputs[i].getFilename()) {
894 CmdArgs.push_back("-fopenmp-host-ir-file-path");
895 CmdArgs.push_back(Args.MakeArgString(Inputs[i].getFilename()));
896 } else {
897 llvm_unreachable("missing openmp host-ir file for device offloading");
898 }
899 } else {
900 llvm_unreachable(
901 "unexpectedly given multiple inputs or given unknown input");
902 }
903 }
904
905 // When in OpenMP offloading mode, forward assumptions information about
906 // thread and team counts in the target device. The host needs to know about
907 // this to prevent the SPMD to SPMD-no-loop promotion being done differently
908 // for host and device on the same target region.
909 if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
910 options::OPT_fno_openmp_assume_teams_oversubscription,
911 /*Default=*/false))
912 CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
913 if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
914 options::OPT_fno_openmp_assume_threads_oversubscription,
915 /*Default=*/false))
916 CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
917
918 // This forwards the option to switch off/on mapper generation for scenarios
919 // where the compiler considers it neccessary to generate a mapper to cover
920 // implicit allocatable member mapping inside of derived types to adhere to
921 // specification compliance.
922 if (!Args.hasFlag(
923 options::OPT_fimplicit_default_mapper_allocatable_members,
924 options::OPT_fno_implicit_default_mapper_allocatable_members,
925 /*Default=*/true))
926 CmdArgs.push_back("-fno-implicit-default-mapper-allocatable-members");
927
928 if (IsOpenMPDevice) {
929 // -fopenmp-is-target-device is passed along to tell the frontend that it is
930 // generating code for a device, so that only the relevant code is emitted.
931 CmdArgs.push_back("-fopenmp-is-target-device");
932
933 // -fopenmp-target-fast implies -fopenmp-assume-no-thread-state and
934 // -fopenmp-assume-no-nested-parallelism, and forces -O3 unless an
935 // explicit optimization level was requested.
936 bool TargetFastUsed =
937 Args.hasFlag(options::OPT_fopenmp_target_fast,
938 options::OPT_fno_openmp_target_fast, false);
939
940 if (TargetFastUsed && !Args.hasArg(options::OPT_O_Group))
941 CmdArgs.push_back("-O3");
942
943 // When in OpenMP offloading mode, enable debugging on the device.
944 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
945 if (Args.hasFlag(options::OPT_fopenmp_target_debug,
946 options::OPT_fno_openmp_target_debug, /*Default=*/false))
947 CmdArgs.push_back("-fopenmp-target-debug");
948
949 // Handle -fopenmp-assume-no-thread-state (implied by target-fast)
950 if (Args.hasFlag(options::OPT_fopenmp_assume_no_thread_state,
951 options::OPT_fno_openmp_assume_no_thread_state,
952 /*Default=*/TargetFastUsed))
953 CmdArgs.push_back("-fopenmp-assume-no-thread-state");
954
955 // Handle -fopenmp-assume-no-nested-parallelism (implied by target-fast)
956 if (Args.hasFlag(options::OPT_fopenmp_assume_no_nested_parallelism,
957 options::OPT_fno_openmp_assume_no_nested_parallelism,
958 /*Default=*/TargetFastUsed))
959 CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
960
961 if (!Args.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib,
962 true))
963 CmdArgs.push_back("-nogpulib");
964 }
965
966 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
967}
968
969static void addFloatingPointOptions(const Driver &D, const ArgList &Args,
970 ArgStringList &CmdArgs) {
971 StringRef FPContract;
972 StringRef LastSeenFfpContractOption;
973 StringRef LastFpContractOverrideOption;
974 bool HonorINFs = true;
975 bool HonorNaNs = true;
976 bool ApproxFunc = false;
977 bool SignedZeros = true;
978 bool AssociativeMath = false;
979 bool ReciprocalMath = false;
980
981 StringRef LastComplexRangeOption;
983
984 for (const Arg *A : Args) {
985 auto optId = A->getOption().getID();
986 switch (optId) {
987 // if this isn't an FP option, skip the claim below
988 default:
989 continue;
990
991 case options::OPT_fcomplex_arithmetic_EQ: {
993 StringRef Val = A->getValue();
994 if (Val == "full")
996 else if (Val == "improved")
998 else if (Val == "basic")
1000 else {
1001 D.Diag(diag::err_drv_unsupported_option_argument)
1002 << A->getSpelling() << Val;
1003 break;
1004 }
1005
1006 setComplexRange(D, Args.MakeArgString(A->getSpelling() + Val), NewRange,
1007 LastComplexRangeOption, Range);
1008 break;
1009 }
1010 case options::OPT_fhonor_infinities:
1011 HonorINFs = true;
1012 break;
1013 case options::OPT_fno_honor_infinities:
1014 HonorINFs = false;
1015 break;
1016 case options::OPT_fhonor_nans:
1017 HonorNaNs = true;
1018 break;
1019 case options::OPT_fno_honor_nans:
1020 HonorNaNs = false;
1021 break;
1022 case options::OPT_fapprox_func:
1023 ApproxFunc = true;
1024 break;
1025 case options::OPT_fno_approx_func:
1026 ApproxFunc = false;
1027 break;
1028 case options::OPT_fsigned_zeros:
1029 SignedZeros = true;
1030 break;
1031 case options::OPT_fno_signed_zeros:
1032 SignedZeros = false;
1033 break;
1034 case options::OPT_fassociative_math:
1035 AssociativeMath = true;
1036 break;
1037 case options::OPT_fno_associative_math:
1038 AssociativeMath = false;
1039 break;
1040 case options::OPT_freciprocal_math:
1041 ReciprocalMath = true;
1042 break;
1043 case options::OPT_fno_reciprocal_math:
1044 ReciprocalMath = false;
1045 break;
1046 case options::OPT_ffp_contract: {
1047 StringRef Val = A->getValue();
1048 if (Val == "fast" || Val == "off") {
1049 if (Val != FPContract && LastFpContractOverrideOption != "") {
1050 D.Diag(clang::diag::warn_drv_overriding_option)
1051 << LastFpContractOverrideOption
1052 << Args.MakeArgString("-ffp-contract=" + Val);
1053 }
1054 FPContract = Val;
1055 LastSeenFfpContractOption = Val;
1056 } else if (Val == "on") {
1057 // Warn instead of error because users might have makefiles written for
1058 // gfortran (which accepts -ffp-contract=on)
1059 D.Diag(diag::warn_drv_unsupported_option_for_flang)
1060 << Val << A->getOption().getName() << "off";
1061 FPContract = "off";
1062 LastSeenFfpContractOption = "off";
1063 } else {
1064 // Clang's "fast-honor-pragmas" option is not supported because it is
1065 // non-standard
1066 D.Diag(diag::err_drv_unsupported_option_argument)
1067 << A->getSpelling() << Val;
1068 }
1069 LastFpContractOverrideOption = "";
1070 break;
1071 }
1072 case options::OPT_Ofast:
1073 [[fallthrough]];
1074 case options::OPT_ffast_math:
1075 HonorINFs = false;
1076 HonorNaNs = false;
1077 AssociativeMath = true;
1078 ReciprocalMath = true;
1079 ApproxFunc = true;
1080 SignedZeros = false;
1081 FPContract = "fast";
1082 if (A->getOption().getID() == options::OPT_Ofast)
1083 LastFpContractOverrideOption = "-Ofast";
1084 else
1085 LastFpContractOverrideOption = "-ffast-math";
1086 setComplexRange(D, A->getSpelling(),
1088 LastComplexRangeOption, Range);
1089 break;
1090 case options::OPT_fno_fast_math:
1091 HonorINFs = true;
1092 HonorNaNs = true;
1093 AssociativeMath = false;
1094 ReciprocalMath = false;
1095 ApproxFunc = false;
1096 SignedZeros = true;
1097 // -fno-fast-math should undo -ffast-math so I return FPContract to the
1098 // default. If -ffp-contract= was explicitly specified, restore the
1099 // user-requested value from LastSeenFfpContractOption so that
1100 // -ffp-contract=off -fno-fast-math --> -ffp-contract=off
1101 if (LastSeenFfpContractOption != "")
1102 FPContract = LastSeenFfpContractOption;
1103 else
1104 FPContract = "";
1105 setComplexRange(D, A->getSpelling(),
1107 LastComplexRangeOption, Range);
1108 LastFpContractOverrideOption = "";
1109 break;
1110 }
1111
1112 // If we handled this option claim it
1113 A->claim();
1114 }
1115
1116 StringRef Recip = parseMRecipOption(D.getDiags(), Args);
1117 if (!Recip.empty())
1118 CmdArgs.push_back(Args.MakeArgString("-mrecip=" + Recip));
1119
1121 std::string ComplexRangeStr = renderComplexRangeOption(Range);
1122 CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
1123 CmdArgs.push_back(Args.MakeArgString("-fcomplex-arithmetic=" +
1124 complexRangeKindToStr(Range)));
1125 }
1126
1127 if (llvm::opt::Arg *A =
1128 Args.getLastArg(clang::options::OPT_ffast_real_mod,
1129 clang::options::OPT_fno_fast_real_mod)) {
1130 if (A->getOption().matches(clang::options::OPT_ffast_real_mod))
1131 CmdArgs.push_back("-ffast-real-mod");
1132 else if (A->getOption().matches(clang::options::OPT_fno_fast_real_mod))
1133 CmdArgs.push_back("-fno-fast-real-mod");
1134 }
1135
1136 if (!HonorINFs && !HonorNaNs && AssociativeMath && ReciprocalMath &&
1137 ApproxFunc && !SignedZeros &&
1138 (FPContract == "fast" || FPContract.empty())) {
1139 CmdArgs.push_back("-ffast-math");
1140 return;
1141 }
1142
1143 if (!FPContract.empty())
1144 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
1145
1146 if (!HonorINFs)
1147 CmdArgs.push_back("-menable-no-infs");
1148
1149 if (!HonorNaNs)
1150 CmdArgs.push_back("-menable-no-nans");
1151
1152 if (ApproxFunc)
1153 CmdArgs.push_back("-fapprox-func");
1154
1155 if (!SignedZeros)
1156 CmdArgs.push_back("-fno-signed-zeros");
1157
1158 if (AssociativeMath && !SignedZeros)
1159 CmdArgs.push_back("-mreassociate");
1160
1161 if (ReciprocalMath)
1162 CmdArgs.push_back("-freciprocal-math");
1163}
1164
1165// Add options related to IEEE Floating point modes
1166//
1167// Initial halting mode:
1168// Validate -ffpe-trap= and forward it to -fc1. This is handled separately from
1169// addFloatingPointOptions() on purpose: -ffpe-trap= is not part of the
1170// fast-math option set, so it must not be skipped by that function's
1171// -ffast-math fast path. The value check and the target-support warnings depend
1172// only on the option value and the target triple (no frontend-only state), so
1173// they are done here in the driver rather than deferred to -fc1; -fc1 only
1174// translates the list into its LangOptions bitmask.
1175//
1176// TODO:
1177// Rounding modes
1178// Underflow mode
1179static void addIEEEFPModesOptions(const Driver &D, const ArgList &Args,
1180 ArgStringList &CmdArgs,
1181 const llvm::Triple &Triple) {
1182 const Arg *A = Args.getLastArg(options::OPT_ffpe_trap_EQ);
1183 if (!A)
1184 return;
1185
1186 // The value is a comma-separated list of exception mnemonics. "none" and an
1187 // empty list request no halting and reset any earlier request in the list;
1188 // any other unrecognized mnemonic is an error.
1190 StringRef(A->getValue())
1191 .split(Traps, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
1192
1193 bool RequestsTrap = false;
1194 bool RequestsDenormal = false;
1195 for (StringRef Trap : Traps) {
1196 if (Trap == "none") {
1197 RequestsTrap = false;
1198 RequestsDenormal = false;
1199 continue;
1200 }
1201 bool IsKnown = llvm::StringSwitch<bool>(Trap)
1202 .Cases({"invalid", "zero", "overflow", "underflow",
1203 "inexact", "denormal"},
1204 true)
1205 .Default(false);
1206 if (!IsKnown) {
1207 D.Diag(diag::err_drv_unsupported_option_argument)
1208 << A->getSpelling() << Trap;
1209 return;
1210 }
1211 RequestsTrap = true;
1212 RequestsDenormal |= (Trap == "denormal");
1213 }
1214
1215 // Run-time halting is implemented in flang-rt only where the target's
1216 // floating-point environment can trap: it relies on glibc's feenableexcept
1217 // (in practice Linux), and "denormal" additionally requires an x86 target.
1218 // Warn (conservatively) when the target cannot honor the request; the runtime
1219 // otherwise ignores it. The denormal-specific warning names just
1220 // "-ffpe-trap=denormal" to point at the unsupported mnemonic.
1221 if (RequestsTrap && !Triple.isX86() && !Triple.isOSLinux())
1222 D.Diag(diag::warn_drv_unsupported_option_for_target)
1223 << A->getAsString(Args) << Triple.str();
1224 else if (RequestsDenormal && !Triple.isX86())
1225 D.Diag(diag::warn_drv_unsupported_option_for_target)
1226 << "-ffpe-trap=denormal" << Triple.str();
1227
1228 A->render(Args, CmdArgs);
1229}
1230
1231static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1232 const InputInfo &Input) {
1233 StringRef Format = "yaml";
1234 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1235 Format = A->getValue();
1236
1237 CmdArgs.push_back("-opt-record-file");
1238
1239 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1240 if (A) {
1241 CmdArgs.push_back(A->getValue());
1242 } else {
1244
1245 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1246 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1247 F = FinalOutput->getValue();
1248 }
1249
1250 if (F.empty()) {
1251 // Use the input filename.
1252 F = llvm::sys::path::stem(Input.getBaseInput());
1253 }
1254
1255 SmallString<32> Extension;
1256 Extension += "opt.";
1257 Extension += Format;
1258
1259 llvm::sys::path::replace_extension(F, Extension);
1260 CmdArgs.push_back(Args.MakeArgString(F));
1261 }
1262
1263 if (const Arg *A =
1264 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1265 CmdArgs.push_back("-opt-record-passes");
1266 CmdArgs.push_back(A->getValue());
1267 }
1268
1269 if (!Format.empty()) {
1270 CmdArgs.push_back("-opt-record-format");
1271 CmdArgs.push_back(Format.data());
1272 }
1273}
1274
1275static void addPGOAndCoverageFlags(const ToolChain &TC, const JobAction &JA,
1276 const ArgList &Args,
1277 ArgStringList &CmdArgs) {
1278 const Driver &D = TC.getDriver();
1279 const llvm::Triple &T = TC.getTriple();
1280
1281 bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
1282 bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
1283
1284 if (T.isOSAIX()) {
1285 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
1286 D.Diag(diag::err_drv_unsupported_opt_for_target)
1287 << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
1288 }
1289
1290 if (!(IsCudaDevice || IsHIPDevice)) {
1291 // recognise options: -fprofile-sample-use= and -fno-profile-sample-use=
1292 if (Arg *A = getLastProfileSampleUseArg(Args)) {
1293 if (Arg *PGOArg = Args.getLastArg(options::OPT_fprofile_generate,
1294 options::OPT_fprofile_generate_EQ)) {
1295 D.Diag(diag::err_drv_argument_not_allowed_with)
1296 << PGOArg->getAsString(Args) << A->getAsString(Args);
1297 }
1298
1299 StringRef fname = A->getValue();
1300 if (!llvm::sys::fs::exists(fname))
1301 D.Diag(diag::err_drv_no_such_file) << fname;
1302 else
1303 A->render(Args, CmdArgs);
1304 }
1305 }
1306
1307 //-fpseudo-probe-for-profiling
1308 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
1309 options::OPT_fno_pseudo_probe_for_profiling, false))
1310 CmdArgs.push_back("-fpseudo-probe-for-profiling");
1311
1312 // TODO: Consider reusing Clang's addPGOAndCoverageFlags() for
1313 // -fprofile-generate and other similar options handling instead of
1314 // duplicating driver logic here.
1315 if (Arg *PGOGenerateArg = Args.getLastArg(
1316 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
1317 options::OPT_fno_profile_generate)) {
1318 if (!PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
1319 PGOGenerateArg->render(Args, CmdArgs);
1320 }
1321
1322 addSplitMachineFunctionsArgs(TC.getDriver(), Args, CmdArgs, TC.getTriple());
1323 Args.addAllArgs(CmdArgs, {options::OPT_fprofile_use_EQ});
1324}
1325
1327 const InputInfo &Output, const InputInfoList &Inputs,
1328 const ArgList &Args, const char *LinkingOutput) const {
1329 const auto &TC = getToolChain();
1330 const llvm::Triple &Triple = TC.getEffectiveTriple();
1331 const std::string &TripleStr = Triple.getTriple();
1332
1333 const Driver &D = TC.getDriver();
1334 ArgStringList CmdArgs;
1335
1336 // Invoke ourselves in -fc1 mode.
1337 CmdArgs.push_back("-fc1");
1338
1339 // Add the "effective" target triple.
1340 CmdArgs.push_back("-triple");
1341 CmdArgs.push_back(Args.MakeArgString(TripleStr));
1342
1343 if (isa<PreprocessJobAction>(JA)) {
1344 if (Output.getType() == types::TY_Dependencies) {
1345 CmdArgs.push_back("-fsyntax-only");
1346 } else {
1347 CmdArgs.push_back("-E");
1348 if (Args.getLastArg(options::OPT_dM))
1349 CmdArgs.push_back("-dM");
1350 }
1351 } else if (isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) {
1352 if (JA.getType() == types::TY_Nothing) {
1353 CmdArgs.push_back("-fsyntax-only");
1354 } else if (JA.getType() == types::TY_AST) {
1355 CmdArgs.push_back("-emit-ast");
1356 } else if (JA.getType() == types::TY_LLVM_IR ||
1357 JA.getType() == types::TY_LTO_IR) {
1358 CmdArgs.push_back("-emit-llvm");
1359 } else if (JA.getType() == types::TY_LLVM_BC ||
1360 JA.getType() == types::TY_LTO_BC) {
1361 CmdArgs.push_back("-emit-llvm-bc");
1362 } else if (JA.getType() == types::TY_PP_Asm) {
1363 CmdArgs.push_back("-S");
1364 } else {
1365 assert(false && "Unexpected output type!");
1366 }
1367 } else if (isa<AssembleJobAction>(JA)) {
1368 CmdArgs.push_back("-emit-obj");
1369 } else if (isa<PrecompileJobAction>(JA)) {
1370 // The precompile job action is only needed for options such as -mcpu=help.
1371 // Those will already have been handled by the fc1 driver.
1372 } else {
1373 assert(false && "Unexpected action class for Flang tool.");
1374 }
1375
1376 // We support some options that are invalid for Fortran and have no effect.
1377 // These are solely for compatibility with other compilers. Emit a warning if
1378 // any such options are provided, then proceed normally.
1379 for (options::ID Opt : {options::OPT_fbuiltin, options::OPT_fno_builtin})
1380 if (const Arg *A = Args.getLastArg(Opt))
1381 D.Diag(diag::warn_drv_invalid_argument_for_flang) << A->getSpelling();
1382
1383 // Warn about options that are ignored by flang. These are options that are
1384 // accepted by gfortran, but have no equivalent in flang.
1385 for (const Arg *A :
1386 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
1387 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
1388 A->claim();
1389 }
1390
1391 // -fkeep-inline-functions/-fno-keep-inline-functions are real Clang options
1392 // but are not supported by Flang; warn and ignore them.
1393 for (options::ID Opt : {options::OPT_fkeep_inline_functions,
1394 options::OPT_fno_keep_inline_functions}) {
1395 if (const Arg *A = Args.getLastArg(Opt)) {
1396 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
1397 A->claim();
1398 }
1399 }
1400
1401 // Reject AIX-specific link option on other targets.
1402 if (!Triple.isOSAIX()) {
1403 if (const Arg *A = Args.getLastArg(options::OPT_b))
1404 D.Diag(diag::err_drv_unsupported_opt_for_target)
1405 << A->getSpelling() << Triple.str();
1406 }
1407
1408 const InputInfo &Input = Inputs[0];
1409 types::ID InputType = Input.getType();
1410
1411 // Add preprocessing options like -I, -D, etc. if we are using the
1412 // preprocessor (i.e. skip when dealing with e.g. binary files).
1414 addPreprocessingOptions(Args, CmdArgs);
1415
1416 addFortranDialectOptions(Args, CmdArgs);
1417
1418 // 'flang -E' always produces output that is suitable for use as fixed form
1419 // Fortran. However it is only valid free form source if the original is also
1420 // free form. Ensure this logic does not incorrectly assume fixed-form for
1421 // cases where it shouldn't, such as `flang -x f95 foo.f90`.
1422 bool isAtemporaryPreprocessedFile =
1423 Input.isFilename() &&
1424 llvm::sys::path::extension(Input.getFilename())
1425 .ends_with(types::getTypeTempSuffix(InputType, /*CLStyle=*/false));
1426 if (InputType == types::TY_PP_Fortran && isAtemporaryPreprocessedFile &&
1427 !Args.getLastArg(options::OPT_ffixed_form, options::OPT_ffree_form))
1428 CmdArgs.push_back("-ffixed-form");
1429
1430 handleColorDiagnosticsArgs(D, Args, CmdArgs);
1431
1432 addLTOOptions(Args, CmdArgs);
1433
1434 // -fPIC and related options.
1435 addPicOptions(Args, CmdArgs);
1436
1437 // Floating point related options
1438 addFloatingPointOptions(D, Args, CmdArgs);
1439
1440 // Initial floating-point exception halting mode. Handled separately so it is
1441 // not skipped by the -ffast-math fast path in addFloatingPointOptions().
1442 addIEEEFPModesOptions(D, Args, CmdArgs, Triple);
1443
1444 // Integer MOD/MODULO zero-divisor check. Forwarded here with -ffpe-trap=
1445 // rather than in addFloatingPointOptions() so -ffast-math does not drop it.
1446 Args.AddLastArg(CmdArgs, options::OPT_fcheck_integer_mod_zero_divisor);
1447
1448 // Add target args, features, etc.
1449 addTargetOptions(Args, CmdArgs, JA.getOffloadingArch(),
1451
1452 if (!TC.useIntegratedAs())
1453 CmdArgs.push_back("-no-integrated-as");
1454
1455 llvm::Reloc::Model RelocationModel =
1456 std::get<0>(ParsePICArgs(getToolChain(), Args));
1457 // Add MCModel information
1458 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
1459
1460 // Add Codegen options
1461 addCodegenOptions(Args, CmdArgs);
1462
1463 // Add R Group options
1464 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
1465
1466 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
1467 if (willEmitRemarks(Args))
1468 renderRemarksOptions(Args, CmdArgs, Input);
1469
1470 // Add debug compile options
1471 addDebugOptions(Args, JA, Output, Input, CmdArgs);
1472
1473 // Disable all warnings
1474 // TODO: Handle interactions between -w, -pedantic, -Wall, -WOption
1475 Args.AddLastArg(CmdArgs, options::OPT_w);
1476
1477 addPGOAndCoverageFlags(TC, JA, Args, CmdArgs);
1478
1479 // Forward flags for OpenMP. We don't do this if the current action is an
1480 // device offloading action other than OpenMP.
1481 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
1482 options::OPT_fno_openmp, false) &&
1485 switch (D.getOpenMPRuntime(Args)) {
1486 case Driver::OMPRT_OMP:
1488 // Clang can generate useful OpenMP code for these two runtime libraries.
1489 CmdArgs.push_back("-fopenmp");
1490 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
1491
1492 if (Args.hasArg(options::OPT_fopenmp_force_usm))
1493 CmdArgs.push_back("-fopenmp-force-usm");
1494 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
1495 options::OPT_fno_openmp_simd);
1496
1497 // FIXME: Clang supports a whole bunch more flags here.
1498 break;
1499 default:
1500 // By default, if Clang doesn't know how to generate useful OpenMP code
1501 // for a specific runtime library, we just don't pass the '-fopenmp' flag
1502 // down to the actual compilation.
1503 // FIXME: It would be better to have a mode which *only* omits IR
1504 // generation based on the OpenMP support so that we get consistent
1505 // semantic analysis, etc.
1506 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
1507 D.Diag(diag::warn_drv_unsupported_openmp_library)
1508 << A->getSpelling() << A->getValue();
1509 break;
1510 }
1511 } else {
1512 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
1513 options::OPT_fno_openmp_simd);
1514 }
1515
1516 // Pass the path to compiler resource files.
1517 CmdArgs.push_back("-resource-dir");
1518 CmdArgs.push_back(D.ResourceDir.c_str());
1519
1520 // Default intrinsic module dirs must be added after any user-provided dirs in
1521 // -fintrinsic-modules-path since the default dirs have lower precedence than
1522 // user-provided dirs
1523 if (std::optional<std::string> IntrModPath =
1525 CmdArgs.push_back("-fintrinsic-modules-path");
1526 CmdArgs.push_back(Args.MakeArgString(*IntrModPath));
1527 }
1528
1529 // Ideally, every target triple has its own set of builtin modules since they
1530 // are compiled with platform-dependent conditionals such as `#if __x86_64__`.
1531 // However, getting the builtin modules for offload targets requires building
1532 // the flang-rt and openmp for those targets as well:
1533 // -DLLVM_RUNTIME_TARGETS=default;amdgcn-amd-amdhsa;nvptx64-nvidia-cuda.
1534 // To reduce friction when build systems have not yet been updated, we also
1535 // add the host's builtin module to the search path (with lower priority), in
1536 // case a module file has not been found for the offload targets itself.
1537 // FIXME: This workaround may mix module files targeting different triples and
1538 // should eventually be removed.
1539 auto &&HostTCs =
1540 C.getOffloadToolChains<clang::driver::OffloadAction ::OFK_Host>();
1541 for (auto [OKind, HostTC] : llvm::make_range(HostTCs.first, HostTCs.second)) {
1542 if (HostTC == &TC)
1543 continue;
1544
1545 if (std::optional<std::string> IntrModPath =
1546 HostTC->getDefaultIntrinsicModuleDir()) {
1547 CmdArgs.push_back("-fintrinsic-modules-path");
1548 CmdArgs.push_back(Args.MakeArgString(*IntrModPath));
1549 }
1550 }
1551
1552 // Offloading related options
1553 addOffloadOptions(C, Inputs, JA, Args, CmdArgs);
1554
1555 // Forward -Xflang arguments to -fc1
1556 Args.AddAllArgValues(CmdArgs, options::OPT_Xflang);
1557
1559 getFramePointerKind(Args, Triple);
1560
1561 const char *FPKeepKindStr = nullptr;
1562 switch (FPKeepKind) {
1564 FPKeepKindStr = "-mframe-pointer=none";
1565 break;
1567 FPKeepKindStr = "-mframe-pointer=reserved";
1568 break;
1570 FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";
1571 break;
1573 FPKeepKindStr = "-mframe-pointer=non-leaf";
1574 break;
1576 FPKeepKindStr = "-mframe-pointer=all";
1577 break;
1578 }
1579 assert(FPKeepKindStr && "unknown FramePointerKind");
1580 CmdArgs.push_back(FPKeepKindStr);
1581
1582 // Forward -mllvm options to the LLVM option parser. In practice, this means
1583 // forwarding to `-fc1` as that's where the LLVM parser is run.
1584 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
1585 A->claim();
1586 A->render(Args, CmdArgs);
1587 }
1588
1589 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
1590 A->claim();
1591 A->render(Args, CmdArgs);
1592 }
1593
1594 // Remove any unsupported gfortran diagnostic options
1595 for (const Arg *A : Args.filtered(options::OPT_flang_ignored_w_Group)) {
1596 A->claim();
1597 D.Diag(diag::warn_drv_unsupported_diag_option_for_flang)
1598 << A->getOption().getName();
1599 }
1600
1601 // Optimization level for CodeGen.
1602 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
1603 if (A->getOption().matches(options::OPT_O4)) {
1604 CmdArgs.push_back("-O3");
1605 D.Diag(diag::warn_O4_is_O3);
1606 } else if (A->getOption().matches(options::OPT_Ofast)) {
1607 CmdArgs.push_back("-O3");
1608 D.Diag(diag::warn_drv_deprecated_arg_ofast_for_flang);
1609 } else {
1610 A->render(Args, CmdArgs);
1611 }
1612 }
1613
1614 renderGlobalISelOptions(D, Args, CmdArgs, Triple);
1615 renderCommonIntegerOverflowOptions(Args, CmdArgs, false);
1616
1617 assert((Output.isFilename() || Output.isNothing()) && "Invalid output.");
1618 if (Output.isFilename()) {
1619 CmdArgs.push_back("-o");
1620 CmdArgs.push_back(Output.getFilename());
1621 }
1622
1623 if (Args.getLastArg(options::OPT_save_temps_EQ))
1624 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
1625
1626 renderDependencyGenerationOptions(C, JA, Args, Output, Inputs, CmdArgs);
1627
1628 addDashXForInput(Args, Input, CmdArgs);
1629
1630 bool FRecordCmdLine = false;
1631 bool GRecordCmdLine = false;
1632 bool DXRecordCmdLine = false;
1633 if (shouldRecordCommandLine(TC, Args, FRecordCmdLine, GRecordCmdLine,
1634 DXRecordCmdLine)) {
1635 const char *CmdLine = renderEscapedCommandLine(TC, Args);
1636 if (FRecordCmdLine) {
1637 CmdArgs.push_back("-record-command-line");
1638 CmdArgs.push_back(CmdLine);
1639 }
1640 if (TC.UseDwarfDebugFlags() || GRecordCmdLine) {
1641 CmdArgs.push_back("-dwarf-debug-flags");
1642 CmdArgs.push_back(CmdLine);
1643 }
1644 }
1645
1646 // The input could be Ty_Nothing when "querying" options such as -mcpu=help
1647 // are used.
1648 ArrayRef<InputInfo> FrontendInputs = Input;
1649 if (Input.isNothing())
1650 FrontendInputs = {};
1651
1652 for (const InputInfo &Input : FrontendInputs) {
1653 if (Input.isFilename())
1654 CmdArgs.push_back(Input.getFilename());
1655 else
1656 Input.getInputArg().renderAsInput(Args, CmdArgs);
1657 }
1658
1659 // Handle "clang --driver-mode=flang" case
1660 bool isClangDriverWithFlangMode = false;
1661 std::string DriverName = D.Name;
1662 if (const char *PA = D.getPrependArg())
1663 DriverName = PA;
1664 if (DriverName.find("clang") != std::string::npos && D.IsFlangMode())
1665 isClangDriverWithFlangMode = true;
1666
1667 const char *Exec = isClangDriverWithFlangMode
1668 ? Args.MakeArgString(D.GetProgramPath("flang", TC))
1670 C.addCommand(std::make_unique<Command>(JA, *this,
1672 Exec, CmdArgs, Inputs, Output));
1673}
1674
1675Flang::Flang(const ToolChain &TC) : Tool("flang", "flang frontend", TC) {}
1676
#define V(N, I)
static void addDashXForInput(const ArgList &Args, const InputInfo &Input, ArgStringList &CmdArgs)
Add -x lang to CmdArgs for Input.
Definition Clang.cpp:338
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input, const InputInfo &Output, const JobAction &JA)
Definition Clang.cpp:1278
static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C, const JobAction &JA, const InputInfo &Output, const ArgList &Args, SanitizerArgs &SanArgs, ArgStringList &CmdArgs)
Definition Clang.cpp:372
clang::CodeGenOptions::FramePointerKind getFramePointerKind(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
static DwarfFissionKind getSplitDWARFKind(const ArgList &Args, const JobAction &JA, const ToolChain &TC, llvm::codegenoptions::DebugInfoKind DebugInfoKind)
Return the kind of split DWARF that JA generates, or None if it generates none.
Definition Flang.cpp:230
static void processVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Flang.cpp:646
static void addVSDefines(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition Flang.cpp:622
static void addDashXForInput(const ArgList &Args, const InputInfo &Input, ArgStringList &CmdArgs)
Add -x lang to CmdArgs for Input.
Definition Flang.cpp:32
static bool shouldLoopVersion(const ArgList &Args, options::ID PosFlag, options::ID NegFlag)
@C shouldLoopVersion
Definition Flang.cpp:193
static void addIEEEFPModesOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple)
Definition Flang.cpp:1179
static void addFloatingPointOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition Flang.cpp:969
static void renderDependencyGenerationOptions(Compilation &C, const JobAction &JA, const ArgList &Args, const InputInfo &Output, const InputInfoList &Inputs, ArgStringList &CmdArgs)
Definition Flang.cpp:53
TokenType getType() const
Returns the token's type, e.g.
llvm::MachO::Target Target
Definition MachO.h:51
ComplexRangeKind
Controls the various implementations for complex multiplication and.
@ CX_Full
Implementation of complex division and multiplication using a call to runtime library functions(gener...
@ CX_Basic
Implementation of complex division and multiplication using algebraic formulas at source precision.
@ CX_None
No range rule is enabled.
@ CX_Improved
Implementation of complex division offering an improved handling for overflow in intermediate calcula...
types::ID getType() const
Definition Action.h:153
BoundArch getOffloadingArch() const
Definition Action.h:216
OffloadKind getOffloadingDeviceKind() const
Definition Action.h:215
bool isHostOffloading(unsigned int OKind) const
Check if this action have any offload kinds.
Definition Action.h:223
bool isDeviceOffloading(OffloadKind OKind) const
Definition Action.h:226
Compilation - A set of tasks to perform for a single driver invocation.
Definition Compilation.h:46
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition Driver.h:93
DiagnosticsEngine & getDiags() const
Definition Driver.h:408
const char * getPrependArg() const
Definition Driver.h:419
OpenMPRuntimeKind getOpenMPRuntime(const llvm::opt::ArgList &Args) const
Compute the desired OpenMP runtime from the flags provided.
Definition Driver.cpp:918
DiagnosticBuilder Diag(unsigned DiagID) const
Definition Driver.h:157
std::string Name
The name the driver was invoked as.
Definition Driver.h:164
const char * getDriverProgramPath() const
Get the path to the main driver executable.
Definition Driver.h:430
std::string GetProgramPath(StringRef Name, const ToolChain &TC) const
GetProgramPath - Lookup Name in the list of program search paths.
Definition Driver.cpp:6021
std::string ResourceDir
The path to the compiler resource directory.
Definition Driver.h:177
@ OMPRT_IOMP5
The legacy name for the LLVM OpenMP runtime from when it was the Intel OpenMP runtime.
Definition Driver.h:153
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition Driver.h:143
bool IsFlangMode() const
Whether the driver should invoke flang for fortran inputs.
Definition Driver.h:233
InputInfo - Wrapper for information about an input source.
Definition InputInfo.h:22
const char * getBaseInput() const
Definition InputInfo.h:78
const llvm::opt::Arg & getInputArg() const
Definition InputInfo.h:87
const char * getFilename() const
Definition InputInfo.h:83
bool isNothing() const
Definition InputInfo.h:74
bool isFilename() const
Definition InputInfo.h:75
types::ID getType() const
Definition InputInfo.h:77
ToolChain - Access to tools for a single platform.
Definition ToolChain.h:92
virtual bool useIntegratedAs() const
Check if the toolchain should use the integrated assembler.
llvm::Triple::ArchType getArch() const
Definition ToolChain.h:298
const Driver & getDriver() const
Definition ToolChain.h:282
virtual LTOKind getLTOMode(const llvm::opt::ArgList &Args, Action::OffloadKind Kind=Action::OFK_None) const
Resolve the requested LTO mode for this toolchain.
virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, BoundArch BA, Action::OffloadKind DeviceOffloadKind) const
Add options that need to be passed to cc1 for this target.
const llvm::Triple & getEffectiveTriple() const
Get the toolchain's effective clang triple.
Definition ToolChain.h:310
const llvm::Triple & getTriple() const
Definition ToolChain.h:284
virtual bool UseDwarfDebugFlags() const
UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf compile unit information.
Definition ToolChain.h:653
virtual VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const
On Windows, returns the MSVC compatibility version.
std::string getCompilerRTBasename(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
std::optional< std::string > getDefaultIntrinsicModuleDir() const
Returns the target-specific path for Flang's intrinsic modules in the resource directory if it exists...
const ToolChain & getToolChain() const
Definition Tool.h:51
Tool(const char *Name, const char *ShortName, const ToolChain &TC)
Definition Tool.cpp:13
Flang(const ToolChain &TC)
Definition Flang.cpp:1675
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition Flang.cpp:1326
std::string getRISCVArch(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition RISCV.cpp:305
StringRef getRISCVABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
void addMCModel(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple, const llvm::Reloc::Model &RelocationModel, llvm::opt::ArgStringList &CmdArgs)
llvm::opt::Arg * getLastProfileSampleUseArg(const llvm::opt::ArgList &Args)
void handleVectorizeSLPArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Enable -fslp-vectorize based on the optimization level selected.
const char * SplitDebugName(const JobAction &JA, const llvm::opt::ArgList &Args, const InputInfo &Input, const InputInfo &Output)
void addOutlineAtomicsArgs(const Driver &D, const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
void getTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool ForAS, bool IsAux=false)
void renderDebugInfoCompressionArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const Driver &D, const ToolChain &TC)
std::string complexRangeKindToStr(LangOptions::ComplexRangeKind Range)
void handleColorDiagnosticsArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Handle the -f{no}-color-diagnostics and -f{no}-diagnostics-colors options.
std::string getCPUName(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &T, bool FromAs=false)
void setComplexRange(const Driver &D, StringRef NewOpt, LangOptions::ComplexRangeKind NewRange, StringRef &LastOpt, LangOptions::ComplexRangeKind &Range)
void addDebugInfoForProfilingArgs(const Driver &D, const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
void addDebugInfoKind(llvm::opt::ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind)
llvm::codegenoptions::DebugInfoKind debugLevelToInfoKind(const llvm::opt::Arg &A)
void renderGlobalISelOptions(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
std::string renderComplexRangeOption(LangOptions::ComplexRangeKind Range)
DwarfFissionKind getDebugFissionKind(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::Arg *&Arg)
void handleInterchangeLoopsArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Enable -floop-interchange based on the optimization level selected.
const char * renderEscapedCommandLine(const ToolChain &TC, const llvm::opt::ArgList &Args)
Join the args in the given ArgList, escape spaces and backslashes and return the joined string.
void renderCommonIntegerOverflowOptions(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool IsMSVCCompat)
void addSplitMachineFunctionsArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
bool checkDebugInfoOption(const llvm::opt::Arg *A, const llvm::opt::ArgList &Args, const Driver &D, const ToolChain &TC)
std::tuple< llvm::Reloc::Model, unsigned, bool > ParsePICArgs(const ToolChain &ToolChain, const llvm::opt::ArgList &Args)
unsigned getDwarfVersion(const ToolChain &TC, const llvm::opt::ArgList &Args)
bool shouldRecordCommandLine(const ToolChain &TC, const llvm::opt::ArgList &Args, bool &FRecordCommandLine, bool &GRecordCommandLine, bool &DXRecordCommandLine)
Check if the command line should be recorded in the object file.
const llvm::opt::Arg * getDwarfNArg(const llvm::opt::ArgList &Args)
void addSeparateSectionFlags(const llvm::Triple &Triple, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Append -ffunction-sections / -fdata-sections to CmdArgs when the corresponding flags are enabled (exp...
void handleVectorizeLoopsArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Enable -fvectorize based on the optimization level selected.
const char * RelocationModelName(llvm::Reloc::Model Model)
void addOpenMPHostOffloadingArgs(const Compilation &C, const JobAction &JA, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Adds offloading options for OpenMP host compilation to CmdArgs.
ID getPreprocessedType(ID Id)
getPreprocessedType - Get the ID of the type for this input when it has been preprocessed,...
Definition Types.cpp:53
const char * getTypeName(ID Id)
getTypeName - Return the name of the type for Id.
Definition Types.cpp:49
const char * getTypeTempSuffix(ID Id, bool CLStyle=false)
getTypeTempSuffix - Return the suffix to use when creating a temp file of this type,...
Definition Types.cpp:81
LTOKind
Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options.
Definition Driver.h:57
SmallVector< InputInfo, 4 > InputInfoList
Definition Driver.h:49
bool willEmitRemarks(const llvm::opt::ArgList &Args)
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
void quoteMakeTarget(StringRef Target, SmallVectorImpl< char > &Res)
Quote target names for inclusion in GNU Make dependency files.
@ Default
Set to the current date and time.
const FunctionProtoType * T
StringRef parseMRecipOption(clang::DiagnosticsEngine &Diags, const llvm::opt::ArgList &Args)
bool(*)(llvm::ArrayRef< const char * >, llvm::raw_ostream &, llvm::raw_ostream &, bool, bool) Driver
Definition Wasm.cpp:39
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
static constexpr ResponseFileSupport AtFileUTF8()
Definition Job.h:86