[DFAJumpThreading] Remove incoming StartBlock from all phis when unfolding select...
[llvm-project.git] / clang / lib / Driver / ToolChains / Clang.cpp
blob79f7fba2257074604207354bb633a8cc905bf369
1 //===-- Clang.cpp - Clang+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 //===----------------------------------------------------------------------===//
9 #include "Clang.h"
10 #include "AMDGPU.h"
11 #include "Arch/AArch64.h"
12 #include "Arch/ARM.h"
13 #include "Arch/CSKY.h"
14 #include "Arch/LoongArch.h"
15 #include "Arch/M68k.h"
16 #include "Arch/Mips.h"
17 #include "Arch/PPC.h"
18 #include "Arch/RISCV.h"
19 #include "Arch/Sparc.h"
20 #include "Arch/SystemZ.h"
21 #include "Arch/VE.h"
22 #include "Arch/X86.h"
23 #include "CommonArgs.h"
24 #include "Hexagon.h"
25 #include "MSP430.h"
26 #include "PS4CPU.h"
27 #include "clang/Basic/CLWarnings.h"
28 #include "clang/Basic/CharInfo.h"
29 #include "clang/Basic/CodeGenOptions.h"
30 #include "clang/Basic/HeaderInclude.h"
31 #include "clang/Basic/LangOptions.h"
32 #include "clang/Basic/MakeSupport.h"
33 #include "clang/Basic/ObjCRuntime.h"
34 #include "clang/Basic/Version.h"
35 #include "clang/Config/config.h"
36 #include "clang/Driver/Action.h"
37 #include "clang/Driver/Distro.h"
38 #include "clang/Driver/DriverDiagnostic.h"
39 #include "clang/Driver/InputInfo.h"
40 #include "clang/Driver/Options.h"
41 #include "clang/Driver/SanitizerArgs.h"
42 #include "clang/Driver/Types.h"
43 #include "clang/Driver/XRayArgs.h"
44 #include "llvm/ADT/SmallSet.h"
45 #include "llvm/ADT/StringExtras.h"
46 #include "llvm/Config/llvm-config.h"
47 #include "llvm/Option/ArgList.h"
48 #include "llvm/Support/CodeGen.h"
49 #include "llvm/Support/Compiler.h"
50 #include "llvm/Support/Compression.h"
51 #include "llvm/Support/Error.h"
52 #include "llvm/Support/FileSystem.h"
53 #include "llvm/Support/Path.h"
54 #include "llvm/Support/Process.h"
55 #include "llvm/Support/RISCVISAInfo.h"
56 #include "llvm/Support/YAMLParser.h"
57 #include "llvm/TargetParser/ARMTargetParserCommon.h"
58 #include "llvm/TargetParser/Host.h"
59 #include "llvm/TargetParser/LoongArchTargetParser.h"
60 #include "llvm/TargetParser/RISCVTargetParser.h"
61 #include <cctype>
63 using namespace clang::driver;
64 using namespace clang::driver::tools;
65 using namespace clang;
66 using namespace llvm::opt;
68 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
69 if (Arg *A = Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC,
70 options::OPT_fminimize_whitespace,
71 options::OPT_fno_minimize_whitespace,
72 options::OPT_fkeep_system_includes,
73 options::OPT_fno_keep_system_includes)) {
74 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
75 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
76 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
77 << A->getBaseArg().getAsString(Args)
78 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
83 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
84 // In gcc, only ARM checks this, but it seems reasonable to check universally.
85 if (Args.hasArg(options::OPT_static))
86 if (const Arg *A =
87 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
88 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
89 << "-static";
92 // Add backslashes to escape spaces and other backslashes.
93 // This is used for the space-separated argument list specified with
94 // the -dwarf-debug-flags option.
95 static void EscapeSpacesAndBackslashes(const char *Arg,
96 SmallVectorImpl<char> &Res) {
97 for (; *Arg; ++Arg) {
98 switch (*Arg) {
99 default:
100 break;
101 case ' ':
102 case '\\':
103 Res.push_back('\\');
104 break;
106 Res.push_back(*Arg);
110 /// Apply \a Work on the current tool chain \a RegularToolChain and any other
111 /// offloading tool chain that is associated with the current action \a JA.
112 static void
113 forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
114 const ToolChain &RegularToolChain,
115 llvm::function_ref<void(const ToolChain &)> Work) {
116 // Apply Work on the current/regular tool chain.
117 Work(RegularToolChain);
119 // Apply Work on all the offloading tool chains associated with the current
120 // action.
121 if (JA.isHostOffloading(Action::OFK_Cuda))
122 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
123 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
124 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
125 else if (JA.isHostOffloading(Action::OFK_HIP))
126 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
127 else if (JA.isDeviceOffloading(Action::OFK_HIP))
128 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
130 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
131 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
132 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
133 Work(*II->second);
134 } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
135 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
138 // TODO: Add support for other offloading programming models here.
142 /// This is a helper function for validating the optional refinement step
143 /// parameter in reciprocal argument strings. Return false if there is an error
144 /// parsing the refinement step. Otherwise, return true and set the Position
145 /// of the refinement step in the input string.
146 static bool getRefinementStep(StringRef In, const Driver &D,
147 const Arg &A, size_t &Position) {
148 const char RefinementStepToken = ':';
149 Position = In.find(RefinementStepToken);
150 if (Position != StringRef::npos) {
151 StringRef Option = A.getOption().getName();
152 StringRef RefStep = In.substr(Position + 1);
153 // Allow exactly one numeric character for the additional refinement
154 // step parameter. This is reasonable for all currently-supported
155 // operations and architectures because we would expect that a larger value
156 // of refinement steps would cause the estimate "optimization" to
157 // under-perform the native operation. Also, if the estimate does not
158 // converge quickly, it probably will not ever converge, so further
159 // refinement steps will not produce a better answer.
160 if (RefStep.size() != 1) {
161 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
162 return false;
164 char RefStepChar = RefStep[0];
165 if (RefStepChar < '0' || RefStepChar > '9') {
166 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
167 return false;
170 return true;
173 /// The -mrecip flag requires processing of many optional parameters.
174 static void ParseMRecip(const Driver &D, const ArgList &Args,
175 ArgStringList &OutStrings) {
176 StringRef DisabledPrefixIn = "!";
177 StringRef DisabledPrefixOut = "!";
178 StringRef EnabledPrefixOut = "";
179 StringRef Out = "-mrecip=";
181 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
182 if (!A)
183 return;
185 unsigned NumOptions = A->getNumValues();
186 if (NumOptions == 0) {
187 // No option is the same as "all".
188 OutStrings.push_back(Args.MakeArgString(Out + "all"));
189 return;
192 // Pass through "all", "none", or "default" with an optional refinement step.
193 if (NumOptions == 1) {
194 StringRef Val = A->getValue(0);
195 size_t RefStepLoc;
196 if (!getRefinementStep(Val, D, *A, RefStepLoc))
197 return;
198 StringRef ValBase = Val.slice(0, RefStepLoc);
199 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
200 OutStrings.push_back(Args.MakeArgString(Out + Val));
201 return;
205 // Each reciprocal type may be enabled or disabled individually.
206 // Check each input value for validity, concatenate them all back together,
207 // and pass through.
209 llvm::StringMap<bool> OptionStrings;
210 OptionStrings.insert(std::make_pair("divd", false));
211 OptionStrings.insert(std::make_pair("divf", false));
212 OptionStrings.insert(std::make_pair("divh", false));
213 OptionStrings.insert(std::make_pair("vec-divd", false));
214 OptionStrings.insert(std::make_pair("vec-divf", false));
215 OptionStrings.insert(std::make_pair("vec-divh", false));
216 OptionStrings.insert(std::make_pair("sqrtd", false));
217 OptionStrings.insert(std::make_pair("sqrtf", false));
218 OptionStrings.insert(std::make_pair("sqrth", false));
219 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
220 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
221 OptionStrings.insert(std::make_pair("vec-sqrth", false));
223 for (unsigned i = 0; i != NumOptions; ++i) {
224 StringRef Val = A->getValue(i);
226 bool IsDisabled = Val.startswith(DisabledPrefixIn);
227 // Ignore the disablement token for string matching.
228 if (IsDisabled)
229 Val = Val.substr(1);
231 size_t RefStep;
232 if (!getRefinementStep(Val, D, *A, RefStep))
233 return;
235 StringRef ValBase = Val.slice(0, RefStep);
236 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
237 if (OptionIter == OptionStrings.end()) {
238 // Try again specifying float suffix.
239 OptionIter = OptionStrings.find(ValBase.str() + 'f');
240 if (OptionIter == OptionStrings.end()) {
241 // The input name did not match any known option string.
242 D.Diag(diag::err_drv_unknown_argument) << Val;
243 return;
245 // The option was specified without a half or float or double suffix.
246 // Make sure that the double or half entry was not already specified.
247 // The float entry will be checked below.
248 if (OptionStrings[ValBase.str() + 'd'] ||
249 OptionStrings[ValBase.str() + 'h']) {
250 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
251 return;
255 if (OptionIter->second == true) {
256 // Duplicate option specified.
257 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
258 return;
261 // Mark the matched option as found. Do not allow duplicate specifiers.
262 OptionIter->second = true;
264 // If the precision was not specified, also mark the double and half entry
265 // as found.
266 if (ValBase.back() != 'f' && ValBase.back() != 'd' && ValBase.back() != 'h') {
267 OptionStrings[ValBase.str() + 'd'] = true;
268 OptionStrings[ValBase.str() + 'h'] = true;
271 // Build the output string.
272 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
273 Out = Args.MakeArgString(Out + Prefix + Val);
274 if (i != NumOptions - 1)
275 Out = Args.MakeArgString(Out + ",");
278 OutStrings.push_back(Args.MakeArgString(Out));
281 /// The -mprefer-vector-width option accepts either a positive integer
282 /// or the string "none".
283 static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
284 ArgStringList &CmdArgs) {
285 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
286 if (!A)
287 return;
289 StringRef Value = A->getValue();
290 if (Value == "none") {
291 CmdArgs.push_back("-mprefer-vector-width=none");
292 } else {
293 unsigned Width;
294 if (Value.getAsInteger(10, Width)) {
295 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
296 return;
298 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
302 static bool
303 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
304 const llvm::Triple &Triple) {
305 // We use the zero-cost exception tables for Objective-C if the non-fragile
306 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
307 // later.
308 if (runtime.isNonFragile())
309 return true;
311 if (!Triple.isMacOSX())
312 return false;
314 return (!Triple.isMacOSXVersionLT(10, 5) &&
315 (Triple.getArch() == llvm::Triple::x86_64 ||
316 Triple.getArch() == llvm::Triple::arm));
319 /// Adds exception related arguments to the driver command arguments. There's a
320 /// main flag, -fexceptions and also language specific flags to enable/disable
321 /// C++ and Objective-C exceptions. This makes it possible to for example
322 /// disable C++ exceptions but enable Objective-C exceptions.
323 static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
324 const ToolChain &TC, bool KernelOrKext,
325 const ObjCRuntime &objcRuntime,
326 ArgStringList &CmdArgs) {
327 const llvm::Triple &Triple = TC.getTriple();
329 if (KernelOrKext) {
330 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
331 // arguments now to avoid warnings about unused arguments.
332 Args.ClaimAllArgs(options::OPT_fexceptions);
333 Args.ClaimAllArgs(options::OPT_fno_exceptions);
334 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
335 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
336 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
337 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
338 Args.ClaimAllArgs(options::OPT_fasync_exceptions);
339 Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
340 return false;
343 // See if the user explicitly enabled exceptions.
344 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
345 false);
347 bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
348 options::OPT_fno_async_exceptions, false);
349 if (EHa) {
350 CmdArgs.push_back("-fasync-exceptions");
351 EH = true;
354 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
355 // is not necessarily sensible, but follows GCC.
356 if (types::isObjC(InputType) &&
357 Args.hasFlag(options::OPT_fobjc_exceptions,
358 options::OPT_fno_objc_exceptions, true)) {
359 CmdArgs.push_back("-fobjc-exceptions");
361 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
364 if (types::isCXX(InputType)) {
365 // Disable C++ EH by default on XCore and PS4/PS5.
366 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
367 !Triple.isPS() && !Triple.isDriverKit();
368 Arg *ExceptionArg = Args.getLastArg(
369 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
370 options::OPT_fexceptions, options::OPT_fno_exceptions);
371 if (ExceptionArg)
372 CXXExceptionsEnabled =
373 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
374 ExceptionArg->getOption().matches(options::OPT_fexceptions);
376 if (CXXExceptionsEnabled) {
377 CmdArgs.push_back("-fcxx-exceptions");
379 EH = true;
383 // OPT_fignore_exceptions means exception could still be thrown,
384 // but no clean up or catch would happen in current module.
385 // So we do not set EH to false.
386 Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
388 if (EH)
389 CmdArgs.push_back("-fexceptions");
390 return EH;
393 static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
394 const JobAction &JA) {
395 bool Default = true;
396 if (TC.getTriple().isOSDarwin()) {
397 // The native darwin assembler doesn't support the linker_option directives,
398 // so we disable them if we think the .s file will be passed to it.
399 Default = TC.useIntegratedAs();
401 // The linker_option directives are intended for host compilation.
402 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
403 JA.isDeviceOffloading(Action::OFK_HIP))
404 Default = false;
405 return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
406 Default);
409 static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
410 switch (Triple.getArch()){
411 default:
412 return false;
413 case llvm::Triple::arm:
414 case llvm::Triple::thumb:
415 // ARM Darwin targets require a frame pointer to be always present to aid
416 // offline debugging via backtraces.
417 return Triple.isOSDarwin();
421 static bool useFramePointerForTargetByDefault(const ArgList &Args,
422 const llvm::Triple &Triple) {
423 if (Args.hasArg(options::OPT_pg) && !Args.hasArg(options::OPT_mfentry))
424 return true;
426 if (Triple.isAndroid()) {
427 switch (Triple.getArch()) {
428 case llvm::Triple::aarch64:
429 case llvm::Triple::arm:
430 case llvm::Triple::armeb:
431 case llvm::Triple::thumb:
432 case llvm::Triple::thumbeb:
433 case llvm::Triple::riscv64:
434 return true;
435 default:
436 break;
440 switch (Triple.getArch()) {
441 case llvm::Triple::xcore:
442 case llvm::Triple::wasm32:
443 case llvm::Triple::wasm64:
444 case llvm::Triple::msp430:
445 // XCore never wants frame pointers, regardless of OS.
446 // WebAssembly never wants frame pointers.
447 return false;
448 case llvm::Triple::ppc:
449 case llvm::Triple::ppcle:
450 case llvm::Triple::ppc64:
451 case llvm::Triple::ppc64le:
452 case llvm::Triple::riscv32:
453 case llvm::Triple::riscv64:
454 case llvm::Triple::sparc:
455 case llvm::Triple::sparcel:
456 case llvm::Triple::sparcv9:
457 case llvm::Triple::amdgcn:
458 case llvm::Triple::r600:
459 case llvm::Triple::csky:
460 case llvm::Triple::loongarch32:
461 case llvm::Triple::loongarch64:
462 return !areOptimizationsEnabled(Args);
463 default:
464 break;
467 if (Triple.isOSFuchsia() || Triple.isOSNetBSD()) {
468 return !areOptimizationsEnabled(Args);
471 if (Triple.isOSLinux() || Triple.isOSHurd()) {
472 switch (Triple.getArch()) {
473 // Don't use a frame pointer on linux if optimizing for certain targets.
474 case llvm::Triple::arm:
475 case llvm::Triple::armeb:
476 case llvm::Triple::thumb:
477 case llvm::Triple::thumbeb:
478 case llvm::Triple::mips64:
479 case llvm::Triple::mips64el:
480 case llvm::Triple::mips:
481 case llvm::Triple::mipsel:
482 case llvm::Triple::systemz:
483 case llvm::Triple::x86:
484 case llvm::Triple::x86_64:
485 return !areOptimizationsEnabled(Args);
486 default:
487 return true;
491 if (Triple.isOSWindows()) {
492 switch (Triple.getArch()) {
493 case llvm::Triple::x86:
494 return !areOptimizationsEnabled(Args);
495 case llvm::Triple::x86_64:
496 return Triple.isOSBinFormatMachO();
497 case llvm::Triple::arm:
498 case llvm::Triple::thumb:
499 // Windows on ARM builds with FPO disabled to aid fast stack walking
500 return true;
501 default:
502 // All other supported Windows ISAs use xdata unwind information, so frame
503 // pointers are not generally useful.
504 return false;
508 return true;
511 static CodeGenOptions::FramePointerKind
512 getFramePointerKind(const ArgList &Args, const llvm::Triple &Triple) {
513 // We have 4 states:
515 // 00) leaf retained, non-leaf retained
516 // 01) leaf retained, non-leaf omitted (this is invalid)
517 // 10) leaf omitted, non-leaf retained
518 // (what -momit-leaf-frame-pointer was designed for)
519 // 11) leaf omitted, non-leaf omitted
521 // "omit" options taking precedence over "no-omit" options is the only way
522 // to make 3 valid states representable
523 Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
524 options::OPT_fno_omit_frame_pointer);
525 bool OmitFP = A && A->getOption().matches(options::OPT_fomit_frame_pointer);
526 bool NoOmitFP =
527 A && A->getOption().matches(options::OPT_fno_omit_frame_pointer);
528 bool OmitLeafFP =
529 Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
530 options::OPT_mno_omit_leaf_frame_pointer,
531 Triple.isAArch64() || Triple.isPS() || Triple.isVE() ||
532 (Triple.isAndroid() && Triple.isRISCV64()));
533 if (NoOmitFP || mustUseNonLeafFramePointerForTarget(Triple) ||
534 (!OmitFP && useFramePointerForTargetByDefault(Args, Triple))) {
535 if (OmitLeafFP)
536 return CodeGenOptions::FramePointerKind::NonLeaf;
537 return CodeGenOptions::FramePointerKind::All;
539 return CodeGenOptions::FramePointerKind::None;
542 /// Add a CC1 option to specify the debug compilation directory.
543 static const char *addDebugCompDirArg(const ArgList &Args,
544 ArgStringList &CmdArgs,
545 const llvm::vfs::FileSystem &VFS) {
546 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
547 options::OPT_fdebug_compilation_dir_EQ)) {
548 if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
549 CmdArgs.push_back(Args.MakeArgString(Twine("-fdebug-compilation-dir=") +
550 A->getValue()));
551 else
552 A->render(Args, CmdArgs);
553 } else if (llvm::ErrorOr<std::string> CWD =
554 VFS.getCurrentWorkingDirectory()) {
555 CmdArgs.push_back(Args.MakeArgString("-fdebug-compilation-dir=" + *CWD));
557 StringRef Path(CmdArgs.back());
558 return Path.substr(Path.find('=') + 1).data();
561 static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
562 const char *DebugCompilationDir,
563 const char *OutputFileName) {
564 // No need to generate a value for -object-file-name if it was provided.
565 for (auto *Arg : Args.filtered(options::OPT_Xclang))
566 if (StringRef(Arg->getValue()).startswith("-object-file-name"))
567 return;
569 if (Args.hasArg(options::OPT_object_file_name_EQ))
570 return;
572 SmallString<128> ObjFileNameForDebug(OutputFileName);
573 if (ObjFileNameForDebug != "-" &&
574 !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
575 (!DebugCompilationDir ||
576 llvm::sys::path::is_absolute(DebugCompilationDir))) {
577 // Make the path absolute in the debug infos like MSVC does.
578 llvm::sys::fs::make_absolute(ObjFileNameForDebug);
580 // If the object file name is a relative path, then always use Windows
581 // backslash style as -object-file-name is used for embedding object file path
582 // in codeview and it can only be generated when targeting on Windows.
583 // Otherwise, just use native absolute path.
584 llvm::sys::path::Style Style =
585 llvm::sys::path::is_absolute(ObjFileNameForDebug)
586 ? llvm::sys::path::Style::native
587 : llvm::sys::path::Style::windows_backslash;
588 llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
589 Style);
590 CmdArgs.push_back(
591 Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
594 /// Add a CC1 and CC1AS option to specify the debug file path prefix map.
595 static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
596 const ArgList &Args, ArgStringList &CmdArgs) {
597 auto AddOneArg = [&](StringRef Map, StringRef Name) {
598 if (!Map.contains('='))
599 D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
600 else
601 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
604 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
605 options::OPT_fdebug_prefix_map_EQ)) {
606 AddOneArg(A->getValue(), A->getOption().getName());
607 A->claim();
609 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
610 if (GlobalRemapEntry.empty())
611 return;
612 AddOneArg(GlobalRemapEntry, "environment");
615 /// Add a CC1 and CC1AS option to specify the macro file path prefix map.
616 static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
617 ArgStringList &CmdArgs) {
618 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
619 options::OPT_fmacro_prefix_map_EQ)) {
620 StringRef Map = A->getValue();
621 if (!Map.contains('='))
622 D.Diag(diag::err_drv_invalid_argument_to_option)
623 << Map << A->getOption().getName();
624 else
625 CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
626 A->claim();
630 /// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
631 static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
632 ArgStringList &CmdArgs) {
633 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
634 options::OPT_fcoverage_prefix_map_EQ)) {
635 StringRef Map = A->getValue();
636 if (!Map.contains('='))
637 D.Diag(diag::err_drv_invalid_argument_to_option)
638 << Map << A->getOption().getName();
639 else
640 CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
641 A->claim();
645 /// Vectorize at all optimization levels greater than 1 except for -Oz.
646 /// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
647 /// enabled.
648 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
649 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
650 if (A->getOption().matches(options::OPT_O4) ||
651 A->getOption().matches(options::OPT_Ofast))
652 return true;
654 if (A->getOption().matches(options::OPT_O0))
655 return false;
657 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
659 // Vectorize -Os.
660 StringRef S(A->getValue());
661 if (S == "s")
662 return true;
664 // Don't vectorize -Oz, unless it's the slp vectorizer.
665 if (S == "z")
666 return isSlpVec;
668 unsigned OptLevel = 0;
669 if (S.getAsInteger(10, OptLevel))
670 return false;
672 return OptLevel > 1;
675 return false;
678 /// Add -x lang to \p CmdArgs for \p Input.
679 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
680 ArgStringList &CmdArgs) {
681 // When using -verify-pch, we don't want to provide the type
682 // 'precompiled-header' if it was inferred from the file extension
683 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
684 return;
686 CmdArgs.push_back("-x");
687 if (Args.hasArg(options::OPT_rewrite_objc))
688 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
689 else {
690 // Map the driver type to the frontend type. This is mostly an identity
691 // mapping, except that the distinction between module interface units
692 // and other source files does not exist at the frontend layer.
693 const char *ClangType;
694 switch (Input.getType()) {
695 case types::TY_CXXModule:
696 ClangType = "c++";
697 break;
698 case types::TY_PP_CXXModule:
699 ClangType = "c++-cpp-output";
700 break;
701 default:
702 ClangType = types::getTypeName(Input.getType());
703 break;
705 CmdArgs.push_back(ClangType);
709 static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
710 const JobAction &JA, const InputInfo &Output,
711 const ArgList &Args, SanitizerArgs &SanArgs,
712 ArgStringList &CmdArgs) {
713 const Driver &D = TC.getDriver();
714 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
715 options::OPT_fprofile_generate_EQ,
716 options::OPT_fno_profile_generate);
717 if (PGOGenerateArg &&
718 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
719 PGOGenerateArg = nullptr;
721 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
723 auto *ProfileGenerateArg = Args.getLastArg(
724 options::OPT_fprofile_instr_generate,
725 options::OPT_fprofile_instr_generate_EQ,
726 options::OPT_fno_profile_instr_generate);
727 if (ProfileGenerateArg &&
728 ProfileGenerateArg->getOption().matches(
729 options::OPT_fno_profile_instr_generate))
730 ProfileGenerateArg = nullptr;
732 if (PGOGenerateArg && ProfileGenerateArg)
733 D.Diag(diag::err_drv_argument_not_allowed_with)
734 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
736 auto *ProfileUseArg = getLastProfileUseArg(Args);
738 if (PGOGenerateArg && ProfileUseArg)
739 D.Diag(diag::err_drv_argument_not_allowed_with)
740 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
742 if (ProfileGenerateArg && ProfileUseArg)
743 D.Diag(diag::err_drv_argument_not_allowed_with)
744 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
746 if (CSPGOGenerateArg && PGOGenerateArg) {
747 D.Diag(diag::err_drv_argument_not_allowed_with)
748 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
749 PGOGenerateArg = nullptr;
752 if (TC.getTriple().isOSAIX()) {
753 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
754 D.Diag(diag::err_drv_unsupported_opt_for_target)
755 << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
758 if (ProfileGenerateArg) {
759 if (ProfileGenerateArg->getOption().matches(
760 options::OPT_fprofile_instr_generate_EQ))
761 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
762 ProfileGenerateArg->getValue()));
763 // The default is to use Clang Instrumentation.
764 CmdArgs.push_back("-fprofile-instrument=clang");
765 if (TC.getTriple().isWindowsMSVCEnvironment()) {
766 // Add dependent lib for clang_rt.profile
767 CmdArgs.push_back(Args.MakeArgString(
768 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
772 Arg *PGOGenArg = nullptr;
773 if (PGOGenerateArg) {
774 assert(!CSPGOGenerateArg);
775 PGOGenArg = PGOGenerateArg;
776 CmdArgs.push_back("-fprofile-instrument=llvm");
778 if (CSPGOGenerateArg) {
779 assert(!PGOGenerateArg);
780 PGOGenArg = CSPGOGenerateArg;
781 CmdArgs.push_back("-fprofile-instrument=csllvm");
783 if (PGOGenArg) {
784 if (TC.getTriple().isWindowsMSVCEnvironment()) {
785 // Add dependent lib for clang_rt.profile
786 CmdArgs.push_back(Args.MakeArgString(
787 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
789 if (PGOGenArg->getOption().matches(
790 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
791 : options::OPT_fcs_profile_generate_EQ)) {
792 SmallString<128> Path(PGOGenArg->getValue());
793 llvm::sys::path::append(Path, "default_%m.profraw");
794 CmdArgs.push_back(
795 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
799 if (ProfileUseArg) {
800 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
801 CmdArgs.push_back(Args.MakeArgString(
802 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
803 else if ((ProfileUseArg->getOption().matches(
804 options::OPT_fprofile_use_EQ) ||
805 ProfileUseArg->getOption().matches(
806 options::OPT_fprofile_instr_use))) {
807 SmallString<128> Path(
808 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
809 if (Path.empty() || llvm::sys::fs::is_directory(Path))
810 llvm::sys::path::append(Path, "default.profdata");
811 CmdArgs.push_back(
812 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
816 bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
817 options::OPT_fno_test_coverage, false) ||
818 Args.hasArg(options::OPT_coverage);
819 bool EmitCovData = TC.needsGCovInstrumentation(Args);
821 if (Args.hasFlag(options::OPT_fcoverage_mapping,
822 options::OPT_fno_coverage_mapping, false)) {
823 if (!ProfileGenerateArg)
824 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
825 << "-fcoverage-mapping"
826 << "-fprofile-instr-generate";
828 CmdArgs.push_back("-fcoverage-mapping");
831 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
832 options::OPT_fcoverage_compilation_dir_EQ)) {
833 if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
834 CmdArgs.push_back(Args.MakeArgString(
835 Twine("-fcoverage-compilation-dir=") + A->getValue()));
836 else
837 A->render(Args, CmdArgs);
838 } else if (llvm::ErrorOr<std::string> CWD =
839 D.getVFS().getCurrentWorkingDirectory()) {
840 CmdArgs.push_back(Args.MakeArgString("-fcoverage-compilation-dir=" + *CWD));
843 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
844 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
845 if (!Args.hasArg(options::OPT_coverage))
846 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
847 << "-fprofile-exclude-files="
848 << "--coverage";
850 StringRef v = Arg->getValue();
851 CmdArgs.push_back(
852 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
855 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
856 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
857 if (!Args.hasArg(options::OPT_coverage))
858 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
859 << "-fprofile-filter-files="
860 << "--coverage";
862 StringRef v = Arg->getValue();
863 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
866 if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
867 StringRef Val = A->getValue();
868 if (Val == "atomic" || Val == "prefer-atomic")
869 CmdArgs.push_back("-fprofile-update=atomic");
870 else if (Val != "single")
871 D.Diag(diag::err_drv_unsupported_option_argument)
872 << A->getSpelling() << Val;
875 int FunctionGroups = 1;
876 int SelectedFunctionGroup = 0;
877 if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
878 StringRef Val = A->getValue();
879 if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
880 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
882 if (const auto *A =
883 Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
884 StringRef Val = A->getValue();
885 if (Val.getAsInteger(0, SelectedFunctionGroup) ||
886 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
887 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
889 if (FunctionGroups != 1)
890 CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
891 Twine(FunctionGroups)));
892 if (SelectedFunctionGroup != 0)
893 CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
894 Twine(SelectedFunctionGroup)));
896 // Leave -fprofile-dir= an unused argument unless .gcda emission is
897 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
898 // the flag used. There is no -fno-profile-dir, so the user has no
899 // targeted way to suppress the warning.
900 Arg *FProfileDir = nullptr;
901 if (Args.hasArg(options::OPT_fprofile_arcs) ||
902 Args.hasArg(options::OPT_coverage))
903 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
905 // TODO: Don't claim -c/-S to warn about -fsyntax-only -c/-S, -E -c/-S,
906 // like we warn about -fsyntax-only -E.
907 (void)(Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S));
909 // Put the .gcno and .gcda files (if needed) next to the primary output file,
910 // or fall back to a file in the current directory for `clang -c --coverage
911 // d/a.c` in the absence of -o.
912 if (EmitCovNotes || EmitCovData) {
913 SmallString<128> CoverageFilename;
914 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
915 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
916 // path separator.
917 CoverageFilename = DumpDir->getValue();
918 CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
919 } else if (Arg *FinalOutput =
920 C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
921 CoverageFilename = FinalOutput->getValue();
922 } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
923 CoverageFilename = FinalOutput->getValue();
924 } else {
925 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
927 if (llvm::sys::path::is_relative(CoverageFilename))
928 (void)D.getVFS().makeAbsolute(CoverageFilename);
929 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
930 if (EmitCovNotes) {
931 CmdArgs.push_back(
932 Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
935 if (EmitCovData) {
936 if (FProfileDir) {
937 SmallString<128> Gcno = std::move(CoverageFilename);
938 CoverageFilename = FProfileDir->getValue();
939 llvm::sys::path::append(CoverageFilename, Gcno);
941 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
942 CmdArgs.push_back(
943 Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
948 /// Check whether the given input tree contains any compilation actions.
949 static bool ContainsCompileAction(const Action *A) {
950 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
951 return true;
953 return llvm::any_of(A->inputs(), ContainsCompileAction);
956 /// Check if -relax-all should be passed to the internal assembler.
957 /// This is done by default when compiling non-assembler source with -O0.
958 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
959 bool RelaxDefault = true;
961 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
962 RelaxDefault = A->getOption().matches(options::OPT_O0);
964 if (RelaxDefault) {
965 RelaxDefault = false;
966 for (const auto &Act : C.getActions()) {
967 if (ContainsCompileAction(Act)) {
968 RelaxDefault = true;
969 break;
974 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
975 RelaxDefault);
978 static void
979 RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
980 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
981 unsigned DwarfVersion,
982 llvm::DebuggerKind DebuggerTuning) {
983 addDebugInfoKind(CmdArgs, DebugInfoKind);
984 if (DwarfVersion > 0)
985 CmdArgs.push_back(
986 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
987 switch (DebuggerTuning) {
988 case llvm::DebuggerKind::GDB:
989 CmdArgs.push_back("-debugger-tuning=gdb");
990 break;
991 case llvm::DebuggerKind::LLDB:
992 CmdArgs.push_back("-debugger-tuning=lldb");
993 break;
994 case llvm::DebuggerKind::SCE:
995 CmdArgs.push_back("-debugger-tuning=sce");
996 break;
997 case llvm::DebuggerKind::DBX:
998 CmdArgs.push_back("-debugger-tuning=dbx");
999 break;
1000 default:
1001 break;
1005 static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
1006 const Driver &D, const ToolChain &TC) {
1007 assert(A && "Expected non-nullptr argument.");
1008 if (TC.supportsDebugInfoOption(A))
1009 return true;
1010 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
1011 << A->getAsString(Args) << TC.getTripleString();
1012 return false;
1015 static void RenderDebugInfoCompressionArgs(const ArgList &Args,
1016 ArgStringList &CmdArgs,
1017 const Driver &D,
1018 const ToolChain &TC) {
1019 const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
1020 if (!A)
1021 return;
1022 if (checkDebugInfoOption(A, Args, D, TC)) {
1023 StringRef Value = A->getValue();
1024 if (Value == "none") {
1025 CmdArgs.push_back("--compress-debug-sections=none");
1026 } else if (Value == "zlib") {
1027 if (llvm::compression::zlib::isAvailable()) {
1028 CmdArgs.push_back(
1029 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
1030 } else {
1031 D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
1033 } else if (Value == "zstd") {
1034 if (llvm::compression::zstd::isAvailable()) {
1035 CmdArgs.push_back(
1036 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
1037 } else {
1038 D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
1040 } else {
1041 D.Diag(diag::err_drv_unsupported_option_argument)
1042 << A->getSpelling() << Value;
1047 static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
1048 const ArgList &Args,
1049 ArgStringList &CmdArgs,
1050 bool IsCC1As = false) {
1051 // If no version was requested by the user, use the default value from the
1052 // back end. This is consistent with the value returned from
1053 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
1054 // requiring the corresponding llvm to have the AMDGPU target enabled,
1055 // provided the user (e.g. front end tests) can use the default.
1056 if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
1057 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
1058 CmdArgs.insert(CmdArgs.begin() + 1,
1059 Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
1060 Twine(CodeObjVer)));
1061 CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
1062 // -cc1as does not accept -mcode-object-version option.
1063 if (!IsCC1As)
1064 CmdArgs.insert(CmdArgs.begin() + 1,
1065 Args.MakeArgString(Twine("-mcode-object-version=") +
1066 Twine(CodeObjVer)));
1070 static bool hasClangPchSignature(const Driver &D, StringRef Path) {
1071 if (llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
1072 D.getVFS().getBufferForFile(Path))
1073 return (*MemBuf)->getBuffer().startswith("CPCH");
1074 return false;
1077 static bool gchProbe(const Driver &D, StringRef Path) {
1078 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
1079 if (!Status)
1080 return false;
1082 if (Status->isDirectory()) {
1083 std::error_code EC;
1084 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
1085 !EC && DI != DE; DI = DI.increment(EC)) {
1086 if (hasClangPchSignature(D, DI->path()))
1087 return true;
1089 D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
1090 return false;
1093 if (hasClangPchSignature(D, Path))
1094 return true;
1095 D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
1096 return false;
1099 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1100 const Driver &D, const ArgList &Args,
1101 ArgStringList &CmdArgs,
1102 const InputInfo &Output,
1103 const InputInfoList &Inputs) const {
1104 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1106 CheckPreprocessingOptions(D, Args);
1108 Args.AddLastArg(CmdArgs, options::OPT_C);
1109 Args.AddLastArg(CmdArgs, options::OPT_CC);
1111 // Handle dependency file generation.
1112 Arg *ArgM = Args.getLastArg(options::OPT_MM);
1113 if (!ArgM)
1114 ArgM = Args.getLastArg(options::OPT_M);
1115 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
1116 if (!ArgMD)
1117 ArgMD = Args.getLastArg(options::OPT_MD);
1119 // -M and -MM imply -w.
1120 if (ArgM)
1121 CmdArgs.push_back("-w");
1122 else
1123 ArgM = ArgMD;
1125 if (ArgM) {
1126 // Determine the output location.
1127 const char *DepFile;
1128 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1129 DepFile = MF->getValue();
1130 C.addFailureResultFile(DepFile, &JA);
1131 } else if (Output.getType() == types::TY_Dependencies) {
1132 DepFile = Output.getFilename();
1133 } else if (!ArgMD) {
1134 DepFile = "-";
1135 } else {
1136 DepFile = getDependencyFileName(Args, Inputs);
1137 C.addFailureResultFile(DepFile, &JA);
1139 CmdArgs.push_back("-dependency-file");
1140 CmdArgs.push_back(DepFile);
1142 bool HasTarget = false;
1143 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1144 HasTarget = true;
1145 A->claim();
1146 if (A->getOption().matches(options::OPT_MT)) {
1147 A->render(Args, CmdArgs);
1148 } else {
1149 CmdArgs.push_back("-MT");
1150 SmallString<128> Quoted;
1151 quoteMakeTarget(A->getValue(), Quoted);
1152 CmdArgs.push_back(Args.MakeArgString(Quoted));
1156 // Add a default target if one wasn't specified.
1157 if (!HasTarget) {
1158 const char *DepTarget;
1160 // If user provided -o, that is the dependency target, except
1161 // when we are only generating a dependency file.
1162 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1163 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1164 DepTarget = OutputOpt->getValue();
1165 } else {
1166 // Otherwise derive from the base input.
1168 // FIXME: This should use the computed output file location.
1169 SmallString<128> P(Inputs[0].getBaseInput());
1170 llvm::sys::path::replace_extension(P, "o");
1171 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1174 CmdArgs.push_back("-MT");
1175 SmallString<128> Quoted;
1176 quoteMakeTarget(DepTarget, Quoted);
1177 CmdArgs.push_back(Args.MakeArgString(Quoted));
1180 if (ArgM->getOption().matches(options::OPT_M) ||
1181 ArgM->getOption().matches(options::OPT_MD))
1182 CmdArgs.push_back("-sys-header-deps");
1183 if (Args.hasFlag(options::OPT_canonical_prefixes,
1184 options::OPT_no_canonical_prefixes, true))
1185 CmdArgs.push_back("-canonical-system-headers");
1186 if ((isa<PrecompileJobAction>(JA) &&
1187 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1188 Args.hasArg(options::OPT_fmodule_file_deps))
1189 CmdArgs.push_back("-module-file-deps");
1192 if (Args.hasArg(options::OPT_MG)) {
1193 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1194 ArgM->getOption().matches(options::OPT_MMD))
1195 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1196 CmdArgs.push_back("-MG");
1199 Args.AddLastArg(CmdArgs, options::OPT_MP);
1200 Args.AddLastArg(CmdArgs, options::OPT_MV);
1202 // Add offload include arguments specific for CUDA/HIP. This must happen
1203 // before we -I or -include anything else, because we must pick up the
1204 // CUDA/HIP headers from the particular CUDA/ROCm installation, rather than
1205 // from e.g. /usr/local/include.
1206 if (JA.isOffloading(Action::OFK_Cuda))
1207 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1208 if (JA.isOffloading(Action::OFK_HIP))
1209 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
1211 // If we are compiling for a GPU target we want to override the system headers
1212 // with ones created by the 'libc' project if present.
1213 if (!Args.hasArg(options::OPT_nostdinc) &&
1214 !Args.hasArg(options::OPT_nogpuinc) &&
1215 !Args.hasArg(options::OPT_nobuiltininc)) {
1216 // Without an offloading language we will include these headers directly.
1217 // Offloading languages will instead only use the declarations stored in
1218 // the resource directory at clang/lib/Headers/llvm_libc_wrappers.
1219 if ((getToolChain().getTriple().isNVPTX() ||
1220 getToolChain().getTriple().isAMDGCN()) &&
1221 C.getActiveOffloadKinds() == Action::OFK_None) {
1222 SmallString<128> P(llvm::sys::path::parent_path(D.InstalledDir));
1223 llvm::sys::path::append(P, "include");
1224 llvm::sys::path::append(P, "gpu-none-llvm");
1225 CmdArgs.push_back("-c-isystem");
1226 CmdArgs.push_back(Args.MakeArgString(P));
1227 } else if (C.getActiveOffloadKinds() == Action::OFK_OpenMP) {
1228 // TODO: CUDA / HIP include their own headers for some common functions
1229 // implemented here. We'll need to clean those up so they do not conflict.
1230 SmallString<128> P(D.ResourceDir);
1231 llvm::sys::path::append(P, "include");
1232 llvm::sys::path::append(P, "llvm_libc_wrappers");
1233 CmdArgs.push_back("-internal-isystem");
1234 CmdArgs.push_back(Args.MakeArgString(P));
1238 // If we are offloading to a target via OpenMP we need to include the
1239 // openmp_wrappers folder which contains alternative system headers.
1240 if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
1241 !Args.hasArg(options::OPT_nostdinc) &&
1242 !Args.hasArg(options::OPT_nogpuinc) &&
1243 (getToolChain().getTriple().isNVPTX() ||
1244 getToolChain().getTriple().isAMDGCN())) {
1245 if (!Args.hasArg(options::OPT_nobuiltininc)) {
1246 // Add openmp_wrappers/* to our system include path. This lets us wrap
1247 // standard library headers.
1248 SmallString<128> P(D.ResourceDir);
1249 llvm::sys::path::append(P, "include");
1250 llvm::sys::path::append(P, "openmp_wrappers");
1251 CmdArgs.push_back("-internal-isystem");
1252 CmdArgs.push_back(Args.MakeArgString(P));
1255 CmdArgs.push_back("-include");
1256 CmdArgs.push_back("__clang_openmp_device_functions.h");
1259 // Add -i* options, and automatically translate to
1260 // -include-pch/-include-pth for transparent PCH support. It's
1261 // wonky, but we include looking for .gch so we can support seamless
1262 // replacement into a build system already set up to be generating
1263 // .gch files.
1265 if (getToolChain().getDriver().IsCLMode()) {
1266 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1267 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1268 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1269 JA.getKind() <= Action::AssembleJobClass) {
1270 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1271 // -fpch-instantiate-templates is the default when creating
1272 // precomp using /Yc
1273 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1274 options::OPT_fno_pch_instantiate_templates, true))
1275 CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1277 if (YcArg || YuArg) {
1278 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1279 if (!isa<PrecompileJobAction>(JA)) {
1280 CmdArgs.push_back("-include-pch");
1281 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1282 C, !ThroughHeader.empty()
1283 ? ThroughHeader
1284 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1287 if (ThroughHeader.empty()) {
1288 CmdArgs.push_back(Args.MakeArgString(
1289 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1290 } else {
1291 CmdArgs.push_back(
1292 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1297 bool RenderedImplicitInclude = false;
1298 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1299 if (A->getOption().matches(options::OPT_include) &&
1300 D.getProbePrecompiled()) {
1301 // Handling of gcc-style gch precompiled headers.
1302 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1303 RenderedImplicitInclude = true;
1305 bool FoundPCH = false;
1306 SmallString<128> P(A->getValue());
1307 // We want the files to have a name like foo.h.pch. Add a dummy extension
1308 // so that replace_extension does the right thing.
1309 P += ".dummy";
1310 llvm::sys::path::replace_extension(P, "pch");
1311 if (D.getVFS().exists(P))
1312 FoundPCH = true;
1314 if (!FoundPCH) {
1315 // For GCC compat, probe for a file or directory ending in .gch instead.
1316 llvm::sys::path::replace_extension(P, "gch");
1317 FoundPCH = gchProbe(D, P.str());
1320 if (FoundPCH) {
1321 if (IsFirstImplicitInclude) {
1322 A->claim();
1323 CmdArgs.push_back("-include-pch");
1324 CmdArgs.push_back(Args.MakeArgString(P));
1325 continue;
1326 } else {
1327 // Ignore the PCH if not first on command line and emit warning.
1328 D.Diag(diag::warn_drv_pch_not_first_include) << P
1329 << A->getAsString(Args);
1332 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1333 // Handling of paths which must come late. These entries are handled by
1334 // the toolchain itself after the resource dir is inserted in the right
1335 // search order.
1336 // Do not claim the argument so that the use of the argument does not
1337 // silently go unnoticed on toolchains which do not honour the option.
1338 continue;
1339 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1340 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1341 continue;
1342 } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
1343 // This is used only by the driver. No need to pass to cc1.
1344 continue;
1347 // Not translated, render as usual.
1348 A->claim();
1349 A->render(Args, CmdArgs);
1352 Args.addAllArgs(CmdArgs,
1353 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1354 options::OPT_F, options::OPT_index_header_map});
1356 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1358 // FIXME: There is a very unfortunate problem here, some troubled
1359 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1360 // really support that we would have to parse and then translate
1361 // those options. :(
1362 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1363 options::OPT_Xpreprocessor);
1365 // -I- is a deprecated GCC feature, reject it.
1366 if (Arg *A = Args.getLastArg(options::OPT_I_))
1367 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1369 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1370 // -isysroot to the CC1 invocation.
1371 StringRef sysroot = C.getSysRoot();
1372 if (sysroot != "") {
1373 if (!Args.hasArg(options::OPT_isysroot)) {
1374 CmdArgs.push_back("-isysroot");
1375 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1379 // Parse additional include paths from environment variables.
1380 // FIXME: We should probably sink the logic for handling these from the
1381 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1382 // CPATH - included following the user specified includes (but prior to
1383 // builtin and standard includes).
1384 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1385 // C_INCLUDE_PATH - system includes enabled when compiling C.
1386 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1387 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1388 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1389 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1390 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1391 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1392 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1394 // While adding the include arguments, we also attempt to retrieve the
1395 // arguments of related offloading toolchains or arguments that are specific
1396 // of an offloading programming model.
1398 // Add C++ include arguments, if needed.
1399 if (types::isCXX(Inputs[0].getType())) {
1400 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1401 forAllAssociatedToolChains(
1402 C, JA, getToolChain(),
1403 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1404 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1405 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1409 // Add system include arguments for all targets but IAMCU.
1410 if (!IsIAMCU)
1411 forAllAssociatedToolChains(C, JA, getToolChain(),
1412 [&Args, &CmdArgs](const ToolChain &TC) {
1413 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1415 else {
1416 // For IAMCU add special include arguments.
1417 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1420 addMacroPrefixMapArg(D, Args, CmdArgs);
1421 addCoveragePrefixMapArg(D, Args, CmdArgs);
1423 Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1424 options::OPT_fno_file_reproducible);
1426 if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1427 CmdArgs.push_back("-source-date-epoch");
1428 CmdArgs.push_back(Args.MakeArgString(Epoch));
1432 // FIXME: Move to target hook.
1433 static bool isSignedCharDefault(const llvm::Triple &Triple) {
1434 switch (Triple.getArch()) {
1435 default:
1436 return true;
1438 case llvm::Triple::aarch64:
1439 case llvm::Triple::aarch64_32:
1440 case llvm::Triple::aarch64_be:
1441 case llvm::Triple::arm:
1442 case llvm::Triple::armeb:
1443 case llvm::Triple::thumb:
1444 case llvm::Triple::thumbeb:
1445 if (Triple.isOSDarwin() || Triple.isOSWindows())
1446 return true;
1447 return false;
1449 case llvm::Triple::ppc:
1450 case llvm::Triple::ppc64:
1451 if (Triple.isOSDarwin())
1452 return true;
1453 return false;
1455 case llvm::Triple::hexagon:
1456 case llvm::Triple::ppcle:
1457 case llvm::Triple::ppc64le:
1458 case llvm::Triple::riscv32:
1459 case llvm::Triple::riscv64:
1460 case llvm::Triple::systemz:
1461 case llvm::Triple::xcore:
1462 return false;
1466 static bool hasMultipleInvocations(const llvm::Triple &Triple,
1467 const ArgList &Args) {
1468 // Supported only on Darwin where we invoke the compiler multiple times
1469 // followed by an invocation to lipo.
1470 if (!Triple.isOSDarwin())
1471 return false;
1472 // If more than one "-arch <arch>" is specified, we're targeting multiple
1473 // architectures resulting in a fat binary.
1474 return Args.getAllArgValues(options::OPT_arch).size() > 1;
1477 static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1478 const llvm::Triple &Triple) {
1479 // When enabling remarks, we need to error if:
1480 // * The remark file is specified but we're targeting multiple architectures,
1481 // which means more than one remark file is being generated.
1482 bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1483 bool hasExplicitOutputFile =
1484 Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1485 if (hasMultipleInvocations && hasExplicitOutputFile) {
1486 D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1487 << "-foptimization-record-file";
1488 return false;
1490 return true;
1493 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1494 const llvm::Triple &Triple,
1495 const InputInfo &Input,
1496 const InputInfo &Output, const JobAction &JA) {
1497 StringRef Format = "yaml";
1498 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1499 Format = A->getValue();
1501 CmdArgs.push_back("-opt-record-file");
1503 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1504 if (A) {
1505 CmdArgs.push_back(A->getValue());
1506 } else {
1507 bool hasMultipleArchs =
1508 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1509 Args.getAllArgValues(options::OPT_arch).size() > 1;
1511 SmallString<128> F;
1513 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1514 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1515 F = FinalOutput->getValue();
1516 } else {
1517 if (Format != "yaml" && // For YAML, keep the original behavior.
1518 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1519 Output.isFilename())
1520 F = Output.getFilename();
1523 if (F.empty()) {
1524 // Use the input filename.
1525 F = llvm::sys::path::stem(Input.getBaseInput());
1527 // If we're compiling for an offload architecture (i.e. a CUDA device),
1528 // we need to make the file name for the device compilation different
1529 // from the host compilation.
1530 if (!JA.isDeviceOffloading(Action::OFK_None) &&
1531 !JA.isDeviceOffloading(Action::OFK_Host)) {
1532 llvm::sys::path::replace_extension(F, "");
1533 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
1534 Triple.normalize());
1535 F += "-";
1536 F += JA.getOffloadingArch();
1540 // If we're having more than one "-arch", we should name the files
1541 // differently so that every cc1 invocation writes to a different file.
1542 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1543 // name from the triple.
1544 if (hasMultipleArchs) {
1545 // First, remember the extension.
1546 SmallString<64> OldExtension = llvm::sys::path::extension(F);
1547 // then, remove it.
1548 llvm::sys::path::replace_extension(F, "");
1549 // attach -<arch> to it.
1550 F += "-";
1551 F += Triple.getArchName();
1552 // put back the extension.
1553 llvm::sys::path::replace_extension(F, OldExtension);
1556 SmallString<32> Extension;
1557 Extension += "opt.";
1558 Extension += Format;
1560 llvm::sys::path::replace_extension(F, Extension);
1561 CmdArgs.push_back(Args.MakeArgString(F));
1564 if (const Arg *A =
1565 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1566 CmdArgs.push_back("-opt-record-passes");
1567 CmdArgs.push_back(A->getValue());
1570 if (!Format.empty()) {
1571 CmdArgs.push_back("-opt-record-format");
1572 CmdArgs.push_back(Format.data());
1576 void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1577 if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1578 options::OPT_fno_aapcs_bitfield_width, true))
1579 CmdArgs.push_back("-fno-aapcs-bitfield-width");
1581 if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1582 CmdArgs.push_back("-faapcs-bitfield-load");
1585 namespace {
1586 void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1587 const ArgList &Args, ArgStringList &CmdArgs) {
1588 // Select the ABI to use.
1589 // FIXME: Support -meabi.
1590 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1591 const char *ABIName = nullptr;
1592 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1593 ABIName = A->getValue();
1594 } else {
1595 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
1596 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1599 CmdArgs.push_back("-target-abi");
1600 CmdArgs.push_back(ABIName);
1603 void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1604 auto StrictAlignIter =
1605 llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
1606 return Arg == "+strict-align" || Arg == "-strict-align";
1608 if (StrictAlignIter != CmdArgs.rend() &&
1609 StringRef(*StrictAlignIter) == "+strict-align")
1610 CmdArgs.push_back("-Wunaligned-access");
1614 static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1615 ArgStringList &CmdArgs, bool isAArch64) {
1616 const Arg *A = isAArch64
1617 ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1618 options::OPT_mbranch_protection_EQ)
1619 : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1620 if (!A)
1621 return;
1623 const Driver &D = TC.getDriver();
1624 const llvm::Triple &Triple = TC.getEffectiveTriple();
1625 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1626 D.Diag(diag::warn_incompatible_branch_protection_option)
1627 << Triple.getArchName();
1629 StringRef Scope, Key;
1630 bool IndirectBranches;
1632 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1633 Scope = A->getValue();
1634 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1635 D.Diag(diag::err_drv_unsupported_option_argument)
1636 << A->getSpelling() << Scope;
1637 Key = "a_key";
1638 IndirectBranches = false;
1639 } else {
1640 StringRef DiagMsg;
1641 llvm::ARM::ParsedBranchProtection PBP;
1642 if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg))
1643 D.Diag(diag::err_drv_unsupported_option_argument)
1644 << A->getSpelling() << DiagMsg;
1645 if (!isAArch64 && PBP.Key == "b_key")
1646 D.Diag(diag::warn_unsupported_branch_protection)
1647 << "b-key" << A->getAsString(Args);
1648 Scope = PBP.Scope;
1649 Key = PBP.Key;
1650 IndirectBranches = PBP.BranchTargetEnforcement;
1653 CmdArgs.push_back(
1654 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1655 if (!Scope.equals("none"))
1656 CmdArgs.push_back(
1657 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1658 if (IndirectBranches)
1659 CmdArgs.push_back("-mbranch-target-enforce");
1662 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1663 ArgStringList &CmdArgs, bool KernelOrKext) const {
1664 RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1666 // Determine floating point ABI from the options & target defaults.
1667 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1668 if (ABI == arm::FloatABI::Soft) {
1669 // Floating point operations and argument passing are soft.
1670 // FIXME: This changes CPP defines, we need -target-soft-float.
1671 CmdArgs.push_back("-msoft-float");
1672 CmdArgs.push_back("-mfloat-abi");
1673 CmdArgs.push_back("soft");
1674 } else if (ABI == arm::FloatABI::SoftFP) {
1675 // Floating point operations are hard, but argument passing is soft.
1676 CmdArgs.push_back("-mfloat-abi");
1677 CmdArgs.push_back("soft");
1678 } else {
1679 // Floating point operations and argument passing are hard.
1680 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1681 CmdArgs.push_back("-mfloat-abi");
1682 CmdArgs.push_back("hard");
1685 // Forward the -mglobal-merge option for explicit control over the pass.
1686 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1687 options::OPT_mno_global_merge)) {
1688 CmdArgs.push_back("-mllvm");
1689 if (A->getOption().matches(options::OPT_mno_global_merge))
1690 CmdArgs.push_back("-arm-global-merge=false");
1691 else
1692 CmdArgs.push_back("-arm-global-merge=true");
1695 if (!Args.hasFlag(options::OPT_mimplicit_float,
1696 options::OPT_mno_implicit_float, true))
1697 CmdArgs.push_back("-no-implicit-float");
1699 if (Args.getLastArg(options::OPT_mcmse))
1700 CmdArgs.push_back("-mcmse");
1702 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1704 // Enable/disable return address signing and indirect branch targets.
1705 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
1707 AddUnalignedAccessWarning(CmdArgs);
1710 void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1711 const ArgList &Args, bool KernelOrKext,
1712 ArgStringList &CmdArgs) const {
1713 const ToolChain &TC = getToolChain();
1715 // Add the target features
1716 getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1718 // Add target specific flags.
1719 switch (TC.getArch()) {
1720 default:
1721 break;
1723 case llvm::Triple::arm:
1724 case llvm::Triple::armeb:
1725 case llvm::Triple::thumb:
1726 case llvm::Triple::thumbeb:
1727 // Use the effective triple, which takes into account the deployment target.
1728 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1729 break;
1731 case llvm::Triple::aarch64:
1732 case llvm::Triple::aarch64_32:
1733 case llvm::Triple::aarch64_be:
1734 AddAArch64TargetArgs(Args, CmdArgs);
1735 break;
1737 case llvm::Triple::loongarch32:
1738 case llvm::Triple::loongarch64:
1739 AddLoongArchTargetArgs(Args, CmdArgs);
1740 break;
1742 case llvm::Triple::mips:
1743 case llvm::Triple::mipsel:
1744 case llvm::Triple::mips64:
1745 case llvm::Triple::mips64el:
1746 AddMIPSTargetArgs(Args, CmdArgs);
1747 break;
1749 case llvm::Triple::ppc:
1750 case llvm::Triple::ppcle:
1751 case llvm::Triple::ppc64:
1752 case llvm::Triple::ppc64le:
1753 AddPPCTargetArgs(Args, CmdArgs);
1754 break;
1756 case llvm::Triple::riscv32:
1757 case llvm::Triple::riscv64:
1758 AddRISCVTargetArgs(Args, CmdArgs);
1759 break;
1761 case llvm::Triple::sparc:
1762 case llvm::Triple::sparcel:
1763 case llvm::Triple::sparcv9:
1764 AddSparcTargetArgs(Args, CmdArgs);
1765 break;
1767 case llvm::Triple::systemz:
1768 AddSystemZTargetArgs(Args, CmdArgs);
1769 break;
1771 case llvm::Triple::x86:
1772 case llvm::Triple::x86_64:
1773 AddX86TargetArgs(Args, CmdArgs);
1774 break;
1776 case llvm::Triple::lanai:
1777 AddLanaiTargetArgs(Args, CmdArgs);
1778 break;
1780 case llvm::Triple::hexagon:
1781 AddHexagonTargetArgs(Args, CmdArgs);
1782 break;
1784 case llvm::Triple::wasm32:
1785 case llvm::Triple::wasm64:
1786 AddWebAssemblyTargetArgs(Args, CmdArgs);
1787 break;
1789 case llvm::Triple::ve:
1790 AddVETargetArgs(Args, CmdArgs);
1791 break;
1795 namespace {
1796 void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1797 ArgStringList &CmdArgs) {
1798 const char *ABIName = nullptr;
1799 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1800 ABIName = A->getValue();
1801 else if (Triple.isOSDarwin())
1802 ABIName = "darwinpcs";
1803 else
1804 ABIName = "aapcs";
1806 CmdArgs.push_back("-target-abi");
1807 CmdArgs.push_back(ABIName);
1811 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1812 ArgStringList &CmdArgs) const {
1813 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1815 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1816 Args.hasArg(options::OPT_mkernel) ||
1817 Args.hasArg(options::OPT_fapple_kext))
1818 CmdArgs.push_back("-disable-red-zone");
1820 if (!Args.hasFlag(options::OPT_mimplicit_float,
1821 options::OPT_mno_implicit_float, true))
1822 CmdArgs.push_back("-no-implicit-float");
1824 RenderAArch64ABI(Triple, Args, CmdArgs);
1826 // Forward the -mglobal-merge option for explicit control over the pass.
1827 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1828 options::OPT_mno_global_merge)) {
1829 CmdArgs.push_back("-mllvm");
1830 if (A->getOption().matches(options::OPT_mno_global_merge))
1831 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1832 else
1833 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1836 // Enable/disable return address signing and indirect branch targets.
1837 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1839 // Handle -msve_vector_bits=<bits>
1840 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
1841 StringRef Val = A->getValue();
1842 const Driver &D = getToolChain().getDriver();
1843 if (Val.equals("128") || Val.equals("256") || Val.equals("512") ||
1844 Val.equals("1024") || Val.equals("2048") || Val.equals("128+") ||
1845 Val.equals("256+") || Val.equals("512+") || Val.equals("1024+") ||
1846 Val.equals("2048+")) {
1847 unsigned Bits = 0;
1848 if (Val.endswith("+"))
1849 Val = Val.substr(0, Val.size() - 1);
1850 else {
1851 bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1852 assert(!Invalid && "Failed to parse value");
1853 CmdArgs.push_back(
1854 Args.MakeArgString("-mvscale-max=" + llvm::Twine(Bits / 128)));
1857 bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1858 assert(!Invalid && "Failed to parse value");
1859 CmdArgs.push_back(
1860 Args.MakeArgString("-mvscale-min=" + llvm::Twine(Bits / 128)));
1861 // Silently drop requests for vector-length agnostic code as it's implied.
1862 } else if (!Val.equals("scalable"))
1863 // Handle the unsupported values passed to msve-vector-bits.
1864 D.Diag(diag::err_drv_unsupported_option_argument)
1865 << A->getSpelling() << Val;
1868 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1870 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
1871 CmdArgs.push_back("-tune-cpu");
1872 if (strcmp(A->getValue(), "native") == 0)
1873 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
1874 else
1875 CmdArgs.push_back(A->getValue());
1878 AddUnalignedAccessWarning(CmdArgs);
1881 void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1882 ArgStringList &CmdArgs) const {
1883 const llvm::Triple &Triple = getToolChain().getTriple();
1885 CmdArgs.push_back("-target-abi");
1886 CmdArgs.push_back(
1887 loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1888 .data());
1890 // Handle -mtune.
1891 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1892 std::string TuneCPU = A->getValue();
1893 TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
1894 CmdArgs.push_back("-tune-cpu");
1895 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
1899 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1900 ArgStringList &CmdArgs) const {
1901 const Driver &D = getToolChain().getDriver();
1902 StringRef CPUName;
1903 StringRef ABIName;
1904 const llvm::Triple &Triple = getToolChain().getTriple();
1905 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1907 CmdArgs.push_back("-target-abi");
1908 CmdArgs.push_back(ABIName.data());
1910 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1911 if (ABI == mips::FloatABI::Soft) {
1912 // Floating point operations and argument passing are soft.
1913 CmdArgs.push_back("-msoft-float");
1914 CmdArgs.push_back("-mfloat-abi");
1915 CmdArgs.push_back("soft");
1916 } else {
1917 // Floating point operations and argument passing are hard.
1918 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1919 CmdArgs.push_back("-mfloat-abi");
1920 CmdArgs.push_back("hard");
1923 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1924 options::OPT_mno_ldc1_sdc1)) {
1925 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1926 CmdArgs.push_back("-mllvm");
1927 CmdArgs.push_back("-mno-ldc1-sdc1");
1931 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1932 options::OPT_mno_check_zero_division)) {
1933 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1934 CmdArgs.push_back("-mllvm");
1935 CmdArgs.push_back("-mno-check-zero-division");
1939 if (Args.getLastArg(options::OPT_mfix4300)) {
1940 CmdArgs.push_back("-mllvm");
1941 CmdArgs.push_back("-mfix4300");
1944 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1945 StringRef v = A->getValue();
1946 CmdArgs.push_back("-mllvm");
1947 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1948 A->claim();
1951 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1952 Arg *ABICalls =
1953 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1955 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1956 // -mgpopt is the default for static, -fno-pic environments but these two
1957 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1958 // the only case where -mllvm -mgpopt is passed.
1959 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1960 // passed explicitly when compiling something with -mabicalls
1961 // (implictly) in affect. Currently the warning is in the backend.
1963 // When the ABI in use is N64, we also need to determine the PIC mode that
1964 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1965 bool NoABICalls =
1966 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1968 llvm::Reloc::Model RelocationModel;
1969 unsigned PICLevel;
1970 bool IsPIE;
1971 std::tie(RelocationModel, PICLevel, IsPIE) =
1972 ParsePICArgs(getToolChain(), Args);
1974 NoABICalls = NoABICalls ||
1975 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1977 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1978 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1979 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1980 CmdArgs.push_back("-mllvm");
1981 CmdArgs.push_back("-mgpopt");
1983 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1984 options::OPT_mno_local_sdata);
1985 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1986 options::OPT_mno_extern_sdata);
1987 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1988 options::OPT_mno_embedded_data);
1989 if (LocalSData) {
1990 CmdArgs.push_back("-mllvm");
1991 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1992 CmdArgs.push_back("-mlocal-sdata=1");
1993 } else {
1994 CmdArgs.push_back("-mlocal-sdata=0");
1996 LocalSData->claim();
1999 if (ExternSData) {
2000 CmdArgs.push_back("-mllvm");
2001 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
2002 CmdArgs.push_back("-mextern-sdata=1");
2003 } else {
2004 CmdArgs.push_back("-mextern-sdata=0");
2006 ExternSData->claim();
2009 if (EmbeddedData) {
2010 CmdArgs.push_back("-mllvm");
2011 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
2012 CmdArgs.push_back("-membedded-data=1");
2013 } else {
2014 CmdArgs.push_back("-membedded-data=0");
2016 EmbeddedData->claim();
2019 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
2020 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
2022 if (GPOpt)
2023 GPOpt->claim();
2025 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
2026 StringRef Val = StringRef(A->getValue());
2027 if (mips::hasCompactBranches(CPUName)) {
2028 if (Val == "never" || Val == "always" || Val == "optimal") {
2029 CmdArgs.push_back("-mllvm");
2030 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
2031 } else
2032 D.Diag(diag::err_drv_unsupported_option_argument)
2033 << A->getSpelling() << Val;
2034 } else
2035 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
2038 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
2039 options::OPT_mno_relax_pic_calls)) {
2040 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
2041 CmdArgs.push_back("-mllvm");
2042 CmdArgs.push_back("-mips-jalr-reloc=0");
2047 void Clang::AddPPCTargetArgs(const ArgList &Args,
2048 ArgStringList &CmdArgs) const {
2049 const Driver &D = getToolChain().getDriver();
2050 const llvm::Triple &T = getToolChain().getTriple();
2051 if (Args.getLastArg(options::OPT_mtune_EQ)) {
2052 CmdArgs.push_back("-tune-cpu");
2053 std::string CPU = ppc::getPPCTuneCPU(Args, T);
2054 CmdArgs.push_back(Args.MakeArgString(CPU));
2057 // Select the ABI to use.
2058 const char *ABIName = nullptr;
2059 if (T.isOSBinFormatELF()) {
2060 switch (getToolChain().getArch()) {
2061 case llvm::Triple::ppc64: {
2062 if (T.isPPC64ELFv2ABI())
2063 ABIName = "elfv2";
2064 else
2065 ABIName = "elfv1";
2066 break;
2068 case llvm::Triple::ppc64le:
2069 ABIName = "elfv2";
2070 break;
2071 default:
2072 break;
2076 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
2077 bool VecExtabi = false;
2078 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
2079 StringRef V = A->getValue();
2080 if (V == "ieeelongdouble") {
2081 IEEELongDouble = true;
2082 A->claim();
2083 } else if (V == "ibmlongdouble") {
2084 IEEELongDouble = false;
2085 A->claim();
2086 } else if (V == "vec-default") {
2087 VecExtabi = false;
2088 A->claim();
2089 } else if (V == "vec-extabi") {
2090 VecExtabi = true;
2091 A->claim();
2092 } else if (V == "elfv1") {
2093 ABIName = "elfv1";
2094 A->claim();
2095 } else if (V == "elfv2") {
2096 ABIName = "elfv2";
2097 A->claim();
2098 } else if (V != "altivec")
2099 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2100 // the option if given as we don't have backend support for any targets
2101 // that don't use the altivec abi.
2102 ABIName = A->getValue();
2104 if (IEEELongDouble)
2105 CmdArgs.push_back("-mabi=ieeelongdouble");
2106 if (VecExtabi) {
2107 if (!T.isOSAIX())
2108 D.Diag(diag::err_drv_unsupported_opt_for_target)
2109 << "-mabi=vec-extabi" << T.str();
2110 CmdArgs.push_back("-mabi=vec-extabi");
2113 ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
2114 if (FloatABI == ppc::FloatABI::Soft) {
2115 // Floating point operations and argument passing are soft.
2116 CmdArgs.push_back("-msoft-float");
2117 CmdArgs.push_back("-mfloat-abi");
2118 CmdArgs.push_back("soft");
2119 } else {
2120 // Floating point operations and argument passing are hard.
2121 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2122 CmdArgs.push_back("-mfloat-abi");
2123 CmdArgs.push_back("hard");
2126 if (ABIName) {
2127 CmdArgs.push_back("-target-abi");
2128 CmdArgs.push_back(ABIName);
2132 static void SetRISCVSmallDataLimit(const ToolChain &TC, const ArgList &Args,
2133 ArgStringList &CmdArgs) {
2134 const Driver &D = TC.getDriver();
2135 const llvm::Triple &Triple = TC.getTriple();
2136 // Default small data limitation is eight.
2137 const char *SmallDataLimit = "8";
2138 // Get small data limitation.
2139 if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
2140 options::OPT_fPIC)) {
2141 // Not support linker relaxation for PIC.
2142 SmallDataLimit = "0";
2143 if (Args.hasArg(options::OPT_G)) {
2144 D.Diag(diag::warn_drv_unsupported_sdata);
2146 } else if (Args.getLastArgValue(options::OPT_mcmodel_EQ)
2147 .equals_insensitive("large") &&
2148 (Triple.getArch() == llvm::Triple::riscv64)) {
2149 // Not support linker relaxation for RV64 with large code model.
2150 SmallDataLimit = "0";
2151 if (Args.hasArg(options::OPT_G)) {
2152 D.Diag(diag::warn_drv_unsupported_sdata);
2154 } else if (Triple.isAndroid()) {
2155 // GP relaxation is not supported on Android.
2156 SmallDataLimit = "0";
2157 if (Args.hasArg(options::OPT_G)) {
2158 D.Diag(diag::warn_drv_unsupported_sdata);
2160 } else if (Arg *A = Args.getLastArg(options::OPT_G)) {
2161 SmallDataLimit = A->getValue();
2163 // Forward the -msmall-data-limit= option.
2164 CmdArgs.push_back("-msmall-data-limit");
2165 CmdArgs.push_back(SmallDataLimit);
2168 void Clang::AddRISCVTargetArgs(const ArgList &Args,
2169 ArgStringList &CmdArgs) const {
2170 const llvm::Triple &Triple = getToolChain().getTriple();
2171 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2173 CmdArgs.push_back("-target-abi");
2174 CmdArgs.push_back(ABIName.data());
2176 SetRISCVSmallDataLimit(getToolChain(), Args, CmdArgs);
2178 if (!Args.hasFlag(options::OPT_mimplicit_float,
2179 options::OPT_mno_implicit_float, true))
2180 CmdArgs.push_back("-no-implicit-float");
2182 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2183 CmdArgs.push_back("-tune-cpu");
2184 if (strcmp(A->getValue(), "native") == 0)
2185 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2186 else
2187 CmdArgs.push_back(A->getValue());
2190 // Handle -mrvv-vector-bits=<bits>
2191 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2192 StringRef Val = A->getValue();
2193 const Driver &D = getToolChain().getDriver();
2195 // Get minimum VLen from march.
2196 unsigned MinVLen = 0;
2197 StringRef Arch = riscv::getRISCVArch(Args, Triple);
2198 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2199 Arch, /*EnableExperimentalExtensions*/ true);
2200 if (!ISAInfo) {
2201 // Ignore parsing error.
2202 consumeError(ISAInfo.takeError());
2203 } else {
2204 MinVLen = (*ISAInfo)->getMinVLen();
2207 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2208 // as integer as long as we have a MinVLen.
2209 unsigned Bits = 0;
2210 if (Val.equals("zvl") && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2211 Bits = MinVLen;
2212 } else if (!Val.getAsInteger(10, Bits)) {
2213 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2214 // at least MinVLen.
2215 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2216 Bits > 65536 || !llvm::isPowerOf2_32(Bits))
2217 Bits = 0;
2220 // If we got a valid value try to use it.
2221 if (Bits != 0) {
2222 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2223 CmdArgs.push_back(
2224 Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
2225 CmdArgs.push_back(
2226 Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
2227 } else if (!Val.equals("scalable")) {
2228 // Handle the unsupported values passed to mrvv-vector-bits.
2229 D.Diag(diag::err_drv_unsupported_option_argument)
2230 << A->getSpelling() << Val;
2235 void Clang::AddSparcTargetArgs(const ArgList &Args,
2236 ArgStringList &CmdArgs) const {
2237 sparc::FloatABI FloatABI =
2238 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2240 if (FloatABI == sparc::FloatABI::Soft) {
2241 // Floating point operations and argument passing are soft.
2242 CmdArgs.push_back("-msoft-float");
2243 CmdArgs.push_back("-mfloat-abi");
2244 CmdArgs.push_back("soft");
2245 } else {
2246 // Floating point operations and argument passing are hard.
2247 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2248 CmdArgs.push_back("-mfloat-abi");
2249 CmdArgs.push_back("hard");
2252 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2253 StringRef Name = A->getValue();
2254 std::string TuneCPU;
2255 if (Name == "native")
2256 TuneCPU = std::string(llvm::sys::getHostCPUName());
2257 else
2258 TuneCPU = std::string(Name);
2260 CmdArgs.push_back("-tune-cpu");
2261 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2265 void Clang::AddSystemZTargetArgs(const ArgList &Args,
2266 ArgStringList &CmdArgs) const {
2267 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2268 CmdArgs.push_back("-tune-cpu");
2269 if (strcmp(A->getValue(), "native") == 0)
2270 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2271 else
2272 CmdArgs.push_back(A->getValue());
2275 bool HasBackchain =
2276 Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2277 bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2278 options::OPT_mno_packed_stack, false);
2279 systemz::FloatABI FloatABI =
2280 systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2281 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2282 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2283 const Driver &D = getToolChain().getDriver();
2284 D.Diag(diag::err_drv_unsupported_opt)
2285 << "-mpacked-stack -mbackchain -mhard-float";
2287 if (HasBackchain)
2288 CmdArgs.push_back("-mbackchain");
2289 if (HasPackedStack)
2290 CmdArgs.push_back("-mpacked-stack");
2291 if (HasSoftFloat) {
2292 // Floating point operations and argument passing are soft.
2293 CmdArgs.push_back("-msoft-float");
2294 CmdArgs.push_back("-mfloat-abi");
2295 CmdArgs.push_back("soft");
2299 void Clang::AddX86TargetArgs(const ArgList &Args,
2300 ArgStringList &CmdArgs) const {
2301 const Driver &D = getToolChain().getDriver();
2302 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2304 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2305 Args.hasArg(options::OPT_mkernel) ||
2306 Args.hasArg(options::OPT_fapple_kext))
2307 CmdArgs.push_back("-disable-red-zone");
2309 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2310 options::OPT_mno_tls_direct_seg_refs, true))
2311 CmdArgs.push_back("-mno-tls-direct-seg-refs");
2313 // Default to avoid implicit floating-point for kernel/kext code, but allow
2314 // that to be overridden with -mno-soft-float.
2315 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2316 Args.hasArg(options::OPT_fapple_kext));
2317 if (Arg *A = Args.getLastArg(
2318 options::OPT_msoft_float, options::OPT_mno_soft_float,
2319 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2320 const Option &O = A->getOption();
2321 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2322 O.matches(options::OPT_msoft_float));
2324 if (NoImplicitFloat)
2325 CmdArgs.push_back("-no-implicit-float");
2327 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2328 StringRef Value = A->getValue();
2329 if (Value == "intel" || Value == "att") {
2330 CmdArgs.push_back("-mllvm");
2331 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2332 CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2333 } else {
2334 D.Diag(diag::err_drv_unsupported_option_argument)
2335 << A->getSpelling() << Value;
2337 } else if (D.IsCLMode()) {
2338 CmdArgs.push_back("-mllvm");
2339 CmdArgs.push_back("-x86-asm-syntax=intel");
2342 if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2343 options::OPT_mno_skip_rax_setup))
2344 if (A->getOption().matches(options::OPT_mskip_rax_setup))
2345 CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2347 // Set flags to support MCU ABI.
2348 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2349 CmdArgs.push_back("-mfloat-abi");
2350 CmdArgs.push_back("soft");
2351 CmdArgs.push_back("-mstack-alignment=4");
2354 // Handle -mtune.
2356 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2357 std::string TuneCPU;
2358 if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
2359 !getToolChain().getTriple().isPS())
2360 TuneCPU = "generic";
2362 // Override based on -mtune.
2363 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2364 StringRef Name = A->getValue();
2366 if (Name == "native") {
2367 Name = llvm::sys::getHostCPUName();
2368 if (!Name.empty())
2369 TuneCPU = std::string(Name);
2370 } else
2371 TuneCPU = std::string(Name);
2374 if (!TuneCPU.empty()) {
2375 CmdArgs.push_back("-tune-cpu");
2376 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2380 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2381 ArgStringList &CmdArgs) const {
2382 CmdArgs.push_back("-mqdsp6-compat");
2383 CmdArgs.push_back("-Wreturn-type");
2385 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2386 CmdArgs.push_back("-mllvm");
2387 CmdArgs.push_back(
2388 Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2391 if (!Args.hasArg(options::OPT_fno_short_enums))
2392 CmdArgs.push_back("-fshort-enums");
2393 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2394 CmdArgs.push_back("-mllvm");
2395 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2397 CmdArgs.push_back("-mllvm");
2398 CmdArgs.push_back("-machine-sink-split=0");
2401 void Clang::AddLanaiTargetArgs(const ArgList &Args,
2402 ArgStringList &CmdArgs) const {
2403 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2404 StringRef CPUName = A->getValue();
2406 CmdArgs.push_back("-target-cpu");
2407 CmdArgs.push_back(Args.MakeArgString(CPUName));
2409 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2410 StringRef Value = A->getValue();
2411 // Only support mregparm=4 to support old usage. Report error for all other
2412 // cases.
2413 int Mregparm;
2414 if (Value.getAsInteger(10, Mregparm)) {
2415 if (Mregparm != 4) {
2416 getToolChain().getDriver().Diag(
2417 diag::err_drv_unsupported_option_argument)
2418 << A->getSpelling() << Value;
2424 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2425 ArgStringList &CmdArgs) const {
2426 // Default to "hidden" visibility.
2427 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2428 options::OPT_fvisibility_ms_compat))
2429 CmdArgs.push_back("-fvisibility=hidden");
2432 void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2433 // Floating point operations and argument passing are hard.
2434 CmdArgs.push_back("-mfloat-abi");
2435 CmdArgs.push_back("hard");
2438 void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2439 StringRef Target, const InputInfo &Output,
2440 const InputInfo &Input, const ArgList &Args) const {
2441 // If this is a dry run, do not create the compilation database file.
2442 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2443 return;
2445 using llvm::yaml::escape;
2446 const Driver &D = getToolChain().getDriver();
2448 if (!CompilationDatabase) {
2449 std::error_code EC;
2450 auto File = std::make_unique<llvm::raw_fd_ostream>(
2451 Filename, EC,
2452 llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2453 if (EC) {
2454 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2455 << EC.message();
2456 return;
2458 CompilationDatabase = std::move(File);
2460 auto &CDB = *CompilationDatabase;
2461 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2462 if (!CWD)
2463 CWD = ".";
2464 CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2465 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2466 if (Output.isFilename())
2467 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2468 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2469 SmallString<128> Buf;
2470 Buf = "-x";
2471 Buf += types::getTypeName(Input.getType());
2472 CDB << ", \"" << escape(Buf) << "\"";
2473 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2474 Buf = "--sysroot=";
2475 Buf += D.SysRoot;
2476 CDB << ", \"" << escape(Buf) << "\"";
2478 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2479 if (Output.isFilename())
2480 CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2481 for (auto &A: Args) {
2482 auto &O = A->getOption();
2483 // Skip language selection, which is positional.
2484 if (O.getID() == options::OPT_x)
2485 continue;
2486 // Skip writing dependency output and the compilation database itself.
2487 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2488 continue;
2489 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2490 continue;
2491 // Skip inputs.
2492 if (O.getKind() == Option::InputClass)
2493 continue;
2494 // Skip output.
2495 if (O.getID() == options::OPT_o)
2496 continue;
2497 // All other arguments are quoted and appended.
2498 ArgStringList ASL;
2499 A->render(Args, ASL);
2500 for (auto &it: ASL)
2501 CDB << ", \"" << escape(it) << "\"";
2503 Buf = "--target=";
2504 Buf += Target;
2505 CDB << ", \"" << escape(Buf) << "\"]},\n";
2508 void Clang::DumpCompilationDatabaseFragmentToDir(
2509 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2510 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2511 // If this is a dry run, do not create the compilation database file.
2512 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2513 return;
2515 if (CompilationDatabase)
2516 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2518 SmallString<256> Path = Dir;
2519 const auto &Driver = C.getDriver();
2520 Driver.getVFS().makeAbsolute(Path);
2521 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2522 if (Err) {
2523 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2524 return;
2527 llvm::sys::path::append(
2528 Path,
2529 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2530 int FD;
2531 SmallString<256> TempPath;
2532 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2533 llvm::sys::fs::OF_Text);
2534 if (Err) {
2535 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2536 return;
2538 CompilationDatabase =
2539 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2540 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2543 static bool CheckARMImplicitITArg(StringRef Value) {
2544 return Value == "always" || Value == "never" || Value == "arm" ||
2545 Value == "thumb";
2548 static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2549 StringRef Value) {
2550 CmdArgs.push_back("-mllvm");
2551 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2554 static void CollectArgsForIntegratedAssembler(Compilation &C,
2555 const ArgList &Args,
2556 ArgStringList &CmdArgs,
2557 const Driver &D) {
2558 if (UseRelaxAll(C, Args))
2559 CmdArgs.push_back("-mrelax-all");
2561 // Only default to -mincremental-linker-compatible if we think we are
2562 // targeting the MSVC linker.
2563 bool DefaultIncrementalLinkerCompatible =
2564 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2565 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2566 options::OPT_mno_incremental_linker_compatible,
2567 DefaultIncrementalLinkerCompatible))
2568 CmdArgs.push_back("-mincremental-linker-compatible");
2570 Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2572 Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2573 options::OPT_fno_emit_compact_unwind_non_canonical);
2575 // If you add more args here, also add them to the block below that
2576 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2578 // When passing -I arguments to the assembler we sometimes need to
2579 // unconditionally take the next argument. For example, when parsing
2580 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2581 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2582 // arg after parsing the '-I' arg.
2583 bool TakeNextArg = false;
2585 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2586 bool UseNoExecStack = false;
2587 const char *MipsTargetFeature = nullptr;
2588 StringRef ImplicitIt;
2589 for (const Arg *A :
2590 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2591 options::OPT_mimplicit_it_EQ)) {
2592 A->claim();
2594 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2595 switch (C.getDefaultToolChain().getArch()) {
2596 case llvm::Triple::arm:
2597 case llvm::Triple::armeb:
2598 case llvm::Triple::thumb:
2599 case llvm::Triple::thumbeb:
2600 // Only store the value; the last value set takes effect.
2601 ImplicitIt = A->getValue();
2602 if (!CheckARMImplicitITArg(ImplicitIt))
2603 D.Diag(diag::err_drv_unsupported_option_argument)
2604 << A->getSpelling() << ImplicitIt;
2605 continue;
2606 default:
2607 break;
2611 for (StringRef Value : A->getValues()) {
2612 if (TakeNextArg) {
2613 CmdArgs.push_back(Value.data());
2614 TakeNextArg = false;
2615 continue;
2618 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2619 Value == "-mbig-obj")
2620 continue; // LLVM handles bigobj automatically
2622 switch (C.getDefaultToolChain().getArch()) {
2623 default:
2624 break;
2625 case llvm::Triple::wasm32:
2626 case llvm::Triple::wasm64:
2627 if (Value == "--no-type-check") {
2628 CmdArgs.push_back("-mno-type-check");
2629 continue;
2631 break;
2632 case llvm::Triple::thumb:
2633 case llvm::Triple::thumbeb:
2634 case llvm::Triple::arm:
2635 case llvm::Triple::armeb:
2636 if (Value.startswith("-mimplicit-it=")) {
2637 // Only store the value; the last value set takes effect.
2638 ImplicitIt = Value.split("=").second;
2639 if (CheckARMImplicitITArg(ImplicitIt))
2640 continue;
2642 if (Value == "-mthumb")
2643 // -mthumb has already been processed in ComputeLLVMTriple()
2644 // recognize but skip over here.
2645 continue;
2646 break;
2647 case llvm::Triple::mips:
2648 case llvm::Triple::mipsel:
2649 case llvm::Triple::mips64:
2650 case llvm::Triple::mips64el:
2651 if (Value == "--trap") {
2652 CmdArgs.push_back("-target-feature");
2653 CmdArgs.push_back("+use-tcc-in-div");
2654 continue;
2656 if (Value == "--break") {
2657 CmdArgs.push_back("-target-feature");
2658 CmdArgs.push_back("-use-tcc-in-div");
2659 continue;
2661 if (Value.startswith("-msoft-float")) {
2662 CmdArgs.push_back("-target-feature");
2663 CmdArgs.push_back("+soft-float");
2664 continue;
2666 if (Value.startswith("-mhard-float")) {
2667 CmdArgs.push_back("-target-feature");
2668 CmdArgs.push_back("-soft-float");
2669 continue;
2672 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2673 .Case("-mips1", "+mips1")
2674 .Case("-mips2", "+mips2")
2675 .Case("-mips3", "+mips3")
2676 .Case("-mips4", "+mips4")
2677 .Case("-mips5", "+mips5")
2678 .Case("-mips32", "+mips32")
2679 .Case("-mips32r2", "+mips32r2")
2680 .Case("-mips32r3", "+mips32r3")
2681 .Case("-mips32r5", "+mips32r5")
2682 .Case("-mips32r6", "+mips32r6")
2683 .Case("-mips64", "+mips64")
2684 .Case("-mips64r2", "+mips64r2")
2685 .Case("-mips64r3", "+mips64r3")
2686 .Case("-mips64r5", "+mips64r5")
2687 .Case("-mips64r6", "+mips64r6")
2688 .Default(nullptr);
2689 if (MipsTargetFeature)
2690 continue;
2693 if (Value == "-force_cpusubtype_ALL") {
2694 // Do nothing, this is the default and we don't support anything else.
2695 } else if (Value == "-L") {
2696 CmdArgs.push_back("-msave-temp-labels");
2697 } else if (Value == "--fatal-warnings") {
2698 CmdArgs.push_back("-massembler-fatal-warnings");
2699 } else if (Value == "--no-warn" || Value == "-W") {
2700 CmdArgs.push_back("-massembler-no-warn");
2701 } else if (Value == "--noexecstack") {
2702 UseNoExecStack = true;
2703 } else if (Value.startswith("-compress-debug-sections") ||
2704 Value.startswith("--compress-debug-sections") ||
2705 Value == "-nocompress-debug-sections" ||
2706 Value == "--nocompress-debug-sections") {
2707 CmdArgs.push_back(Value.data());
2708 } else if (Value == "-mrelax-relocations=yes" ||
2709 Value == "--mrelax-relocations=yes") {
2710 UseRelaxRelocations = true;
2711 } else if (Value == "-mrelax-relocations=no" ||
2712 Value == "--mrelax-relocations=no") {
2713 UseRelaxRelocations = false;
2714 } else if (Value.startswith("-I")) {
2715 CmdArgs.push_back(Value.data());
2716 // We need to consume the next argument if the current arg is a plain
2717 // -I. The next arg will be the include directory.
2718 if (Value == "-I")
2719 TakeNextArg = true;
2720 } else if (Value.startswith("-gdwarf-")) {
2721 // "-gdwarf-N" options are not cc1as options.
2722 unsigned DwarfVersion = DwarfVersionNum(Value);
2723 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2724 CmdArgs.push_back(Value.data());
2725 } else {
2726 RenderDebugEnablingArgs(Args, CmdArgs,
2727 llvm::codegenoptions::DebugInfoConstructor,
2728 DwarfVersion, llvm::DebuggerKind::Default);
2730 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2731 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2732 // Do nothing, we'll validate it later.
2733 } else if (Value == "-defsym") {
2734 if (A->getNumValues() != 2) {
2735 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2736 break;
2738 const char *S = A->getValue(1);
2739 auto Pair = StringRef(S).split('=');
2740 auto Sym = Pair.first;
2741 auto SVal = Pair.second;
2743 if (Sym.empty() || SVal.empty()) {
2744 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2745 break;
2747 int64_t IVal;
2748 if (SVal.getAsInteger(0, IVal)) {
2749 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2750 break;
2752 CmdArgs.push_back(Value.data());
2753 TakeNextArg = true;
2754 } else if (Value == "-fdebug-compilation-dir") {
2755 CmdArgs.push_back("-fdebug-compilation-dir");
2756 TakeNextArg = true;
2757 } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2758 // The flag is a -Wa / -Xassembler argument and Options doesn't
2759 // parse the argument, so this isn't automatically aliased to
2760 // -fdebug-compilation-dir (without '=') here.
2761 CmdArgs.push_back("-fdebug-compilation-dir");
2762 CmdArgs.push_back(Value.data());
2763 } else if (Value == "--version") {
2764 D.PrintVersion(C, llvm::outs());
2765 } else {
2766 D.Diag(diag::err_drv_unsupported_option_argument)
2767 << A->getSpelling() << Value;
2771 if (ImplicitIt.size())
2772 AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2773 if (!UseRelaxRelocations)
2774 CmdArgs.push_back("-mrelax-relocations=no");
2775 if (UseNoExecStack)
2776 CmdArgs.push_back("-mnoexecstack");
2777 if (MipsTargetFeature != nullptr) {
2778 CmdArgs.push_back("-target-feature");
2779 CmdArgs.push_back(MipsTargetFeature);
2782 // forward -fembed-bitcode to assmebler
2783 if (C.getDriver().embedBitcodeEnabled() ||
2784 C.getDriver().embedBitcodeMarkerOnly())
2785 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2787 if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2788 CmdArgs.push_back("-as-secure-log-file");
2789 CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2793 static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2794 bool OFastEnabled, const ArgList &Args,
2795 ArgStringList &CmdArgs,
2796 const JobAction &JA) {
2797 // Handle various floating point optimization flags, mapping them to the
2798 // appropriate LLVM code generation flags. This is complicated by several
2799 // "umbrella" flags, so we do this by stepping through the flags incrementally
2800 // adjusting what we think is enabled/disabled, then at the end setting the
2801 // LLVM flags based on the final state.
2802 bool HonorINFs = true;
2803 bool HonorNaNs = true;
2804 bool ApproxFunc = false;
2805 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2806 bool MathErrno = TC.IsMathErrnoDefault();
2807 bool AssociativeMath = false;
2808 bool ReciprocalMath = false;
2809 bool SignedZeros = true;
2810 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2811 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2812 // overriden by ffp-exception-behavior?
2813 bool RoundingFPMath = false;
2814 bool RoundingMathPresent = false; // Is rounding-math in args?
2815 // -ffp-model values: strict, fast, precise
2816 StringRef FPModel = "";
2817 // -ffp-exception-behavior options: strict, maytrap, ignore
2818 StringRef FPExceptionBehavior = "";
2819 // -ffp-eval-method options: double, extended, source
2820 StringRef FPEvalMethod = "";
2821 const llvm::DenormalMode DefaultDenormalFPMath =
2822 TC.getDefaultDenormalModeForType(Args, JA);
2823 const llvm::DenormalMode DefaultDenormalFP32Math =
2824 TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2826 llvm::DenormalMode DenormalFPMath = DefaultDenormalFPMath;
2827 llvm::DenormalMode DenormalFP32Math = DefaultDenormalFP32Math;
2828 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2829 // If one wasn't given by the user, don't pass it here.
2830 StringRef FPContract;
2831 StringRef LastSeenFfpContractOption;
2832 bool SeenUnsafeMathModeOption = false;
2833 if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
2834 !JA.isOffloading(Action::OFK_HIP))
2835 FPContract = "on";
2836 bool StrictFPModel = false;
2837 StringRef Float16ExcessPrecision = "";
2838 StringRef BFloat16ExcessPrecision = "";
2840 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2841 CmdArgs.push_back("-mlimit-float-precision");
2842 CmdArgs.push_back(A->getValue());
2845 for (const Arg *A : Args) {
2846 auto optID = A->getOption().getID();
2847 bool PreciseFPModel = false;
2848 switch (optID) {
2849 default:
2850 break;
2851 case options::OPT_ffp_model_EQ: {
2852 // If -ffp-model= is seen, reset to fno-fast-math
2853 HonorINFs = true;
2854 HonorNaNs = true;
2855 ApproxFunc = false;
2856 // Turning *off* -ffast-math restores the toolchain default.
2857 MathErrno = TC.IsMathErrnoDefault();
2858 AssociativeMath = false;
2859 ReciprocalMath = false;
2860 SignedZeros = true;
2861 // -fno_fast_math restores default denormal and fpcontract handling
2862 FPContract = "on";
2863 DenormalFPMath = llvm::DenormalMode::getIEEE();
2865 // FIXME: The target may have picked a non-IEEE default mode here based on
2866 // -cl-denorms-are-zero. Should the target consider -fp-model interaction?
2867 DenormalFP32Math = llvm::DenormalMode::getIEEE();
2869 StringRef Val = A->getValue();
2870 if (OFastEnabled && !Val.equals("fast")) {
2871 // Only -ffp-model=fast is compatible with OFast, ignore.
2872 D.Diag(clang::diag::warn_drv_overriding_option)
2873 << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
2874 break;
2876 StrictFPModel = false;
2877 PreciseFPModel = true;
2878 // ffp-model= is a Driver option, it is entirely rewritten into more
2879 // granular options before being passed into cc1.
2880 // Use the gcc option in the switch below.
2881 if (!FPModel.empty() && !FPModel.equals(Val))
2882 D.Diag(clang::diag::warn_drv_overriding_option)
2883 << Args.MakeArgString("-ffp-model=" + FPModel)
2884 << Args.MakeArgString("-ffp-model=" + Val);
2885 if (Val.equals("fast")) {
2886 optID = options::OPT_ffast_math;
2887 FPModel = Val;
2888 FPContract = "fast";
2889 } else if (Val.equals("precise")) {
2890 optID = options::OPT_ffp_contract;
2891 FPModel = Val;
2892 FPContract = "on";
2893 PreciseFPModel = true;
2894 } else if (Val.equals("strict")) {
2895 StrictFPModel = true;
2896 optID = options::OPT_frounding_math;
2897 FPExceptionBehavior = "strict";
2898 FPModel = Val;
2899 FPContract = "off";
2900 TrappingMath = true;
2901 } else
2902 D.Diag(diag::err_drv_unsupported_option_argument)
2903 << A->getSpelling() << Val;
2904 break;
2908 switch (optID) {
2909 // If this isn't an FP option skip the claim below
2910 default: continue;
2912 // Options controlling individual features
2913 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2914 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2915 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2916 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2917 case options::OPT_fapprox_func: ApproxFunc = true; break;
2918 case options::OPT_fno_approx_func: ApproxFunc = false; break;
2919 case options::OPT_fmath_errno: MathErrno = true; break;
2920 case options::OPT_fno_math_errno: MathErrno = false; break;
2921 case options::OPT_fassociative_math: AssociativeMath = true; break;
2922 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2923 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2924 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2925 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2926 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2927 case options::OPT_ftrapping_math:
2928 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2929 !FPExceptionBehavior.equals("strict"))
2930 // Warn that previous value of option is overridden.
2931 D.Diag(clang::diag::warn_drv_overriding_option)
2932 << Args.MakeArgString("-ffp-exception-behavior=" +
2933 FPExceptionBehavior)
2934 << "-ftrapping-math";
2935 TrappingMath = true;
2936 TrappingMathPresent = true;
2937 FPExceptionBehavior = "strict";
2938 break;
2939 case options::OPT_fno_trapping_math:
2940 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2941 !FPExceptionBehavior.equals("ignore"))
2942 // Warn that previous value of option is overridden.
2943 D.Diag(clang::diag::warn_drv_overriding_option)
2944 << Args.MakeArgString("-ffp-exception-behavior=" +
2945 FPExceptionBehavior)
2946 << "-fno-trapping-math";
2947 TrappingMath = false;
2948 TrappingMathPresent = true;
2949 FPExceptionBehavior = "ignore";
2950 break;
2952 case options::OPT_frounding_math:
2953 RoundingFPMath = true;
2954 RoundingMathPresent = true;
2955 break;
2957 case options::OPT_fno_rounding_math:
2958 RoundingFPMath = false;
2959 RoundingMathPresent = false;
2960 break;
2962 case options::OPT_fdenormal_fp_math_EQ:
2963 DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
2964 DenormalFP32Math = DenormalFPMath;
2965 if (!DenormalFPMath.isValid()) {
2966 D.Diag(diag::err_drv_invalid_value)
2967 << A->getAsString(Args) << A->getValue();
2969 break;
2971 case options::OPT_fdenormal_fp_math_f32_EQ:
2972 DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
2973 if (!DenormalFP32Math.isValid()) {
2974 D.Diag(diag::err_drv_invalid_value)
2975 << A->getAsString(Args) << A->getValue();
2977 break;
2979 // Validate and pass through -ffp-contract option.
2980 case options::OPT_ffp_contract: {
2981 StringRef Val = A->getValue();
2982 if (PreciseFPModel) {
2983 // -ffp-model=precise enables ffp-contract=on.
2984 // -ffp-model=precise sets PreciseFPModel to on and Val to
2985 // "precise". FPContract is set.
2987 } else if (Val.equals("fast") || Val.equals("on") || Val.equals("off") ||
2988 Val.equals("fast-honor-pragmas")) {
2989 FPContract = Val;
2990 LastSeenFfpContractOption = Val;
2991 } else
2992 D.Diag(diag::err_drv_unsupported_option_argument)
2993 << A->getSpelling() << Val;
2994 break;
2997 // Validate and pass through -ffp-model option.
2998 case options::OPT_ffp_model_EQ:
2999 // This should only occur in the error case
3000 // since the optID has been replaced by a more granular
3001 // floating point option.
3002 break;
3004 // Validate and pass through -ffp-exception-behavior option.
3005 case options::OPT_ffp_exception_behavior_EQ: {
3006 StringRef Val = A->getValue();
3007 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3008 !FPExceptionBehavior.equals(Val))
3009 // Warn that previous value of option is overridden.
3010 D.Diag(clang::diag::warn_drv_overriding_option)
3011 << Args.MakeArgString("-ffp-exception-behavior=" +
3012 FPExceptionBehavior)
3013 << Args.MakeArgString("-ffp-exception-behavior=" + Val);
3014 TrappingMath = TrappingMathPresent = false;
3015 if (Val.equals("ignore") || Val.equals("maytrap"))
3016 FPExceptionBehavior = Val;
3017 else if (Val.equals("strict")) {
3018 FPExceptionBehavior = Val;
3019 TrappingMath = TrappingMathPresent = true;
3020 } else
3021 D.Diag(diag::err_drv_unsupported_option_argument)
3022 << A->getSpelling() << Val;
3023 break;
3026 // Validate and pass through -ffp-eval-method option.
3027 case options::OPT_ffp_eval_method_EQ: {
3028 StringRef Val = A->getValue();
3029 if (Val.equals("double") || Val.equals("extended") ||
3030 Val.equals("source"))
3031 FPEvalMethod = Val;
3032 else
3033 D.Diag(diag::err_drv_unsupported_option_argument)
3034 << A->getSpelling() << Val;
3035 break;
3038 case options::OPT_fexcess_precision_EQ: {
3039 StringRef Val = A->getValue();
3040 const llvm::Triple::ArchType Arch = TC.getArch();
3041 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3042 if (Val.equals("standard") || Val.equals("fast"))
3043 Float16ExcessPrecision = Val;
3044 // To make it GCC compatible, allow the value of "16" which
3045 // means disable excess precision, the same meaning than clang's
3046 // equivalent value "none".
3047 else if (Val.equals("16"))
3048 Float16ExcessPrecision = "none";
3049 else
3050 D.Diag(diag::err_drv_unsupported_option_argument)
3051 << A->getSpelling() << Val;
3052 } else {
3053 if (!(Val.equals("standard") || Val.equals("fast")))
3054 D.Diag(diag::err_drv_unsupported_option_argument)
3055 << A->getSpelling() << Val;
3057 BFloat16ExcessPrecision = Float16ExcessPrecision;
3058 break;
3060 case options::OPT_ffinite_math_only:
3061 HonorINFs = false;
3062 HonorNaNs = false;
3063 break;
3064 case options::OPT_fno_finite_math_only:
3065 HonorINFs = true;
3066 HonorNaNs = true;
3067 break;
3069 case options::OPT_funsafe_math_optimizations:
3070 AssociativeMath = true;
3071 ReciprocalMath = true;
3072 SignedZeros = false;
3073 ApproxFunc = true;
3074 TrappingMath = false;
3075 FPExceptionBehavior = "";
3076 FPContract = "fast";
3077 SeenUnsafeMathModeOption = true;
3078 break;
3079 case options::OPT_fno_unsafe_math_optimizations:
3080 AssociativeMath = false;
3081 ReciprocalMath = false;
3082 SignedZeros = true;
3083 ApproxFunc = false;
3084 TrappingMath = true;
3085 FPExceptionBehavior = "strict";
3087 // The target may have opted to flush by default, so force IEEE.
3088 DenormalFPMath = llvm::DenormalMode::getIEEE();
3089 DenormalFP32Math = llvm::DenormalMode::getIEEE();
3090 if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
3091 !JA.isOffloading(Action::OFK_HIP)) {
3092 if (LastSeenFfpContractOption != "") {
3093 FPContract = LastSeenFfpContractOption;
3094 } else if (SeenUnsafeMathModeOption)
3095 FPContract = "on";
3097 break;
3099 case options::OPT_Ofast:
3100 // If -Ofast is the optimization level, then -ffast-math should be enabled
3101 if (!OFastEnabled)
3102 continue;
3103 [[fallthrough]];
3104 case options::OPT_ffast_math:
3105 HonorINFs = false;
3106 HonorNaNs = false;
3107 MathErrno = false;
3108 AssociativeMath = true;
3109 ReciprocalMath = true;
3110 ApproxFunc = true;
3111 SignedZeros = false;
3112 TrappingMath = false;
3113 RoundingFPMath = false;
3114 FPExceptionBehavior = "";
3115 // If fast-math is set then set the fp-contract mode to fast.
3116 FPContract = "fast";
3117 SeenUnsafeMathModeOption = true;
3118 break;
3119 case options::OPT_fno_fast_math:
3120 HonorINFs = true;
3121 HonorNaNs = true;
3122 // Turning on -ffast-math (with either flag) removes the need for
3123 // MathErrno. However, turning *off* -ffast-math merely restores the
3124 // toolchain default (which may be false).
3125 MathErrno = TC.IsMathErrnoDefault();
3126 AssociativeMath = false;
3127 ReciprocalMath = false;
3128 ApproxFunc = false;
3129 SignedZeros = true;
3130 // -fno_fast_math restores default denormal and fpcontract handling
3131 DenormalFPMath = DefaultDenormalFPMath;
3132 DenormalFP32Math = llvm::DenormalMode::getIEEE();
3133 if (!JA.isDeviceOffloading(Action::OFK_Cuda) &&
3134 !JA.isOffloading(Action::OFK_HIP)) {
3135 if (LastSeenFfpContractOption != "") {
3136 FPContract = LastSeenFfpContractOption;
3137 } else if (SeenUnsafeMathModeOption)
3138 FPContract = "on";
3140 break;
3142 if (StrictFPModel) {
3143 // If -ffp-model=strict has been specified on command line but
3144 // subsequent options conflict then emit warning diagnostic.
3145 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3146 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3147 DenormalFPMath == llvm::DenormalMode::getIEEE() &&
3148 DenormalFP32Math == llvm::DenormalMode::getIEEE() &&
3149 FPContract.equals("off"))
3150 // OK: Current Arg doesn't conflict with -ffp-model=strict
3152 else {
3153 StrictFPModel = false;
3154 FPModel = "";
3155 auto RHS = (A->getNumValues() == 0)
3156 ? A->getSpelling()
3157 : Args.MakeArgString(A->getSpelling() + A->getValue());
3158 if (RHS != "-ffp-model=strict")
3159 D.Diag(clang::diag::warn_drv_overriding_option)
3160 << "-ffp-model=strict" << RHS;
3164 // If we handled this option claim it
3165 A->claim();
3168 if (!HonorINFs)
3169 CmdArgs.push_back("-menable-no-infs");
3171 if (!HonorNaNs)
3172 CmdArgs.push_back("-menable-no-nans");
3174 if (ApproxFunc)
3175 CmdArgs.push_back("-fapprox-func");
3177 if (MathErrno)
3178 CmdArgs.push_back("-fmath-errno");
3180 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3181 !TrappingMath)
3182 CmdArgs.push_back("-funsafe-math-optimizations");
3184 if (!SignedZeros)
3185 CmdArgs.push_back("-fno-signed-zeros");
3187 if (AssociativeMath && !SignedZeros && !TrappingMath)
3188 CmdArgs.push_back("-mreassociate");
3190 if (ReciprocalMath)
3191 CmdArgs.push_back("-freciprocal-math");
3193 if (TrappingMath) {
3194 // FP Exception Behavior is also set to strict
3195 assert(FPExceptionBehavior.equals("strict"));
3198 // The default is IEEE.
3199 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3200 llvm::SmallString<64> DenormFlag;
3201 llvm::raw_svector_ostream ArgStr(DenormFlag);
3202 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3203 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3206 // Add f32 specific denormal mode flag if it's different.
3207 if (DenormalFP32Math != DenormalFPMath) {
3208 llvm::SmallString<64> DenormFlag;
3209 llvm::raw_svector_ostream ArgStr(DenormFlag);
3210 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3211 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3214 if (!FPContract.empty())
3215 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3217 if (!RoundingFPMath)
3218 CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3220 if (RoundingFPMath && RoundingMathPresent)
3221 CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3223 if (!FPExceptionBehavior.empty())
3224 CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3225 FPExceptionBehavior));
3227 if (!FPEvalMethod.empty())
3228 CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3230 if (!Float16ExcessPrecision.empty())
3231 CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3232 Float16ExcessPrecision));
3233 if (!BFloat16ExcessPrecision.empty())
3234 CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
3235 BFloat16ExcessPrecision));
3237 ParseMRecip(D, Args, CmdArgs);
3239 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3240 // individual features enabled by -ffast-math instead of the option itself as
3241 // that's consistent with gcc's behaviour.
3242 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3243 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath) {
3244 CmdArgs.push_back("-ffast-math");
3245 if (FPModel.equals("fast")) {
3246 if (FPContract.equals("fast"))
3247 // All set, do nothing.
3249 else if (FPContract.empty())
3250 // Enable -ffp-contract=fast
3251 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
3252 else
3253 D.Diag(clang::diag::warn_drv_overriding_option)
3254 << "-ffp-model=fast"
3255 << Args.MakeArgString("-ffp-contract=" + FPContract);
3259 // Handle __FINITE_MATH_ONLY__ similarly.
3260 if (!HonorINFs && !HonorNaNs)
3261 CmdArgs.push_back("-ffinite-math-only");
3263 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3264 CmdArgs.push_back("-mfpmath");
3265 CmdArgs.push_back(A->getValue());
3268 // Disable a codegen optimization for floating-point casts.
3269 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3270 options::OPT_fstrict_float_cast_overflow, false))
3271 CmdArgs.push_back("-fno-strict-float-cast-overflow");
3274 static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3275 const llvm::Triple &Triple,
3276 const InputInfo &Input) {
3277 // Add default argument set.
3278 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3279 CmdArgs.push_back("-analyzer-checker=core");
3280 CmdArgs.push_back("-analyzer-checker=apiModeling");
3282 if (!Triple.isWindowsMSVCEnvironment()) {
3283 CmdArgs.push_back("-analyzer-checker=unix");
3284 } else {
3285 // Enable "unix" checkers that also work on Windows.
3286 CmdArgs.push_back("-analyzer-checker=unix.API");
3287 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3288 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3289 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3290 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3291 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3294 // Disable some unix checkers for PS4/PS5.
3295 if (Triple.isPS()) {
3296 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3297 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3300 if (Triple.isOSDarwin()) {
3301 CmdArgs.push_back("-analyzer-checker=osx");
3302 CmdArgs.push_back(
3303 "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3305 else if (Triple.isOSFuchsia())
3306 CmdArgs.push_back("-analyzer-checker=fuchsia");
3308 CmdArgs.push_back("-analyzer-checker=deadcode");
3310 if (types::isCXX(Input.getType()))
3311 CmdArgs.push_back("-analyzer-checker=cplusplus");
3313 if (!Triple.isPS()) {
3314 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3315 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3316 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3317 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3318 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3319 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3322 // Default nullability checks.
3323 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3324 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3327 // Set the output format. The default is plist, for (lame) historical reasons.
3328 CmdArgs.push_back("-analyzer-output");
3329 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3330 CmdArgs.push_back(A->getValue());
3331 else
3332 CmdArgs.push_back("plist");
3334 // Disable the presentation of standard compiler warnings when using
3335 // --analyze. We only want to show static analyzer diagnostics or frontend
3336 // errors.
3337 CmdArgs.push_back("-w");
3339 // Add -Xanalyzer arguments when running as analyzer.
3340 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3343 static bool isValidSymbolName(StringRef S) {
3344 if (S.empty())
3345 return false;
3347 if (std::isdigit(S[0]))
3348 return false;
3350 return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3353 static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3354 const ArgList &Args, ArgStringList &CmdArgs,
3355 bool KernelOrKext) {
3356 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3358 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3359 // doesn't even have a stack!
3360 if (EffectiveTriple.isNVPTX())
3361 return;
3363 // -stack-protector=0 is default.
3364 LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3365 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3366 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3368 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3369 options::OPT_fstack_protector_all,
3370 options::OPT_fstack_protector_strong,
3371 options::OPT_fstack_protector)) {
3372 if (A->getOption().matches(options::OPT_fstack_protector))
3373 StackProtectorLevel =
3374 std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3375 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3376 StackProtectorLevel = LangOptions::SSPStrong;
3377 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3378 StackProtectorLevel = LangOptions::SSPReq;
3380 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3381 D.Diag(diag::warn_drv_unsupported_option_for_target)
3382 << A->getSpelling() << EffectiveTriple.getTriple();
3383 StackProtectorLevel = DefaultStackProtectorLevel;
3385 } else {
3386 StackProtectorLevel = DefaultStackProtectorLevel;
3389 if (StackProtectorLevel) {
3390 CmdArgs.push_back("-stack-protector");
3391 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3394 // --param ssp-buffer-size=
3395 for (const Arg *A : Args.filtered(options::OPT__param)) {
3396 StringRef Str(A->getValue());
3397 if (Str.startswith("ssp-buffer-size=")) {
3398 if (StackProtectorLevel) {
3399 CmdArgs.push_back("-stack-protector-buffer-size");
3400 // FIXME: Verify the argument is a valid integer.
3401 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3403 A->claim();
3407 const std::string &TripleStr = EffectiveTriple.getTriple();
3408 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3409 StringRef Value = A->getValue();
3410 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3411 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3412 D.Diag(diag::err_drv_unsupported_opt_for_target)
3413 << A->getAsString(Args) << TripleStr;
3414 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3415 EffectiveTriple.isThumb()) &&
3416 Value != "tls" && Value != "global") {
3417 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3418 << A->getOption().getName() << Value << "tls global";
3419 return;
3421 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3422 Value == "tls") {
3423 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3424 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3425 << A->getAsString(Args);
3426 return;
3428 // Check whether the target subarch supports the hardware TLS register
3429 if (!arm::isHardTPSupported(EffectiveTriple)) {
3430 D.Diag(diag::err_target_unsupported_tp_hard)
3431 << EffectiveTriple.getArchName();
3432 return;
3434 // Check whether the user asked for something other than -mtp=cp15
3435 if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3436 StringRef Value = A->getValue();
3437 if (Value != "cp15") {
3438 D.Diag(diag::err_drv_argument_not_allowed_with)
3439 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3440 return;
3443 CmdArgs.push_back("-target-feature");
3444 CmdArgs.push_back("+read-tp-tpidruro");
3446 if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3447 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3448 << A->getOption().getName() << Value << "sysreg global";
3449 return;
3451 A->render(Args, CmdArgs);
3454 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3455 StringRef Value = A->getValue();
3456 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3457 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb())
3458 D.Diag(diag::err_drv_unsupported_opt_for_target)
3459 << A->getAsString(Args) << TripleStr;
3460 int Offset;
3461 if (Value.getAsInteger(10, Offset)) {
3462 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3463 return;
3465 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3466 (Offset < 0 || Offset > 0xfffff)) {
3467 D.Diag(diag::err_drv_invalid_int_value)
3468 << A->getOption().getName() << Value;
3469 return;
3471 A->render(Args, CmdArgs);
3474 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3475 StringRef Value = A->getValue();
3476 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
3477 D.Diag(diag::err_drv_unsupported_opt_for_target)
3478 << A->getAsString(Args) << TripleStr;
3479 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3480 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3481 << A->getOption().getName() << Value << "fs gs";
3482 return;
3484 if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3485 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3486 return;
3488 A->render(Args, CmdArgs);
3491 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3492 StringRef Value = A->getValue();
3493 if (!isValidSymbolName(Value)) {
3494 D.Diag(diag::err_drv_argument_only_allowed_with)
3495 << A->getOption().getName() << "legal symbol name";
3496 return;
3498 A->render(Args, CmdArgs);
3502 static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3503 ArgStringList &CmdArgs) {
3504 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3506 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux())
3507 return;
3509 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3510 !EffectiveTriple.isPPC64())
3511 return;
3513 Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
3514 options::OPT_fno_stack_clash_protection);
3517 static void RenderTrivialAutoVarInitOptions(const Driver &D,
3518 const ToolChain &TC,
3519 const ArgList &Args,
3520 ArgStringList &CmdArgs) {
3521 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3522 StringRef TrivialAutoVarInit = "";
3524 for (const Arg *A : Args) {
3525 switch (A->getOption().getID()) {
3526 default:
3527 continue;
3528 case options::OPT_ftrivial_auto_var_init: {
3529 A->claim();
3530 StringRef Val = A->getValue();
3531 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3532 TrivialAutoVarInit = Val;
3533 else
3534 D.Diag(diag::err_drv_unsupported_option_argument)
3535 << A->getSpelling() << Val;
3536 break;
3541 if (TrivialAutoVarInit.empty())
3542 switch (DefaultTrivialAutoVarInit) {
3543 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3544 break;
3545 case LangOptions::TrivialAutoVarInitKind::Pattern:
3546 TrivialAutoVarInit = "pattern";
3547 break;
3548 case LangOptions::TrivialAutoVarInitKind::Zero:
3549 TrivialAutoVarInit = "zero";
3550 break;
3553 if (!TrivialAutoVarInit.empty()) {
3554 CmdArgs.push_back(
3555 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3558 if (Arg *A =
3559 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3560 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3561 StringRef(
3562 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3563 "uninitialized")
3564 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3565 A->claim();
3566 StringRef Val = A->getValue();
3567 if (std::stoi(Val.str()) <= 0)
3568 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3569 CmdArgs.push_back(
3570 Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3574 static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3575 types::ID InputType) {
3576 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3577 // for denormal flushing handling based on the target.
3578 const unsigned ForwardedArguments[] = {
3579 options::OPT_cl_opt_disable,
3580 options::OPT_cl_strict_aliasing,
3581 options::OPT_cl_single_precision_constant,
3582 options::OPT_cl_finite_math_only,
3583 options::OPT_cl_kernel_arg_info,
3584 options::OPT_cl_unsafe_math_optimizations,
3585 options::OPT_cl_fast_relaxed_math,
3586 options::OPT_cl_mad_enable,
3587 options::OPT_cl_no_signed_zeros,
3588 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3589 options::OPT_cl_uniform_work_group_size
3592 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3593 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3594 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3595 } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3596 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3597 CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3600 for (const auto &Arg : ForwardedArguments)
3601 if (const auto *A = Args.getLastArg(Arg))
3602 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3604 // Only add the default headers if we are compiling OpenCL sources.
3605 if ((types::isOpenCL(InputType) ||
3606 (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3607 !Args.hasArg(options::OPT_cl_no_stdinc)) {
3608 CmdArgs.push_back("-finclude-default-header");
3609 CmdArgs.push_back("-fdeclare-opencl-builtins");
3613 static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3614 types::ID InputType) {
3615 const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
3616 options::OPT_D,
3617 options::OPT_I,
3618 options::OPT_S,
3619 options::OPT_O,
3620 options::OPT_emit_llvm,
3621 options::OPT_emit_obj,
3622 options::OPT_disable_llvm_passes,
3623 options::OPT_fnative_half_type,
3624 options::OPT_hlsl_entrypoint};
3625 if (!types::isHLSL(InputType))
3626 return;
3627 for (const auto &Arg : ForwardedArguments)
3628 if (const auto *A = Args.getLastArg(Arg))
3629 A->renderAsInput(Args, CmdArgs);
3630 // Add the default headers if dxc_no_stdinc is not set.
3631 if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3632 !Args.hasArg(options::OPT_nostdinc))
3633 CmdArgs.push_back("-finclude-default-header");
3636 static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
3637 ArgStringList &CmdArgs) {
3638 bool ARCMTEnabled = false;
3639 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3640 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3641 options::OPT_ccc_arcmt_modify,
3642 options::OPT_ccc_arcmt_migrate)) {
3643 ARCMTEnabled = true;
3644 switch (A->getOption().getID()) {
3645 default: llvm_unreachable("missed a case");
3646 case options::OPT_ccc_arcmt_check:
3647 CmdArgs.push_back("-arcmt-action=check");
3648 break;
3649 case options::OPT_ccc_arcmt_modify:
3650 CmdArgs.push_back("-arcmt-action=modify");
3651 break;
3652 case options::OPT_ccc_arcmt_migrate:
3653 CmdArgs.push_back("-arcmt-action=migrate");
3654 CmdArgs.push_back("-mt-migrate-directory");
3655 CmdArgs.push_back(A->getValue());
3657 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3658 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3659 break;
3662 } else {
3663 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3664 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3665 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3668 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3669 if (ARCMTEnabled)
3670 D.Diag(diag::err_drv_argument_not_allowed_with)
3671 << A->getAsString(Args) << "-ccc-arcmt-migrate";
3673 CmdArgs.push_back("-mt-migrate-directory");
3674 CmdArgs.push_back(A->getValue());
3676 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3677 options::OPT_objcmt_migrate_subscripting,
3678 options::OPT_objcmt_migrate_property)) {
3679 // None specified, means enable them all.
3680 CmdArgs.push_back("-objcmt-migrate-literals");
3681 CmdArgs.push_back("-objcmt-migrate-subscripting");
3682 CmdArgs.push_back("-objcmt-migrate-property");
3683 } else {
3684 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3685 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3686 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3688 } else {
3689 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3690 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3691 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3692 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3693 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3694 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3695 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3696 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3697 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3698 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3699 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3700 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3701 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3702 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3703 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3704 Args.AddLastArg(CmdArgs, options::OPT_objcmt_allowlist_dir_path);
3708 static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3709 const ArgList &Args, ArgStringList &CmdArgs) {
3710 // -fbuiltin is default unless -mkernel is used.
3711 bool UseBuiltins =
3712 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3713 !Args.hasArg(options::OPT_mkernel));
3714 if (!UseBuiltins)
3715 CmdArgs.push_back("-fno-builtin");
3717 // -ffreestanding implies -fno-builtin.
3718 if (Args.hasArg(options::OPT_ffreestanding))
3719 UseBuiltins = false;
3721 // Process the -fno-builtin-* options.
3722 for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
3723 A->claim();
3725 // If -fno-builtin is specified, then there's no need to pass the option to
3726 // the frontend.
3727 if (UseBuiltins)
3728 A->render(Args, CmdArgs);
3731 // le32-specific flags:
3732 // -fno-math-builtin: clang should not convert math builtins to intrinsics
3733 // by default.
3734 if (TC.getArch() == llvm::Triple::le32)
3735 CmdArgs.push_back("-fno-math-builtin");
3738 bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
3739 if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
3740 Twine Path{Str};
3741 Path.toVector(Result);
3742 return Path.getSingleStringRef() != "";
3744 if (llvm::sys::path::cache_directory(Result)) {
3745 llvm::sys::path::append(Result, "clang");
3746 llvm::sys::path::append(Result, "ModuleCache");
3747 return true;
3749 return false;
3752 static bool RenderModulesOptions(Compilation &C, const Driver &D,
3753 const ArgList &Args, const InputInfo &Input,
3754 const InputInfo &Output, bool HaveStd20,
3755 ArgStringList &CmdArgs) {
3756 bool IsCXX = types::isCXX(Input.getType());
3757 bool HaveStdCXXModules = IsCXX && HaveStd20;
3758 bool HaveModules = HaveStdCXXModules;
3760 // -fmodules enables the use of precompiled modules (off by default).
3761 // Users can pass -fno-cxx-modules to turn off modules support for
3762 // C++/Objective-C++ programs.
3763 bool HaveClangModules = false;
3764 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3765 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3766 options::OPT_fno_cxx_modules, true);
3767 if (AllowedInCXX || !IsCXX) {
3768 CmdArgs.push_back("-fmodules");
3769 HaveClangModules = true;
3773 HaveModules |= HaveClangModules;
3775 // -fmodule-maps enables implicit reading of module map files. By default,
3776 // this is enabled if we are using Clang's flavor of precompiled modules.
3777 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3778 options::OPT_fno_implicit_module_maps, HaveClangModules))
3779 CmdArgs.push_back("-fimplicit-module-maps");
3781 // -fmodules-decluse checks that modules used are declared so (off by default)
3782 Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
3783 options::OPT_fno_modules_decluse);
3785 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3786 // all #included headers are part of modules.
3787 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3788 options::OPT_fno_modules_strict_decluse, false))
3789 CmdArgs.push_back("-fmodules-strict-decluse");
3791 // -fno-implicit-modules turns off implicitly compiling modules on demand.
3792 bool ImplicitModules = false;
3793 if (!Args.hasFlag(options::OPT_fimplicit_modules,
3794 options::OPT_fno_implicit_modules, HaveClangModules)) {
3795 if (HaveModules)
3796 CmdArgs.push_back("-fno-implicit-modules");
3797 } else if (HaveModules) {
3798 ImplicitModules = true;
3799 // -fmodule-cache-path specifies where our implicitly-built module files
3800 // should be written.
3801 SmallString<128> Path;
3802 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3803 Path = A->getValue();
3805 bool HasPath = true;
3806 if (C.isForDiagnostics()) {
3807 // When generating crash reports, we want to emit the modules along with
3808 // the reproduction sources, so we ignore any provided module path.
3809 Path = Output.getFilename();
3810 llvm::sys::path::replace_extension(Path, ".cache");
3811 llvm::sys::path::append(Path, "modules");
3812 } else if (Path.empty()) {
3813 // No module path was provided: use the default.
3814 HasPath = Driver::getDefaultModuleCachePath(Path);
3817 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3818 // That being said, that failure is unlikely and not caching is harmless.
3819 if (HasPath) {
3820 const char Arg[] = "-fmodules-cache-path=";
3821 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3822 CmdArgs.push_back(Args.MakeArgString(Path));
3826 if (HaveModules) {
3827 if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
3828 options::OPT_fno_prebuilt_implicit_modules, false))
3829 CmdArgs.push_back("-fprebuilt-implicit-modules");
3830 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
3831 options::OPT_fno_modules_validate_input_files_content,
3832 false))
3833 CmdArgs.push_back("-fvalidate-ast-input-files-content");
3836 // -fmodule-name specifies the module that is currently being built (or
3837 // used for header checking by -fmodule-maps).
3838 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3840 // -fmodule-map-file can be used to specify files containing module
3841 // definitions.
3842 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3844 // -fbuiltin-module-map can be used to load the clang
3845 // builtin headers modulemap file.
3846 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
3847 SmallString<128> BuiltinModuleMap(D.ResourceDir);
3848 llvm::sys::path::append(BuiltinModuleMap, "include");
3849 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
3850 if (llvm::sys::fs::exists(BuiltinModuleMap))
3851 CmdArgs.push_back(
3852 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
3855 // The -fmodule-file=<name>=<file> form specifies the mapping of module
3856 // names to precompiled module files (the module is loaded only if used).
3857 // The -fmodule-file=<file> form can be used to unconditionally load
3858 // precompiled module files (whether used or not).
3859 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
3860 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
3862 // -fprebuilt-module-path specifies where to load the prebuilt module files.
3863 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
3864 CmdArgs.push_back(Args.MakeArgString(
3865 std::string("-fprebuilt-module-path=") + A->getValue()));
3866 A->claim();
3868 } else
3869 Args.ClaimAllArgs(options::OPT_fmodule_file);
3871 // When building modules and generating crashdumps, we need to dump a module
3872 // dependency VFS alongside the output.
3873 if (HaveClangModules && C.isForDiagnostics()) {
3874 SmallString<128> VFSDir(Output.getFilename());
3875 llvm::sys::path::replace_extension(VFSDir, ".cache");
3876 // Add the cache directory as a temp so the crash diagnostics pick it up.
3877 C.addTempFile(Args.MakeArgString(VFSDir));
3879 llvm::sys::path::append(VFSDir, "vfs");
3880 CmdArgs.push_back("-module-dependency-dir");
3881 CmdArgs.push_back(Args.MakeArgString(VFSDir));
3884 if (HaveClangModules)
3885 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
3887 // Pass through all -fmodules-ignore-macro arguments.
3888 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3889 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3890 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3892 if (HaveClangModules) {
3893 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3895 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
3896 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
3897 D.Diag(diag::err_drv_argument_not_allowed_with)
3898 << A->getAsString(Args) << "-fbuild-session-timestamp";
3900 llvm::sys::fs::file_status Status;
3901 if (llvm::sys::fs::status(A->getValue(), Status))
3902 D.Diag(diag::err_drv_no_such_file) << A->getValue();
3903 CmdArgs.push_back(Args.MakeArgString(
3904 "-fbuild-session-timestamp=" +
3905 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
3906 Status.getLastModificationTime().time_since_epoch())
3907 .count())));
3910 if (Args.getLastArg(
3911 options::OPT_fmodules_validate_once_per_build_session)) {
3912 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
3913 options::OPT_fbuild_session_file))
3914 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
3916 Args.AddLastArg(CmdArgs,
3917 options::OPT_fmodules_validate_once_per_build_session);
3920 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
3921 options::OPT_fno_modules_validate_system_headers,
3922 ImplicitModules))
3923 CmdArgs.push_back("-fmodules-validate-system-headers");
3925 Args.AddLastArg(CmdArgs,
3926 options::OPT_fmodules_disable_diagnostic_validation);
3927 } else {
3928 Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
3929 Args.ClaimAllArgs(options::OPT_fbuild_session_file);
3930 Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
3931 Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
3932 Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
3933 Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
3936 // Claim `-fmodule-output` and `-fmodule-output=` to avoid unused warnings.
3937 Args.ClaimAllArgs(options::OPT_fmodule_output);
3938 Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
3940 return HaveModules;
3943 static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
3944 ArgStringList &CmdArgs) {
3945 // -fsigned-char is default.
3946 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
3947 options::OPT_fno_signed_char,
3948 options::OPT_funsigned_char,
3949 options::OPT_fno_unsigned_char)) {
3950 if (A->getOption().matches(options::OPT_funsigned_char) ||
3951 A->getOption().matches(options::OPT_fno_signed_char)) {
3952 CmdArgs.push_back("-fno-signed-char");
3954 } else if (!isSignedCharDefault(T)) {
3955 CmdArgs.push_back("-fno-signed-char");
3958 // The default depends on the language standard.
3959 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
3961 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
3962 options::OPT_fno_short_wchar)) {
3963 if (A->getOption().matches(options::OPT_fshort_wchar)) {
3964 CmdArgs.push_back("-fwchar-type=short");
3965 CmdArgs.push_back("-fno-signed-wchar");
3966 } else {
3967 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
3968 CmdArgs.push_back("-fwchar-type=int");
3969 if (T.isOSzOS() ||
3970 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
3971 CmdArgs.push_back("-fno-signed-wchar");
3972 else
3973 CmdArgs.push_back("-fsigned-wchar");
3975 } else if (T.isOSzOS())
3976 CmdArgs.push_back("-fno-signed-wchar");
3979 static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
3980 const llvm::Triple &T, const ArgList &Args,
3981 ObjCRuntime &Runtime, bool InferCovariantReturns,
3982 const InputInfo &Input, ArgStringList &CmdArgs) {
3983 const llvm::Triple::ArchType Arch = TC.getArch();
3985 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
3986 // is the default. Except for deployment target of 10.5, next runtime is
3987 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
3988 if (Runtime.isNonFragile()) {
3989 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3990 options::OPT_fno_objc_legacy_dispatch,
3991 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
3992 if (TC.UseObjCMixedDispatch())
3993 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3994 else
3995 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3999 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4000 // to do Array/Dictionary subscripting by default.
4001 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4002 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4003 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4005 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4006 // NOTE: This logic is duplicated in ToolChains.cpp.
4007 if (isObjCAutoRefCount(Args)) {
4008 TC.CheckObjCARC();
4010 CmdArgs.push_back("-fobjc-arc");
4012 // FIXME: It seems like this entire block, and several around it should be
4013 // wrapped in isObjC, but for now we just use it here as this is where it
4014 // was being used previously.
4015 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
4016 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4017 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4018 else
4019 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4022 // Allow the user to enable full exceptions code emission.
4023 // We default off for Objective-C, on for Objective-C++.
4024 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4025 options::OPT_fno_objc_arc_exceptions,
4026 /*Default=*/types::isCXX(Input.getType())))
4027 CmdArgs.push_back("-fobjc-arc-exceptions");
4030 // Silence warning for full exception code emission options when explicitly
4031 // set to use no ARC.
4032 if (Args.hasArg(options::OPT_fno_objc_arc)) {
4033 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
4034 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
4037 // Allow the user to control whether messages can be converted to runtime
4038 // functions.
4039 if (types::isObjC(Input.getType())) {
4040 auto *Arg = Args.getLastArg(
4041 options::OPT_fobjc_convert_messages_to_runtime_calls,
4042 options::OPT_fno_objc_convert_messages_to_runtime_calls);
4043 if (Arg &&
4044 Arg->getOption().matches(
4045 options::OPT_fno_objc_convert_messages_to_runtime_calls))
4046 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
4049 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4050 // rewriter.
4051 if (InferCovariantReturns)
4052 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4054 // Pass down -fobjc-weak or -fno-objc-weak if present.
4055 if (types::isObjC(Input.getType())) {
4056 auto WeakArg =
4057 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4058 if (!WeakArg) {
4059 // nothing to do
4060 } else if (!Runtime.allowsWeak()) {
4061 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4062 D.Diag(diag::err_objc_weak_unsupported);
4063 } else {
4064 WeakArg->render(Args, CmdArgs);
4068 if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4069 CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
4072 static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4073 ArgStringList &CmdArgs) {
4074 bool CaretDefault = true;
4075 bool ColumnDefault = true;
4077 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4078 options::OPT__SLASH_diagnostics_column,
4079 options::OPT__SLASH_diagnostics_caret)) {
4080 switch (A->getOption().getID()) {
4081 case options::OPT__SLASH_diagnostics_caret:
4082 CaretDefault = true;
4083 ColumnDefault = true;
4084 break;
4085 case options::OPT__SLASH_diagnostics_column:
4086 CaretDefault = false;
4087 ColumnDefault = true;
4088 break;
4089 case options::OPT__SLASH_diagnostics_classic:
4090 CaretDefault = false;
4091 ColumnDefault = false;
4092 break;
4096 // -fcaret-diagnostics is default.
4097 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4098 options::OPT_fno_caret_diagnostics, CaretDefault))
4099 CmdArgs.push_back("-fno-caret-diagnostics");
4101 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4102 options::OPT_fno_diagnostics_fixit_info);
4103 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4104 options::OPT_fno_diagnostics_show_option);
4106 if (const Arg *A =
4107 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4108 CmdArgs.push_back("-fdiagnostics-show-category");
4109 CmdArgs.push_back(A->getValue());
4112 Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4113 options::OPT_fno_diagnostics_show_hotness);
4115 if (const Arg *A =
4116 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4117 std::string Opt =
4118 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4119 CmdArgs.push_back(Args.MakeArgString(Opt));
4122 if (const Arg *A =
4123 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4124 std::string Opt =
4125 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4126 CmdArgs.push_back(Args.MakeArgString(Opt));
4129 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4130 CmdArgs.push_back("-fdiagnostics-format");
4131 CmdArgs.push_back(A->getValue());
4132 if (StringRef(A->getValue()) == "sarif" ||
4133 StringRef(A->getValue()) == "SARIF")
4134 D.Diag(diag::warn_drv_sarif_format_unstable);
4137 if (const Arg *A = Args.getLastArg(
4138 options::OPT_fdiagnostics_show_note_include_stack,
4139 options::OPT_fno_diagnostics_show_note_include_stack)) {
4140 const Option &O = A->getOption();
4141 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4142 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4143 else
4144 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4147 // Color diagnostics are parsed by the driver directly from argv and later
4148 // re-parsed to construct this job; claim any possible color diagnostic here
4149 // to avoid warn_drv_unused_argument and diagnose bad
4150 // OPT_fdiagnostics_color_EQ values.
4151 Args.getLastArg(options::OPT_fcolor_diagnostics,
4152 options::OPT_fno_color_diagnostics);
4153 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_color_EQ)) {
4154 StringRef Value(A->getValue());
4155 if (Value != "always" && Value != "never" && Value != "auto")
4156 D.Diag(diag::err_drv_invalid_argument_to_option)
4157 << Value << A->getOption().getName();
4160 if (D.getDiags().getDiagnosticOptions().ShowColors)
4161 CmdArgs.push_back("-fcolor-diagnostics");
4163 if (Args.hasArg(options::OPT_fansi_escape_codes))
4164 CmdArgs.push_back("-fansi-escape-codes");
4166 Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4167 options::OPT_fno_show_source_location);
4169 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4170 options::OPT_fno_diagnostics_show_line_numbers);
4172 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4173 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4175 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4176 ColumnDefault))
4177 CmdArgs.push_back("-fno-show-column");
4179 Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4180 options::OPT_fno_spell_checking);
4183 DwarfFissionKind tools::getDebugFissionKind(const Driver &D,
4184 const ArgList &Args, Arg *&Arg) {
4185 Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
4186 options::OPT_gno_split_dwarf);
4187 if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf))
4188 return DwarfFissionKind::None;
4190 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
4191 return DwarfFissionKind::Split;
4193 StringRef Value = Arg->getValue();
4194 if (Value == "split")
4195 return DwarfFissionKind::Split;
4196 if (Value == "single")
4197 return DwarfFissionKind::Single;
4199 D.Diag(diag::err_drv_unsupported_option_argument)
4200 << Arg->getSpelling() << Arg->getValue();
4201 return DwarfFissionKind::None;
4204 static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4205 const ArgList &Args, ArgStringList &CmdArgs,
4206 unsigned DwarfVersion) {
4207 auto *DwarfFormatArg =
4208 Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4209 if (!DwarfFormatArg)
4210 return;
4212 if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4213 if (DwarfVersion < 3)
4214 D.Diag(diag::err_drv_argument_only_allowed_with)
4215 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4216 else if (!T.isArch64Bit())
4217 D.Diag(diag::err_drv_argument_only_allowed_with)
4218 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4219 else if (!T.isOSBinFormatELF())
4220 D.Diag(diag::err_drv_argument_only_allowed_with)
4221 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4224 DwarfFormatArg->render(Args, CmdArgs);
4227 static void
4228 renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4229 const ArgList &Args, bool IRInput, ArgStringList &CmdArgs,
4230 const InputInfo &Output,
4231 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4232 DwarfFissionKind &DwarfFission) {
4233 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
4234 options::OPT_fno_debug_info_for_profiling, false) &&
4235 checkDebugInfoOption(
4236 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
4237 CmdArgs.push_back("-fdebug-info-for-profiling");
4239 // The 'g' groups options involve a somewhat intricate sequence of decisions
4240 // about what to pass from the driver to the frontend, but by the time they
4241 // reach cc1 they've been factored into three well-defined orthogonal choices:
4242 // * what level of debug info to generate
4243 // * what dwarf version to write
4244 // * what debugger tuning to use
4245 // This avoids having to monkey around further in cc1 other than to disable
4246 // codeview if not running in a Windows environment. Perhaps even that
4247 // decision should be made in the driver as well though.
4248 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4250 bool SplitDWARFInlining =
4251 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4252 options::OPT_fno_split_dwarf_inlining, false);
4254 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4255 // object file generation and no IR generation, -gN should not be needed. So
4256 // allow -gsplit-dwarf with either -gN or IR input.
4257 if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4258 Arg *SplitDWARFArg;
4259 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4260 if (DwarfFission != DwarfFissionKind::None &&
4261 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4262 DwarfFission = DwarfFissionKind::None;
4263 SplitDWARFInlining = false;
4266 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4267 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4269 // If the last option explicitly specified a debug-info level, use it.
4270 if (checkDebugInfoOption(A, Args, D, TC) &&
4271 A->getOption().matches(options::OPT_gN_Group)) {
4272 DebugInfoKind = debugLevelToInfoKind(*A);
4273 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4274 // complicated if you've disabled inline info in the skeleton CUs
4275 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4276 // line-tables-only, so let those compose naturally in that case.
4277 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4278 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4279 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4280 SplitDWARFInlining))
4281 DwarfFission = DwarfFissionKind::None;
4285 // If a debugger tuning argument appeared, remember it.
4286 bool HasDebuggerTuning = false;
4287 if (const Arg *A =
4288 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4289 HasDebuggerTuning = true;
4290 if (checkDebugInfoOption(A, Args, D, TC)) {
4291 if (A->getOption().matches(options::OPT_glldb))
4292 DebuggerTuning = llvm::DebuggerKind::LLDB;
4293 else if (A->getOption().matches(options::OPT_gsce))
4294 DebuggerTuning = llvm::DebuggerKind::SCE;
4295 else if (A->getOption().matches(options::OPT_gdbx))
4296 DebuggerTuning = llvm::DebuggerKind::DBX;
4297 else
4298 DebuggerTuning = llvm::DebuggerKind::GDB;
4302 // If a -gdwarf argument appeared, remember it.
4303 bool EmitDwarf = false;
4304 if (const Arg *A = getDwarfNArg(Args))
4305 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4307 bool EmitCodeView = false;
4308 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4309 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4311 // If the user asked for debug info but did not explicitly specify -gcodeview
4312 // or -gdwarf, ask the toolchain for the default format.
4313 if (!EmitCodeView && !EmitDwarf &&
4314 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4315 switch (TC.getDefaultDebugFormat()) {
4316 case llvm::codegenoptions::DIF_CodeView:
4317 EmitCodeView = true;
4318 break;
4319 case llvm::codegenoptions::DIF_DWARF:
4320 EmitDwarf = true;
4321 break;
4325 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4326 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4327 // be lower than what the user wanted.
4328 if (EmitDwarf) {
4329 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4330 // Clamp effective DWARF version to the max supported by the toolchain.
4331 EffectiveDWARFVersion =
4332 std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4333 } else {
4334 Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4337 // -gline-directives-only supported only for the DWARF debug info.
4338 if (RequestedDWARFVersion == 0 &&
4339 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4340 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4342 // strict DWARF is set to false by default. But for DBX, we need it to be set
4343 // as true by default.
4344 if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4345 (void)checkDebugInfoOption(A, Args, D, TC);
4346 if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4347 DebuggerTuning == llvm::DebuggerKind::DBX))
4348 CmdArgs.push_back("-gstrict-dwarf");
4350 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4351 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4353 // Column info is included by default for everything except SCE and
4354 // CodeView. Clang doesn't track end columns, just starting columns, which,
4355 // in theory, is fine for CodeView (and PDB). In practice, however, the
4356 // Microsoft debuggers don't handle missing end columns well, and the AIX
4357 // debugger DBX also doesn't handle the columns well, so it's better not to
4358 // include any column info.
4359 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4360 (void)checkDebugInfoOption(A, Args, D, TC);
4361 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4362 !EmitCodeView &&
4363 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4364 DebuggerTuning != llvm::DebuggerKind::DBX)))
4365 CmdArgs.push_back("-gno-column-info");
4367 // FIXME: Move backend command line options to the module.
4368 if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4369 // If -gline-tables-only or -gline-directives-only is the last option it
4370 // wins.
4371 if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4372 TC)) {
4373 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4374 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4375 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4376 CmdArgs.push_back("-dwarf-ext-refs");
4377 CmdArgs.push_back("-fmodule-format=obj");
4382 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4383 CmdArgs.push_back("-fsplit-dwarf-inlining");
4385 // After we've dealt with all combinations of things that could
4386 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4387 // figure out if we need to "upgrade" it to standalone debug info.
4388 // We parse these two '-f' options whether or not they will be used,
4389 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4390 bool NeedFullDebug = Args.hasFlag(
4391 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4392 DebuggerTuning == llvm::DebuggerKind::LLDB ||
4393 TC.GetDefaultStandaloneDebug());
4394 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4395 (void)checkDebugInfoOption(A, Args, D, TC);
4397 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4398 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4399 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4400 options::OPT_feliminate_unused_debug_types, false))
4401 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4402 else if (NeedFullDebug)
4403 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4406 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4407 false)) {
4408 // Source embedding is a vendor extension to DWARF v5. By now we have
4409 // checked if a DWARF version was stated explicitly, and have otherwise
4410 // fallen back to the target default, so if this is still not at least 5
4411 // we emit an error.
4412 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4413 if (RequestedDWARFVersion < 5)
4414 D.Diag(diag::err_drv_argument_only_allowed_with)
4415 << A->getAsString(Args) << "-gdwarf-5";
4416 else if (EffectiveDWARFVersion < 5)
4417 // The toolchain has reduced allowed dwarf version, so we can't enable
4418 // -gembed-source.
4419 D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4420 << A->getAsString(Args) << TC.getTripleString() << 5
4421 << EffectiveDWARFVersion;
4422 else if (checkDebugInfoOption(A, Args, D, TC))
4423 CmdArgs.push_back("-gembed-source");
4426 if (EmitCodeView) {
4427 CmdArgs.push_back("-gcodeview");
4429 Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4430 options::OPT_gno_codeview_ghash);
4432 Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4433 options::OPT_gno_codeview_command_line);
4436 Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4437 options::OPT_gno_inline_line_tables);
4439 // When emitting remarks, we need at least debug lines in the output.
4440 if (willEmitRemarks(Args) &&
4441 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4442 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4444 // Adjust the debug info kind for the given toolchain.
4445 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4447 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4448 // set.
4449 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4450 T.isOSAIX() && !HasDebuggerTuning
4451 ? llvm::DebuggerKind::Default
4452 : DebuggerTuning);
4454 // -fdebug-macro turns on macro debug info generation.
4455 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4456 false))
4457 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4458 D, TC))
4459 CmdArgs.push_back("-debug-info-macro");
4461 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4462 const auto *PubnamesArg =
4463 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4464 options::OPT_gpubnames, options::OPT_gno_pubnames);
4465 if (DwarfFission != DwarfFissionKind::None ||
4466 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
4467 if (!PubnamesArg ||
4468 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4469 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
4470 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4471 options::OPT_gpubnames)
4472 ? "-gpubnames"
4473 : "-ggnu-pubnames");
4474 const auto *SimpleTemplateNamesArg =
4475 Args.getLastArg(options::OPT_gsimple_template_names,
4476 options::OPT_gno_simple_template_names);
4477 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4478 if (SimpleTemplateNamesArg &&
4479 checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
4480 const auto &Opt = SimpleTemplateNamesArg->getOption();
4481 if (Opt.matches(options::OPT_gsimple_template_names)) {
4482 ForwardTemplateParams = true;
4483 CmdArgs.push_back("-gsimple-template-names=simple");
4487 if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4488 StringRef v = A->getValue();
4489 CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
4492 Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
4493 options::OPT_fno_debug_ranges_base_address);
4495 // -gdwarf-aranges turns on the emission of the aranges section in the
4496 // backend.
4497 // Always enabled for SCE tuning.
4498 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
4499 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
4500 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
4501 if (NeedAranges) {
4502 CmdArgs.push_back("-mllvm");
4503 CmdArgs.push_back("-generate-arange-section");
4506 Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
4507 options::OPT_fno_force_dwarf_frame);
4509 if (Args.hasFlag(options::OPT_fdebug_types_section,
4510 options::OPT_fno_debug_types_section, false)) {
4511 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4512 D.Diag(diag::err_drv_unsupported_opt_for_target)
4513 << Args.getLastArg(options::OPT_fdebug_types_section)
4514 ->getAsString(Args)
4515 << T.getTriple();
4516 } else if (checkDebugInfoOption(
4517 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4518 TC)) {
4519 CmdArgs.push_back("-mllvm");
4520 CmdArgs.push_back("-generate-type-units");
4524 // To avoid join/split of directory+filename, the integrated assembler prefers
4525 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4526 // form before DWARF v5.
4527 if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4528 options::OPT_fno_dwarf_directory_asm,
4529 TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4530 CmdArgs.push_back("-fno-dwarf-directory-asm");
4532 // Decide how to render forward declarations of template instantiations.
4533 // SCE wants full descriptions, others just get them in the name.
4534 if (ForwardTemplateParams)
4535 CmdArgs.push_back("-debug-forward-template-params");
4537 // Do we need to explicitly import anonymous namespaces into the parent
4538 // scope?
4539 if (DebuggerTuning == llvm::DebuggerKind::SCE)
4540 CmdArgs.push_back("-dwarf-explicit-import");
4542 renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
4543 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4545 // This controls whether or not we perform JustMyCode instrumentation.
4546 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
4547 if (TC.getTriple().isOSBinFormatELF() || D.IsCLMode()) {
4548 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
4549 CmdArgs.push_back("-fjmc");
4550 else if (D.IsCLMode())
4551 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
4552 << "'/Zi', '/Z7'";
4553 else
4554 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
4555 << "-g";
4556 } else {
4557 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
4561 // Add in -fdebug-compilation-dir if necessary.
4562 const char *DebugCompilationDir =
4563 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
4565 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
4567 // Add the output path to the object file for CodeView debug infos.
4568 if (EmitCodeView && Output.isFilename())
4569 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
4570 Output.getFilename());
4573 static void ProcessVSRuntimeLibrary(const ArgList &Args,
4574 ArgStringList &CmdArgs) {
4575 unsigned RTOptionID = options::OPT__SLASH_MT;
4577 if (Args.hasArg(options::OPT__SLASH_LDd))
4578 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4579 // but defining _DEBUG is sticky.
4580 RTOptionID = options::OPT__SLASH_MTd;
4582 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4583 RTOptionID = A->getOption().getID();
4585 if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
4586 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4587 .Case("static", options::OPT__SLASH_MT)
4588 .Case("static_dbg", options::OPT__SLASH_MTd)
4589 .Case("dll", options::OPT__SLASH_MD)
4590 .Case("dll_dbg", options::OPT__SLASH_MDd)
4591 .Default(options::OPT__SLASH_MT);
4594 StringRef FlagForCRT;
4595 switch (RTOptionID) {
4596 case options::OPT__SLASH_MD:
4597 if (Args.hasArg(options::OPT__SLASH_LDd))
4598 CmdArgs.push_back("-D_DEBUG");
4599 CmdArgs.push_back("-D_MT");
4600 CmdArgs.push_back("-D_DLL");
4601 FlagForCRT = "--dependent-lib=msvcrt";
4602 break;
4603 case options::OPT__SLASH_MDd:
4604 CmdArgs.push_back("-D_DEBUG");
4605 CmdArgs.push_back("-D_MT");
4606 CmdArgs.push_back("-D_DLL");
4607 FlagForCRT = "--dependent-lib=msvcrtd";
4608 break;
4609 case options::OPT__SLASH_MT:
4610 if (Args.hasArg(options::OPT__SLASH_LDd))
4611 CmdArgs.push_back("-D_DEBUG");
4612 CmdArgs.push_back("-D_MT");
4613 CmdArgs.push_back("-flto-visibility-public-std");
4614 FlagForCRT = "--dependent-lib=libcmt";
4615 break;
4616 case options::OPT__SLASH_MTd:
4617 CmdArgs.push_back("-D_DEBUG");
4618 CmdArgs.push_back("-D_MT");
4619 CmdArgs.push_back("-flto-visibility-public-std");
4620 FlagForCRT = "--dependent-lib=libcmtd";
4621 break;
4622 default:
4623 llvm_unreachable("Unexpected option ID.");
4626 if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
4627 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
4628 } else {
4629 CmdArgs.push_back(FlagForCRT.data());
4631 // This provides POSIX compatibility (maps 'open' to '_open'), which most
4632 // users want. The /Za flag to cl.exe turns this off, but it's not
4633 // implemented in clang.
4634 CmdArgs.push_back("--dependent-lib=oldnames");
4638 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
4639 const InputInfo &Output, const InputInfoList &Inputs,
4640 const ArgList &Args, const char *LinkingOutput) const {
4641 const auto &TC = getToolChain();
4642 const llvm::Triple &RawTriple = TC.getTriple();
4643 const llvm::Triple &Triple = TC.getEffectiveTriple();
4644 const std::string &TripleStr = Triple.getTriple();
4646 bool KernelOrKext =
4647 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
4648 const Driver &D = TC.getDriver();
4649 ArgStringList CmdArgs;
4651 assert(Inputs.size() >= 1 && "Must have at least one input.");
4652 // CUDA/HIP compilation may have multiple inputs (source file + results of
4653 // device-side compilations). OpenMP device jobs also take the host IR as a
4654 // second input. Module precompilation accepts a list of header files to
4655 // include as part of the module. API extraction accepts a list of header
4656 // files whose API information is emitted in the output. All other jobs are
4657 // expected to have exactly one input.
4658 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
4659 bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
4660 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
4661 bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
4662 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
4663 bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
4664 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
4665 JA.isDeviceOffloading(Action::OFK_Host));
4666 bool IsHostOffloadingAction =
4667 JA.isHostOffloading(Action::OFK_OpenMP) ||
4668 (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
4669 Args.hasFlag(options::OPT_offload_new_driver,
4670 options::OPT_no_offload_new_driver, false));
4672 bool IsRDCMode =
4673 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
4674 bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction);
4675 auto LTOMode = D.getLTOMode(IsDeviceOffloadAction);
4677 // Extract API doesn't have a main input file, so invent a fake one as a
4678 // placeholder.
4679 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
4680 "extract-api");
4682 const InputInfo &Input =
4683 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
4685 InputInfoList ExtractAPIInputs;
4686 InputInfoList HostOffloadingInputs;
4687 const InputInfo *CudaDeviceInput = nullptr;
4688 const InputInfo *OpenMPDeviceInput = nullptr;
4689 for (const InputInfo &I : Inputs) {
4690 if (&I == &Input || I.getType() == types::TY_Nothing) {
4691 // This is the primary input or contains nothing.
4692 } else if (IsExtractAPI) {
4693 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
4694 if (I.getType() != ExpectedInputType) {
4695 D.Diag(diag::err_drv_extract_api_wrong_kind)
4696 << I.getFilename() << types::getTypeName(I.getType())
4697 << types::getTypeName(ExpectedInputType);
4699 ExtractAPIInputs.push_back(I);
4700 } else if (IsHostOffloadingAction) {
4701 HostOffloadingInputs.push_back(I);
4702 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
4703 CudaDeviceInput = &I;
4704 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
4705 OpenMPDeviceInput = &I;
4706 } else {
4707 llvm_unreachable("unexpectedly given multiple inputs");
4711 const llvm::Triple *AuxTriple =
4712 (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
4713 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
4714 bool IsIAMCU = RawTriple.isOSIAMCU();
4716 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
4717 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
4718 // Windows), we need to pass Windows-specific flags to cc1.
4719 if (IsCuda || IsHIP)
4720 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
4722 // C++ is not supported for IAMCU.
4723 if (IsIAMCU && types::isCXX(Input.getType()))
4724 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
4726 // Invoke ourselves in -cc1 mode.
4728 // FIXME: Implement custom jobs for internal actions.
4729 CmdArgs.push_back("-cc1");
4731 // Add the "effective" target triple.
4732 CmdArgs.push_back("-triple");
4733 CmdArgs.push_back(Args.MakeArgString(TripleStr));
4735 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
4736 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
4737 Args.ClaimAllArgs(options::OPT_MJ);
4738 } else if (const Arg *GenCDBFragment =
4739 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
4740 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
4741 TripleStr, Output, Input, Args);
4742 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
4745 if (IsCuda || IsHIP) {
4746 // We have to pass the triple of the host if compiling for a CUDA/HIP device
4747 // and vice-versa.
4748 std::string NormalizedTriple;
4749 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
4750 JA.isDeviceOffloading(Action::OFK_HIP))
4751 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
4752 ->getTriple()
4753 .normalize();
4754 else {
4755 // Host-side compilation.
4756 NormalizedTriple =
4757 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
4758 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
4759 ->getTriple()
4760 .normalize();
4761 if (IsCuda) {
4762 // We need to figure out which CUDA version we're compiling for, as that
4763 // determines how we load and launch GPU kernels.
4764 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
4765 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
4766 assert(CTC && "Expected valid CUDA Toolchain.");
4767 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
4768 CmdArgs.push_back(Args.MakeArgString(
4769 Twine("-target-sdk-version=") +
4770 CudaVersionToString(CTC->CudaInstallation.version())));
4771 // Unsized function arguments used for variadics were introduced in
4772 // CUDA-9.0. We still do not support generating code that actually uses
4773 // variadic arguments yet, but we do need to allow parsing them as
4774 // recent CUDA headers rely on that.
4775 // https://github.com/llvm/llvm-project/issues/58410
4776 if (CTC->CudaInstallation.version() >= CudaVersion::CUDA_90)
4777 CmdArgs.push_back("-fcuda-allow-variadic-functions");
4780 CmdArgs.push_back("-aux-triple");
4781 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4783 if (JA.isDeviceOffloading(Action::OFK_HIP) &&
4784 getToolChain().getTriple().isAMDGPU()) {
4785 // Device side compilation printf
4786 if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
4787 CmdArgs.push_back(Args.MakeArgString(
4788 "-mprintf-kind=" +
4789 Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
4790 // Force compiler error on invalid conversion specifiers
4791 CmdArgs.push_back(
4792 Args.MakeArgString("-Werror=format-invalid-specifier"));
4797 // Unconditionally claim the printf option now to avoid unused diagnostic.
4798 if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
4799 PF->claim();
4801 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) {
4802 CmdArgs.push_back("-fsycl-is-device");
4804 if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) {
4805 A->render(Args, CmdArgs);
4806 } else {
4807 // Ensure the default version in SYCL mode is 2020.
4808 CmdArgs.push_back("-sycl-std=2020");
4812 if (IsOpenMPDevice) {
4813 // We have to pass the triple of the host if compiling for an OpenMP device.
4814 std::string NormalizedTriple =
4815 C.getSingleOffloadToolChain<Action::OFK_Host>()
4816 ->getTriple()
4817 .normalize();
4818 CmdArgs.push_back("-aux-triple");
4819 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4822 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
4823 Triple.getArch() == llvm::Triple::thumb)) {
4824 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
4825 unsigned Version = 0;
4826 bool Failure =
4827 Triple.getArchName().substr(Offset).consumeInteger(10, Version);
4828 if (Failure || Version < 7)
4829 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
4830 << TripleStr;
4833 // Push all default warning arguments that are specific to
4834 // the given target. These come before user provided warning options
4835 // are provided.
4836 TC.addClangWarningOptions(CmdArgs);
4838 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
4839 if (Triple.isSPIR() || Triple.isSPIRV())
4840 CmdArgs.push_back("-Wspir-compat");
4842 // Select the appropriate action.
4843 RewriteKind rewriteKind = RK_None;
4845 bool UnifiedLTO = false;
4846 if (IsUsingLTO) {
4847 UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
4848 options::OPT_fno_unified_lto, Triple.isPS());
4849 if (UnifiedLTO)
4850 CmdArgs.push_back("-funified-lto");
4853 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
4854 // it claims when not running an assembler. Otherwise, clang would emit
4855 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
4856 // flags while debugging something. That'd be somewhat inconvenient, and it's
4857 // also inconsistent with most other flags -- we don't warn on
4858 // -ffunction-sections not being used in -E mode either for example, even
4859 // though it's not really used either.
4860 if (!isa<AssembleJobAction>(JA)) {
4861 // The args claimed here should match the args used in
4862 // CollectArgsForIntegratedAssembler().
4863 if (TC.useIntegratedAs()) {
4864 Args.ClaimAllArgs(options::OPT_mrelax_all);
4865 Args.ClaimAllArgs(options::OPT_mno_relax_all);
4866 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
4867 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
4868 switch (C.getDefaultToolChain().getArch()) {
4869 case llvm::Triple::arm:
4870 case llvm::Triple::armeb:
4871 case llvm::Triple::thumb:
4872 case llvm::Triple::thumbeb:
4873 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
4874 break;
4875 default:
4876 break;
4879 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
4880 Args.ClaimAllArgs(options::OPT_Xassembler);
4881 Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
4884 if (isa<AnalyzeJobAction>(JA)) {
4885 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
4886 CmdArgs.push_back("-analyze");
4887 } else if (isa<MigrateJobAction>(JA)) {
4888 CmdArgs.push_back("-migrate");
4889 } else if (isa<PreprocessJobAction>(JA)) {
4890 if (Output.getType() == types::TY_Dependencies)
4891 CmdArgs.push_back("-Eonly");
4892 else {
4893 CmdArgs.push_back("-E");
4894 if (Args.hasArg(options::OPT_rewrite_objc) &&
4895 !Args.hasArg(options::OPT_g_Group))
4896 CmdArgs.push_back("-P");
4897 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
4898 CmdArgs.push_back("-fdirectives-only");
4900 } else if (isa<AssembleJobAction>(JA)) {
4901 CmdArgs.push_back("-emit-obj");
4903 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
4905 // Also ignore explicit -force_cpusubtype_ALL option.
4906 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
4907 } else if (isa<PrecompileJobAction>(JA)) {
4908 if (JA.getType() == types::TY_Nothing)
4909 CmdArgs.push_back("-fsyntax-only");
4910 else if (JA.getType() == types::TY_ModuleFile)
4911 CmdArgs.push_back("-emit-module-interface");
4912 else if (JA.getType() == types::TY_HeaderUnit)
4913 CmdArgs.push_back("-emit-header-unit");
4914 else
4915 CmdArgs.push_back("-emit-pch");
4916 } else if (isa<VerifyPCHJobAction>(JA)) {
4917 CmdArgs.push_back("-verify-pch");
4918 } else if (isa<ExtractAPIJobAction>(JA)) {
4919 assert(JA.getType() == types::TY_API_INFO &&
4920 "Extract API actions must generate a API information.");
4921 CmdArgs.push_back("-extract-api");
4922 if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
4923 ProductNameArg->render(Args, CmdArgs);
4924 if (Arg *ExtractAPIIgnoresFileArg =
4925 Args.getLastArg(options::OPT_extract_api_ignores_EQ))
4926 ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
4927 } else {
4928 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
4929 "Invalid action for clang tool.");
4930 if (JA.getType() == types::TY_Nothing) {
4931 CmdArgs.push_back("-fsyntax-only");
4932 } else if (JA.getType() == types::TY_LLVM_IR ||
4933 JA.getType() == types::TY_LTO_IR) {
4934 CmdArgs.push_back("-emit-llvm");
4935 } else if (JA.getType() == types::TY_LLVM_BC ||
4936 JA.getType() == types::TY_LTO_BC) {
4937 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
4938 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
4939 Args.hasArg(options::OPT_emit_llvm)) {
4940 CmdArgs.push_back("-emit-llvm");
4941 } else {
4942 CmdArgs.push_back("-emit-llvm-bc");
4944 } else if (JA.getType() == types::TY_IFS ||
4945 JA.getType() == types::TY_IFS_CPP) {
4946 StringRef ArgStr =
4947 Args.hasArg(options::OPT_interface_stub_version_EQ)
4948 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
4949 : "ifs-v1";
4950 CmdArgs.push_back("-emit-interface-stubs");
4951 CmdArgs.push_back(
4952 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
4953 } else if (JA.getType() == types::TY_PP_Asm) {
4954 CmdArgs.push_back("-S");
4955 } else if (JA.getType() == types::TY_AST) {
4956 CmdArgs.push_back("-emit-pch");
4957 } else if (JA.getType() == types::TY_ModuleFile) {
4958 CmdArgs.push_back("-module-file-info");
4959 } else if (JA.getType() == types::TY_RewrittenObjC) {
4960 CmdArgs.push_back("-rewrite-objc");
4961 rewriteKind = RK_NonFragile;
4962 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
4963 CmdArgs.push_back("-rewrite-objc");
4964 rewriteKind = RK_Fragile;
4965 } else {
4966 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
4969 // Preserve use-list order by default when emitting bitcode, so that
4970 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
4971 // same result as running passes here. For LTO, we don't need to preserve
4972 // the use-list order, since serialization to bitcode is part of the flow.
4973 if (JA.getType() == types::TY_LLVM_BC)
4974 CmdArgs.push_back("-emit-llvm-uselists");
4976 if (IsUsingLTO) {
4977 if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
4978 !Args.hasFlag(options::OPT_offload_new_driver,
4979 options::OPT_no_offload_new_driver, false) &&
4980 !Triple.isAMDGPU()) {
4981 D.Diag(diag::err_drv_unsupported_opt_for_target)
4982 << Args.getLastArg(options::OPT_foffload_lto,
4983 options::OPT_foffload_lto_EQ)
4984 ->getAsString(Args)
4985 << Triple.getTriple();
4986 } else if (Triple.isNVPTX() && !IsRDCMode &&
4987 JA.isDeviceOffloading(Action::OFK_Cuda)) {
4988 D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
4989 << Args.getLastArg(options::OPT_foffload_lto,
4990 options::OPT_foffload_lto_EQ)
4991 ->getAsString(Args)
4992 << "-fno-gpu-rdc";
4993 } else {
4994 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
4995 CmdArgs.push_back(Args.MakeArgString(
4996 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
4997 // PS4 uses the legacy LTO API, which does not support some of the
4998 // features enabled by -flto-unit.
4999 if (!RawTriple.isPS4() ||
5000 (D.getLTOMode() == LTOK_Full) || !UnifiedLTO)
5001 CmdArgs.push_back("-flto-unit");
5006 Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
5008 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
5009 if (!types::isLLVMIR(Input.getType()))
5010 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5011 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
5014 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
5015 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
5017 if (Args.getLastArg(options::OPT_save_temps_EQ))
5018 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
5020 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
5021 options::OPT_fmemory_profile_EQ,
5022 options::OPT_fno_memory_profile);
5023 if (MemProfArg &&
5024 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
5025 MemProfArg->render(Args, CmdArgs);
5027 if (auto *MemProfUseArg =
5028 Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
5029 if (MemProfArg)
5030 D.Diag(diag::err_drv_argument_not_allowed_with)
5031 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5032 if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
5033 options::OPT_fprofile_generate_EQ))
5034 D.Diag(diag::err_drv_argument_not_allowed_with)
5035 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5036 MemProfUseArg->render(Args, CmdArgs);
5039 // Embed-bitcode option.
5040 // Only white-listed flags below are allowed to be embedded.
5041 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5042 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
5043 // Add flags implied by -fembed-bitcode.
5044 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
5045 // Disable all llvm IR level optimizations.
5046 CmdArgs.push_back("-disable-llvm-passes");
5048 // Render target options.
5049 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5051 // reject options that shouldn't be supported in bitcode
5052 // also reject kernel/kext
5053 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5054 options::OPT_mkernel,
5055 options::OPT_fapple_kext,
5056 options::OPT_ffunction_sections,
5057 options::OPT_fno_function_sections,
5058 options::OPT_fdata_sections,
5059 options::OPT_fno_data_sections,
5060 options::OPT_fbasic_block_sections_EQ,
5061 options::OPT_funique_internal_linkage_names,
5062 options::OPT_fno_unique_internal_linkage_names,
5063 options::OPT_funique_section_names,
5064 options::OPT_fno_unique_section_names,
5065 options::OPT_funique_basic_block_section_names,
5066 options::OPT_fno_unique_basic_block_section_names,
5067 options::OPT_mrestrict_it,
5068 options::OPT_mno_restrict_it,
5069 options::OPT_mstackrealign,
5070 options::OPT_mno_stackrealign,
5071 options::OPT_mstack_alignment,
5072 options::OPT_mcmodel_EQ,
5073 options::OPT_mlong_calls,
5074 options::OPT_mno_long_calls,
5075 options::OPT_ggnu_pubnames,
5076 options::OPT_gdwarf_aranges,
5077 options::OPT_fdebug_types_section,
5078 options::OPT_fno_debug_types_section,
5079 options::OPT_fdwarf_directory_asm,
5080 options::OPT_fno_dwarf_directory_asm,
5081 options::OPT_mrelax_all,
5082 options::OPT_mno_relax_all,
5083 options::OPT_ftrap_function_EQ,
5084 options::OPT_ffixed_r9,
5085 options::OPT_mfix_cortex_a53_835769,
5086 options::OPT_mno_fix_cortex_a53_835769,
5087 options::OPT_ffixed_x18,
5088 options::OPT_mglobal_merge,
5089 options::OPT_mno_global_merge,
5090 options::OPT_mred_zone,
5091 options::OPT_mno_red_zone,
5092 options::OPT_Wa_COMMA,
5093 options::OPT_Xassembler,
5094 options::OPT_mllvm,
5096 for (const auto &A : Args)
5097 if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5098 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5100 // Render the CodeGen options that need to be passed.
5101 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5102 options::OPT_fno_optimize_sibling_calls);
5104 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
5105 CmdArgs, JA);
5107 // Render ABI arguments
5108 switch (TC.getArch()) {
5109 default: break;
5110 case llvm::Triple::arm:
5111 case llvm::Triple::armeb:
5112 case llvm::Triple::thumbeb:
5113 RenderARMABI(D, Triple, Args, CmdArgs);
5114 break;
5115 case llvm::Triple::aarch64:
5116 case llvm::Triple::aarch64_32:
5117 case llvm::Triple::aarch64_be:
5118 RenderAArch64ABI(Triple, Args, CmdArgs);
5119 break;
5122 // Optimization level for CodeGen.
5123 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5124 if (A->getOption().matches(options::OPT_O4)) {
5125 CmdArgs.push_back("-O3");
5126 D.Diag(diag::warn_O4_is_O3);
5127 } else {
5128 A->render(Args, CmdArgs);
5132 // Input/Output file.
5133 if (Output.getType() == types::TY_Dependencies) {
5134 // Handled with other dependency code.
5135 } else if (Output.isFilename()) {
5136 CmdArgs.push_back("-o");
5137 CmdArgs.push_back(Output.getFilename());
5138 } else {
5139 assert(Output.isNothing() && "Input output.");
5142 for (const auto &II : Inputs) {
5143 addDashXForInput(Args, II, CmdArgs);
5144 if (II.isFilename())
5145 CmdArgs.push_back(II.getFilename());
5146 else
5147 II.getInputArg().renderAsInput(Args, CmdArgs);
5150 C.addCommand(std::make_unique<Command>(
5151 JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(),
5152 CmdArgs, Inputs, Output, D.getPrependArg()));
5153 return;
5156 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5157 CmdArgs.push_back("-fembed-bitcode=marker");
5159 // We normally speed up the clang process a bit by skipping destructors at
5160 // exit, but when we're generating diagnostics we can rely on some of the
5161 // cleanup.
5162 if (!C.isForDiagnostics())
5163 CmdArgs.push_back("-disable-free");
5164 CmdArgs.push_back("-clear-ast-before-backend");
5166 #ifdef NDEBUG
5167 const bool IsAssertBuild = false;
5168 #else
5169 const bool IsAssertBuild = true;
5170 #endif
5172 // Disable the verification pass in asserts builds unless otherwise specified.
5173 if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
5174 options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
5175 CmdArgs.push_back("-disable-llvm-verifier");
5178 // Discard value names in assert builds unless otherwise specified.
5179 if (Args.hasFlag(options::OPT_fdiscard_value_names,
5180 options::OPT_fno_discard_value_names, !IsAssertBuild)) {
5181 if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5182 llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
5183 return types::isLLVMIR(II.getType());
5184 })) {
5185 D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
5187 CmdArgs.push_back("-discard-value-names");
5190 // Set the main file name, so that debug info works even with
5191 // -save-temps.
5192 CmdArgs.push_back("-main-file-name");
5193 CmdArgs.push_back(getBaseInputName(Args, Input));
5195 // Some flags which affect the language (via preprocessor
5196 // defines).
5197 if (Args.hasArg(options::OPT_static))
5198 CmdArgs.push_back("-static-define");
5200 if (Args.hasArg(options::OPT_municode))
5201 CmdArgs.push_back("-DUNICODE");
5203 if (isa<AnalyzeJobAction>(JA))
5204 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5206 if (isa<AnalyzeJobAction>(JA) ||
5207 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5208 CmdArgs.push_back("-setup-static-analyzer");
5210 // Enable compatilibily mode to avoid analyzer-config related errors.
5211 // Since we can't access frontend flags through hasArg, let's manually iterate
5212 // through them.
5213 bool FoundAnalyzerConfig = false;
5214 for (auto *Arg : Args.filtered(options::OPT_Xclang))
5215 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5216 FoundAnalyzerConfig = true;
5217 break;
5219 if (!FoundAnalyzerConfig)
5220 for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5221 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5222 FoundAnalyzerConfig = true;
5223 break;
5225 if (FoundAnalyzerConfig)
5226 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5228 CheckCodeGenerationOptions(D, Args);
5230 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5231 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5232 if (FunctionAlignment) {
5233 CmdArgs.push_back("-function-alignment");
5234 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
5237 // We support -falign-loops=N where N is a power of 2. GCC supports more
5238 // forms.
5239 if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5240 unsigned Value = 0;
5241 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5242 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5243 << A->getAsString(Args) << A->getValue();
5244 else if (Value & (Value - 1))
5245 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5246 << A->getAsString(Args) << A->getValue();
5247 // Treat =0 as unspecified (use the target preference).
5248 if (Value)
5249 CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5250 Twine(std::min(Value, 65536u))));
5253 if (Triple.isOSzOS()) {
5254 // On z/OS some of the system header feature macros need to
5255 // be defined to enable most cross platform projects to build
5256 // successfully. Ths include the libc++ library. A
5257 // complicating factor is that users can define these
5258 // macros to the same or different values. We need to add
5259 // the definition for these macros to the compilation command
5260 // if the user hasn't already defined them.
5262 auto findMacroDefinition = [&](const std::string &Macro) {
5263 auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5264 return llvm::any_of(MacroDefs, [&](const std::string &M) {
5265 return M == Macro || M.find(Macro + '=') != std::string::npos;
5269 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5270 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5271 CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
5272 // _OPEN_DEFAULT is required for XL compat
5273 if (!findMacroDefinition("_OPEN_DEFAULT"))
5274 CmdArgs.push_back("-D_OPEN_DEFAULT");
5275 if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
5276 // _XOPEN_SOURCE=600 is required for libcxx.
5277 if (!findMacroDefinition("_XOPEN_SOURCE"))
5278 CmdArgs.push_back("-D_XOPEN_SOURCE=600");
5282 llvm::Reloc::Model RelocationModel;
5283 unsigned PICLevel;
5284 bool IsPIE;
5285 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5286 Arg *LastPICDataRelArg =
5287 Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5288 options::OPT_mpic_data_is_text_relative);
5289 bool NoPICDataIsTextRelative = false;
5290 if (LastPICDataRelArg) {
5291 if (LastPICDataRelArg->getOption().matches(
5292 options::OPT_mno_pic_data_is_text_relative)) {
5293 NoPICDataIsTextRelative = true;
5294 if (!PICLevel)
5295 D.Diag(diag::err_drv_argument_only_allowed_with)
5296 << "-mno-pic-data-is-text-relative"
5297 << "-fpic/-fpie";
5299 if (!Triple.isSystemZ())
5300 D.Diag(diag::err_drv_unsupported_opt_for_target)
5301 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5302 : "-mpic-data-is-text-relative")
5303 << RawTriple.str();
5306 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5307 RelocationModel == llvm::Reloc::ROPI_RWPI;
5308 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5309 RelocationModel == llvm::Reloc::ROPI_RWPI;
5311 if (Args.hasArg(options::OPT_mcmse) &&
5312 !Args.hasArg(options::OPT_fallow_unsupported)) {
5313 if (IsROPI)
5314 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
5315 if (IsRWPI)
5316 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5319 if (IsROPI && types::isCXX(Input.getType()) &&
5320 !Args.hasArg(options::OPT_fallow_unsupported))
5321 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
5323 const char *RMName = RelocationModelName(RelocationModel);
5324 if (RMName) {
5325 CmdArgs.push_back("-mrelocation-model");
5326 CmdArgs.push_back(RMName);
5328 if (PICLevel > 0) {
5329 CmdArgs.push_back("-pic-level");
5330 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
5331 if (IsPIE)
5332 CmdArgs.push_back("-pic-is-pie");
5333 if (NoPICDataIsTextRelative)
5334 CmdArgs.push_back("-mcmodel=medium");
5337 if (RelocationModel == llvm::Reloc::ROPI ||
5338 RelocationModel == llvm::Reloc::ROPI_RWPI)
5339 CmdArgs.push_back("-fropi");
5340 if (RelocationModel == llvm::Reloc::RWPI ||
5341 RelocationModel == llvm::Reloc::ROPI_RWPI)
5342 CmdArgs.push_back("-frwpi");
5344 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
5345 CmdArgs.push_back("-meabi");
5346 CmdArgs.push_back(A->getValue());
5349 // -fsemantic-interposition is forwarded to CC1: set the
5350 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5351 // make default visibility external linkage definitions dso_preemptable.
5353 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5354 // aliases (make default visibility external linkage definitions dso_local).
5355 // This is the CC1 default for ELF to match COFF/Mach-O.
5357 // Otherwise use Clang's traditional behavior: like
5358 // -fno-semantic-interposition but local aliases are not used. So references
5359 // can be interposed if not optimized out.
5360 if (Triple.isOSBinFormatELF()) {
5361 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5362 options::OPT_fno_semantic_interposition);
5363 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5364 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5365 bool SupportsLocalAlias =
5366 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5367 if (!A)
5368 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5369 else if (A->getOption().matches(options::OPT_fsemantic_interposition))
5370 A->render(Args, CmdArgs);
5371 else if (!SupportsLocalAlias)
5372 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5377 std::string Model;
5378 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
5379 if (!TC.isThreadModelSupported(A->getValue()))
5380 D.Diag(diag::err_drv_invalid_thread_model_for_target)
5381 << A->getValue() << A->getAsString(Args);
5382 Model = A->getValue();
5383 } else
5384 Model = TC.getThreadModel();
5385 if (Model != "posix") {
5386 CmdArgs.push_back("-mthread-model");
5387 CmdArgs.push_back(Args.MakeArgString(Model));
5391 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
5392 StringRef Name = A->getValue();
5393 if (Name == "SVML") {
5394 if (Triple.getArch() != llvm::Triple::x86 &&
5395 Triple.getArch() != llvm::Triple::x86_64)
5396 D.Diag(diag::err_drv_unsupported_opt_for_target)
5397 << Name << Triple.getArchName();
5398 } else if (Name == "LIBMVEC-X86") {
5399 if (Triple.getArch() != llvm::Triple::x86 &&
5400 Triple.getArch() != llvm::Triple::x86_64)
5401 D.Diag(diag::err_drv_unsupported_opt_for_target)
5402 << Name << Triple.getArchName();
5403 } else if (Name == "SLEEF" || Name == "ArmPL") {
5404 if (Triple.getArch() != llvm::Triple::aarch64 &&
5405 Triple.getArch() != llvm::Triple::aarch64_be)
5406 D.Diag(diag::err_drv_unsupported_opt_for_target)
5407 << Name << Triple.getArchName();
5409 A->render(Args, CmdArgs);
5412 if (Args.hasFlag(options::OPT_fmerge_all_constants,
5413 options::OPT_fno_merge_all_constants, false))
5414 CmdArgs.push_back("-fmerge-all-constants");
5416 Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
5417 options::OPT_fno_delete_null_pointer_checks);
5419 // LLVM Code Generator Options.
5421 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
5422 if (!Triple.isOSAIX() || Triple.isPPC32())
5423 D.Diag(diag::err_drv_unsupported_opt_for_target)
5424 << A->getSpelling() << RawTriple.str();
5425 CmdArgs.push_back("-mabi=quadword-atomics");
5428 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
5429 // Emit the unsupported option error until the Clang's library integration
5430 // support for 128-bit long double is available for AIX.
5431 if (Triple.isOSAIX())
5432 D.Diag(diag::err_drv_unsupported_opt_for_target)
5433 << A->getSpelling() << RawTriple.str();
5436 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
5437 StringRef V = A->getValue(), V1 = V;
5438 unsigned Size;
5439 if (V1.consumeInteger(10, Size) || !V1.empty())
5440 D.Diag(diag::err_drv_invalid_argument_to_option)
5441 << V << A->getOption().getName();
5442 else
5443 CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
5446 Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
5447 options::OPT_fno_jump_tables);
5448 Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
5449 options::OPT_fno_profile_sample_accurate);
5450 Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
5451 options::OPT_fno_preserve_as_comments);
5453 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
5454 CmdArgs.push_back("-mregparm");
5455 CmdArgs.push_back(A->getValue());
5458 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
5459 options::OPT_msvr4_struct_return)) {
5460 if (!TC.getTriple().isPPC32()) {
5461 D.Diag(diag::err_drv_unsupported_opt_for_target)
5462 << A->getSpelling() << RawTriple.str();
5463 } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
5464 CmdArgs.push_back("-maix-struct-return");
5465 } else {
5466 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5467 CmdArgs.push_back("-msvr4-struct-return");
5471 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
5472 options::OPT_freg_struct_return)) {
5473 if (TC.getArch() != llvm::Triple::x86) {
5474 D.Diag(diag::err_drv_unsupported_opt_for_target)
5475 << A->getSpelling() << RawTriple.str();
5476 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
5477 CmdArgs.push_back("-fpcc-struct-return");
5478 } else {
5479 assert(A->getOption().matches(options::OPT_freg_struct_return));
5480 CmdArgs.push_back("-freg-struct-return");
5484 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
5485 if (Triple.getArch() == llvm::Triple::m68k)
5486 CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
5487 else
5488 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
5491 if (Args.hasArg(options::OPT_fenable_matrix)) {
5492 // enable-matrix is needed by both the LangOpts and by LLVM.
5493 CmdArgs.push_back("-fenable-matrix");
5494 CmdArgs.push_back("-mllvm");
5495 CmdArgs.push_back("-enable-matrix");
5498 CodeGenOptions::FramePointerKind FPKeepKind =
5499 getFramePointerKind(Args, RawTriple);
5500 const char *FPKeepKindStr = nullptr;
5501 switch (FPKeepKind) {
5502 case CodeGenOptions::FramePointerKind::None:
5503 FPKeepKindStr = "-mframe-pointer=none";
5504 break;
5505 case CodeGenOptions::FramePointerKind::NonLeaf:
5506 FPKeepKindStr = "-mframe-pointer=non-leaf";
5507 break;
5508 case CodeGenOptions::FramePointerKind::All:
5509 FPKeepKindStr = "-mframe-pointer=all";
5510 break;
5512 assert(FPKeepKindStr && "unknown FramePointerKind");
5513 CmdArgs.push_back(FPKeepKindStr);
5515 Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
5516 options::OPT_fno_zero_initialized_in_bss);
5518 bool OFastEnabled = isOptimizationLevelFast(Args);
5519 // If -Ofast is the optimization level, then -fstrict-aliasing should be
5520 // enabled. This alias option is being used to simplify the hasFlag logic.
5521 OptSpecifier StrictAliasingAliasOption =
5522 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
5523 // We turn strict aliasing off by default if we're in CL mode, since MSVC
5524 // doesn't do any TBAA.
5525 bool TBAAOnByDefault = !D.IsCLMode();
5526 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
5527 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
5528 CmdArgs.push_back("-relaxed-aliasing");
5529 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
5530 options::OPT_fno_struct_path_tbaa, true))
5531 CmdArgs.push_back("-no-struct-path-tbaa");
5532 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
5533 options::OPT_fno_strict_enums);
5534 Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
5535 options::OPT_fno_strict_return);
5536 Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
5537 options::OPT_fno_allow_editor_placeholders);
5538 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
5539 options::OPT_fno_strict_vtable_pointers);
5540 Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
5541 options::OPT_fno_force_emit_vtables);
5542 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5543 options::OPT_fno_optimize_sibling_calls);
5544 Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
5545 options::OPT_fno_escaping_block_tail_calls);
5547 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
5548 options::OPT_fno_fine_grained_bitfield_accesses);
5550 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5551 options::OPT_fno_experimental_relative_cxx_abi_vtables);
5553 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
5554 options::OPT_fno_experimental_omit_vtable_rtti);
5556 // Handle segmented stacks.
5557 Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
5558 options::OPT_fno_split_stack);
5560 // -fprotect-parens=0 is default.
5561 if (Args.hasFlag(options::OPT_fprotect_parens,
5562 options::OPT_fno_protect_parens, false))
5563 CmdArgs.push_back("-fprotect-parens");
5565 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
5567 if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
5568 const llvm::Triple::ArchType Arch = TC.getArch();
5569 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5570 StringRef V = A->getValue();
5571 if (V == "64")
5572 CmdArgs.push_back("-fextend-arguments=64");
5573 else if (V != "32")
5574 D.Diag(diag::err_drv_invalid_argument_to_option)
5575 << A->getValue() << A->getOption().getName();
5576 } else
5577 D.Diag(diag::err_drv_unsupported_opt_for_target)
5578 << A->getOption().getName() << TripleStr;
5581 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
5582 if (TC.getArch() == llvm::Triple::avr)
5583 A->render(Args, CmdArgs);
5584 else
5585 D.Diag(diag::err_drv_unsupported_opt_for_target)
5586 << A->getAsString(Args) << TripleStr;
5589 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
5590 if (TC.getTriple().isX86())
5591 A->render(Args, CmdArgs);
5592 else if (TC.getTriple().isPPC() &&
5593 (A->getOption().getID() != options::OPT_mlong_double_80))
5594 A->render(Args, CmdArgs);
5595 else
5596 D.Diag(diag::err_drv_unsupported_opt_for_target)
5597 << A->getAsString(Args) << TripleStr;
5600 // Decide whether to use verbose asm. Verbose assembly is the default on
5601 // toolchains which have the integrated assembler on by default.
5602 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
5603 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
5604 IsIntegratedAssemblerDefault))
5605 CmdArgs.push_back("-fno-verbose-asm");
5607 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5608 // use that to indicate the MC default in the backend.
5609 if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
5610 StringRef V = A->getValue();
5611 unsigned Num;
5612 if (V == "none")
5613 A->render(Args, CmdArgs);
5614 else if (!V.consumeInteger(10, Num) && Num > 0 &&
5615 (V.empty() || (V.consume_front(".") &&
5616 !V.consumeInteger(10, Num) && V.empty())))
5617 A->render(Args, CmdArgs);
5618 else
5619 D.Diag(diag::err_drv_invalid_argument_to_option)
5620 << A->getValue() << A->getOption().getName();
5623 // If toolchain choose to use MCAsmParser for inline asm don't pass the
5624 // option to disable integrated-as explictly.
5625 if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
5626 CmdArgs.push_back("-no-integrated-as");
5628 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
5629 CmdArgs.push_back("-mdebug-pass");
5630 CmdArgs.push_back("Structure");
5632 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
5633 CmdArgs.push_back("-mdebug-pass");
5634 CmdArgs.push_back("Arguments");
5637 // Enable -mconstructor-aliases except on darwin, where we have to work around
5638 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
5639 // code, where aliases aren't supported.
5640 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
5641 CmdArgs.push_back("-mconstructor-aliases");
5643 // Darwin's kernel doesn't support guard variables; just die if we
5644 // try to use them.
5645 if (KernelOrKext && RawTriple.isOSDarwin())
5646 CmdArgs.push_back("-fforbid-guard-variables");
5648 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
5649 Triple.isWindowsGNUEnvironment())) {
5650 CmdArgs.push_back("-mms-bitfields");
5653 if (Triple.isWindowsGNUEnvironment()) {
5654 Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
5655 options::OPT_fno_auto_import);
5658 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
5659 // defaults to -fno-direct-access-external-data. Pass the option if different
5660 // from the default.
5661 if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
5662 options::OPT_fno_direct_access_external_data))
5663 if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
5664 (PICLevel == 0))
5665 A->render(Args, CmdArgs);
5667 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
5668 CmdArgs.push_back("-fno-plt");
5671 // -fhosted is default.
5672 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
5673 // use Freestanding.
5674 bool Freestanding =
5675 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
5676 KernelOrKext;
5677 if (Freestanding)
5678 CmdArgs.push_back("-ffreestanding");
5680 Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
5682 // This is a coarse approximation of what llvm-gcc actually does, both
5683 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
5684 // complicated ways.
5685 auto SanitizeArgs = TC.getSanitizerArgs(Args);
5687 bool IsAsyncUnwindTablesDefault =
5688 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
5689 bool IsSyncUnwindTablesDefault =
5690 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
5692 bool AsyncUnwindTables = Args.hasFlag(
5693 options::OPT_fasynchronous_unwind_tables,
5694 options::OPT_fno_asynchronous_unwind_tables,
5695 (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
5696 !Freestanding);
5697 bool UnwindTables =
5698 Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
5699 IsSyncUnwindTablesDefault && !Freestanding);
5700 if (AsyncUnwindTables)
5701 CmdArgs.push_back("-funwind-tables=2");
5702 else if (UnwindTables)
5703 CmdArgs.push_back("-funwind-tables=1");
5705 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
5706 // `--gpu-use-aux-triple-only` is specified.
5707 if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
5708 (IsCudaDevice || IsHIPDevice)) {
5709 const ArgList &HostArgs =
5710 C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
5711 std::string HostCPU =
5712 getCPUName(D, HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
5713 if (!HostCPU.empty()) {
5714 CmdArgs.push_back("-aux-target-cpu");
5715 CmdArgs.push_back(Args.MakeArgString(HostCPU));
5717 getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
5718 /*ForAS*/ false, /*IsAux*/ true);
5721 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5723 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
5724 StringRef CM = A->getValue();
5725 bool Ok = false;
5726 if (Triple.isOSAIX() && CM == "medium") {
5727 CM = "large";
5728 Ok = true;
5730 if (Triple.isAArch64(64)) {
5731 Ok = CM == "tiny" || CM == "small" || CM == "large";
5732 if (CM == "large" && RelocationModel != llvm::Reloc::Static)
5733 D.Diag(diag::err_drv_argument_only_allowed_with)
5734 << A->getAsString(Args) << "-fno-pic";
5735 } else if (Triple.isPPC64()) {
5736 Ok = CM == "small" || CM == "medium" || CM == "large";
5737 } else if (Triple.isRISCV()) {
5738 if (CM == "medlow")
5739 CM = "small";
5740 else if (CM == "medany")
5741 CM = "medium";
5742 Ok = CM == "small" || CM == "medium";
5743 } else if (Triple.getArch() == llvm::Triple::x86_64) {
5744 Ok = llvm::is_contained({"small", "kernel", "medium", "large", "tiny"},
5745 CM);
5746 } else if (Triple.isNVPTX() || Triple.isAMDGPU()) {
5747 // NVPTX/AMDGPU does not care about the code model and will accept
5748 // whatever works for the host.
5749 Ok = true;
5751 if (Ok) {
5752 CmdArgs.push_back(Args.MakeArgString("-mcmodel=" + CM));
5753 } else {
5754 D.Diag(diag::err_drv_unsupported_option_argument_for_target)
5755 << A->getSpelling() << CM << TripleStr;
5759 if (Arg *A = Args.getLastArg(options::OPT_mlarge_data_threshold_EQ)) {
5760 if (!Triple.isX86()) {
5761 D.Diag(diag::err_drv_unsupported_opt_for_target)
5762 << A->getOption().getName() << TripleStr;
5763 } else {
5764 bool IsMediumCM = false;
5765 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ))
5766 IsMediumCM = StringRef(A->getValue()) == "medium";
5767 if (!IsMediumCM) {
5768 D.Diag(diag::warn_drv_large_data_threshold_invalid_code_model)
5769 << A->getOption().getRenderName();
5770 } else {
5771 A->render(Args, CmdArgs);
5776 if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
5777 StringRef Value = A->getValue();
5778 unsigned TLSSize = 0;
5779 Value.getAsInteger(10, TLSSize);
5780 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
5781 D.Diag(diag::err_drv_unsupported_opt_for_target)
5782 << A->getOption().getName() << TripleStr;
5783 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
5784 D.Diag(diag::err_drv_invalid_int_value)
5785 << A->getOption().getName() << Value;
5786 Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
5789 // Add the target cpu
5790 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
5791 if (!CPU.empty()) {
5792 CmdArgs.push_back("-target-cpu");
5793 CmdArgs.push_back(Args.MakeArgString(CPU));
5796 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
5798 // Add clang-cl arguments.
5799 types::ID InputType = Input.getType();
5800 if (D.IsCLMode())
5801 AddClangCLArgs(Args, InputType, CmdArgs);
5803 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
5804 llvm::codegenoptions::NoDebugInfo;
5805 DwarfFissionKind DwarfFission = DwarfFissionKind::None;
5806 renderDebugOptions(TC, D, RawTriple, Args, types::isLLVMIR(InputType),
5807 CmdArgs, Output, DebugInfoKind, DwarfFission);
5809 // Add the split debug info name to the command lines here so we
5810 // can propagate it to the backend.
5811 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
5812 (TC.getTriple().isOSBinFormatELF() ||
5813 TC.getTriple().isOSBinFormatWasm() ||
5814 TC.getTriple().isOSBinFormatCOFF()) &&
5815 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5816 isa<BackendJobAction>(JA));
5817 if (SplitDWARF) {
5818 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
5819 CmdArgs.push_back("-split-dwarf-file");
5820 CmdArgs.push_back(SplitDWARFOut);
5821 if (DwarfFission == DwarfFissionKind::Split) {
5822 CmdArgs.push_back("-split-dwarf-output");
5823 CmdArgs.push_back(SplitDWARFOut);
5827 // Pass the linker version in use.
5828 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
5829 CmdArgs.push_back("-target-linker-version");
5830 CmdArgs.push_back(A->getValue());
5833 // Explicitly error on some things we know we don't support and can't just
5834 // ignore.
5835 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
5836 Arg *Unsupported;
5837 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
5838 TC.getArch() == llvm::Triple::x86) {
5839 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
5840 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
5841 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
5842 << Unsupported->getOption().getName();
5844 // The faltivec option has been superseded by the maltivec option.
5845 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
5846 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5847 << Unsupported->getOption().getName()
5848 << "please use -maltivec and include altivec.h explicitly";
5849 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
5850 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5851 << Unsupported->getOption().getName() << "please use -mno-altivec";
5854 Args.AddAllArgs(CmdArgs, options::OPT_v);
5856 if (Args.getLastArg(options::OPT_H)) {
5857 CmdArgs.push_back("-H");
5858 CmdArgs.push_back("-sys-header-deps");
5860 Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
5862 if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
5863 CmdArgs.push_back("-header-include-file");
5864 CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
5865 ? D.CCPrintHeadersFilename.c_str()
5866 : "-");
5867 CmdArgs.push_back("-sys-header-deps");
5868 CmdArgs.push_back(Args.MakeArgString(
5869 "-header-include-format=" +
5870 std::string(headerIncludeFormatKindToString(D.CCPrintHeadersFormat))));
5871 CmdArgs.push_back(
5872 Args.MakeArgString("-header-include-filtering=" +
5873 std::string(headerIncludeFilteringKindToString(
5874 D.CCPrintHeadersFiltering))));
5876 Args.AddLastArg(CmdArgs, options::OPT_P);
5877 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
5879 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
5880 CmdArgs.push_back("-diagnostic-log-file");
5881 CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
5882 ? D.CCLogDiagnosticsFilename.c_str()
5883 : "-");
5886 // Give the gen diagnostics more chances to succeed, by avoiding intentional
5887 // crashes.
5888 if (D.CCGenDiagnostics)
5889 CmdArgs.push_back("-disable-pragma-debug-crash");
5891 // Allow backend to put its diagnostic files in the same place as frontend
5892 // crash diagnostics files.
5893 if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
5894 StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
5895 CmdArgs.push_back("-mllvm");
5896 CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
5899 bool UseSeparateSections = isUseSeparateSections(Triple);
5901 if (Args.hasFlag(options::OPT_ffunction_sections,
5902 options::OPT_fno_function_sections, UseSeparateSections)) {
5903 CmdArgs.push_back("-ffunction-sections");
5906 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
5907 StringRef Val = A->getValue();
5908 if (Triple.isX86() && Triple.isOSBinFormatELF()) {
5909 if (Val != "all" && Val != "labels" && Val != "none" &&
5910 !Val.startswith("list="))
5911 D.Diag(diag::err_drv_invalid_value)
5912 << A->getAsString(Args) << A->getValue();
5913 else
5914 A->render(Args, CmdArgs);
5915 } else if (Triple.isNVPTX()) {
5916 // Do not pass the option to the GPU compilation. We still want it enabled
5917 // for the host-side compilation, so seeing it here is not an error.
5918 } else if (Val != "none") {
5919 // =none is allowed everywhere. It's useful for overriding the option
5920 // and is the same as not specifying the option.
5921 D.Diag(diag::err_drv_unsupported_opt_for_target)
5922 << A->getAsString(Args) << TripleStr;
5926 bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
5927 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
5928 UseSeparateSections || HasDefaultDataSections)) {
5929 CmdArgs.push_back("-fdata-sections");
5932 Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
5933 options::OPT_fno_unique_section_names);
5934 Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
5935 options::OPT_fno_unique_internal_linkage_names);
5936 Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
5937 options::OPT_fno_unique_basic_block_section_names);
5938 Args.addOptInFlag(CmdArgs, options::OPT_fconvergent_functions,
5939 options::OPT_fno_convergent_functions);
5941 if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
5942 options::OPT_fno_split_machine_functions)) {
5943 if (!A->getOption().matches(options::OPT_fno_split_machine_functions)) {
5944 // This codegen pass is only available on x86 and AArch64 ELF targets.
5945 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
5946 A->render(Args, CmdArgs);
5947 else
5948 D.Diag(diag::err_drv_unsupported_opt_for_target)
5949 << A->getAsString(Args) << TripleStr;
5953 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
5954 options::OPT_finstrument_functions_after_inlining,
5955 options::OPT_finstrument_function_entry_bare);
5957 // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support
5958 // for sampling, overhead of call arc collection is way too high and there's
5959 // no way to collect the output.
5960 if (!Triple.isNVPTX() && !Triple.isAMDGCN())
5961 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
5963 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
5965 if (getLastProfileSampleUseArg(Args) &&
5966 Args.hasArg(options::OPT_fsample_profile_use_profi)) {
5967 CmdArgs.push_back("-mllvm");
5968 CmdArgs.push_back("-sample-profile-use-profi");
5971 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
5972 if (RawTriple.isPS() &&
5973 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
5974 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
5975 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
5978 // Pass options for controlling the default header search paths.
5979 if (Args.hasArg(options::OPT_nostdinc)) {
5980 CmdArgs.push_back("-nostdsysteminc");
5981 CmdArgs.push_back("-nobuiltininc");
5982 } else {
5983 if (Args.hasArg(options::OPT_nostdlibinc))
5984 CmdArgs.push_back("-nostdsysteminc");
5985 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
5986 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
5989 // Pass the path to compiler resource files.
5990 CmdArgs.push_back("-resource-dir");
5991 CmdArgs.push_back(D.ResourceDir.c_str());
5993 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
5995 RenderARCMigrateToolOptions(D, Args, CmdArgs);
5997 // Add preprocessing options like -I, -D, etc. if we are using the
5998 // preprocessor.
6000 // FIXME: Support -fpreprocessed
6001 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
6002 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6004 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6005 // that "The compiler can only warn and ignore the option if not recognized".
6006 // When building with ccache, it will pass -D options to clang even on
6007 // preprocessed inputs and configure concludes that -fPIC is not supported.
6008 Args.ClaimAllArgs(options::OPT_D);
6010 // Manually translate -O4 to -O3; let clang reject others.
6011 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
6012 if (A->getOption().matches(options::OPT_O4)) {
6013 CmdArgs.push_back("-O3");
6014 D.Diag(diag::warn_O4_is_O3);
6015 } else {
6016 A->render(Args, CmdArgs);
6020 // Warn about ignored options to clang.
6021 for (const Arg *A :
6022 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6023 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6024 A->claim();
6027 for (const Arg *A :
6028 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
6029 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
6030 A->claim();
6033 claimNoWarnArgs(Args);
6035 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
6037 for (const Arg *A :
6038 Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
6039 A->claim();
6040 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6041 unsigned WarningNumber;
6042 if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
6043 D.Diag(diag::err_drv_invalid_int_value)
6044 << A->getAsString(Args) << A->getValue();
6045 continue;
6048 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6049 CmdArgs.push_back(Args.MakeArgString(
6050 "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6052 continue;
6054 A->render(Args, CmdArgs);
6057 Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
6059 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
6060 CmdArgs.push_back("-pedantic");
6061 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
6062 Args.AddLastArg(CmdArgs, options::OPT_w);
6064 Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
6065 options::OPT_fno_fixed_point);
6067 if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
6068 A->render(Args, CmdArgs);
6070 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6071 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6073 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6074 options::OPT_fno_experimental_omit_vtable_rtti);
6076 if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
6077 A->render(Args, CmdArgs);
6079 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6080 // (-ansi is equivalent to -std=c89 or -std=c++98).
6082 // If a std is supplied, only add -trigraphs if it follows the
6083 // option.
6084 bool ImplyVCPPCVer = false;
6085 bool ImplyVCPPCXXVer = false;
6086 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
6087 if (Std) {
6088 if (Std->getOption().matches(options::OPT_ansi))
6089 if (types::isCXX(InputType))
6090 CmdArgs.push_back("-std=c++98");
6091 else
6092 CmdArgs.push_back("-std=c89");
6093 else
6094 Std->render(Args, CmdArgs);
6096 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6097 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
6098 options::OPT_ftrigraphs,
6099 options::OPT_fno_trigraphs))
6100 if (A != Std)
6101 A->render(Args, CmdArgs);
6102 } else {
6103 // Honor -std-default.
6105 // FIXME: Clang doesn't correctly handle -std= when the input language
6106 // doesn't match. For the time being just ignore this for C++ inputs;
6107 // eventually we want to do all the standard defaulting here instead of
6108 // splitting it between the driver and clang -cc1.
6109 if (!types::isCXX(InputType)) {
6110 if (!Args.hasArg(options::OPT__SLASH_std)) {
6111 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
6112 /*Joined=*/true);
6113 } else
6114 ImplyVCPPCVer = true;
6116 else if (IsWindowsMSVC)
6117 ImplyVCPPCXXVer = true;
6119 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
6120 options::OPT_fno_trigraphs);
6123 // GCC's behavior for -Wwrite-strings is a bit strange:
6124 // * In C, this "warning flag" changes the types of string literals from
6125 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6126 // for the discarded qualifier.
6127 // * In C++, this is just a normal warning flag.
6129 // Implementing this warning correctly in C is hard, so we follow GCC's
6130 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6131 // a non-const char* in C, rather than using this crude hack.
6132 if (!types::isCXX(InputType)) {
6133 // FIXME: This should behave just like a warning flag, and thus should also
6134 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6135 Arg *WriteStrings =
6136 Args.getLastArg(options::OPT_Wwrite_strings,
6137 options::OPT_Wno_write_strings, options::OPT_w);
6138 if (WriteStrings &&
6139 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
6140 CmdArgs.push_back("-fconst-strings");
6143 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6144 // during C++ compilation, which it is by default. GCC keeps this define even
6145 // in the presence of '-w', match this behavior bug-for-bug.
6146 if (types::isCXX(InputType) &&
6147 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
6148 true)) {
6149 CmdArgs.push_back("-fdeprecated-macro");
6152 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6153 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
6154 if (Asm->getOption().matches(options::OPT_fasm))
6155 CmdArgs.push_back("-fgnu-keywords");
6156 else
6157 CmdArgs.push_back("-fno-gnu-keywords");
6160 if (!ShouldEnableAutolink(Args, TC, JA))
6161 CmdArgs.push_back("-fno-autolink");
6163 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
6164 Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
6165 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
6166 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
6168 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
6170 if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
6171 CmdArgs.push_back("-fexperimental-new-constant-interpreter");
6173 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
6174 CmdArgs.push_back("-fbracket-depth");
6175 CmdArgs.push_back(A->getValue());
6178 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
6179 options::OPT_Wlarge_by_value_copy_def)) {
6180 if (A->getNumValues()) {
6181 StringRef bytes = A->getValue();
6182 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
6183 } else
6184 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
6187 if (Args.hasArg(options::OPT_relocatable_pch))
6188 CmdArgs.push_back("-relocatable-pch");
6190 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
6191 static const char *kCFABIs[] = {
6192 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6195 if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
6196 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6197 else
6198 A->render(Args, CmdArgs);
6201 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
6202 CmdArgs.push_back("-fconstant-string-class");
6203 CmdArgs.push_back(A->getValue());
6206 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
6207 CmdArgs.push_back("-ftabstop");
6208 CmdArgs.push_back(A->getValue());
6211 Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
6212 options::OPT_fno_stack_size_section);
6214 if (Args.hasArg(options::OPT_fstack_usage)) {
6215 CmdArgs.push_back("-stack-usage-file");
6217 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6218 SmallString<128> OutputFilename(OutputOpt->getValue());
6219 llvm::sys::path::replace_extension(OutputFilename, "su");
6220 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6221 } else
6222 CmdArgs.push_back(
6223 Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6226 CmdArgs.push_back("-ferror-limit");
6227 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
6228 CmdArgs.push_back(A->getValue());
6229 else
6230 CmdArgs.push_back("19");
6232 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
6233 Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
6234 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
6235 Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
6236 Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
6238 // Pass -fmessage-length=.
6239 unsigned MessageLength = 0;
6240 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
6241 StringRef V(A->getValue());
6242 if (V.getAsInteger(0, MessageLength))
6243 D.Diag(diag::err_drv_invalid_argument_to_option)
6244 << V << A->getOption().getName();
6245 } else {
6246 // If -fmessage-length=N was not specified, determine whether this is a
6247 // terminal and, if so, implicitly define -fmessage-length appropriately.
6248 MessageLength = llvm::sys::Process::StandardErrColumns();
6250 if (MessageLength != 0)
6251 CmdArgs.push_back(
6252 Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
6254 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
6255 CmdArgs.push_back(
6256 Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
6258 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
6259 CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
6260 Twine(A->getValue(0))));
6262 // -fvisibility= and -fvisibility-ms-compat are of a piece.
6263 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
6264 options::OPT_fvisibility_ms_compat)) {
6265 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
6266 A->render(Args, CmdArgs);
6267 } else {
6268 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6269 CmdArgs.push_back("-fvisibility=hidden");
6270 CmdArgs.push_back("-ftype-visibility=default");
6272 } else if (IsOpenMPDevice) {
6273 // When compiling for the OpenMP device we want protected visibility by
6274 // default. This prevents the device from accidentally preempting code on
6275 // the host, makes the system more robust, and improves performance.
6276 CmdArgs.push_back("-fvisibility=protected");
6279 // PS4/PS5 process these options in addClangTargetOptions.
6280 if (!RawTriple.isPS()) {
6281 if (const Arg *A =
6282 Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
6283 options::OPT_fno_visibility_from_dllstorageclass)) {
6284 if (A->getOption().matches(
6285 options::OPT_fvisibility_from_dllstorageclass)) {
6286 CmdArgs.push_back("-fvisibility-from-dllstorageclass");
6287 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
6288 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
6289 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
6290 Args.AddLastArg(CmdArgs,
6291 options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6296 if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
6297 options::OPT_fno_visibility_inlines_hidden, false))
6298 CmdArgs.push_back("-fvisibility-inlines-hidden");
6300 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
6301 options::OPT_fno_visibility_inlines_hidden_static_local_var);
6302 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
6303 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
6305 if (Args.hasFlag(options::OPT_fnew_infallible,
6306 options::OPT_fno_new_infallible, false))
6307 CmdArgs.push_back("-fnew-infallible");
6309 if (Args.hasFlag(options::OPT_fno_operator_names,
6310 options::OPT_foperator_names, false))
6311 CmdArgs.push_back("-fno-operator-names");
6313 // Forward -f (flag) options which we can pass directly.
6314 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
6315 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
6316 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
6317 Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
6319 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
6320 Triple.hasDefaultEmulatedTLS()))
6321 CmdArgs.push_back("-femulated-tls");
6323 Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
6324 options::OPT_fno_check_new);
6326 if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
6327 // FIXME: There's no reason for this to be restricted to X86. The backend
6328 // code needs to be changed to include the appropriate function calls
6329 // automatically.
6330 if (!Triple.isX86() && !Triple.isAArch64())
6331 D.Diag(diag::err_drv_unsupported_opt_for_target)
6332 << A->getAsString(Args) << TripleStr;
6335 // AltiVec-like language extensions aren't relevant for assembling.
6336 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
6337 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
6339 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
6340 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
6342 // Forward flags for OpenMP. We don't do this if the current action is an
6343 // device offloading action other than OpenMP.
6344 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
6345 options::OPT_fno_openmp, false) &&
6346 (JA.isDeviceOffloading(Action::OFK_None) ||
6347 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
6348 switch (D.getOpenMPRuntime(Args)) {
6349 case Driver::OMPRT_OMP:
6350 case Driver::OMPRT_IOMP5:
6351 // Clang can generate useful OpenMP code for these two runtime libraries.
6352 CmdArgs.push_back("-fopenmp");
6354 // If no option regarding the use of TLS in OpenMP codegeneration is
6355 // given, decide a default based on the target. Otherwise rely on the
6356 // options and pass the right information to the frontend.
6357 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
6358 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
6359 CmdArgs.push_back("-fnoopenmp-use-tls");
6360 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6361 options::OPT_fno_openmp_simd);
6362 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
6363 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6364 if (!Args.hasFlag(options::OPT_fopenmp_extensions,
6365 options::OPT_fno_openmp_extensions, /*Default=*/true))
6366 CmdArgs.push_back("-fno-openmp-extensions");
6367 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
6368 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
6369 Args.AddAllArgs(CmdArgs,
6370 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
6371 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
6372 options::OPT_fno_openmp_optimistic_collapse,
6373 /*Default=*/false))
6374 CmdArgs.push_back("-fopenmp-optimistic-collapse");
6376 // When in OpenMP offloading mode with NVPTX target, forward
6377 // cuda-mode flag
6378 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
6379 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
6380 CmdArgs.push_back("-fopenmp-cuda-mode");
6382 // When in OpenMP offloading mode, enable debugging on the device.
6383 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
6384 if (Args.hasFlag(options::OPT_fopenmp_target_debug,
6385 options::OPT_fno_openmp_target_debug, /*Default=*/false))
6386 CmdArgs.push_back("-fopenmp-target-debug");
6388 // When in OpenMP offloading mode, forward assumptions information about
6389 // thread and team counts in the device.
6390 if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
6391 options::OPT_fno_openmp_assume_teams_oversubscription,
6392 /*Default=*/false))
6393 CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
6394 if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
6395 options::OPT_fno_openmp_assume_threads_oversubscription,
6396 /*Default=*/false))
6397 CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
6398 if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state))
6399 CmdArgs.push_back("-fopenmp-assume-no-thread-state");
6400 if (Args.hasArg(options::OPT_fopenmp_assume_no_nested_parallelism))
6401 CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
6402 if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
6403 CmdArgs.push_back("-fopenmp-offload-mandatory");
6404 break;
6405 default:
6406 // By default, if Clang doesn't know how to generate useful OpenMP code
6407 // for a specific runtime library, we just don't pass the '-fopenmp' flag
6408 // down to the actual compilation.
6409 // FIXME: It would be better to have a mode which *only* omits IR
6410 // generation based on the OpenMP support so that we get consistent
6411 // semantic analysis, etc.
6412 break;
6414 } else {
6415 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6416 options::OPT_fno_openmp_simd);
6417 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6418 Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
6419 options::OPT_fno_openmp_extensions);
6422 // Forward the new driver to change offloading code generation.
6423 if (Args.hasFlag(options::OPT_offload_new_driver,
6424 options::OPT_no_offload_new_driver, false))
6425 CmdArgs.push_back("--offload-new-driver");
6427 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
6429 const XRayArgs &XRay = TC.getXRayArgs();
6430 XRay.addArgs(TC, Args, CmdArgs, InputType);
6432 for (const auto &Filename :
6433 Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
6434 if (D.getVFS().exists(Filename))
6435 CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
6436 else
6437 D.Diag(clang::diag::err_drv_no_such_file) << Filename;
6440 if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
6441 StringRef S0 = A->getValue(), S = S0;
6442 unsigned Size, Offset = 0;
6443 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
6444 !Triple.isX86())
6445 D.Diag(diag::err_drv_unsupported_opt_for_target)
6446 << A->getAsString(Args) << TripleStr;
6447 else if (S.consumeInteger(10, Size) ||
6448 (!S.empty() && (!S.consume_front(",") ||
6449 S.consumeInteger(10, Offset) || !S.empty())))
6450 D.Diag(diag::err_drv_invalid_argument_to_option)
6451 << S0 << A->getOption().getName();
6452 else if (Size < Offset)
6453 D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
6454 else {
6455 CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
6456 CmdArgs.push_back(Args.MakeArgString(
6457 "-fpatchable-function-entry-offset=" + Twine(Offset)));
6461 Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
6463 if (TC.SupportsProfiling()) {
6464 Args.AddLastArg(CmdArgs, options::OPT_pg);
6466 llvm::Triple::ArchType Arch = TC.getArch();
6467 if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
6468 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
6469 A->render(Args, CmdArgs);
6470 else
6471 D.Diag(diag::err_drv_unsupported_opt_for_target)
6472 << A->getAsString(Args) << TripleStr;
6474 if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
6475 if (Arch == llvm::Triple::systemz)
6476 A->render(Args, CmdArgs);
6477 else
6478 D.Diag(diag::err_drv_unsupported_opt_for_target)
6479 << A->getAsString(Args) << TripleStr;
6481 if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
6482 if (Arch == llvm::Triple::systemz)
6483 A->render(Args, CmdArgs);
6484 else
6485 D.Diag(diag::err_drv_unsupported_opt_for_target)
6486 << A->getAsString(Args) << TripleStr;
6490 if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
6491 if (TC.getTriple().isOSzOS()) {
6492 D.Diag(diag::err_drv_unsupported_opt_for_target)
6493 << A->getAsString(Args) << TripleStr;
6496 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
6497 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
6498 D.Diag(diag::err_drv_unsupported_opt_for_target)
6499 << A->getAsString(Args) << TripleStr;
6502 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
6503 if (A->getOption().matches(options::OPT_p)) {
6504 A->claim();
6505 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
6506 CmdArgs.push_back("-pg");
6510 // Reject AIX-specific link options on other targets.
6511 if (!TC.getTriple().isOSAIX()) {
6512 for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
6513 options::OPT_mxcoff_build_id_EQ)) {
6514 D.Diag(diag::err_drv_unsupported_opt_for_target)
6515 << A->getSpelling() << TripleStr;
6519 if (Args.getLastArg(options::OPT_fapple_kext) ||
6520 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
6521 CmdArgs.push_back("-fapple-kext");
6523 Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
6524 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
6525 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
6526 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
6527 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
6528 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
6529 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
6530 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
6531 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
6532 Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
6534 if (const char *Name = C.getTimeTraceFile(&JA)) {
6535 CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
6536 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
6539 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
6540 CmdArgs.push_back("-ftrapv-handler");
6541 CmdArgs.push_back(A->getValue());
6544 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
6546 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
6547 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
6548 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
6549 if (A->getOption().matches(options::OPT_fwrapv))
6550 CmdArgs.push_back("-fwrapv");
6551 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
6552 options::OPT_fno_strict_overflow)) {
6553 if (A->getOption().matches(options::OPT_fno_strict_overflow))
6554 CmdArgs.push_back("-fwrapv");
6557 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
6558 options::OPT_fno_reroll_loops))
6559 if (A->getOption().matches(options::OPT_freroll_loops))
6560 CmdArgs.push_back("-freroll-loops");
6562 Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
6563 options::OPT_fno_finite_loops);
6565 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
6566 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
6567 options::OPT_fno_unroll_loops);
6569 Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
6571 Args.AddLastArg(CmdArgs, options::OPT_pthread);
6573 Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
6574 options::OPT_mno_speculative_load_hardening);
6576 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
6577 RenderSCPOptions(TC, Args, CmdArgs);
6578 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
6580 Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
6582 Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
6583 options::OPT_mno_stackrealign);
6585 if (Args.hasArg(options::OPT_mstack_alignment)) {
6586 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
6587 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
6590 if (Args.hasArg(options::OPT_mstack_probe_size)) {
6591 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
6593 if (!Size.empty())
6594 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
6595 else
6596 CmdArgs.push_back("-mstack-probe-size=0");
6599 Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
6600 options::OPT_mno_stack_arg_probe);
6602 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
6603 options::OPT_mno_restrict_it)) {
6604 if (A->getOption().matches(options::OPT_mrestrict_it)) {
6605 CmdArgs.push_back("-mllvm");
6606 CmdArgs.push_back("-arm-restrict-it");
6607 } else {
6608 CmdArgs.push_back("-mllvm");
6609 CmdArgs.push_back("-arm-default-it");
6613 // Forward -cl options to -cc1
6614 RenderOpenCLOptions(Args, CmdArgs, InputType);
6616 // Forward hlsl options to -cc1
6617 RenderHLSLOptions(Args, CmdArgs, InputType);
6619 if (IsHIP) {
6620 if (Args.hasFlag(options::OPT_fhip_new_launch_api,
6621 options::OPT_fno_hip_new_launch_api, true))
6622 CmdArgs.push_back("-fhip-new-launch-api");
6623 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
6624 options::OPT_fno_gpu_allow_device_init);
6625 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
6626 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
6627 Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
6628 options::OPT_fno_hip_kernel_arg_name);
6631 if (IsCuda || IsHIP) {
6632 if (IsRDCMode)
6633 CmdArgs.push_back("-fgpu-rdc");
6634 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,
6635 options::OPT_fno_gpu_defer_diag);
6636 if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
6637 options::OPT_fno_gpu_exclude_wrong_side_overloads,
6638 false)) {
6639 CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
6640 CmdArgs.push_back("-fgpu-defer-diag");
6644 // Forward -nogpulib to -cc1.
6645 if (Args.hasArg(options::OPT_nogpulib))
6646 CmdArgs.push_back("-nogpulib");
6648 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
6649 CmdArgs.push_back(
6650 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
6653 if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
6654 CmdArgs.push_back(
6655 Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
6657 Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
6659 // Forward -f options with positive and negative forms; we translate these by
6660 // hand. Do not propagate PGO options to the GPU-side compilations as the
6661 // profile info is for the host-side compilation only.
6662 if (!(IsCudaDevice || IsHIPDevice)) {
6663 if (Arg *A = getLastProfileSampleUseArg(Args)) {
6664 auto *PGOArg = Args.getLastArg(
6665 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
6666 options::OPT_fcs_profile_generate,
6667 options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
6668 options::OPT_fprofile_use_EQ);
6669 if (PGOArg)
6670 D.Diag(diag::err_drv_argument_not_allowed_with)
6671 << "SampleUse with PGO options";
6673 StringRef fname = A->getValue();
6674 if (!llvm::sys::fs::exists(fname))
6675 D.Diag(diag::err_drv_no_such_file) << fname;
6676 else
6677 A->render(Args, CmdArgs);
6679 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
6681 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
6682 options::OPT_fno_pseudo_probe_for_profiling, false)) {
6683 CmdArgs.push_back("-fpseudo-probe-for-profiling");
6684 // Enforce -funique-internal-linkage-names if it's not explicitly turned
6685 // off.
6686 if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
6687 options::OPT_fno_unique_internal_linkage_names, true))
6688 CmdArgs.push_back("-funique-internal-linkage-names");
6691 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
6693 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
6694 options::OPT_fno_assume_sane_operator_new);
6696 // -fblocks=0 is default.
6697 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
6698 TC.IsBlocksDefault()) ||
6699 (Args.hasArg(options::OPT_fgnu_runtime) &&
6700 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
6701 !Args.hasArg(options::OPT_fno_blocks))) {
6702 CmdArgs.push_back("-fblocks");
6704 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
6705 CmdArgs.push_back("-fblocks-runtime-optional");
6708 // -fencode-extended-block-signature=1 is default.
6709 if (TC.IsEncodeExtendedBlockSignatureDefault())
6710 CmdArgs.push_back("-fencode-extended-block-signature");
6712 if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
6713 options::OPT_fno_coro_aligned_allocation, false) &&
6714 types::isCXX(InputType))
6715 CmdArgs.push_back("-fcoro-aligned-allocation");
6717 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
6718 options::OPT_fno_double_square_bracket_attributes);
6720 Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
6721 options::OPT_fno_access_control);
6722 Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
6723 options::OPT_fno_elide_constructors);
6725 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
6727 if (KernelOrKext || (types::isCXX(InputType) &&
6728 (RTTIMode == ToolChain::RM_Disabled)))
6729 CmdArgs.push_back("-fno-rtti");
6731 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
6732 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
6733 TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
6734 CmdArgs.push_back("-fshort-enums");
6736 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
6738 // -fuse-cxa-atexit is default.
6739 if (!Args.hasFlag(
6740 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
6741 !RawTriple.isOSAIX() && !RawTriple.isOSWindows() &&
6742 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
6743 RawTriple.hasEnvironment())) ||
6744 KernelOrKext)
6745 CmdArgs.push_back("-fno-use-cxa-atexit");
6747 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
6748 options::OPT_fno_register_global_dtors_with_atexit,
6749 RawTriple.isOSDarwin() && !KernelOrKext))
6750 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
6752 Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
6753 options::OPT_fno_use_line_directives);
6755 // -fno-minimize-whitespace is default.
6756 if (Args.hasFlag(options::OPT_fminimize_whitespace,
6757 options::OPT_fno_minimize_whitespace, false)) {
6758 types::ID InputType = Inputs[0].getType();
6759 if (!isDerivedFromC(InputType))
6760 D.Diag(diag::err_drv_opt_unsupported_input_type)
6761 << "-fminimize-whitespace" << types::getTypeName(InputType);
6762 CmdArgs.push_back("-fminimize-whitespace");
6765 // -fno-keep-system-includes is default.
6766 if (Args.hasFlag(options::OPT_fkeep_system_includes,
6767 options::OPT_fno_keep_system_includes, false)) {
6768 types::ID InputType = Inputs[0].getType();
6769 if (!isDerivedFromC(InputType))
6770 D.Diag(diag::err_drv_opt_unsupported_input_type)
6771 << "-fkeep-system-includes" << types::getTypeName(InputType);
6772 CmdArgs.push_back("-fkeep-system-includes");
6775 // -fms-extensions=0 is default.
6776 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
6777 IsWindowsMSVC))
6778 CmdArgs.push_back("-fms-extensions");
6780 // -fms-compatibility=0 is default.
6781 bool IsMSVCCompat = Args.hasFlag(
6782 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
6783 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
6784 options::OPT_fno_ms_extensions, true)));
6785 if (IsMSVCCompat)
6786 CmdArgs.push_back("-fms-compatibility");
6788 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
6789 Args.hasArg(options::OPT_fms_runtime_lib_EQ))
6790 ProcessVSRuntimeLibrary(Args, CmdArgs);
6792 // Handle -fgcc-version, if present.
6793 VersionTuple GNUCVer;
6794 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
6795 // Check that the version has 1 to 3 components and the minor and patch
6796 // versions fit in two decimal digits.
6797 StringRef Val = A->getValue();
6798 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
6799 bool Invalid = GNUCVer.tryParse(Val);
6800 unsigned Minor = GNUCVer.getMinor().value_or(0);
6801 unsigned Patch = GNUCVer.getSubminor().value_or(0);
6802 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
6803 D.Diag(diag::err_drv_invalid_value)
6804 << A->getAsString(Args) << A->getValue();
6806 } else if (!IsMSVCCompat) {
6807 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
6808 GNUCVer = VersionTuple(4, 2, 1);
6810 if (!GNUCVer.empty()) {
6811 CmdArgs.push_back(
6812 Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
6815 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
6816 if (!MSVT.empty())
6817 CmdArgs.push_back(
6818 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
6820 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
6821 if (ImplyVCPPCVer) {
6822 StringRef LanguageStandard;
6823 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6824 Std = StdArg;
6825 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6826 .Case("c11", "-std=c11")
6827 .Case("c17", "-std=c17")
6828 .Default("");
6829 if (LanguageStandard.empty())
6830 D.Diag(clang::diag::warn_drv_unused_argument)
6831 << StdArg->getAsString(Args);
6833 CmdArgs.push_back(LanguageStandard.data());
6835 if (ImplyVCPPCXXVer) {
6836 StringRef LanguageStandard;
6837 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6838 Std = StdArg;
6839 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6840 .Case("c++14", "-std=c++14")
6841 .Case("c++17", "-std=c++17")
6842 .Case("c++20", "-std=c++20")
6843 // TODO add c++23 and c++26 when MSVC supports it.
6844 .Case("c++latest", "-std=c++26")
6845 .Default("");
6846 if (LanguageStandard.empty())
6847 D.Diag(clang::diag::warn_drv_unused_argument)
6848 << StdArg->getAsString(Args);
6851 if (LanguageStandard.empty()) {
6852 if (IsMSVC2015Compatible)
6853 LanguageStandard = "-std=c++14";
6854 else
6855 LanguageStandard = "-std=c++11";
6858 CmdArgs.push_back(LanguageStandard.data());
6861 Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
6862 options::OPT_fno_borland_extensions);
6864 // -fno-declspec is default, except for PS4/PS5.
6865 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
6866 RawTriple.isPS()))
6867 CmdArgs.push_back("-fdeclspec");
6868 else if (Args.hasArg(options::OPT_fno_declspec))
6869 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
6871 // -fthreadsafe-static is default, except for MSVC compatibility versions less
6872 // than 19.
6873 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
6874 options::OPT_fno_threadsafe_statics,
6875 !types::isOpenCL(InputType) &&
6876 (!IsWindowsMSVC || IsMSVC2015Compatible)))
6877 CmdArgs.push_back("-fno-threadsafe-statics");
6879 // -fgnu-keywords default varies depending on language; only pass if
6880 // specified.
6881 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
6882 options::OPT_fno_gnu_keywords);
6884 Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
6885 options::OPT_fno_gnu89_inline);
6887 const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
6888 options::OPT_finline_hint_functions,
6889 options::OPT_fno_inline_functions);
6890 if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
6891 if (A->getOption().matches(options::OPT_fno_inline))
6892 A->render(Args, CmdArgs);
6893 } else if (InlineArg) {
6894 InlineArg->render(Args, CmdArgs);
6897 Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
6899 // FIXME: Find a better way to determine whether we are in C++20.
6900 bool HaveCxx20 =
6901 Std &&
6902 (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
6903 Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
6904 Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
6905 Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
6906 Std->containsValue("c++2c") || Std->containsValue("gnu++2c") ||
6907 Std->containsValue("c++26") || Std->containsValue("gnu++26") ||
6908 Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
6909 bool HaveModules =
6910 RenderModulesOptions(C, D, Args, Input, Output, HaveCxx20, CmdArgs);
6912 // -fdelayed-template-parsing is default when targeting MSVC.
6913 // Many old Windows SDK versions require this to parse.
6915 // According to
6916 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
6917 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
6918 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
6919 // not enable -fdelayed-template-parsing by default after C++20.
6921 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
6922 // able to disable this by default at some point.
6923 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
6924 options::OPT_fno_delayed_template_parsing,
6925 IsWindowsMSVC && !HaveCxx20)) {
6926 if (HaveCxx20)
6927 D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
6929 CmdArgs.push_back("-fdelayed-template-parsing");
6932 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
6933 options::OPT_fno_pch_validate_input_files_content, false))
6934 CmdArgs.push_back("-fvalidate-ast-input-files-content");
6935 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
6936 options::OPT_fno_pch_instantiate_templates, false))
6937 CmdArgs.push_back("-fpch-instantiate-templates");
6938 if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
6939 false))
6940 CmdArgs.push_back("-fmodules-codegen");
6941 if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
6942 false))
6943 CmdArgs.push_back("-fmodules-debuginfo");
6945 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
6946 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
6947 Input, CmdArgs);
6949 if (types::isObjC(Input.getType()) &&
6950 Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
6951 options::OPT_fno_objc_encode_cxx_class_template_spec,
6952 !Runtime.isNeXTFamily()))
6953 CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
6955 if (Args.hasFlag(options::OPT_fapplication_extension,
6956 options::OPT_fno_application_extension, false))
6957 CmdArgs.push_back("-fapplication-extension");
6959 // Handle GCC-style exception args.
6960 bool EH = false;
6961 if (!C.getDriver().IsCLMode())
6962 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
6964 // Handle exception personalities
6965 Arg *A = Args.getLastArg(
6966 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
6967 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
6968 if (A) {
6969 const Option &Opt = A->getOption();
6970 if (Opt.matches(options::OPT_fsjlj_exceptions))
6971 CmdArgs.push_back("-exception-model=sjlj");
6972 if (Opt.matches(options::OPT_fseh_exceptions))
6973 CmdArgs.push_back("-exception-model=seh");
6974 if (Opt.matches(options::OPT_fdwarf_exceptions))
6975 CmdArgs.push_back("-exception-model=dwarf");
6976 if (Opt.matches(options::OPT_fwasm_exceptions))
6977 CmdArgs.push_back("-exception-model=wasm");
6978 } else {
6979 switch (TC.GetExceptionModel(Args)) {
6980 default:
6981 break;
6982 case llvm::ExceptionHandling::DwarfCFI:
6983 CmdArgs.push_back("-exception-model=dwarf");
6984 break;
6985 case llvm::ExceptionHandling::SjLj:
6986 CmdArgs.push_back("-exception-model=sjlj");
6987 break;
6988 case llvm::ExceptionHandling::WinEH:
6989 CmdArgs.push_back("-exception-model=seh");
6990 break;
6994 // C++ "sane" operator new.
6995 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
6996 options::OPT_fno_assume_sane_operator_new);
6998 // -fassume-unique-vtables is on by default.
6999 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
7000 options::OPT_fno_assume_unique_vtables);
7002 // -frelaxed-template-template-args is off by default, as it is a severe
7003 // breaking change until a corresponding change to template partial ordering
7004 // is provided.
7005 Args.addOptInFlag(CmdArgs, options::OPT_frelaxed_template_template_args,
7006 options::OPT_fno_relaxed_template_template_args);
7008 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
7009 // most platforms.
7010 Args.addOptInFlag(CmdArgs, options::OPT_fsized_deallocation,
7011 options::OPT_fno_sized_deallocation);
7013 // -faligned-allocation is on by default in C++17 onwards and otherwise off
7014 // by default.
7015 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
7016 options::OPT_fno_aligned_allocation,
7017 options::OPT_faligned_new_EQ)) {
7018 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
7019 CmdArgs.push_back("-fno-aligned-allocation");
7020 else
7021 CmdArgs.push_back("-faligned-allocation");
7024 // The default new alignment can be specified using a dedicated option or via
7025 // a GCC-compatible option that also turns on aligned allocation.
7026 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
7027 options::OPT_faligned_new_EQ))
7028 CmdArgs.push_back(
7029 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
7031 // -fconstant-cfstrings is default, and may be subject to argument translation
7032 // on Darwin.
7033 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
7034 options::OPT_fno_constant_cfstrings, true) ||
7035 !Args.hasFlag(options::OPT_mconstant_cfstrings,
7036 options::OPT_mno_constant_cfstrings, true))
7037 CmdArgs.push_back("-fno-constant-cfstrings");
7039 Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
7040 options::OPT_fno_pascal_strings);
7042 // Honor -fpack-struct= and -fpack-struct, if given. Note that
7043 // -fno-pack-struct doesn't apply to -fpack-struct=.
7044 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
7045 std::string PackStructStr = "-fpack-struct=";
7046 PackStructStr += A->getValue();
7047 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
7048 } else if (Args.hasFlag(options::OPT_fpack_struct,
7049 options::OPT_fno_pack_struct, false)) {
7050 CmdArgs.push_back("-fpack-struct=1");
7053 // Handle -fmax-type-align=N and -fno-type-align
7054 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
7055 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
7056 if (!SkipMaxTypeAlign) {
7057 std::string MaxTypeAlignStr = "-fmax-type-align=";
7058 MaxTypeAlignStr += A->getValue();
7059 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
7061 } else if (RawTriple.isOSDarwin()) {
7062 if (!SkipMaxTypeAlign) {
7063 std::string MaxTypeAlignStr = "-fmax-type-align=16";
7064 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
7068 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
7069 CmdArgs.push_back("-Qn");
7071 // -fno-common is the default, set -fcommon only when that flag is set.
7072 Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
7074 // -fsigned-bitfields is default, and clang doesn't yet support
7075 // -funsigned-bitfields.
7076 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
7077 options::OPT_funsigned_bitfields, true))
7078 D.Diag(diag::warn_drv_clang_unsupported)
7079 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
7081 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
7082 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
7083 D.Diag(diag::err_drv_clang_unsupported)
7084 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
7086 // -finput_charset=UTF-8 is default. Reject others
7087 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
7088 StringRef value = inputCharset->getValue();
7089 if (!value.equals_insensitive("utf-8"))
7090 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
7091 << value;
7094 // -fexec_charset=UTF-8 is default. Reject others
7095 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
7096 StringRef value = execCharset->getValue();
7097 if (!value.equals_insensitive("utf-8"))
7098 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
7099 << value;
7102 RenderDiagnosticsOptions(D, Args, CmdArgs);
7104 Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
7105 options::OPT_fno_asm_blocks);
7107 Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
7108 options::OPT_fno_gnu_inline_asm);
7110 // Enable vectorization per default according to the optimization level
7111 // selected. For optimization levels that want vectorization we use the alias
7112 // option to simplify the hasFlag logic.
7113 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
7114 OptSpecifier VectorizeAliasOption =
7115 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
7116 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
7117 options::OPT_fno_vectorize, EnableVec))
7118 CmdArgs.push_back("-vectorize-loops");
7120 // -fslp-vectorize is enabled based on the optimization level selected.
7121 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
7122 OptSpecifier SLPVectAliasOption =
7123 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
7124 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
7125 options::OPT_fno_slp_vectorize, EnableSLPVec))
7126 CmdArgs.push_back("-vectorize-slp");
7128 ParseMPreferVectorWidth(D, Args, CmdArgs);
7130 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
7131 Args.AddLastArg(CmdArgs,
7132 options::OPT_fsanitize_undefined_strip_path_components_EQ);
7134 // -fdollars-in-identifiers default varies depending on platform and
7135 // language; only pass if specified.
7136 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
7137 options::OPT_fno_dollars_in_identifiers)) {
7138 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
7139 CmdArgs.push_back("-fdollars-in-identifiers");
7140 else
7141 CmdArgs.push_back("-fno-dollars-in-identifiers");
7144 Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
7145 options::OPT_fno_apple_pragma_pack);
7147 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
7148 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
7149 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
7151 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
7152 options::OPT_fno_rewrite_imports, false);
7153 if (RewriteImports)
7154 CmdArgs.push_back("-frewrite-imports");
7156 Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
7157 options::OPT_fno_directives_only);
7159 // Enable rewrite includes if the user's asked for it or if we're generating
7160 // diagnostics.
7161 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
7162 // nice to enable this when doing a crashdump for modules as well.
7163 if (Args.hasFlag(options::OPT_frewrite_includes,
7164 options::OPT_fno_rewrite_includes, false) ||
7165 (C.isForDiagnostics() && !HaveModules))
7166 CmdArgs.push_back("-frewrite-includes");
7168 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
7169 if (Arg *A = Args.getLastArg(options::OPT_traditional,
7170 options::OPT_traditional_cpp)) {
7171 if (isa<PreprocessJobAction>(JA))
7172 CmdArgs.push_back("-traditional-cpp");
7173 else
7174 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
7177 Args.AddLastArg(CmdArgs, options::OPT_dM);
7178 Args.AddLastArg(CmdArgs, options::OPT_dD);
7179 Args.AddLastArg(CmdArgs, options::OPT_dI);
7181 Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
7183 // Handle serialized diagnostics.
7184 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
7185 CmdArgs.push_back("-serialize-diagnostic-file");
7186 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
7189 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
7190 CmdArgs.push_back("-fretain-comments-from-system-headers");
7192 // Forward -fcomment-block-commands to -cc1.
7193 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
7194 // Forward -fparse-all-comments to -cc1.
7195 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
7197 // Turn -fplugin=name.so into -load name.so
7198 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
7199 CmdArgs.push_back("-load");
7200 CmdArgs.push_back(A->getValue());
7201 A->claim();
7204 // Turn -fplugin-arg-pluginname-key=value into
7205 // -plugin-arg-pluginname key=value
7206 // GCC has an actual plugin_argument struct with key/value pairs that it
7207 // passes to its plugins, but we don't, so just pass it on as-is.
7209 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
7210 // argument key are allowed to contain dashes. GCC therefore only
7211 // allows dashes in the key. We do the same.
7212 for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
7213 auto ArgValue = StringRef(A->getValue());
7214 auto FirstDashIndex = ArgValue.find('-');
7215 StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
7216 StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
7218 A->claim();
7219 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
7220 if (PluginName.empty()) {
7221 D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
7222 } else {
7223 D.Diag(diag::warn_drv_missing_plugin_arg)
7224 << PluginName << A->getAsString(Args);
7226 continue;
7229 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
7230 CmdArgs.push_back(Args.MakeArgString(Arg));
7233 // Forward -fpass-plugin=name.so to -cc1.
7234 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
7235 CmdArgs.push_back(
7236 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
7237 A->claim();
7240 // Forward --vfsoverlay to -cc1.
7241 for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
7242 CmdArgs.push_back("--vfsoverlay");
7243 CmdArgs.push_back(A->getValue());
7244 A->claim();
7247 Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
7248 options::OPT_fno_safe_buffer_usage_suggestions);
7250 // Setup statistics file output.
7251 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
7252 if (!StatsFile.empty()) {
7253 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
7254 if (D.CCPrintInternalStats)
7255 CmdArgs.push_back("-stats-file-append");
7258 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
7259 // parser.
7260 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
7261 Arg->claim();
7262 // -finclude-default-header flag is for preprocessor,
7263 // do not pass it to other cc1 commands when save-temps is enabled
7264 if (C.getDriver().isSaveTempsEnabled() &&
7265 !isa<PreprocessJobAction>(JA)) {
7266 if (StringRef(Arg->getValue()) == "-finclude-default-header")
7267 continue;
7269 CmdArgs.push_back(Arg->getValue());
7271 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
7272 A->claim();
7274 // We translate this by hand to the -cc1 argument, since nightly test uses
7275 // it and developers have been trained to spell it with -mllvm. Both
7276 // spellings are now deprecated and should be removed.
7277 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
7278 CmdArgs.push_back("-disable-llvm-optzns");
7279 } else {
7280 A->render(Args, CmdArgs);
7284 // With -save-temps, we want to save the unoptimized bitcode output from the
7285 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
7286 // by the frontend.
7287 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
7288 // has slightly different breakdown between stages.
7289 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
7290 // pristine IR generated by the frontend. Ideally, a new compile action should
7291 // be added so both IR can be captured.
7292 if ((C.getDriver().isSaveTempsEnabled() ||
7293 JA.isHostOffloading(Action::OFK_OpenMP)) &&
7294 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
7295 isa<CompileJobAction>(JA))
7296 CmdArgs.push_back("-disable-llvm-passes");
7298 Args.AddAllArgs(CmdArgs, options::OPT_undef);
7300 const char *Exec = D.getClangProgramPath();
7302 // Optionally embed the -cc1 level arguments into the debug info or a
7303 // section, for build analysis.
7304 // Also record command line arguments into the debug info if
7305 // -grecord-gcc-switches options is set on.
7306 // By default, -gno-record-gcc-switches is set on and no recording.
7307 auto GRecordSwitches =
7308 Args.hasFlag(options::OPT_grecord_command_line,
7309 options::OPT_gno_record_command_line, false);
7310 auto FRecordSwitches =
7311 Args.hasFlag(options::OPT_frecord_command_line,
7312 options::OPT_fno_record_command_line, false);
7313 if (FRecordSwitches && !Triple.isOSBinFormatELF() &&
7314 !Triple.isOSBinFormatXCOFF() && !Triple.isOSBinFormatMachO())
7315 D.Diag(diag::err_drv_unsupported_opt_for_target)
7316 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
7317 << TripleStr;
7318 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
7319 ArgStringList OriginalArgs;
7320 for (const auto &Arg : Args)
7321 Arg->render(Args, OriginalArgs);
7323 SmallString<256> Flags;
7324 EscapeSpacesAndBackslashes(Exec, Flags);
7325 for (const char *OriginalArg : OriginalArgs) {
7326 SmallString<128> EscapedArg;
7327 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
7328 Flags += " ";
7329 Flags += EscapedArg;
7331 auto FlagsArgString = Args.MakeArgString(Flags);
7332 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
7333 CmdArgs.push_back("-dwarf-debug-flags");
7334 CmdArgs.push_back(FlagsArgString);
7336 if (FRecordSwitches) {
7337 CmdArgs.push_back("-record-command-line");
7338 CmdArgs.push_back(FlagsArgString);
7342 // Host-side offloading compilation receives all device-side outputs. Include
7343 // them in the host compilation depending on the target. If the host inputs
7344 // are not empty we use the new-driver scheme, otherwise use the old scheme.
7345 if ((IsCuda || IsHIP) && CudaDeviceInput) {
7346 CmdArgs.push_back("-fcuda-include-gpubinary");
7347 CmdArgs.push_back(CudaDeviceInput->getFilename());
7348 } else if (!HostOffloadingInputs.empty()) {
7349 if ((IsCuda || IsHIP) && !IsRDCMode) {
7350 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
7351 CmdArgs.push_back("-fcuda-include-gpubinary");
7352 CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
7353 } else {
7354 for (const InputInfo Input : HostOffloadingInputs)
7355 CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
7356 TC.getInputFilename(Input)));
7360 if (IsCuda) {
7361 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
7362 options::OPT_fno_cuda_short_ptr, false))
7363 CmdArgs.push_back("-fcuda-short-ptr");
7366 if (IsCuda || IsHIP) {
7367 // Determine the original source input.
7368 const Action *SourceAction = &JA;
7369 while (SourceAction->getKind() != Action::InputClass) {
7370 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7371 SourceAction = SourceAction->getInputs()[0];
7373 auto CUID = cast<InputAction>(SourceAction)->getId();
7374 if (!CUID.empty())
7375 CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
7377 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
7378 // be overriden by -fno-gpu-approx-transcendentals.
7379 bool UseApproxTranscendentals = Args.hasFlag(
7380 options::OPT_ffast_math, options::OPT_fno_fast_math, false);
7381 if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,
7382 options::OPT_fno_gpu_approx_transcendentals,
7383 UseApproxTranscendentals))
7384 CmdArgs.push_back("-fgpu-approx-transcendentals");
7385 } else {
7386 Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,
7387 options::OPT_fno_gpu_approx_transcendentals);
7390 if (IsHIP) {
7391 CmdArgs.push_back("-fcuda-allow-variadic-functions");
7392 Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
7395 Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,
7396 options::OPT_fno_offload_uniform_block);
7398 if (IsCudaDevice || IsHIPDevice) {
7399 StringRef InlineThresh =
7400 Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
7401 if (!InlineThresh.empty()) {
7402 std::string ArgStr =
7403 std::string("-inline-threshold=") + InlineThresh.str();
7404 CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
7408 if (IsHIPDevice)
7409 Args.addOptOutFlag(CmdArgs,
7410 options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
7411 options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
7413 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
7414 // to specify the result of the compile phase on the host, so the meaningful
7415 // device declarations can be identified. Also, -fopenmp-is-target-device is
7416 // passed along to tell the frontend that it is generating code for a device,
7417 // so that only the relevant declarations are emitted.
7418 if (IsOpenMPDevice) {
7419 CmdArgs.push_back("-fopenmp-is-target-device");
7420 if (OpenMPDeviceInput) {
7421 CmdArgs.push_back("-fopenmp-host-ir-file-path");
7422 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
7426 if (Triple.isAMDGPU()) {
7427 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
7429 Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
7430 options::OPT_mno_unsafe_fp_atomics);
7431 Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
7432 options::OPT_mno_amdgpu_ieee);
7435 // For all the host OpenMP offloading compile jobs we need to pass the targets
7436 // information using -fopenmp-targets= option.
7437 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
7438 SmallString<128> Targets("-fopenmp-targets=");
7440 SmallVector<std::string, 4> Triples;
7441 auto TCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
7442 std::transform(TCRange.first, TCRange.second, std::back_inserter(Triples),
7443 [](auto TC) { return TC.second->getTripleString(); });
7444 CmdArgs.push_back(Args.MakeArgString(Targets + llvm::join(Triples, ",")));
7447 bool VirtualFunctionElimination =
7448 Args.hasFlag(options::OPT_fvirtual_function_elimination,
7449 options::OPT_fno_virtual_function_elimination, false);
7450 if (VirtualFunctionElimination) {
7451 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
7452 // in the future).
7453 if (LTOMode != LTOK_Full)
7454 D.Diag(diag::err_drv_argument_only_allowed_with)
7455 << "-fvirtual-function-elimination"
7456 << "-flto=full";
7458 CmdArgs.push_back("-fvirtual-function-elimination");
7461 // VFE requires whole-program-vtables, and enables it by default.
7462 bool WholeProgramVTables = Args.hasFlag(
7463 options::OPT_fwhole_program_vtables,
7464 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
7465 if (VirtualFunctionElimination && !WholeProgramVTables) {
7466 D.Diag(diag::err_drv_argument_not_allowed_with)
7467 << "-fno-whole-program-vtables"
7468 << "-fvirtual-function-elimination";
7471 if (WholeProgramVTables) {
7472 // PS4 uses the legacy LTO API, which does not support this feature in
7473 // ThinLTO mode.
7474 bool IsPS4 = getToolChain().getTriple().isPS4();
7476 // Check if we passed LTO options but they were suppressed because this is a
7477 // device offloading action, or we passed device offload LTO options which
7478 // were suppressed because this is not the device offload action.
7479 // Check if we are using PS4 in regular LTO mode.
7480 // Otherwise, issue an error.
7481 if ((!IsUsingLTO && !D.isUsingLTO(!IsDeviceOffloadAction)) ||
7482 (IsPS4 && !UnifiedLTO && (D.getLTOMode() != LTOK_Full)))
7483 D.Diag(diag::err_drv_argument_only_allowed_with)
7484 << "-fwhole-program-vtables"
7485 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
7487 // Propagate -fwhole-program-vtables if this is an LTO compile.
7488 if (IsUsingLTO)
7489 CmdArgs.push_back("-fwhole-program-vtables");
7492 bool DefaultsSplitLTOUnit =
7493 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
7494 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
7495 (!Triple.isPS4() && UnifiedLTO);
7496 bool SplitLTOUnit =
7497 Args.hasFlag(options::OPT_fsplit_lto_unit,
7498 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
7499 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
7500 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
7501 << "-fsanitize=cfi";
7502 if (SplitLTOUnit)
7503 CmdArgs.push_back("-fsplit-lto-unit");
7505 if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
7506 options::OPT_fno_fat_lto_objects)) {
7507 if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {
7508 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
7509 if (!Triple.isOSBinFormatELF()) {
7510 D.Diag(diag::err_drv_unsupported_opt_for_target)
7511 << A->getAsString(Args) << TC.getTripleString();
7513 CmdArgs.push_back(Args.MakeArgString(
7514 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
7515 CmdArgs.push_back("-flto-unit");
7516 CmdArgs.push_back("-ffat-lto-objects");
7517 A->render(Args, CmdArgs);
7521 if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
7522 options::OPT_fno_global_isel)) {
7523 CmdArgs.push_back("-mllvm");
7524 if (A->getOption().matches(options::OPT_fglobal_isel)) {
7525 CmdArgs.push_back("-global-isel=1");
7527 // GISel is on by default on AArch64 -O0, so don't bother adding
7528 // the fallback remarks for it. Other combinations will add a warning of
7529 // some kind.
7530 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
7531 bool IsOptLevelSupported = false;
7533 Arg *A = Args.getLastArg(options::OPT_O_Group);
7534 if (Triple.getArch() == llvm::Triple::aarch64) {
7535 if (!A || A->getOption().matches(options::OPT_O0))
7536 IsOptLevelSupported = true;
7538 if (!IsArchSupported || !IsOptLevelSupported) {
7539 CmdArgs.push_back("-mllvm");
7540 CmdArgs.push_back("-global-isel-abort=2");
7542 if (!IsArchSupported)
7543 D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName();
7544 else
7545 D.Diag(diag::warn_drv_global_isel_incomplete_opt);
7547 } else {
7548 CmdArgs.push_back("-global-isel=0");
7552 if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
7553 CmdArgs.push_back("-forder-file-instrumentation");
7554 // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
7555 // on, we need to pass these flags as linker flags and that will be handled
7556 // outside of the compiler.
7557 if (!IsUsingLTO) {
7558 CmdArgs.push_back("-mllvm");
7559 CmdArgs.push_back("-enable-order-file-instrumentation");
7563 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
7564 options::OPT_fno_force_enable_int128)) {
7565 if (A->getOption().matches(options::OPT_fforce_enable_int128))
7566 CmdArgs.push_back("-fforce-enable-int128");
7569 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
7570 options::OPT_fno_keep_static_consts);
7571 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
7572 options::OPT_fno_keep_persistent_storage_variables);
7573 Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
7574 options::OPT_fno_complete_member_pointers);
7575 Args.addOptOutFlag(CmdArgs, options::OPT_fcxx_static_destructors,
7576 options::OPT_fno_cxx_static_destructors);
7578 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
7580 if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics,
7581 options::OPT_mno_outline_atomics)) {
7582 // Option -moutline-atomics supported for AArch64 target only.
7583 if (!Triple.isAArch64()) {
7584 D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt)
7585 << Triple.getArchName() << A->getOption().getName();
7586 } else {
7587 if (A->getOption().matches(options::OPT_moutline_atomics)) {
7588 CmdArgs.push_back("-target-feature");
7589 CmdArgs.push_back("+outline-atomics");
7590 } else {
7591 CmdArgs.push_back("-target-feature");
7592 CmdArgs.push_back("-outline-atomics");
7595 } else if (Triple.isAArch64() &&
7596 getToolChain().IsAArch64OutlineAtomicsDefault(Args)) {
7597 CmdArgs.push_back("-target-feature");
7598 CmdArgs.push_back("+outline-atomics");
7601 if (Triple.isAArch64() &&
7602 (Args.hasArg(options::OPT_mno_fmv) ||
7603 (Triple.isAndroid() && Triple.isAndroidVersionLT(23)) ||
7604 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
7605 // Disable Function Multiversioning on AArch64 target.
7606 CmdArgs.push_back("-target-feature");
7607 CmdArgs.push_back("-fmv");
7610 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
7611 (TC.getTriple().isOSBinFormatELF() ||
7612 TC.getTriple().isOSBinFormatCOFF()) &&
7613 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
7614 !TC.getTriple().isOSNetBSD() &&
7615 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
7616 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
7617 CmdArgs.push_back("-faddrsig");
7619 if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
7620 (EH || UnwindTables || AsyncUnwindTables ||
7621 DebugInfoKind != llvm::codegenoptions::NoDebugInfo))
7622 CmdArgs.push_back("-D__GCC_HAVE_DWARF2_CFI_ASM=1");
7624 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
7625 std::string Str = A->getAsString(Args);
7626 if (!TC.getTriple().isOSBinFormatELF())
7627 D.Diag(diag::err_drv_unsupported_opt_for_target)
7628 << Str << TC.getTripleString();
7629 CmdArgs.push_back(Args.MakeArgString(Str));
7632 // Add the "-o out -x type src.c" flags last. This is done primarily to make
7633 // the -cc1 command easier to edit when reproducing compiler crashes.
7634 if (Output.getType() == types::TY_Dependencies) {
7635 // Handled with other dependency code.
7636 } else if (Output.isFilename()) {
7637 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
7638 Output.getType() == clang::driver::types::TY_IFS) {
7639 SmallString<128> OutputFilename(Output.getFilename());
7640 llvm::sys::path::replace_extension(OutputFilename, "ifs");
7641 CmdArgs.push_back("-o");
7642 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
7643 } else {
7644 CmdArgs.push_back("-o");
7645 CmdArgs.push_back(Output.getFilename());
7647 } else {
7648 assert(Output.isNothing() && "Invalid output.");
7651 addDashXForInput(Args, Input, CmdArgs);
7653 ArrayRef<InputInfo> FrontendInputs = Input;
7654 if (IsExtractAPI)
7655 FrontendInputs = ExtractAPIInputs;
7656 else if (Input.isNothing())
7657 FrontendInputs = {};
7659 for (const InputInfo &Input : FrontendInputs) {
7660 if (Input.isFilename())
7661 CmdArgs.push_back(Input.getFilename());
7662 else
7663 Input.getInputArg().renderAsInput(Args, CmdArgs);
7666 if (D.CC1Main && !D.CCGenDiagnostics) {
7667 // Invoke the CC1 directly in this process
7668 C.addCommand(std::make_unique<CC1Command>(
7669 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
7670 Output, D.getPrependArg()));
7671 } else {
7672 C.addCommand(std::make_unique<Command>(
7673 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
7674 Output, D.getPrependArg()));
7677 // Make the compile command echo its inputs for /showFilenames.
7678 if (Output.getType() == types::TY_Object &&
7679 Args.hasFlag(options::OPT__SLASH_showFilenames,
7680 options::OPT__SLASH_showFilenames_, false)) {
7681 C.getJobs().getJobs().back()->PrintInputFilenames = true;
7684 if (Arg *A = Args.getLastArg(options::OPT_pg))
7685 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
7686 !Args.hasArg(options::OPT_mfentry))
7687 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
7688 << A->getAsString(Args);
7690 // Claim some arguments which clang supports automatically.
7692 // -fpch-preprocess is used with gcc to add a special marker in the output to
7693 // include the PCH file.
7694 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
7696 // Claim some arguments which clang doesn't support, but we don't
7697 // care to warn the user about.
7698 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
7699 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
7701 // Disable warnings for clang -E -emit-llvm foo.c
7702 Args.ClaimAllArgs(options::OPT_emit_llvm);
7705 Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
7706 // CAUTION! The first constructor argument ("clang") is not arbitrary,
7707 // as it is for other tools. Some operations on a Tool actually test
7708 // whether that tool is Clang based on the Tool's Name as a string.
7709 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
7711 Clang::~Clang() {}
7713 /// Add options related to the Objective-C runtime/ABI.
7715 /// Returns true if the runtime is non-fragile.
7716 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
7717 const InputInfoList &inputs,
7718 ArgStringList &cmdArgs,
7719 RewriteKind rewriteKind) const {
7720 // Look for the controlling runtime option.
7721 Arg *runtimeArg =
7722 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
7723 options::OPT_fobjc_runtime_EQ);
7725 // Just forward -fobjc-runtime= to the frontend. This supercedes
7726 // options about fragility.
7727 if (runtimeArg &&
7728 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
7729 ObjCRuntime runtime;
7730 StringRef value = runtimeArg->getValue();
7731 if (runtime.tryParse(value)) {
7732 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
7733 << value;
7735 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
7736 (runtime.getVersion() >= VersionTuple(2, 0)))
7737 if (!getToolChain().getTriple().isOSBinFormatELF() &&
7738 !getToolChain().getTriple().isOSBinFormatCOFF()) {
7739 getToolChain().getDriver().Diag(
7740 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
7741 << runtime.getVersion().getMajor();
7744 runtimeArg->render(args, cmdArgs);
7745 return runtime;
7748 // Otherwise, we'll need the ABI "version". Version numbers are
7749 // slightly confusing for historical reasons:
7750 // 1 - Traditional "fragile" ABI
7751 // 2 - Non-fragile ABI, version 1
7752 // 3 - Non-fragile ABI, version 2
7753 unsigned objcABIVersion = 1;
7754 // If -fobjc-abi-version= is present, use that to set the version.
7755 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
7756 StringRef value = abiArg->getValue();
7757 if (value == "1")
7758 objcABIVersion = 1;
7759 else if (value == "2")
7760 objcABIVersion = 2;
7761 else if (value == "3")
7762 objcABIVersion = 3;
7763 else
7764 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
7765 } else {
7766 // Otherwise, determine if we are using the non-fragile ABI.
7767 bool nonFragileABIIsDefault =
7768 (rewriteKind == RK_NonFragile ||
7769 (rewriteKind == RK_None &&
7770 getToolChain().IsObjCNonFragileABIDefault()));
7771 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
7772 options::OPT_fno_objc_nonfragile_abi,
7773 nonFragileABIIsDefault)) {
7774 // Determine the non-fragile ABI version to use.
7775 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
7776 unsigned nonFragileABIVersion = 1;
7777 #else
7778 unsigned nonFragileABIVersion = 2;
7779 #endif
7781 if (Arg *abiArg =
7782 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
7783 StringRef value = abiArg->getValue();
7784 if (value == "1")
7785 nonFragileABIVersion = 1;
7786 else if (value == "2")
7787 nonFragileABIVersion = 2;
7788 else
7789 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
7790 << value;
7793 objcABIVersion = 1 + nonFragileABIVersion;
7794 } else {
7795 objcABIVersion = 1;
7799 // We don't actually care about the ABI version other than whether
7800 // it's non-fragile.
7801 bool isNonFragile = objcABIVersion != 1;
7803 // If we have no runtime argument, ask the toolchain for its default runtime.
7804 // However, the rewriter only really supports the Mac runtime, so assume that.
7805 ObjCRuntime runtime;
7806 if (!runtimeArg) {
7807 switch (rewriteKind) {
7808 case RK_None:
7809 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
7810 break;
7811 case RK_Fragile:
7812 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
7813 break;
7814 case RK_NonFragile:
7815 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
7816 break;
7819 // -fnext-runtime
7820 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
7821 // On Darwin, make this use the default behavior for the toolchain.
7822 if (getToolChain().getTriple().isOSDarwin()) {
7823 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
7825 // Otherwise, build for a generic macosx port.
7826 } else {
7827 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
7830 // -fgnu-runtime
7831 } else {
7832 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
7833 // Legacy behaviour is to target the gnustep runtime if we are in
7834 // non-fragile mode or the GCC runtime in fragile mode.
7835 if (isNonFragile)
7836 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
7837 else
7838 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
7841 if (llvm::any_of(inputs, [](const InputInfo &input) {
7842 return types::isObjC(input.getType());
7844 cmdArgs.push_back(
7845 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
7846 return runtime;
7849 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
7850 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
7851 I += HaveDash;
7852 return !HaveDash;
7855 namespace {
7856 struct EHFlags {
7857 bool Synch = false;
7858 bool Asynch = false;
7859 bool NoUnwindC = false;
7861 } // end anonymous namespace
7863 /// /EH controls whether to run destructor cleanups when exceptions are
7864 /// thrown. There are three modifiers:
7865 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
7866 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
7867 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
7868 /// - c: Assume that extern "C" functions are implicitly nounwind.
7869 /// The default is /EHs-c-, meaning cleanups are disabled.
7870 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
7871 EHFlags EH;
7873 std::vector<std::string> EHArgs =
7874 Args.getAllArgValues(options::OPT__SLASH_EH);
7875 for (auto EHVal : EHArgs) {
7876 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
7877 switch (EHVal[I]) {
7878 case 'a':
7879 EH.Asynch = maybeConsumeDash(EHVal, I);
7880 if (EH.Asynch)
7881 EH.Synch = false;
7882 continue;
7883 case 'c':
7884 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
7885 continue;
7886 case 's':
7887 EH.Synch = maybeConsumeDash(EHVal, I);
7888 if (EH.Synch)
7889 EH.Asynch = false;
7890 continue;
7891 default:
7892 break;
7894 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
7895 break;
7898 // The /GX, /GX- flags are only processed if there are not /EH flags.
7899 // The default is that /GX is not specified.
7900 if (EHArgs.empty() &&
7901 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
7902 /*Default=*/false)) {
7903 EH.Synch = true;
7904 EH.NoUnwindC = true;
7907 if (Args.hasArg(options::OPT__SLASH_kernel)) {
7908 EH.Synch = false;
7909 EH.NoUnwindC = false;
7910 EH.Asynch = false;
7913 return EH;
7916 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
7917 ArgStringList &CmdArgs) const {
7918 bool isNVPTX = getToolChain().getTriple().isNVPTX();
7920 ProcessVSRuntimeLibrary(Args, CmdArgs);
7922 if (Arg *ShowIncludes =
7923 Args.getLastArg(options::OPT__SLASH_showIncludes,
7924 options::OPT__SLASH_showIncludes_user)) {
7925 CmdArgs.push_back("--show-includes");
7926 if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
7927 CmdArgs.push_back("-sys-header-deps");
7930 // This controls whether or not we emit RTTI data for polymorphic types.
7931 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
7932 /*Default=*/false))
7933 CmdArgs.push_back("-fno-rtti-data");
7935 // This controls whether or not we emit stack-protector instrumentation.
7936 // In MSVC, Buffer Security Check (/GS) is on by default.
7937 if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
7938 /*Default=*/true)) {
7939 CmdArgs.push_back("-stack-protector");
7940 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
7943 const Driver &D = getToolChain().getDriver();
7945 EHFlags EH = parseClangCLEHFlags(D, Args);
7946 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
7947 if (types::isCXX(InputType))
7948 CmdArgs.push_back("-fcxx-exceptions");
7949 CmdArgs.push_back("-fexceptions");
7950 if (EH.Asynch)
7951 CmdArgs.push_back("-fasync-exceptions");
7953 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
7954 CmdArgs.push_back("-fexternc-nounwind");
7956 // /EP should expand to -E -P.
7957 if (Args.hasArg(options::OPT__SLASH_EP)) {
7958 CmdArgs.push_back("-E");
7959 CmdArgs.push_back("-P");
7962 unsigned VolatileOptionID;
7963 if (getToolChain().getTriple().isX86())
7964 VolatileOptionID = options::OPT__SLASH_volatile_ms;
7965 else
7966 VolatileOptionID = options::OPT__SLASH_volatile_iso;
7968 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
7969 VolatileOptionID = A->getOption().getID();
7971 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
7972 CmdArgs.push_back("-fms-volatile");
7974 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
7975 options::OPT__SLASH_Zc_dllexportInlines,
7976 false)) {
7977 CmdArgs.push_back("-fno-dllexport-inlines");
7980 if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
7981 options::OPT__SLASH_Zc_wchar_t, false)) {
7982 CmdArgs.push_back("-fno-wchar");
7985 if (Args.hasArg(options::OPT__SLASH_kernel)) {
7986 llvm::Triple::ArchType Arch = getToolChain().getArch();
7987 std::vector<std::string> Values =
7988 Args.getAllArgValues(options::OPT__SLASH_arch);
7989 if (!Values.empty()) {
7990 llvm::SmallSet<std::string, 4> SupportedArches;
7991 if (Arch == llvm::Triple::x86)
7992 SupportedArches.insert("IA32");
7994 for (auto &V : Values)
7995 if (!SupportedArches.contains(V))
7996 D.Diag(diag::err_drv_argument_not_allowed_with)
7997 << std::string("/arch:").append(V) << "/kernel";
8000 CmdArgs.push_back("-fno-rtti");
8001 if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
8002 D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
8003 << "/kernel";
8006 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
8007 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
8008 if (MostGeneralArg && BestCaseArg)
8009 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8010 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
8012 if (MostGeneralArg) {
8013 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
8014 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
8015 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
8017 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
8018 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
8019 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
8020 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8021 << FirstConflict->getAsString(Args)
8022 << SecondConflict->getAsString(Args);
8024 if (SingleArg)
8025 CmdArgs.push_back("-fms-memptr-rep=single");
8026 else if (MultipleArg)
8027 CmdArgs.push_back("-fms-memptr-rep=multiple");
8028 else
8029 CmdArgs.push_back("-fms-memptr-rep=virtual");
8032 if (Args.hasArg(options::OPT_regcall4))
8033 CmdArgs.push_back("-regcall4");
8035 // Parse the default calling convention options.
8036 if (Arg *CCArg =
8037 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
8038 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
8039 options::OPT__SLASH_Gregcall)) {
8040 unsigned DCCOptId = CCArg->getOption().getID();
8041 const char *DCCFlag = nullptr;
8042 bool ArchSupported = !isNVPTX;
8043 llvm::Triple::ArchType Arch = getToolChain().getArch();
8044 switch (DCCOptId) {
8045 case options::OPT__SLASH_Gd:
8046 DCCFlag = "-fdefault-calling-conv=cdecl";
8047 break;
8048 case options::OPT__SLASH_Gr:
8049 ArchSupported = Arch == llvm::Triple::x86;
8050 DCCFlag = "-fdefault-calling-conv=fastcall";
8051 break;
8052 case options::OPT__SLASH_Gz:
8053 ArchSupported = Arch == llvm::Triple::x86;
8054 DCCFlag = "-fdefault-calling-conv=stdcall";
8055 break;
8056 case options::OPT__SLASH_Gv:
8057 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8058 DCCFlag = "-fdefault-calling-conv=vectorcall";
8059 break;
8060 case options::OPT__SLASH_Gregcall:
8061 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8062 DCCFlag = "-fdefault-calling-conv=regcall";
8063 break;
8066 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
8067 if (ArchSupported && DCCFlag)
8068 CmdArgs.push_back(DCCFlag);
8071 if (Args.hasArg(options::OPT__SLASH_Gregcall4))
8072 CmdArgs.push_back("-regcall4");
8074 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
8076 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
8077 CmdArgs.push_back("-fdiagnostics-format");
8078 CmdArgs.push_back("msvc");
8081 if (Args.hasArg(options::OPT__SLASH_kernel))
8082 CmdArgs.push_back("-fms-kernel");
8084 for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
8085 StringRef GuardArgs = A->getValue();
8086 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
8087 // "ehcont-".
8088 if (GuardArgs.equals_insensitive("cf")) {
8089 // Emit CFG instrumentation and the table of address-taken functions.
8090 CmdArgs.push_back("-cfguard");
8091 } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
8092 // Emit only the table of address-taken functions.
8093 CmdArgs.push_back("-cfguard-no-checks");
8094 } else if (GuardArgs.equals_insensitive("ehcont")) {
8095 // Emit EH continuation table.
8096 CmdArgs.push_back("-ehcontguard");
8097 } else if (GuardArgs.equals_insensitive("cf-") ||
8098 GuardArgs.equals_insensitive("ehcont-")) {
8099 // Do nothing, but we might want to emit a security warning in future.
8100 } else {
8101 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
8103 A->claim();
8107 const char *Clang::getBaseInputName(const ArgList &Args,
8108 const InputInfo &Input) {
8109 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
8112 const char *Clang::getBaseInputStem(const ArgList &Args,
8113 const InputInfoList &Inputs) {
8114 const char *Str = getBaseInputName(Args, Inputs[0]);
8116 if (const char *End = strrchr(Str, '.'))
8117 return Args.MakeArgString(std::string(Str, End));
8119 return Str;
8122 const char *Clang::getDependencyFileName(const ArgList &Args,
8123 const InputInfoList &Inputs) {
8124 // FIXME: Think about this more.
8126 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
8127 SmallString<128> OutputFilename(OutputOpt->getValue());
8128 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
8129 return Args.MakeArgString(OutputFilename);
8132 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
8135 // Begin ClangAs
8137 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
8138 ArgStringList &CmdArgs) const {
8139 StringRef CPUName;
8140 StringRef ABIName;
8141 const llvm::Triple &Triple = getToolChain().getTriple();
8142 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
8144 CmdArgs.push_back("-target-abi");
8145 CmdArgs.push_back(ABIName.data());
8148 void ClangAs::AddX86TargetArgs(const ArgList &Args,
8149 ArgStringList &CmdArgs) const {
8150 addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
8151 /*IsLTO=*/false);
8153 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
8154 StringRef Value = A->getValue();
8155 if (Value == "intel" || Value == "att") {
8156 CmdArgs.push_back("-mllvm");
8157 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
8158 } else {
8159 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
8160 << A->getSpelling() << Value;
8165 void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
8166 ArgStringList &CmdArgs) const {
8167 CmdArgs.push_back("-target-abi");
8168 CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
8169 getToolChain().getTriple())
8170 .data());
8173 void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
8174 ArgStringList &CmdArgs) const {
8175 const llvm::Triple &Triple = getToolChain().getTriple();
8176 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
8178 CmdArgs.push_back("-target-abi");
8179 CmdArgs.push_back(ABIName.data());
8181 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8182 options::OPT_mno_default_build_attributes, true)) {
8183 CmdArgs.push_back("-mllvm");
8184 CmdArgs.push_back("-riscv-add-build-attributes");
8188 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
8189 const InputInfo &Output, const InputInfoList &Inputs,
8190 const ArgList &Args,
8191 const char *LinkingOutput) const {
8192 ArgStringList CmdArgs;
8194 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
8195 const InputInfo &Input = Inputs[0];
8197 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
8198 const std::string &TripleStr = Triple.getTriple();
8199 const auto &D = getToolChain().getDriver();
8201 // Don't warn about "clang -w -c foo.s"
8202 Args.ClaimAllArgs(options::OPT_w);
8203 // and "clang -emit-llvm -c foo.s"
8204 Args.ClaimAllArgs(options::OPT_emit_llvm);
8206 claimNoWarnArgs(Args);
8208 // Invoke ourselves in -cc1as mode.
8210 // FIXME: Implement custom jobs for internal actions.
8211 CmdArgs.push_back("-cc1as");
8213 // Add the "effective" target triple.
8214 CmdArgs.push_back("-triple");
8215 CmdArgs.push_back(Args.MakeArgString(TripleStr));
8217 getToolChain().addClangCC1ASTargetOptions(Args, CmdArgs);
8219 // Set the output mode, we currently only expect to be used as a real
8220 // assembler.
8221 CmdArgs.push_back("-filetype");
8222 CmdArgs.push_back("obj");
8224 // Set the main file name, so that debug info works even with
8225 // -save-temps or preprocessed assembly.
8226 CmdArgs.push_back("-main-file-name");
8227 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
8229 // Add the target cpu
8230 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
8231 if (!CPU.empty()) {
8232 CmdArgs.push_back("-target-cpu");
8233 CmdArgs.push_back(Args.MakeArgString(CPU));
8236 // Add the target features
8237 getTargetFeatures(D, Triple, Args, CmdArgs, true);
8239 // Ignore explicit -force_cpusubtype_ALL option.
8240 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
8242 // Pass along any -I options so we get proper .include search paths.
8243 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
8245 // Determine the original source input.
8246 auto FindSource = [](const Action *S) -> const Action * {
8247 while (S->getKind() != Action::InputClass) {
8248 assert(!S->getInputs().empty() && "unexpected root action!");
8249 S = S->getInputs()[0];
8251 return S;
8253 const Action *SourceAction = FindSource(&JA);
8255 // Forward -g and handle debug info related flags, assuming we are dealing
8256 // with an actual assembly file.
8257 bool WantDebug = false;
8258 Args.ClaimAllArgs(options::OPT_g_Group);
8259 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
8260 WantDebug = !A->getOption().matches(options::OPT_g0) &&
8261 !A->getOption().matches(options::OPT_ggdb0);
8263 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
8264 llvm::codegenoptions::NoDebugInfo;
8266 // Add the -fdebug-compilation-dir flag if needed.
8267 const char *DebugCompilationDir =
8268 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
8270 if (SourceAction->getType() == types::TY_Asm ||
8271 SourceAction->getType() == types::TY_PP_Asm) {
8272 // You might think that it would be ok to set DebugInfoKind outside of
8273 // the guard for source type, however there is a test which asserts
8274 // that some assembler invocation receives no -debug-info-kind,
8275 // and it's not clear whether that test is just overly restrictive.
8276 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
8277 : llvm::codegenoptions::NoDebugInfo);
8279 addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
8280 CmdArgs);
8282 // Set the AT_producer to the clang version when using the integrated
8283 // assembler on assembly source files.
8284 CmdArgs.push_back("-dwarf-debug-producer");
8285 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
8287 // And pass along -I options
8288 Args.AddAllArgs(CmdArgs, options::OPT_I);
8290 const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
8291 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
8292 llvm::DebuggerKind::Default);
8293 renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
8294 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
8296 // Handle -fPIC et al -- the relocation-model affects the assembler
8297 // for some targets.
8298 llvm::Reloc::Model RelocationModel;
8299 unsigned PICLevel;
8300 bool IsPIE;
8301 std::tie(RelocationModel, PICLevel, IsPIE) =
8302 ParsePICArgs(getToolChain(), Args);
8304 const char *RMName = RelocationModelName(RelocationModel);
8305 if (RMName) {
8306 CmdArgs.push_back("-mrelocation-model");
8307 CmdArgs.push_back(RMName);
8310 // Optionally embed the -cc1as level arguments into the debug info, for build
8311 // analysis.
8312 if (getToolChain().UseDwarfDebugFlags()) {
8313 ArgStringList OriginalArgs;
8314 for (const auto &Arg : Args)
8315 Arg->render(Args, OriginalArgs);
8317 SmallString<256> Flags;
8318 const char *Exec = getToolChain().getDriver().getClangProgramPath();
8319 EscapeSpacesAndBackslashes(Exec, Flags);
8320 for (const char *OriginalArg : OriginalArgs) {
8321 SmallString<128> EscapedArg;
8322 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
8323 Flags += " ";
8324 Flags += EscapedArg;
8326 CmdArgs.push_back("-dwarf-debug-flags");
8327 CmdArgs.push_back(Args.MakeArgString(Flags));
8330 // FIXME: Add -static support, once we have it.
8332 // Add target specific flags.
8333 switch (getToolChain().getArch()) {
8334 default:
8335 break;
8337 case llvm::Triple::mips:
8338 case llvm::Triple::mipsel:
8339 case llvm::Triple::mips64:
8340 case llvm::Triple::mips64el:
8341 AddMIPSTargetArgs(Args, CmdArgs);
8342 break;
8344 case llvm::Triple::x86:
8345 case llvm::Triple::x86_64:
8346 AddX86TargetArgs(Args, CmdArgs);
8347 break;
8349 case llvm::Triple::arm:
8350 case llvm::Triple::armeb:
8351 case llvm::Triple::thumb:
8352 case llvm::Triple::thumbeb:
8353 // This isn't in AddARMTargetArgs because we want to do this for assembly
8354 // only, not C/C++.
8355 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8356 options::OPT_mno_default_build_attributes, true)) {
8357 CmdArgs.push_back("-mllvm");
8358 CmdArgs.push_back("-arm-add-build-attributes");
8360 break;
8362 case llvm::Triple::aarch64:
8363 case llvm::Triple::aarch64_32:
8364 case llvm::Triple::aarch64_be:
8365 if (Args.hasArg(options::OPT_mmark_bti_property)) {
8366 CmdArgs.push_back("-mllvm");
8367 CmdArgs.push_back("-aarch64-mark-bti-property");
8369 break;
8371 case llvm::Triple::loongarch32:
8372 case llvm::Triple::loongarch64:
8373 AddLoongArchTargetArgs(Args, CmdArgs);
8374 break;
8376 case llvm::Triple::riscv32:
8377 case llvm::Triple::riscv64:
8378 AddRISCVTargetArgs(Args, CmdArgs);
8379 break;
8382 // Consume all the warning flags. Usually this would be handled more
8383 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
8384 // doesn't handle that so rather than warning about unused flags that are
8385 // actually used, we'll lie by omission instead.
8386 // FIXME: Stop lying and consume only the appropriate driver flags
8387 Args.ClaimAllArgs(options::OPT_W_Group);
8389 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
8390 getToolChain().getDriver());
8392 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
8394 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
8395 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
8396 Output.getFilename());
8398 // Fixup any previous commands that use -object-file-name because when we
8399 // generated them, the final .obj name wasn't yet known.
8400 for (Command &J : C.getJobs()) {
8401 if (SourceAction != FindSource(&J.getSource()))
8402 continue;
8403 auto &JArgs = J.getArguments();
8404 for (unsigned I = 0; I < JArgs.size(); ++I) {
8405 if (StringRef(JArgs[I]).startswith("-object-file-name=") &&
8406 Output.isFilename()) {
8407 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
8408 addDebugObjectName(Args, NewArgs, DebugCompilationDir,
8409 Output.getFilename());
8410 NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
8411 J.replaceArguments(NewArgs);
8412 break;
8417 assert(Output.isFilename() && "Unexpected lipo output.");
8418 CmdArgs.push_back("-o");
8419 CmdArgs.push_back(Output.getFilename());
8421 const llvm::Triple &T = getToolChain().getTriple();
8422 Arg *A;
8423 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
8424 T.isOSBinFormatELF()) {
8425 CmdArgs.push_back("-split-dwarf-output");
8426 CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
8429 if (Triple.isAMDGPU())
8430 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
8432 assert(Input.isFilename() && "Invalid input.");
8433 CmdArgs.push_back(Input.getFilename());
8435 const char *Exec = getToolChain().getDriver().getClangProgramPath();
8436 if (D.CC1Main && !D.CCGenDiagnostics) {
8437 // Invoke cc1as directly in this process.
8438 C.addCommand(std::make_unique<CC1Command>(
8439 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8440 Output, D.getPrependArg()));
8441 } else {
8442 C.addCommand(std::make_unique<Command>(
8443 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8444 Output, D.getPrependArg()));
8448 // Begin OffloadBundler
8450 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
8451 const InputInfo &Output,
8452 const InputInfoList &Inputs,
8453 const llvm::opt::ArgList &TCArgs,
8454 const char *LinkingOutput) const {
8455 // The version with only one output is expected to refer to a bundling job.
8456 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
8458 // The bundling command looks like this:
8459 // clang-offload-bundler -type=bc
8460 // -targets=host-triple,openmp-triple1,openmp-triple2
8461 // -output=output_file
8462 // -input=unbundle_file_host
8463 // -input=unbundle_file_tgt1
8464 // -input=unbundle_file_tgt2
8466 ArgStringList CmdArgs;
8468 // Get the type.
8469 CmdArgs.push_back(TCArgs.MakeArgString(
8470 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
8472 assert(JA.getInputs().size() == Inputs.size() &&
8473 "Not have inputs for all dependence actions??");
8475 // Get the targets.
8476 SmallString<128> Triples;
8477 Triples += "-targets=";
8478 for (unsigned I = 0; I < Inputs.size(); ++I) {
8479 if (I)
8480 Triples += ',';
8482 // Find ToolChain for this input.
8483 Action::OffloadKind CurKind = Action::OFK_Host;
8484 const ToolChain *CurTC = &getToolChain();
8485 const Action *CurDep = JA.getInputs()[I];
8487 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
8488 CurTC = nullptr;
8489 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
8490 assert(CurTC == nullptr && "Expected one dependence!");
8491 CurKind = A->getOffloadingDeviceKind();
8492 CurTC = TC;
8495 Triples += Action::GetOffloadKindName(CurKind);
8496 Triples += '-';
8497 Triples += CurTC->getTriple().normalize();
8498 if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&
8499 !StringRef(CurDep->getOffloadingArch()).empty()) {
8500 Triples += '-';
8501 Triples += CurDep->getOffloadingArch();
8504 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8505 // with each toolchain.
8506 StringRef GPUArchName;
8507 if (CurKind == Action::OFK_OpenMP) {
8508 // Extract GPUArch from -march argument in TC argument list.
8509 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8510 auto ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
8511 auto Arch = ArchStr.starts_with_insensitive("-march=");
8512 if (Arch) {
8513 GPUArchName = ArchStr.substr(7);
8514 Triples += "-";
8515 break;
8518 Triples += GPUArchName.str();
8521 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
8523 // Get bundled file command.
8524 CmdArgs.push_back(
8525 TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
8527 // Get unbundled files command.
8528 for (unsigned I = 0; I < Inputs.size(); ++I) {
8529 SmallString<128> UB;
8530 UB += "-input=";
8532 // Find ToolChain for this input.
8533 const ToolChain *CurTC = &getToolChain();
8534 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
8535 CurTC = nullptr;
8536 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
8537 assert(CurTC == nullptr && "Expected one dependence!");
8538 CurTC = TC;
8540 UB += C.addTempFile(
8541 C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
8542 } else {
8543 UB += CurTC->getInputFilename(Inputs[I]);
8545 CmdArgs.push_back(TCArgs.MakeArgString(UB));
8547 if (TCArgs.hasFlag(options::OPT_offload_compress,
8548 options::OPT_no_offload_compress, false))
8549 CmdArgs.push_back("-compress");
8550 if (TCArgs.hasArg(options::OPT_v))
8551 CmdArgs.push_back("-verbose");
8552 // All the inputs are encoded as commands.
8553 C.addCommand(std::make_unique<Command>(
8554 JA, *this, ResponseFileSupport::None(),
8555 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8556 CmdArgs, std::nullopt, Output));
8559 void OffloadBundler::ConstructJobMultipleOutputs(
8560 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
8561 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
8562 const char *LinkingOutput) const {
8563 // The version with multiple outputs is expected to refer to a unbundling job.
8564 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
8566 // The unbundling command looks like this:
8567 // clang-offload-bundler -type=bc
8568 // -targets=host-triple,openmp-triple1,openmp-triple2
8569 // -input=input_file
8570 // -output=unbundle_file_host
8571 // -output=unbundle_file_tgt1
8572 // -output=unbundle_file_tgt2
8573 // -unbundle
8575 ArgStringList CmdArgs;
8577 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
8578 InputInfo Input = Inputs.front();
8580 // Get the type.
8581 CmdArgs.push_back(TCArgs.MakeArgString(
8582 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
8584 // Get the targets.
8585 SmallString<128> Triples;
8586 Triples += "-targets=";
8587 auto DepInfo = UA.getDependentActionsInfo();
8588 for (unsigned I = 0; I < DepInfo.size(); ++I) {
8589 if (I)
8590 Triples += ',';
8592 auto &Dep = DepInfo[I];
8593 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
8594 Triples += '-';
8595 Triples += Dep.DependentToolChain->getTriple().normalize();
8596 if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
8597 Dep.DependentOffloadKind == Action::OFK_Cuda) &&
8598 !Dep.DependentBoundArch.empty()) {
8599 Triples += '-';
8600 Triples += Dep.DependentBoundArch;
8602 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
8603 // with each toolchain.
8604 StringRef GPUArchName;
8605 if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {
8606 // Extract GPUArch from -march argument in TC argument list.
8607 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
8608 StringRef ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
8609 auto Arch = ArchStr.starts_with_insensitive("-march=");
8610 if (Arch) {
8611 GPUArchName = ArchStr.substr(7);
8612 Triples += "-";
8613 break;
8616 Triples += GPUArchName.str();
8620 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
8622 // Get bundled file command.
8623 CmdArgs.push_back(
8624 TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));
8626 // Get unbundled files command.
8627 for (unsigned I = 0; I < Outputs.size(); ++I) {
8628 SmallString<128> UB;
8629 UB += "-output=";
8630 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
8631 CmdArgs.push_back(TCArgs.MakeArgString(UB));
8633 CmdArgs.push_back("-unbundle");
8634 CmdArgs.push_back("-allow-missing-bundles");
8635 if (TCArgs.hasArg(options::OPT_v))
8636 CmdArgs.push_back("-verbose");
8638 // All the inputs are encoded as commands.
8639 C.addCommand(std::make_unique<Command>(
8640 JA, *this, ResponseFileSupport::None(),
8641 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8642 CmdArgs, std::nullopt, Outputs));
8645 void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
8646 const InputInfo &Output,
8647 const InputInfoList &Inputs,
8648 const llvm::opt::ArgList &Args,
8649 const char *LinkingOutput) const {
8650 ArgStringList CmdArgs;
8652 // Add the output file name.
8653 assert(Output.isFilename() && "Invalid output.");
8654 CmdArgs.push_back("-o");
8655 CmdArgs.push_back(Output.getFilename());
8657 // Create the inputs to bundle the needed metadata.
8658 for (const InputInfo &Input : Inputs) {
8659 const Action *OffloadAction = Input.getAction();
8660 const ToolChain *TC = OffloadAction->getOffloadingToolChain();
8661 const ArgList &TCArgs =
8662 C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
8663 OffloadAction->getOffloadingDeviceKind());
8664 StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
8665 StringRef Arch = OffloadAction->getOffloadingArch()
8666 ? OffloadAction->getOffloadingArch()
8667 : TCArgs.getLastArgValue(options::OPT_march_EQ);
8668 StringRef Kind =
8669 Action::GetOffloadKindName(OffloadAction->getOffloadingDeviceKind());
8671 ArgStringList Features;
8672 SmallVector<StringRef> FeatureArgs;
8673 getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
8674 false);
8675 llvm::copy_if(Features, std::back_inserter(FeatureArgs),
8676 [](StringRef Arg) { return !Arg.startswith("-target"); });
8678 if (TC->getTriple().isAMDGPU()) {
8679 for (StringRef Feature : llvm::split(Arch.split(':').second, ':')) {
8680 FeatureArgs.emplace_back(
8681 Args.MakeArgString(Feature.take_back() + Feature.drop_back()));
8685 // TODO: We need to pass in the full target-id and handle it properly in the
8686 // linker wrapper.
8687 SmallVector<std::string> Parts{
8688 "file=" + File.str(),
8689 "triple=" + TC->getTripleString(),
8690 "arch=" + getProcessorFromTargetID(TC->getTriple(), Arch).str(),
8691 "kind=" + Kind.str(),
8694 if (TC->getDriver().isUsingLTO(/* IsOffload */ true) ||
8695 TC->getTriple().isAMDGPU())
8696 for (StringRef Feature : FeatureArgs)
8697 Parts.emplace_back("feature=" + Feature.str());
8699 CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
8702 C.addCommand(std::make_unique<Command>(
8703 JA, *this, ResponseFileSupport::None(),
8704 Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
8705 CmdArgs, Inputs, Output));
8708 void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
8709 const InputInfo &Output,
8710 const InputInfoList &Inputs,
8711 const ArgList &Args,
8712 const char *LinkingOutput) const {
8713 const Driver &D = getToolChain().getDriver();
8714 const llvm::Triple TheTriple = getToolChain().getTriple();
8715 ArgStringList CmdArgs;
8717 // Pass the CUDA path to the linker wrapper tool.
8718 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP}) {
8719 auto TCRange = C.getOffloadToolChains(Kind);
8720 for (auto &I : llvm::make_range(TCRange.first, TCRange.second)) {
8721 const ToolChain *TC = I.second;
8722 if (TC->getTriple().isNVPTX()) {
8723 CudaInstallationDetector CudaInstallation(D, TheTriple, Args);
8724 if (CudaInstallation.isValid())
8725 CmdArgs.push_back(Args.MakeArgString(
8726 "--cuda-path=" + CudaInstallation.getInstallPath()));
8727 break;
8732 // Pass in the optimization level to use for LTO.
8733 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
8734 StringRef OOpt;
8735 if (A->getOption().matches(options::OPT_O4) ||
8736 A->getOption().matches(options::OPT_Ofast))
8737 OOpt = "3";
8738 else if (A->getOption().matches(options::OPT_O)) {
8739 OOpt = A->getValue();
8740 if (OOpt == "g")
8741 OOpt = "1";
8742 else if (OOpt == "s" || OOpt == "z")
8743 OOpt = "2";
8744 } else if (A->getOption().matches(options::OPT_O0))
8745 OOpt = "0";
8746 if (!OOpt.empty())
8747 CmdArgs.push_back(Args.MakeArgString(Twine("--opt-level=O") + OOpt));
8750 CmdArgs.push_back(
8751 Args.MakeArgString("--host-triple=" + TheTriple.getTriple()));
8752 if (Args.hasArg(options::OPT_v))
8753 CmdArgs.push_back("--wrapper-verbose");
8755 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
8756 if (!A->getOption().matches(options::OPT_g0))
8757 CmdArgs.push_back("--device-debug");
8760 // code-object-version=X needs to be passed to clang-linker-wrapper to ensure
8761 // that it is used by lld.
8762 if (const Arg *A = Args.getLastArg(options::OPT_mcode_object_version_EQ)) {
8763 CmdArgs.push_back(Args.MakeArgString("-mllvm"));
8764 CmdArgs.push_back(Args.MakeArgString(
8765 Twine("--amdhsa-code-object-version=") + A->getValue()));
8768 for (const auto &A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
8769 CmdArgs.push_back(Args.MakeArgString("--ptxas-arg=" + A));
8771 // Forward remarks passes to the LLVM backend in the wrapper.
8772 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
8773 CmdArgs.push_back(Args.MakeArgString(Twine("--offload-opt=-pass-remarks=") +
8774 A->getValue()));
8775 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
8776 CmdArgs.push_back(Args.MakeArgString(
8777 Twine("--offload-opt=-pass-remarks-missed=") + A->getValue()));
8778 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
8779 CmdArgs.push_back(Args.MakeArgString(
8780 Twine("--offload-opt=-pass-remarks-analysis=") + A->getValue()));
8781 if (Args.getLastArg(options::OPT_save_temps_EQ))
8782 CmdArgs.push_back("--save-temps");
8784 // Construct the link job so we can wrap around it.
8785 Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
8786 const auto &LinkCommand = C.getJobs().getJobs().back();
8788 // Forward -Xoffload-linker<-triple> arguments to the device link job.
8789 for (Arg *A : Args.filtered(options::OPT_Xoffload_linker)) {
8790 StringRef Val = A->getValue(0);
8791 if (Val.empty())
8792 CmdArgs.push_back(
8793 Args.MakeArgString(Twine("--device-linker=") + A->getValue(1)));
8794 else
8795 CmdArgs.push_back(Args.MakeArgString(
8796 "--device-linker=" +
8797 ToolChain::getOpenMPTriple(Val.drop_front()).getTriple() + "=" +
8798 A->getValue(1)));
8800 Args.ClaimAllArgs(options::OPT_Xoffload_linker);
8802 // Embed bitcode instead of an object in JIT mode.
8803 if (Args.hasFlag(options::OPT_fopenmp_target_jit,
8804 options::OPT_fno_openmp_target_jit, false))
8805 CmdArgs.push_back("--embed-bitcode");
8807 // Forward `-mllvm` arguments to the LLVM invocations if present.
8808 for (Arg *A : Args.filtered(options::OPT_mllvm)) {
8809 CmdArgs.push_back("-mllvm");
8810 CmdArgs.push_back(A->getValue());
8811 A->claim();
8814 // Add the linker arguments to be forwarded by the wrapper.
8815 CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
8816 LinkCommand->getExecutable()));
8817 CmdArgs.push_back("--");
8818 for (const char *LinkArg : LinkCommand->getArguments())
8819 CmdArgs.push_back(LinkArg);
8821 const char *Exec =
8822 Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
8824 // Replace the executable and arguments of the link job with the
8825 // wrapper.
8826 LinkCommand->replaceExecutable(Exec);
8827 LinkCommand->replaceArguments(CmdArgs);