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