clang 20.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/Host.h"
19#include "llvm/TargetParser/RISCVISAInfo.h"
20#include "llvm/TargetParser/RISCVTargetParser.h"
21
22#include <cassert>
23
24using namespace clang::driver;
25using namespace clang::driver::tools;
26using namespace clang;
27using namespace llvm::opt;
28
29/// Add -x lang to \p CmdArgs for \p Input.
30static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
31 ArgStringList &CmdArgs) {
32 CmdArgs.push_back("-x");
33 // Map the driver type to the frontend type.
34 CmdArgs.push_back(types::getTypeName(Input.getType()));
35}
36
37void Flang::addFortranDialectOptions(const ArgList &Args,
38 ArgStringList &CmdArgs) const {
39 Args.addAllArgs(CmdArgs, {options::OPT_ffixed_form,
40 options::OPT_ffree_form,
41 options::OPT_ffixed_line_length_EQ,
42 options::OPT_fopenacc,
43 options::OPT_finput_charset_EQ,
44 options::OPT_fimplicit_none,
45 options::OPT_fno_implicit_none,
46 options::OPT_fbackslash,
47 options::OPT_fno_backslash,
48 options::OPT_flogical_abbreviations,
49 options::OPT_fno_logical_abbreviations,
50 options::OPT_fxor_operator,
51 options::OPT_fno_xor_operator,
52 options::OPT_falternative_parameter_statement,
53 options::OPT_fdefault_real_8,
54 options::OPT_fdefault_integer_8,
55 options::OPT_fdefault_double_8,
56 options::OPT_flarge_sizes,
57 options::OPT_fno_automatic,
58 options::OPT_fhermetic_module_files});
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::FullDebugInfo;
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_integer_overflow,
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 == "128" || Val == "256" || Val == "512" || Val == "1024" ||
184 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
185 Val == "1024+" || Val == "2048+") {
186 unsigned Bits = 0;
187 if (!Val.consume_back("+")) {
188 [[maybe_unused]] bool Invalid = Val.getAsInteger(10, Bits);
189 assert(!Invalid && "Failed to parse value");
190 CmdArgs.push_back(
191 Args.MakeArgString("-mvscale-max=" + llvm::Twine(Bits / 128)));
192 }
193
194 [[maybe_unused]] bool Invalid = Val.getAsInteger(10, Bits);
195 assert(!Invalid && "Failed to parse value");
196 CmdArgs.push_back(
197 Args.MakeArgString("-mvscale-min=" + llvm::Twine(Bits / 128)));
198 // Silently drop requests for vector-length agnostic code as it's implied.
199 } else if (Val != "scalable")
200 // Handle the unsupported values passed to msve-vector-bits.
201 D.Diag(diag::err_drv_unsupported_option_argument)
202 << A->getSpelling() << Val;
203 }
204}
205
206void Flang::AddRISCVTargetArgs(const ArgList &Args,
207 ArgStringList &CmdArgs) const {
208 const llvm::Triple &Triple = getToolChain().getTriple();
209 // Handle -mrvv-vector-bits=<bits>
210 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
211 StringRef Val = A->getValue();
212 const Driver &D = getToolChain().getDriver();
213
214 // Get minimum VLen from march.
215 unsigned MinVLen = 0;
216 std::string Arch = riscv::getRISCVArch(Args, Triple);
217 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
218 Arch, /*EnableExperimentalExtensions*/ true);
219 // Ignore parsing error.
220 if (!errorToBool(ISAInfo.takeError()))
221 MinVLen = (*ISAInfo)->getMinVLen();
222
223 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
224 // as integer as long as we have a MinVLen.
225 unsigned Bits = 0;
226 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
227 Bits = MinVLen;
228 } else if (!Val.getAsInteger(10, Bits)) {
229 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
230 // at least MinVLen.
231 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
232 Bits > 65536 || !llvm::isPowerOf2_32(Bits))
233 Bits = 0;
234 }
235
236 // If we got a valid value try to use it.
237 if (Bits != 0) {
238 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
239 CmdArgs.push_back(
240 Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
241 CmdArgs.push_back(
242 Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
243 } else if (Val != "scalable") {
244 // Handle the unsupported values passed to mrvv-vector-bits.
245 D.Diag(diag::err_drv_unsupported_option_argument)
246 << A->getSpelling() << Val;
247 }
248 }
249}
250
251void Flang::AddX86_64TargetArgs(const ArgList &Args,
252 ArgStringList &CmdArgs) const {
253 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
254 StringRef Value = A->getValue();
255 if (Value == "intel" || Value == "att") {
256 CmdArgs.push_back(Args.MakeArgString("-mllvm"));
257 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
258 } else {
259 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
260 << A->getSpelling() << Value;
261 }
262 }
263}
264
265static void addVSDefines(const ToolChain &TC, const ArgList &Args,
266 ArgStringList &CmdArgs) {
267
268 unsigned ver = 0;
269 const VersionTuple vt = TC.computeMSVCVersion(nullptr, Args);
270 ver = vt.getMajor() * 10000000 + vt.getMinor().value_or(0) * 100000 +
271 vt.getSubminor().value_or(0);
272 CmdArgs.push_back(Args.MakeArgString("-D_MSC_VER=" + Twine(ver / 100000)));
273 CmdArgs.push_back(Args.MakeArgString("-D_MSC_FULL_VER=" + Twine(ver)));
274 CmdArgs.push_back(Args.MakeArgString("-D_WIN32"));
275
276 const llvm::Triple &triple = TC.getTriple();
277 if (triple.isAArch64()) {
278 CmdArgs.push_back("-D_M_ARM64=1");
279 } else if (triple.isX86() && triple.isArch32Bit()) {
280 CmdArgs.push_back("-D_M_IX86=600");
281 } else if (triple.isX86() && triple.isArch64Bit()) {
282 CmdArgs.push_back("-D_M_X64=100");
283 } else {
284 llvm_unreachable(
285 "Flang on Windows only supports X86_32, X86_64 and AArch64");
286 }
287}
288
289static void processVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
290 ArgStringList &CmdArgs) {
291 assert(TC.getTriple().isKnownWindowsMSVCEnvironment() &&
292 "can only add VS runtime library on Windows!");
293 // if -fno-fortran-main has been passed, skip linking Fortran_main.a
294 if (TC.getTriple().isKnownWindowsMSVCEnvironment()) {
295 CmdArgs.push_back(Args.MakeArgString(
296 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "builtins")));
297 }
298 unsigned RTOptionID = options::OPT__SLASH_MT;
299 if (auto *rtl = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
300 RTOptionID = llvm::StringSwitch<unsigned>(rtl->getValue())
301 .Case("static", options::OPT__SLASH_MT)
302 .Case("static_dbg", options::OPT__SLASH_MTd)
303 .Case("dll", options::OPT__SLASH_MD)
304 .Case("dll_dbg", options::OPT__SLASH_MDd)
305 .Default(options::OPT__SLASH_MT);
306 }
307 switch (RTOptionID) {
308 case options::OPT__SLASH_MT:
309 CmdArgs.push_back("-D_MT");
310 CmdArgs.push_back("--dependent-lib=libcmt");
311 CmdArgs.push_back("--dependent-lib=FortranRuntime.static.lib");
312 CmdArgs.push_back("--dependent-lib=FortranDecimal.static.lib");
313 break;
314 case options::OPT__SLASH_MTd:
315 CmdArgs.push_back("-D_MT");
316 CmdArgs.push_back("-D_DEBUG");
317 CmdArgs.push_back("--dependent-lib=libcmtd");
318 CmdArgs.push_back("--dependent-lib=FortranRuntime.static_dbg.lib");
319 CmdArgs.push_back("--dependent-lib=FortranDecimal.static_dbg.lib");
320 break;
321 case options::OPT__SLASH_MD:
322 CmdArgs.push_back("-D_MT");
323 CmdArgs.push_back("-D_DLL");
324 CmdArgs.push_back("--dependent-lib=msvcrt");
325 CmdArgs.push_back("--dependent-lib=FortranRuntime.dynamic.lib");
326 CmdArgs.push_back("--dependent-lib=FortranDecimal.dynamic.lib");
327 break;
328 case options::OPT__SLASH_MDd:
329 CmdArgs.push_back("-D_MT");
330 CmdArgs.push_back("-D_DEBUG");
331 CmdArgs.push_back("-D_DLL");
332 CmdArgs.push_back("--dependent-lib=msvcrtd");
333 CmdArgs.push_back("--dependent-lib=FortranRuntime.dynamic_dbg.lib");
334 CmdArgs.push_back("--dependent-lib=FortranDecimal.dynamic_dbg.lib");
335 break;
336 }
337}
338
339void Flang::AddAMDGPUTargetArgs(const ArgList &Args,
340 ArgStringList &CmdArgs) const {
341 if (Arg *A = Args.getLastArg(options::OPT_mcode_object_version_EQ)) {
342 StringRef Val = A->getValue();
343 CmdArgs.push_back(Args.MakeArgString("-mcode-object-version=" + Val));
344 }
345
346 const ToolChain &TC = getToolChain();
348}
349
350void Flang::addTargetOptions(const ArgList &Args,
351 ArgStringList &CmdArgs) const {
352 const ToolChain &TC = getToolChain();
353 const llvm::Triple &Triple = TC.getEffectiveTriple();
354 const Driver &D = TC.getDriver();
355
356 std::string CPU = getCPUName(D, Args, Triple);
357 if (!CPU.empty()) {
358 CmdArgs.push_back("-target-cpu");
359 CmdArgs.push_back(Args.MakeArgString(CPU));
360 }
361
362 addOutlineAtomicsArgs(D, getToolChain(), Args, CmdArgs, Triple);
363
364 // Add the target features.
365 switch (TC.getArch()) {
366 default:
367 break;
368 case llvm::Triple::aarch64:
369 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
370 AddAArch64TargetArgs(Args, CmdArgs);
371 break;
372
373 case llvm::Triple::r600:
374 case llvm::Triple::amdgcn:
375 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
376 AddAMDGPUTargetArgs(Args, CmdArgs);
377 break;
378 case llvm::Triple::riscv64:
379 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
380 AddRISCVTargetArgs(Args, CmdArgs);
381 break;
382 case llvm::Triple::x86_64:
383 getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
384 AddX86_64TargetArgs(Args, CmdArgs);
385 break;
386 }
387
388 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
389 StringRef Name = A->getValue();
390 if (Name == "SVML") {
391 if (Triple.getArch() != llvm::Triple::x86 &&
392 Triple.getArch() != llvm::Triple::x86_64)
393 D.Diag(diag::err_drv_unsupported_opt_for_target)
394 << Name << Triple.getArchName();
395 } else if (Name == "LIBMVEC-X86") {
396 if (Triple.getArch() != llvm::Triple::x86 &&
397 Triple.getArch() != llvm::Triple::x86_64)
398 D.Diag(diag::err_drv_unsupported_opt_for_target)
399 << Name << Triple.getArchName();
400 } else if (Name == "SLEEF" || Name == "ArmPL") {
401 if (Triple.getArch() != llvm::Triple::aarch64 &&
402 Triple.getArch() != llvm::Triple::aarch64_be)
403 D.Diag(diag::err_drv_unsupported_opt_for_target)
404 << Name << Triple.getArchName();
405 }
406
407 if (Triple.isOSDarwin()) {
408 // flang doesn't currently suport nostdlib, nodefaultlibs. Adding these
409 // here incase they are added someday
410 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
411 if (A->getValue() == StringRef{"Accelerate"}) {
412 CmdArgs.push_back("-framework");
413 CmdArgs.push_back("Accelerate");
414 }
415 }
416 }
417 A->render(Args, CmdArgs);
418 }
419
420 if (Triple.isKnownWindowsMSVCEnvironment()) {
421 processVSRuntimeLibrary(TC, Args, CmdArgs);
422 addVSDefines(TC, Args, CmdArgs);
423 }
424
425 // TODO: Add target specific flags, ABI, mtune option etc.
426 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
427 CmdArgs.push_back("-tune-cpu");
428 if (A->getValue() == StringRef{"native"})
429 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
430 else
431 CmdArgs.push_back(A->getValue());
432 }
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 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
500}
501
502static void addFloatingPointOptions(const Driver &D, const ArgList &Args,
503 ArgStringList &CmdArgs) {
504 StringRef FPContract;
505 bool HonorINFs = true;
506 bool HonorNaNs = true;
507 bool ApproxFunc = false;
508 bool SignedZeros = true;
509 bool AssociativeMath = false;
510 bool ReciprocalMath = false;
511
512 if (const Arg *A = Args.getLastArg(options::OPT_ffp_contract)) {
513 const StringRef Val = A->getValue();
514 if (Val == "fast" || Val == "off") {
515 FPContract = Val;
516 } else if (Val == "on") {
517 // Warn instead of error because users might have makefiles written for
518 // gfortran (which accepts -ffp-contract=on)
519 D.Diag(diag::warn_drv_unsupported_option_for_flang)
520 << Val << A->getOption().getName() << "off";
521 FPContract = "off";
522 } else
523 // Clang's "fast-honor-pragmas" option is not supported because it is
524 // non-standard
525 D.Diag(diag::err_drv_unsupported_option_argument)
526 << A->getSpelling() << Val;
527 }
528
529 for (const Arg *A : Args) {
530 auto optId = A->getOption().getID();
531 switch (optId) {
532 // if this isn't an FP option, skip the claim below
533 default:
534 continue;
535
536 case options::OPT_fhonor_infinities:
537 HonorINFs = true;
538 break;
539 case options::OPT_fno_honor_infinities:
540 HonorINFs = false;
541 break;
542 case options::OPT_fhonor_nans:
543 HonorNaNs = true;
544 break;
545 case options::OPT_fno_honor_nans:
546 HonorNaNs = false;
547 break;
548 case options::OPT_fapprox_func:
549 ApproxFunc = true;
550 break;
551 case options::OPT_fno_approx_func:
552 ApproxFunc = false;
553 break;
554 case options::OPT_fsigned_zeros:
555 SignedZeros = true;
556 break;
557 case options::OPT_fno_signed_zeros:
558 SignedZeros = false;
559 break;
560 case options::OPT_fassociative_math:
561 AssociativeMath = true;
562 break;
563 case options::OPT_fno_associative_math:
564 AssociativeMath = false;
565 break;
566 case options::OPT_freciprocal_math:
567 ReciprocalMath = true;
568 break;
569 case options::OPT_fno_reciprocal_math:
570 ReciprocalMath = false;
571 break;
572 case options::OPT_Ofast:
573 [[fallthrough]];
574 case options::OPT_ffast_math:
575 HonorINFs = false;
576 HonorNaNs = false;
577 AssociativeMath = true;
578 ReciprocalMath = true;
579 ApproxFunc = true;
580 SignedZeros = false;
581 FPContract = "fast";
582 break;
583 case options::OPT_fno_fast_math:
584 HonorINFs = true;
585 HonorNaNs = true;
586 AssociativeMath = false;
587 ReciprocalMath = false;
588 ApproxFunc = false;
589 SignedZeros = true;
590 // -fno-fast-math should undo -ffast-math so I return FPContract to the
591 // default. It is important to check it is "fast" (the default) so that
592 // --ffp-contract=off -fno-fast-math --> -ffp-contract=off
593 if (FPContract == "fast")
594 FPContract = "";
595 break;
596 }
597
598 // If we handled this option claim it
599 A->claim();
600 }
601
602 if (!HonorINFs && !HonorNaNs && AssociativeMath && ReciprocalMath &&
603 ApproxFunc && !SignedZeros &&
604 (FPContract == "fast" || FPContract.empty())) {
605 CmdArgs.push_back("-ffast-math");
606 return;
607 }
608
609 if (!FPContract.empty())
610 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
611
612 if (!HonorINFs)
613 CmdArgs.push_back("-menable-no-infs");
614
615 if (!HonorNaNs)
616 CmdArgs.push_back("-menable-no-nans");
617
618 if (ApproxFunc)
619 CmdArgs.push_back("-fapprox-func");
620
621 if (!SignedZeros)
622 CmdArgs.push_back("-fno-signed-zeros");
623
624 if (AssociativeMath && !SignedZeros)
625 CmdArgs.push_back("-mreassociate");
626
627 if (ReciprocalMath)
628 CmdArgs.push_back("-freciprocal-math");
629}
630
631static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
632 const InputInfo &Input) {
633 StringRef Format = "yaml";
634 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
635 Format = A->getValue();
636
637 CmdArgs.push_back("-opt-record-file");
638
639 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
640 if (A) {
641 CmdArgs.push_back(A->getValue());
642 } else {
644
645 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
646 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
647 F = FinalOutput->getValue();
648 }
649
650 if (F.empty()) {
651 // Use the input filename.
652 F = llvm::sys::path::stem(Input.getBaseInput());
653 }
654
655 SmallString<32> Extension;
656 Extension += "opt.";
657 Extension += Format;
658
659 llvm::sys::path::replace_extension(F, Extension);
660 CmdArgs.push_back(Args.MakeArgString(F));
661 }
662
663 if (const Arg *A =
664 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
665 CmdArgs.push_back("-opt-record-passes");
666 CmdArgs.push_back(A->getValue());
667 }
668
669 if (!Format.empty()) {
670 CmdArgs.push_back("-opt-record-format");
671 CmdArgs.push_back(Format.data());
672 }
673}
674
676 const InputInfo &Output, const InputInfoList &Inputs,
677 const ArgList &Args, const char *LinkingOutput) const {
678 const auto &TC = getToolChain();
679 const llvm::Triple &Triple = TC.getEffectiveTriple();
680 const std::string &TripleStr = Triple.getTriple();
681
682 const Driver &D = TC.getDriver();
683 ArgStringList CmdArgs;
684 DiagnosticsEngine &Diags = D.getDiags();
685
686 // Invoke ourselves in -fc1 mode.
687 CmdArgs.push_back("-fc1");
688
689 // Add the "effective" target triple.
690 CmdArgs.push_back("-triple");
691 CmdArgs.push_back(Args.MakeArgString(TripleStr));
692
693 if (isa<PreprocessJobAction>(JA)) {
694 CmdArgs.push_back("-E");
695 if (Args.getLastArg(options::OPT_dM)) {
696 CmdArgs.push_back("-dM");
697 }
698 } else if (isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) {
699 if (JA.getType() == types::TY_Nothing) {
700 CmdArgs.push_back("-fsyntax-only");
701 } else if (JA.getType() == types::TY_AST) {
702 CmdArgs.push_back("-emit-ast");
703 } else if (JA.getType() == types::TY_LLVM_IR ||
704 JA.getType() == types::TY_LTO_IR) {
705 CmdArgs.push_back("-emit-llvm");
706 } else if (JA.getType() == types::TY_LLVM_BC ||
707 JA.getType() == types::TY_LTO_BC) {
708 CmdArgs.push_back("-emit-llvm-bc");
709 } else if (JA.getType() == types::TY_PP_Asm) {
710 CmdArgs.push_back("-S");
711 } else {
712 assert(false && "Unexpected output type!");
713 }
714 } else if (isa<AssembleJobAction>(JA)) {
715 CmdArgs.push_back("-emit-obj");
716 } else {
717 assert(false && "Unexpected action class for Flang tool.");
718 }
719
720 const InputInfo &Input = Inputs[0];
721 types::ID InputType = Input.getType();
722
723 // Add preprocessing options like -I, -D, etc. if we are using the
724 // preprocessor (i.e. skip when dealing with e.g. binary files).
726 addPreprocessingOptions(Args, CmdArgs);
727
728 addFortranDialectOptions(Args, CmdArgs);
729
730 // Color diagnostics are parsed by the driver directly from argv and later
731 // re-parsed to construct this job; claim any possible color diagnostic here
732 // to avoid warn_drv_unused_argument.
733 Args.getLastArg(options::OPT_fcolor_diagnostics,
734 options::OPT_fno_color_diagnostics);
735 if (Diags.getDiagnosticOptions().ShowColors)
736 CmdArgs.push_back("-fcolor-diagnostics");
737
738 // LTO mode is parsed by the Clang driver library.
739 LTOKind LTOMode = D.getLTOMode();
740 assert(LTOMode != LTOK_Unknown && "Unknown LTO mode.");
741 if (LTOMode == LTOK_Full)
742 CmdArgs.push_back("-flto=full");
743 else if (LTOMode == LTOK_Thin) {
744 Diags.Report(
746 "the option '-flto=thin' is a work in progress"));
747 CmdArgs.push_back("-flto=thin");
748 }
749
750 // -fPIC and related options.
751 addPicOptions(Args, CmdArgs);
752
753 // Floating point related options
754 addFloatingPointOptions(D, Args, CmdArgs);
755
756 // Add target args, features, etc.
757 addTargetOptions(Args, CmdArgs);
758
759 llvm::Reloc::Model RelocationModel =
760 std::get<0>(ParsePICArgs(getToolChain(), Args));
761 // Add MCModel information
762 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
763
764 // Add Codegen options
765 addCodegenOptions(Args, CmdArgs);
766
767 // Add R Group options
768 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
769
770 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
771 if (willEmitRemarks(Args))
772 renderRemarksOptions(Args, CmdArgs, Input);
773
774 // Add other compile options
775 addOtherOptions(Args, CmdArgs);
776
777 // Disable all warnings
778 // TODO: Handle interactions between -w, -pedantic, -Wall, -WOption
779 Args.AddLastArg(CmdArgs, options::OPT_w);
780
781 // Forward flags for OpenMP. We don't do this if the current action is an
782 // device offloading action other than OpenMP.
783 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
784 options::OPT_fno_openmp, false) &&
787 switch (D.getOpenMPRuntime(Args)) {
790 // Clang can generate useful OpenMP code for these two runtime libraries.
791 CmdArgs.push_back("-fopenmp");
792 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
793
794 if (Args.hasArg(options::OPT_fopenmp_force_usm))
795 CmdArgs.push_back("-fopenmp-force-usm");
796
797 // FIXME: Clang supports a whole bunch more flags here.
798 break;
799 default:
800 // By default, if Clang doesn't know how to generate useful OpenMP code
801 // for a specific runtime library, we just don't pass the '-fopenmp' flag
802 // down to the actual compilation.
803 // FIXME: It would be better to have a mode which *only* omits IR
804 // generation based on the OpenMP support so that we get consistent
805 // semantic analysis, etc.
806 const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
807 D.Diag(diag::warn_drv_unsupported_openmp_library)
808 << A->getSpelling() << A->getValue();
809 break;
810 }
811 }
812
813 // Pass the path to compiler resource files.
814 CmdArgs.push_back("-resource-dir");
815 CmdArgs.push_back(D.ResourceDir.c_str());
816
817 // Offloading related options
818 addOffloadOptions(C, Inputs, JA, Args, CmdArgs);
819
820 // Forward -Xflang arguments to -fc1
821 Args.AddAllArgValues(CmdArgs, options::OPT_Xflang);
822
824 getFramePointerKind(Args, Triple);
825
826 const char *FPKeepKindStr = nullptr;
827 switch (FPKeepKind) {
829 FPKeepKindStr = "-mframe-pointer=none";
830 break;
832 FPKeepKindStr = "-mframe-pointer=reserved";
833 break;
835 FPKeepKindStr = "-mframe-pointer=non-leaf";
836 break;
838 FPKeepKindStr = "-mframe-pointer=all";
839 break;
840 }
841 assert(FPKeepKindStr && "unknown FramePointerKind");
842 CmdArgs.push_back(FPKeepKindStr);
843
844 // Forward -mllvm options to the LLVM option parser. In practice, this means
845 // forwarding to `-fc1` as that's where the LLVM parser is run.
846 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
847 A->claim();
848 A->render(Args, CmdArgs);
849 }
850
851 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
852 A->claim();
853 A->render(Args, CmdArgs);
854 }
855
856 // Remove any unsupported gfortran diagnostic options
857 for (const Arg *A : Args.filtered(options::OPT_flang_ignored_w_Group)) {
858 A->claim();
859 D.Diag(diag::warn_drv_unsupported_diag_option_for_flang)
860 << A->getOption().getName();
861 }
862
863 // Optimization level for CodeGen.
864 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
865 if (A->getOption().matches(options::OPT_O4)) {
866 CmdArgs.push_back("-O3");
867 D.Diag(diag::warn_O4_is_O3);
868 } else if (A->getOption().matches(options::OPT_Ofast)) {
869 CmdArgs.push_back("-O3");
870 } else {
871 A->render(Args, CmdArgs);
872 }
873 }
874
875 assert((Output.isFilename() || Output.isNothing()) && "Invalid output.");
876 if (Output.isFilename()) {
877 CmdArgs.push_back("-o");
878 CmdArgs.push_back(Output.getFilename());
879 }
880
881 assert(Input.isFilename() && "Invalid input.");
882
883 if (Args.getLastArg(options::OPT_save_temps_EQ))
884 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
885
886 addDashXForInput(Args, Input, CmdArgs);
887
888 CmdArgs.push_back(Input.getFilename());
889
890 // TODO: Replace flang-new with flang once the new driver replaces the
891 // throwaway driver
892 const char *Exec = Args.MakeArgString(D.GetProgramPath("flang-new", TC));
893 C.addCommand(std::make_unique<Command>(JA, *this,
895 Exec, CmdArgs, Inputs, Output));
896}
897
898Flang::Flang(const ToolChain &TC) : Tool("flang-new", "flang frontend", TC) {}
899
const Decl * D
static void addDashXForInput(const ArgList &Args, const InputInfo &Input, ArgStringList &CmdArgs)
Add -x lang to CmdArgs for Input.
Definition: Clang.cpp:557
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input, const InputInfo &Output, const JobAction &JA)
Definition: Clang.cpp:1377
clang::CodeGenOptions::FramePointerKind getFramePointerKind(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition: CommonArgs.cpp:212
static void processVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Flang.cpp:289
static void addVSDefines(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Flang.cpp:265
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:30
static void addFloatingPointOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Flang.cpp:502
int64_t getID() const
Definition: DeclBase.cpp:1174
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: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:1454
virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, Action::OffloadKind DeviceOffloadKind) const
Add options that need to be passed to cc1 for this target.
Definition: ToolChain.cpp:1104
std::string getCompilerRTBasename(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
Definition: ToolChain.cpp:665
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:898
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:675
std::string getRISCVArch(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition: RISCV.cpp:249
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)
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: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