clang 19.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 "CommonArgs.h"
12
15#include "llvm/Frontend/Debug/Options.h"
16#include "llvm/Support/FileSystem.h"
17#include "llvm/Support/Path.h"
18#include "llvm/TargetParser/RISCVISAInfo.h"
19#include "llvm/TargetParser/RISCVTargetParser.h"
20
21#include <cassert>
22
23using namespace clang::driver;
24using namespace clang::driver::tools;
25using namespace clang;
26using namespace llvm::opt;
27
28/// Add -x lang to \p CmdArgs for \p Input.
29static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
30 ArgStringList &CmdArgs) {
31 CmdArgs.push_back("-x");
32 // Map the driver type to the frontend type.
33 CmdArgs.push_back(types::getTypeName(Input.getType()));
34}
35
36void Flang::addFortranDialectOptions(const ArgList &Args,
37 ArgStringList &CmdArgs) const {
38 Args.addAllArgs(CmdArgs, {options::OPT_ffixed_form,
39 options::OPT_ffree_form,
40 options::OPT_ffixed_line_length_EQ,
41 options::OPT_fopenacc,
42 options::OPT_finput_charset_EQ,
43 options::OPT_fimplicit_none,
44 options::OPT_fno_implicit_none,
45 options::OPT_fbackslash,
46 options::OPT_fno_backslash,
47 options::OPT_flogical_abbreviations,
48 options::OPT_fno_logical_abbreviations,
49 options::OPT_fxor_operator,
50 options::OPT_fno_xor_operator,
51 options::OPT_falternative_parameter_statement,
52 options::OPT_fdefault_real_8,
53 options::OPT_fdefault_integer_8,
54 options::OPT_fdefault_double_8,
55 options::OPT_flarge_sizes,
56 options::OPT_fno_automatic,
57 options::OPT_fhermetic_module_files});
58}
59
60void Flang::addPreprocessingOptions(const ArgList &Args,
61 ArgStringList &CmdArgs) const {
62 Args.addAllArgs(CmdArgs,
63 {options::OPT_P, options::OPT_D, options::OPT_U,
64 options::OPT_I, options::OPT_cpp, options::OPT_nocpp});
65}
66
67/// @C shouldLoopVersion
68///
69/// Check if Loop Versioning should be enabled.
70/// We look for the last of one of the following:
71/// -Ofast, -O4, -O<number> and -f[no-]version-loops-for-stride.
72/// Loop versioning is disabled if the last option is
73/// -fno-version-loops-for-stride.
74/// Loop versioning is enabled if the last option is one of:
75/// -floop-versioning
76/// -Ofast
77/// -O4
78/// -O3
79/// For all other cases, loop versioning is is disabled.
80///
81/// The gfortran compiler automatically enables the option for -O3 or -Ofast.
82///
83/// @return true if loop-versioning should be enabled, otherwise false.
84static bool shouldLoopVersion(const ArgList &Args) {
85 const Arg *LoopVersioningArg = Args.getLastArg(
86 options::OPT_Ofast, options::OPT_O, options::OPT_O4,
87 options::OPT_floop_versioning, options::OPT_fno_loop_versioning);
88 if (!LoopVersioningArg)
89 return false;
90
91 if (LoopVersioningArg->getOption().matches(options::OPT_fno_loop_versioning))
92 return false;
93
94 if (LoopVersioningArg->getOption().matches(options::OPT_floop_versioning))
95 return true;
96
97 if (LoopVersioningArg->getOption().matches(options::OPT_Ofast) ||
98 LoopVersioningArg->getOption().matches(options::OPT_O4))
99 return true;
100
101 if (LoopVersioningArg->getOption().matches(options::OPT_O)) {
102 StringRef S(LoopVersioningArg->getValue());
103 unsigned OptLevel = 0;
104 // Note -Os or Oz woould "fail" here, so return false. Which is the
105 // desiered behavior.
106 if (S.getAsInteger(10, OptLevel))
107 return false;
108
109 return OptLevel > 2;
110 }
111
112 llvm_unreachable("We should not end up here");
113 return false;
114}
115
116void Flang::addOtherOptions(const ArgList &Args, ArgStringList &CmdArgs) const {
117 Args.addAllArgs(CmdArgs,
118 {options::OPT_module_dir, options::OPT_fdebug_module_writer,
119 options::OPT_fintrinsic_modules_path, options::OPT_pedantic,
120 options::OPT_std_EQ, options::OPT_W_Joined,
121 options::OPT_fconvert_EQ, options::OPT_fpass_plugin_EQ,
122 options::OPT_funderscoring, options::OPT_fno_underscoring});
123
124 llvm::codegenoptions::DebugInfoKind DebugInfoKind;
125 if (Args.hasArg(options::OPT_gN_Group)) {
126 Arg *gNArg = Args.getLastArg(options::OPT_gN_Group);
127 DebugInfoKind = debugLevelToInfoKind(*gNArg);
128 } else if (Args.hasArg(options::OPT_g_Flag)) {
129 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
130 } else {
131 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
132 }
133 addDebugInfoKind(CmdArgs, DebugInfoKind);
134}
135
136void Flang::addCodegenOptions(const ArgList &Args,
137 ArgStringList &CmdArgs) const {
138 Arg *stackArrays =
139 Args.getLastArg(options::OPT_Ofast, options::OPT_fstack_arrays,
140 options::OPT_fno_stack_arrays);
141 if (stackArrays &&
142 !stackArrays->getOption().matches(options::OPT_fno_stack_arrays))
143 CmdArgs.push_back("-fstack-arrays");
144
145 if (shouldLoopVersion(Args))
146 CmdArgs.push_back("-fversion-loops-for-stride");
147
148 Args.addAllArgs(CmdArgs, {options::OPT_flang_experimental_hlfir,
149 options::OPT_flang_deprecated_no_hlfir,
150 options::OPT_flang_experimental_integer_overflow,
151 options::OPT_fno_ppc_native_vec_elem_order,
152 options::OPT_fppc_native_vec_elem_order});
153}
154
155void Flang::addPicOptions(const ArgList &Args, ArgStringList &CmdArgs) const {
156 // ParsePICArgs parses -fPIC/-fPIE and their variants and returns a tuple of
157 // (RelocationModel, PICLevel, IsPIE).
158 llvm::Reloc::Model RelocationModel;
159 unsigned PICLevel;
160 bool IsPIE;
161 std::tie(RelocationModel, PICLevel, IsPIE) =
162 ParsePICArgs(getToolChain(), Args);
163
164 if (auto *RMName = RelocationModelName(RelocationModel)) {
165 CmdArgs.push_back("-mrelocation-model");
166 CmdArgs.push_back(RMName);
167 }
168 if (PICLevel > 0) {
169 CmdArgs.push_back("-pic-level");
170 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
171 if (IsPIE)
172 CmdArgs.push_back("-pic-is-pie");
173 }
174}
175
176void Flang::AddAArch64TargetArgs(const ArgList &Args,
177 ArgStringList &CmdArgs) const {
178 // Handle -msve_vector_bits=<bits>
179 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
180 StringRef Val = A->getValue();
181 const Driver &D = getToolChain().getDriver();
182 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
183 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
184 Val == "1024+" || Val == "2048+") {
185 unsigned Bits = 0;
186 if (!Val.consume_back("+")) {
187 [[maybe_unused]] bool Invalid = Val.getAsInteger(10, Bits);
188 assert(!Invalid && "Failed to parse value");
189 CmdArgs.push_back(
190 Args.MakeArgString("-mvscale-max=" + llvm::Twine(Bits / 128)));
191 }
192
193 [[maybe_unused]] bool Invalid = Val.getAsInteger(10, Bits);
194 assert(!Invalid && "Failed to parse value");
195 CmdArgs.push_back(
196 Args.MakeArgString("-mvscale-min=" + llvm::Twine(Bits / 128)));
197 // Silently drop requests for vector-length agnostic code as it's implied.
198 } else if (Val != "scalable")
199 // Handle the unsupported values passed to msve-vector-bits.
200 D.Diag(diag::err_drv_unsupported_option_argument)
201 << A->getSpelling() << Val;
202 }
203}
204
205void Flang::AddRISCVTargetArgs(const ArgList &Args,
206 ArgStringList &CmdArgs) const {
207 const llvm::Triple &Triple = getToolChain().getTriple();
208 // Handle -mrvv-vector-bits=<bits>
209 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
210 StringRef Val = A->getValue();
211 const Driver &D = getToolChain().getDriver();
212
213 // Get minimum VLen from march.
214 unsigned MinVLen = 0;
215 std::string Arch = riscv::getRISCVArch(Args, Triple);
216 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
217 Arch, /*EnableExperimentalExtensions*/ true);
218 // Ignore parsing error.
219 if (!errorToBool(ISAInfo.takeError()))
220 MinVLen = (*ISAInfo)->getMinVLen();
221
222 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
223 // as integer as long as we have a MinVLen.
224 unsigned Bits = 0;
225 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
226 Bits = MinVLen;
227 } else if (!Val.getAsInteger(10, Bits)) {
228 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
229 // at least MinVLen.
230 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
231 Bits > 65536 || !llvm::isPowerOf2_32(Bits))
232 Bits = 0;
233 }
234
235 // If we got a valid value try to use it.
236 if (Bits != 0) {
237 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
238 CmdArgs.push_back(
239 Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
240 CmdArgs.push_back(
241 Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
242 } else if (Val != "scalable") {
243 // Handle the unsupported values passed to mrvv-vector-bits.
244 D.Diag(diag::err_drv_unsupported_option_argument)
245 << A->getSpelling() << Val;
246 }
247 }
248}
249
250void Flang::AddX86_64TargetArgs(const ArgList &Args,
251 ArgStringList &CmdArgs) const {
252 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
253 StringRef Value = A->getValue();
254 if (Value == "intel" || Value == "att") {
255 CmdArgs.push_back(Args.MakeArgString("-mllvm"));
256 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
257 } else {
258 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
259 << A->getSpelling() << Value;
260 }
261 }
262}
263
264static void addVSDefines(const ToolChain &TC, const ArgList &Args,
265 ArgStringList &CmdArgs) {
266
267 unsigned ver = 0;
268 const VersionTuple vt = TC.computeMSVCVersion(nullptr, Args);
269 ver = vt.getMajor() * 10000000 + vt.getMinor().value_or(0) * 100000 +
270 vt.getSubminor().value_or(0);
271 CmdArgs.push_back(Args.MakeArgString("-D_MSC_VER=" + Twine(ver / 100000)));
272 CmdArgs.push_back(Args.MakeArgString("-D_MSC_FULL_VER=" + Twine(ver)));
273 CmdArgs.push_back(Args.MakeArgString("-D_WIN32"));
274
275 const llvm::Triple &triple = TC.getTriple();
276 if (triple.isAArch64()) {
277 CmdArgs.push_back("-D_M_ARM64=1");
278 } else if (triple.isX86() && triple.isArch32Bit()) {
279 CmdArgs.push_back("-D_M_IX86=600");
280 } else if (triple.isX86() && triple.isArch64Bit()) {
281 CmdArgs.push_back("-D_M_X64=100");
282 } else {
283 llvm_unreachable(
284 "Flang on Windows only supports X86_32, X86_64 and AArch64");
285 }
286}
287
288static void processVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
289 ArgStringList &CmdArgs) {
290 assert(TC.getTriple().isKnownWindowsMSVCEnvironment() &&
291 "can only add VS runtime library on Windows!");
292 // if -fno-fortran-main has been passed, skip linking Fortran_main.a
293 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
294 CmdArgs.push_back(Args.MakeArgString(
295 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "builtins")));
296 }
297 unsigned RTOptionID = options::OPT__SLASH_MT;
298 if (auto *rtl = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
299 RTOptionID = llvm::StringSwitch<unsigned>(rtl->getValue())
300 .Case("static", options::OPT__SLASH_MT)
301 .Case("static_dbg", options::OPT__SLASH_MTd)
302 .Case("dll", options::OPT__SLASH_MD)
303 .Case("dll_dbg", options::OPT__SLASH_MDd)
304 .Default(options::OPT__SLASH_MT);
305 }
306 switch (RTOptionID) {
307 case options::OPT__SLASH_MT:
308 CmdArgs.push_back("-D_MT");
309 CmdArgs.push_back("--dependent-lib=libcmt");
310 CmdArgs.push_back("--dependent-lib=FortranRuntime.static.lib");
311 CmdArgs.push_back("--dependent-lib=FortranDecimal.static.lib");
312 break;
313 case options::OPT__SLASH_MTd:
314 CmdArgs.push_back("-D_MT");
315 CmdArgs.push_back("-D_DEBUG");
316 CmdArgs.push_back("--dependent-lib=libcmtd");
317 CmdArgs.push_back("--dependent-lib=FortranRuntime.static_dbg.lib");
318 CmdArgs.push_back("--dependent-lib=FortranDecimal.static_dbg.lib");
319 break;
320 case options::OPT__SLASH_MD:
321 CmdArgs.push_back("-D_MT");
322 CmdArgs.push_back("-D_DLL");
323 CmdArgs.push_back("--dependent-lib=msvcrt");
324 CmdArgs.push_back("--dependent-lib=FortranRuntime.dynamic.lib");
325 CmdArgs.push_back("--dependent-lib=FortranDecimal.dynamic.lib");
326 break;
327 case options::OPT__SLASH_MDd:
328 CmdArgs.push_back("-D_MT");
329 CmdArgs.push_back("-D_DEBUG");
330 CmdArgs.push_back("-D_DLL");
331 CmdArgs.push_back("--dependent-lib=msvcrtd");
332 CmdArgs.push_back("--dependent-lib=FortranRuntime.dynamic_dbg.lib");
333 CmdArgs.push_back("--dependent-lib=FortranDecimal.dynamic_dbg.lib");
334 break;
335 }
336}
337
338void Flang::AddAMDGPUTargetArgs(const ArgList &Args,
339 ArgStringList &CmdArgs) const {
340 if (Arg *A = Args.getLastArg(options::OPT_mcode_object_version_EQ)) {
341 StringRef Val = A->getValue();
342 CmdArgs.push_back(Args.MakeArgString("-mcode-object-version=" + Val));
343 }
344}
345
346void Flang::addTargetOptions(const ArgList &Args,
347 ArgStringList &CmdArgs) const {
348 const ToolChain &TC = getToolChain();
349 const llvm::Triple &Triple = TC.getEffectiveTriple();
350 const Driver &D = TC.getDriver();
351
352 std::string CPU = getCPUName(D, Args, Triple);
353 if (!CPU.empty()) {
354 CmdArgs.push_back("-target-cpu");
355 CmdArgs.push_back(Args.MakeArgString(CPU));
356 }
357
358 addOutlineAtomicsArgs(D, getToolChain(), Args, CmdArgs, Triple);
359
360 // Add the target features.
361 switch (TC.getArch()) {
362 default:
363 break;
364 case llvm::Triple::aarch64:
365 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
366 AddAArch64TargetArgs(Args, CmdArgs);
367 break;
368
369 case llvm::Triple::r600:
370 case llvm::Triple::amdgcn:
371 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
372 AddAMDGPUTargetArgs(Args, CmdArgs);
373 break;
374 case llvm::Triple::riscv64:
375 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
376 AddRISCVTargetArgs(Args, CmdArgs);
377 break;
378 case llvm::Triple::x86_64:
379 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
380 AddX86_64TargetArgs(Args, CmdArgs);
381 break;
382 }
383
384 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
385 StringRef Name = A->getValue();
386 if (Name == "SVML") {
387 if (Triple.getArch() != llvm::Triple::x86 &&
388 Triple.getArch() != llvm::Triple::x86_64)
389 D.Diag(diag::err_drv_unsupported_opt_for_target)
390 << Name << Triple.getArchName();
391 } else if (Name == "LIBMVEC-X86") {
392 if (Triple.getArch() != llvm::Triple::x86 &&
393 Triple.getArch() != llvm::Triple::x86_64)
394 D.Diag(diag::err_drv_unsupported_opt_for_target)
395 << Name << Triple.getArchName();
396 } else if (Name == "SLEEF" || Name == "ArmPL") {
397 if (Triple.getArch() != llvm::Triple::aarch64 &&
398 Triple.getArch() != llvm::Triple::aarch64_be)
399 D.Diag(diag::err_drv_unsupported_opt_for_target)
400 << Name << Triple.getArchName();
401 }
402
403 if (Triple.isOSDarwin()) {
404 // flang doesn't currently suport nostdlib, nodefaultlibs. Adding these
405 // here incase they are added someday
406 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
407 if (A->getValue() == StringRef{"Accelerate"}) {
408 CmdArgs.push_back("-framework");
409 CmdArgs.push_back("Accelerate");
410 }
411 }
412 }
413 A->render(Args, CmdArgs);
414 }
415
416 if (Triple.isKnownWindowsMSVCEnvironment()) {
417 processVSRuntimeLibrary(TC, Args, CmdArgs);
418 addVSDefines(TC, Args, CmdArgs);
419 }
420
421 // TODO: Add target specific flags, ABI, mtune option etc.
422}
423
424void Flang::addOffloadOptions(Compilation &C, const InputInfoList &Inputs,
425 const JobAction &JA, const ArgList &Args,
426 ArgStringList &CmdArgs) const {
427 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
428 bool IsHostOffloadingAction = JA.isHostOffloading(Action::OFK_OpenMP) ||
429 JA.isHostOffloading(C.getActiveOffloadKinds());
430
431 // Skips the primary input file, which is the input file that the compilation
432 // proccess will be executed upon (e.g. the host bitcode file) and
433 // adds other secondary input (e.g. device bitcode files for embedding to the
434 // -fembed-offload-object argument or the host IR file for proccessing
435 // during device compilation to the fopenmp-host-ir-file-path argument via
436 // OpenMPDeviceInput). This is condensed logic from the ConstructJob
437 // function inside of the Clang driver for pushing on further input arguments
438 // needed for offloading during various phases of compilation.
439 for (size_t i = 1; i < Inputs.size(); ++i) {
440 if (Inputs[i].getType() == types::TY_Nothing) {
441 // contains nothing, so it's skippable
442 } else if (IsHostOffloadingAction) {
443 CmdArgs.push_back(
444 Args.MakeArgString("-fembed-offload-object=" +
445 getToolChain().getInputFilename(Inputs[i])));
446 } else if (IsOpenMPDevice) {
447 if (Inputs[i].getFilename()) {
448 CmdArgs.push_back("-fopenmp-host-ir-file-path");
449 CmdArgs.push_back(Args.MakeArgString(Inputs[i].getFilename()));
450 } else {
451 llvm_unreachable("missing openmp host-ir file for device offloading");
452 }
453 } else {
454 llvm_unreachable(
455 "unexpectedly given multiple inputs or given unknown input");
456 }
457 }
458
459 if (IsOpenMPDevice) {
460 // -fopenmp-is-target-device is passed along to tell the frontend that it is
461 // generating code for a device, so that only the relevant code is emitted.
462 CmdArgs.push_back("-fopenmp-is-target-device");
463
464 // When in OpenMP offloading mode, enable debugging on the device.
465 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
466 if (Args.hasFlag(options::OPT_fopenmp_target_debug,
467 options::OPT_fno_openmp_target_debug, /*Default=*/false))
468 CmdArgs.push_back("-fopenmp-target-debug");
469
470 // When in OpenMP offloading mode, forward assumptions information about
471 // thread and team counts in the device.
472 if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
473 options::OPT_fno_openmp_assume_teams_oversubscription,
474 /*Default=*/false))
475 CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
476 if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
477 options::OPT_fno_openmp_assume_threads_oversubscription,
478 /*Default=*/false))
479 CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
480 if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state))
481 CmdArgs.push_back("-fopenmp-assume-no-thread-state");
482 if (Args.hasArg(options::OPT_fopenmp_assume_no_nested_parallelism))
483 CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
484 if (Args.hasArg(options::OPT_nogpulib))
485 CmdArgs.push_back("-nogpulib");
486 }
487}
488
489static void addFloatingPointOptions(const Driver &D, const ArgList &Args,
490 ArgStringList &CmdArgs) {
491 StringRef FPContract;
492 bool HonorINFs = true;
493 bool HonorNaNs = true;
494 bool ApproxFunc = false;
495 bool SignedZeros = true;
496 bool AssociativeMath = false;
497 bool ReciprocalMath = false;
498
499 if (const Arg *A = Args.getLastArg(options::OPT_ffp_contract)) {
500 const StringRef Val = A->getValue();
501 if (Val == "fast" || Val == "off") {
502 FPContract = Val;
503 } else if (Val == "on") {
504 // Warn instead of error because users might have makefiles written for
505 // gfortran (which accepts -ffp-contract=on)
506 D.Diag(diag::warn_drv_unsupported_option_for_flang)
507 << Val << A->getOption().getName() << "off";
508 FPContract = "off";
509 } else
510 // Clang's "fast-honor-pragmas" option is not supported because it is
511 // non-standard
512 D.Diag(diag::err_drv_unsupported_option_argument)
513 << A->getSpelling() << Val;
514 }
515
516 for (const Arg *A : Args) {
517 auto optId = A->getOption().getID();
518 switch (optId) {
519 // if this isn't an FP option, skip the claim below
520 default:
521 continue;
522
523 case options::OPT_fhonor_infinities:
524 HonorINFs = true;
525 break;
526 case options::OPT_fno_honor_infinities:
527 HonorINFs = false;
528 break;
529 case options::OPT_fhonor_nans:
530 HonorNaNs = true;
531 break;
532 case options::OPT_fno_honor_nans:
533 HonorNaNs = false;
534 break;
535 case options::OPT_fapprox_func:
536 ApproxFunc = true;
537 break;
538 case options::OPT_fno_approx_func:
539 ApproxFunc = false;
540 break;
541 case options::OPT_fsigned_zeros:
542 SignedZeros = true;
543 break;
544 case options::OPT_fno_signed_zeros:
545 SignedZeros = false;
546 break;
547 case options::OPT_fassociative_math:
548 AssociativeMath = true;
549 break;
550 case options::OPT_fno_associative_math:
551 AssociativeMath = false;
552 break;
553 case options::OPT_freciprocal_math:
554 ReciprocalMath = true;
555 break;
556 case options::OPT_fno_reciprocal_math:
557 ReciprocalMath = false;
558 break;
559 case options::OPT_Ofast:
560 [[fallthrough]];
561 case options::OPT_ffast_math:
562 HonorINFs = false;
563 HonorNaNs = false;
564 AssociativeMath = true;
565 ReciprocalMath = true;
566 ApproxFunc = true;
567 SignedZeros = false;
568 FPContract = "fast";
569 break;
570 case options::OPT_fno_fast_math:
571 HonorINFs = true;
572 HonorNaNs = true;
573 AssociativeMath = false;
574 ReciprocalMath = false;
575 ApproxFunc = false;
576 SignedZeros = true;
577 // -fno-fast-math should undo -ffast-math so I return FPContract to the
578 // default. It is important to check it is "fast" (the default) so that
579 // --ffp-contract=off -fno-fast-math --> -ffp-contract=off
580 if (FPContract == "fast")
581 FPContract = "";
582 break;
583 }
584
585 // If we handled this option claim it
586 A->claim();
587 }
588
589 if (!HonorINFs && !HonorNaNs && AssociativeMath && ReciprocalMath &&
590 ApproxFunc && !SignedZeros &&
591 (FPContract == "fast" || FPContract.empty())) {
592 CmdArgs.push_back("-ffast-math");
593 return;
594 }
595
596 if (!FPContract.empty())
597 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
598
599 if (!HonorINFs)
600 CmdArgs.push_back("-menable-no-infs");
601
602 if (!HonorNaNs)
603 CmdArgs.push_back("-menable-no-nans");
604
605 if (ApproxFunc)
606 CmdArgs.push_back("-fapprox-func");
607
608 if (!SignedZeros)
609 CmdArgs.push_back("-fno-signed-zeros");
610
611 if (AssociativeMath && !SignedZeros)
612 CmdArgs.push_back("-mreassociate");
613
614 if (ReciprocalMath)
615 CmdArgs.push_back("-freciprocal-math");
616}
617
618static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
619 const InputInfo &Input) {
620 StringRef Format = "yaml";
621 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
622 Format = A->getValue();
623
624 CmdArgs.push_back("-opt-record-file");
625
626 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
627 if (A) {
628 CmdArgs.push_back(A->getValue());
629 } else {
631
632 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
633 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
634 F = FinalOutput->getValue();
635 }
636
637 if (F.empty()) {
638 // Use the input filename.
639 F = llvm::sys::path::stem(Input.getBaseInput());
640 }
641
642 SmallString<32> Extension;
643 Extension += "opt.";
644 Extension += Format;
645
646 llvm::sys::path::replace_extension(F, Extension);
647 CmdArgs.push_back(Args.MakeArgString(F));
648 }
649
650 if (const Arg *A =
651 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
652 CmdArgs.push_back("-opt-record-passes");
653 CmdArgs.push_back(A->getValue());
654 }
655
656 if (!Format.empty()) {
657 CmdArgs.push_back("-opt-record-format");
658 CmdArgs.push_back(Format.data());
659 }
660}
661
663 const InputInfo &Output, const InputInfoList &Inputs,
664 const ArgList &Args, const char *LinkingOutput) const {
665 const auto &TC = getToolChain();
666 const llvm::Triple &Triple = TC.getEffectiveTriple();
667 const std::string &TripleStr = Triple.getTriple();
668
669 const Driver &D = TC.getDriver();
670 ArgStringList CmdArgs;
671 DiagnosticsEngine &Diags = D.getDiags();
672
673 // Invoke ourselves in -fc1 mode.
674 CmdArgs.push_back("-fc1");
675
676 // Add the "effective" target triple.
677 CmdArgs.push_back("-triple");
678 CmdArgs.push_back(Args.MakeArgString(TripleStr));
679
680 if (isa<PreprocessJobAction>(JA)) {
681 CmdArgs.push_back("-E");
682 if (Args.getLastArg(options::OPT_dM)) {
683 CmdArgs.push_back("-dM");
684 }
685 } else if (isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) {
686 if (JA.getType() == types::TY_Nothing) {
687 CmdArgs.push_back("-fsyntax-only");
688 } else if (JA.getType() == types::TY_AST) {
689 CmdArgs.push_back("-emit-ast");
690 } else if (JA.getType() == types::TY_LLVM_IR ||
691 JA.getType() == types::TY_LTO_IR) {
692 CmdArgs.push_back("-emit-llvm");
693 } else if (JA.getType() == types::TY_LLVM_BC ||
694 JA.getType() == types::TY_LTO_BC) {
695 CmdArgs.push_back("-emit-llvm-bc");
696 } else if (JA.getType() == types::TY_PP_Asm) {
697 CmdArgs.push_back("-S");
698 } else {
699 assert(false && "Unexpected output type!");
700 }
701 } else if (isa<AssembleJobAction>(JA)) {
702 CmdArgs.push_back("-emit-obj");
703 } else {
704 assert(false && "Unexpected action class for Flang tool.");
705 }
706
707 const InputInfo &Input = Inputs[0];
708 types::ID InputType = Input.getType();
709
710 // Add preprocessing options like -I, -D, etc. if we are using the
711 // preprocessor (i.e. skip when dealing with e.g. binary files).
713 addPreprocessingOptions(Args, CmdArgs);
714
715 addFortranDialectOptions(Args, CmdArgs);
716
717 // Color diagnostics are parsed by the driver directly from argv and later
718 // re-parsed to construct this job; claim any possible color diagnostic here
719 // to avoid warn_drv_unused_argument.
720 Args.getLastArg(options::OPT_fcolor_diagnostics,
721 options::OPT_fno_color_diagnostics);
722 if (Diags.getDiagnosticOptions().ShowColors)
723 CmdArgs.push_back("-fcolor-diagnostics");
724
725 // LTO mode is parsed by the Clang driver library.
726 LTOKind LTOMode = D.getLTOMode(/* IsOffload */ false);
727 assert(LTOMode != LTOK_Unknown && "Unknown LTO mode.");
728 if (LTOMode == LTOK_Full)
729 CmdArgs.push_back("-flto=full");
730 else if (LTOMode == LTOK_Thin) {
731 Diags.Report(
733 "the option '-flto=thin' is a work in progress"));
734 CmdArgs.push_back("-flto=thin");
735 }
736
737 // -fPIC and related options.
738 addPicOptions(Args, CmdArgs);
739
740 // Floating point related options
741 addFloatingPointOptions(D, Args, CmdArgs);
742
743 // Add target args, features, etc.
744 addTargetOptions(Args, CmdArgs);
745
746 llvm::Reloc::Model RelocationModel =
747 std::get<0>(ParsePICArgs(getToolChain(), Args));
748 // Add MCModel information
749 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
750
751 // Add Codegen options
752 addCodegenOptions(Args, CmdArgs);
753
754 // Add R Group options
755 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
756
757 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
758 if (willEmitRemarks(Args))
759 renderRemarksOptions(Args, CmdArgs, Input);
760
761 // Add other compile options
762 addOtherOptions(Args, CmdArgs);
763
764 // Disable all warnings
765 // TODO: Handle interactions between -w, -pedantic, -Wall, -WOption
766 Args.AddLastArg(CmdArgs, options::OPT_w);
767
768 // Forward flags for OpenMP. We don't do this if the current action is an
769 // device offloading action other than OpenMP.
770 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
771 options::OPT_fno_openmp, false) &&
774 switch (D.getOpenMPRuntime(Args)) {
777 // Clang can generate useful OpenMP code for these two runtime libraries.
778 CmdArgs.push_back("-fopenmp");
779 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
780
781 if (Args.hasArg(options::OPT_fopenmp_force_usm))
782 CmdArgs.push_back("-fopenmp-force-usm");
783
784 // FIXME: Clang supports a whole bunch more flags here.
785 break;
786 default:
787 // By default, if Clang doesn't know how to generate useful OpenMP code
788 // for a specific runtime library, we just don't pass the '-fopenmp' flag
789 // down to the actual compilation.
790 // FIXME: It would be better to have a mode which *only* omits IR
791 // generation based on the OpenMP support so that we get consistent
792 // semantic analysis, etc.
793 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
794 D.Diag(diag::warn_drv_unsupported_openmp_library)
795 << A->getSpelling() << A->getValue();
796 break;
797 }
798 }
799
800 // Pass the path to compiler resource files.
801 CmdArgs.push_back("-resource-dir");
802 CmdArgs.push_back(D.ResourceDir.c_str());
803
804 // Offloading related options
805 addOffloadOptions(C, Inputs, JA, Args, CmdArgs);
806
807 // Forward -Xflang arguments to -fc1
808 Args.AddAllArgValues(CmdArgs, options::OPT_Xflang);
809
811 getFramePointerKind(Args, Triple);
812
813 const char *FPKeepKindStr = nullptr;
814 switch (FPKeepKind) {
816 FPKeepKindStr = "-mframe-pointer=none";
817 break;
819 FPKeepKindStr = "-mframe-pointer=reserved";
820 break;
822 FPKeepKindStr = "-mframe-pointer=non-leaf";
823 break;
825 FPKeepKindStr = "-mframe-pointer=all";
826 break;
827 }
828 assert(FPKeepKindStr && "unknown FramePointerKind");
829 CmdArgs.push_back(FPKeepKindStr);
830
831 // Forward -mllvm options to the LLVM option parser. In practice, this means
832 // forwarding to `-fc1` as that's where the LLVM parser is run.
833 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
834 A->claim();
835 A->render(Args, CmdArgs);
836 }
837
838 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
839 A->claim();
840 A->render(Args, CmdArgs);
841 }
842
843 // Remove any unsupported gfortran diagnostic options
844 for (const Arg *A : Args.filtered(options::OPT_flang_ignored_w_Group)) {
845 A->claim();
846 D.Diag(diag::warn_drv_unsupported_diag_option_for_flang)
847 << A->getOption().getName();
848 }
849
850 // Optimization level for CodeGen.
851 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
852 if (A->getOption().matches(options::OPT_O4)) {
853 CmdArgs.push_back("-O3");
854 D.Diag(diag::warn_O4_is_O3);
855 } else if (A->getOption().matches(options::OPT_Ofast)) {
856 CmdArgs.push_back("-O3");
857 } else {
858 A->render(Args, CmdArgs);
859 }
860 }
861
862 assert((Output.isFilename() || Output.isNothing()) && "Invalid output.");
863 if (Output.isFilename()) {
864 CmdArgs.push_back("-o");
865 CmdArgs.push_back(Output.getFilename());
866 }
867
868 assert(Input.isFilename() && "Invalid input.");
869
870 if (Args.getLastArg(options::OPT_save_temps_EQ))
871 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
872
873 addDashXForInput(Args, Input, CmdArgs);
874
875 CmdArgs.push_back(Input.getFilename());
876
877 // TODO: Replace flang-new with flang once the new driver replaces the
878 // throwaway driver
879 const char *Exec = Args.MakeArgString(D.GetProgramPath("flang-new", TC));
880 C.addCommand(std::make_unique<Command>(JA, *this,
882 Exec, CmdArgs, Inputs, Output));
883}
884
885Flang::Flang(const ToolChain &TC) : Tool("flang-new", "flang frontend", TC) {}
886
const Decl * D
static void addDashXForInput(const ArgList &Args, const InputInfo &Input, ArgStringList &CmdArgs)
Add -x lang to CmdArgs for Input.
Definition: Clang.cpp:556
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input, const InputInfo &Output, const JobAction &JA)
Definition: Clang.cpp:1366
clang::CodeGenOptions::FramePointerKind getFramePointerKind(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition: CommonArgs.cpp:211
static void processVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Flang.cpp:288
static void addVSDefines(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Flang.cpp:264
static bool shouldLoopVersion(const ArgList &Args)
@C shouldLoopVersion
Definition: Flang.cpp:84
static void addDashXForInput(const ArgList &Args, const InputInfo &Input, ArgStringList &CmdArgs)
Add -x lang to CmdArgs for Input.
Definition: Flang.cpp:29
static void addFloatingPointOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Flang.cpp:489
int64_t getID() const
Definition: DeclBase.cpp:1155
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
unsigned getCustomDiagID(Level L, const char(&FormatString)[N])
Return an ID for a diagnostic with the specified format string and level.
Definition: Diagnostic.h:873
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition: Diagnostic.h:562
types::ID getType() const
Definition: Action.h:148
bool isHostOffloading(unsigned int OKind) const
Check if this action have any offload kinds.
Definition: Action.h:218
bool isDeviceOffloading(OffloadKind OKind) const
Definition: Action.h:221
Compilation - A set of tasks to perform for a single driver invocation.
Definition: Compilation.h:45
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:77
DiagnosticBuilder Diag(unsigned DiagID) const
Definition: Driver.h:144
@ OMPRT_IOMP5
The legacy name for the LLVM OpenMP runtime from when it was the Intel OpenMP runtime.
Definition: Driver.h:140
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition: Driver.h:130
InputInfo - Wrapper for information about an input source.
Definition: InputInfo.h:22
const char * getBaseInput() const
Definition: InputInfo.h:78
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
llvm::Triple::ArchType getArch() const
Definition: ToolChain.h:269
const Driver & getDriver() const
Definition: ToolChain.h:253
const llvm::Triple & getEffectiveTriple() const
Get the toolchain's effective clang triple.
Definition: ToolChain.h:283
const llvm::Triple & getTriple() const
Definition: ToolChain.h:255
virtual VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const
On Windows, returns the MSVC compatibility version.
Definition: ToolChain.cpp:1423
std::string getCompilerRTBasename(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
Definition: ToolChain.cpp:636
Tool - Information on a specific compilation tool.
Definition: Tool.h:32
const ToolChain & getToolChain() const
Definition: Tool.h:52
Flang(const ToolChain &TC)
Definition: Flang.cpp:885
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:662
std::string getRISCVArch(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition: RISCV.cpp:256
void addMCModel(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple, const llvm::Reloc::Model &RelocationModel, llvm::opt::ArgStringList &CmdArgs)
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)
std::string getCPUName(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &T, bool FromAs=false)
void addDebugInfoKind(llvm::opt::ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind)
llvm::codegenoptions::DebugInfoKind debugLevelToInfoKind(const llvm::opt::Arg &A)
std::tuple< llvm::Reloc::Model, unsigned, bool > ParsePICArgs(const ToolChain &ToolChain, const llvm::opt::ArgList &Args)
const char * RelocationModelName(llvm::Reloc::Model Model)
ID getPreprocessedType(ID Id)
getPreprocessedType - Get the ID of the type for this input when it has been preprocessed,...
Definition: Types.cpp:56
const char * getTypeName(ID Id)
getTypeName - Return the name of the type for Id.
Definition: Types.cpp:52
LTOKind
Describes the kind of LTO mode selected via -f(no-)?lto(=.*)? options.
Definition: Driver.h:58
@ LTOK_Unknown
Definition: Driver.h:62
bool willEmitRemarks(const llvm::opt::ArgList &Args)
The JSON file list parser is used to communicate input to InstallAPI.
static constexpr ResponseFileSupport AtFileUTF8()
Definition: Job.h:85