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