1 //===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
11 #include "Arch/AArch64.h"
13 #include "Arch/M68k.h"
14 #include "Arch/Mips.h"
16 #include "Arch/RISCV.h"
17 #include "Arch/Sparc.h"
18 #include "Arch/SystemZ.h"
21 #include "CommonArgs.h"
25 #include "clang/Basic/CharInfo.h"
26 #include "clang/Basic/CodeGenOptions.h"
27 #include "clang/Basic/LangOptions.h"
28 #include "clang/Basic/ObjCRuntime.h"
29 #include "clang/Basic/Version.h"
30 #include "clang/Driver/Distro.h"
31 #include "clang/Driver/DriverDiagnostic.h"
32 #include "clang/Driver/InputInfo.h"
33 #include "clang/Driver/Options.h"
34 #include "clang/Driver/SanitizerArgs.h"
35 #include "clang/Driver/XRayArgs.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/Config/llvm-config.h"
38 #include "llvm/Option/ArgList.h"
39 #include "llvm/Support/CodeGen.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/Compression.h"
42 #include "llvm/Support/FileSystem.h"
43 #include "llvm/Support/Host.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Process.h"
46 #include "llvm/Support/TargetParser.h"
47 #include "llvm/Support/YAMLParser.h"
49 using namespace clang::driver;
50 using namespace clang::driver::tools;
51 using namespace clang;
52 using namespace llvm::opt;
54 static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
56 Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) {
57 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
58 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
59 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
60 << A->getBaseArg().getAsString(Args)
61 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
66 static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
67 // In gcc, only ARM checks this, but it seems reasonable to check universally.
68 if (Args.hasArg(options::OPT_static))
70 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
71 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
75 // Add backslashes to escape spaces and other backslashes.
76 // This is used for the space-separated argument list specified with
77 // the -dwarf-debug-flags option.
78 static void EscapeSpacesAndBackslashes(const char *Arg,
79 SmallVectorImpl<char> &Res) {
93 // Quote target names for inclusion in GNU Make dependency files.
94 // Only the characters '$', '#', ' ', '\t' are quoted.
95 static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
96 for (unsigned i = 0, e = Target.size(); i != e; ++i) {
100 // Escape the preceding backslashes
101 for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
104 // Escape the space/tab
117 Res.push_back(Target[i]);
121 /// Apply \a Work on the current tool chain \a RegularToolChain and any other
122 /// offloading tool chain that is associated with the current action \a JA.
124 forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
125 const ToolChain &RegularToolChain,
126 llvm::function_ref<void(const ToolChain &)> Work) {
127 // Apply Work on the current/regular tool chain.
128 Work(RegularToolChain);
130 // Apply Work on all the offloading tool chains associated with the current
132 if (JA.isHostOffloading(Action::OFK_Cuda))
133 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
134 else if (JA.isDeviceOffloading(Action::OFK_Cuda))
135 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
136 else if (JA.isHostOffloading(Action::OFK_HIP))
137 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
138 else if (JA.isDeviceOffloading(Action::OFK_HIP))
139 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
141 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
142 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
143 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
145 } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
146 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
149 // TODO: Add support for other offloading programming models here.
153 /// This is a helper function for validating the optional refinement step
154 /// parameter in reciprocal argument strings. Return false if there is an error
155 /// parsing the refinement step. Otherwise, return true and set the Position
156 /// of the refinement step in the input string.
157 static bool getRefinementStep(StringRef In, const Driver &D,
158 const Arg &A, size_t &Position) {
159 const char RefinementStepToken = ':';
160 Position = In.find(RefinementStepToken);
161 if (Position != StringRef::npos) {
162 StringRef Option = A.getOption().getName();
163 StringRef RefStep = In.substr(Position + 1);
164 // Allow exactly one numeric character for the additional refinement
165 // step parameter. This is reasonable for all currently-supported
166 // operations and architectures because we would expect that a larger value
167 // of refinement steps would cause the estimate "optimization" to
168 // under-perform the native operation. Also, if the estimate does not
169 // converge quickly, it probably will not ever converge, so further
170 // refinement steps will not produce a better answer.
171 if (RefStep.size() != 1) {
172 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
175 char RefStepChar = RefStep[0];
176 if (RefStepChar < '0' || RefStepChar > '9') {
177 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
184 /// The -mrecip flag requires processing of many optional parameters.
185 static void ParseMRecip(const Driver &D, const ArgList &Args,
186 ArgStringList &OutStrings) {
187 StringRef DisabledPrefixIn = "!";
188 StringRef DisabledPrefixOut = "!";
189 StringRef EnabledPrefixOut = "";
190 StringRef Out = "-mrecip=";
192 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
196 unsigned NumOptions = A->getNumValues();
197 if (NumOptions == 0) {
198 // No option is the same as "all".
199 OutStrings.push_back(Args.MakeArgString(Out + "all"));
203 // Pass through "all", "none", or "default" with an optional refinement step.
204 if (NumOptions == 1) {
205 StringRef Val = A->getValue(0);
207 if (!getRefinementStep(Val, D, *A, RefStepLoc))
209 StringRef ValBase = Val.slice(0, RefStepLoc);
210 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
211 OutStrings.push_back(Args.MakeArgString(Out + Val));
216 // Each reciprocal type may be enabled or disabled individually.
217 // Check each input value for validity, concatenate them all back together,
220 llvm::StringMap<bool> OptionStrings;
221 OptionStrings.insert(std::make_pair("divd", false));
222 OptionStrings.insert(std::make_pair("divf", false));
223 OptionStrings.insert(std::make_pair("vec-divd", false));
224 OptionStrings.insert(std::make_pair("vec-divf", false));
225 OptionStrings.insert(std::make_pair("sqrtd", false));
226 OptionStrings.insert(std::make_pair("sqrtf", false));
227 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
228 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
230 for (unsigned i = 0; i != NumOptions; ++i) {
231 StringRef Val = A->getValue(i);
233 bool IsDisabled = Val.startswith(DisabledPrefixIn);
234 // Ignore the disablement token for string matching.
239 if (!getRefinementStep(Val, D, *A, RefStep))
242 StringRef ValBase = Val.slice(0, RefStep);
243 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
244 if (OptionIter == OptionStrings.end()) {
245 // Try again specifying float suffix.
246 OptionIter = OptionStrings.find(ValBase.str() + 'f');
247 if (OptionIter == OptionStrings.end()) {
248 // The input name did not match any known option string.
249 D.Diag(diag::err_drv_unknown_argument) << Val;
252 // The option was specified without a float or double suffix.
253 // Make sure that the double entry was not already specified.
254 // The float entry will be checked below.
255 if (OptionStrings[ValBase.str() + 'd']) {
256 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
261 if (OptionIter->second == true) {
262 // Duplicate option specified.
263 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
267 // Mark the matched option as found. Do not allow duplicate specifiers.
268 OptionIter->second = true;
270 // If the precision was not specified, also mark the double entry as found.
271 if (ValBase.back() != 'f' && ValBase.back() != 'd')
272 OptionStrings[ValBase.str() + 'd'] = true;
274 // Build the output string.
275 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
276 Out = Args.MakeArgString(Out + Prefix + Val);
277 if (i != NumOptions - 1)
278 Out = Args.MakeArgString(Out + ",");
281 OutStrings.push_back(Args.MakeArgString(Out));
284 /// The -mprefer-vector-width option accepts either a positive integer
285 /// or the string "none".
286 static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
287 ArgStringList &CmdArgs) {
288 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
292 StringRef Value = A->getValue();
293 if (Value == "none") {
294 CmdArgs.push_back("-mprefer-vector-width=none");
297 if (Value.getAsInteger(10, Width)) {
298 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
301 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
305 static void getWebAssemblyTargetFeatures(const ArgList &Args,
306 std::vector<StringRef> &Features) {
307 handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
310 static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
311 const ArgList &Args, ArgStringList &CmdArgs,
312 bool ForAS, bool IsAux = false) {
313 std::vector<StringRef> Features;
314 switch (Triple.getArch()) {
317 case llvm::Triple::mips:
318 case llvm::Triple::mipsel:
319 case llvm::Triple::mips64:
320 case llvm::Triple::mips64el:
321 mips::getMIPSTargetFeatures(D, Triple, Args, Features);
324 case llvm::Triple::arm:
325 case llvm::Triple::armeb:
326 case llvm::Triple::thumb:
327 case llvm::Triple::thumbeb:
328 arm::getARMTargetFeatures(D, Triple, Args, CmdArgs, Features, ForAS);
331 case llvm::Triple::ppc:
332 case llvm::Triple::ppcle:
333 case llvm::Triple::ppc64:
334 case llvm::Triple::ppc64le:
335 ppc::getPPCTargetFeatures(D, Triple, Args, Features);
337 case llvm::Triple::riscv32:
338 case llvm::Triple::riscv64:
339 riscv::getRISCVTargetFeatures(D, Triple, Args, Features);
341 case llvm::Triple::systemz:
342 systemz::getSystemZTargetFeatures(D, Args, Features);
344 case llvm::Triple::aarch64:
345 case llvm::Triple::aarch64_32:
346 case llvm::Triple::aarch64_be:
347 aarch64::getAArch64TargetFeatures(D, Triple, Args, Features, ForAS);
349 case llvm::Triple::x86:
350 case llvm::Triple::x86_64:
351 x86::getX86TargetFeatures(D, Triple, Args, Features);
353 case llvm::Triple::hexagon:
354 hexagon::getHexagonTargetFeatures(D, Args, Features);
356 case llvm::Triple::wasm32:
357 case llvm::Triple::wasm64:
358 getWebAssemblyTargetFeatures(Args, Features);
360 case llvm::Triple::sparc:
361 case llvm::Triple::sparcel:
362 case llvm::Triple::sparcv9:
363 sparc::getSparcTargetFeatures(D, Args, Features);
365 case llvm::Triple::r600:
366 case llvm::Triple::amdgcn:
367 amdgpu::getAMDGPUTargetFeatures(D, Triple, Args, Features);
369 case llvm::Triple::m68k:
370 m68k::getM68kTargetFeatures(D, Triple, Args, Features);
372 case llvm::Triple::msp430:
373 msp430::getMSP430TargetFeatures(D, Args, Features);
375 case llvm::Triple::ve:
376 ve::getVETargetFeatures(D, Args, Features);
380 for (auto Feature : unifyTargetFeatures(Features)) {
381 CmdArgs.push_back(IsAux ? "-aux-target-feature" : "-target-feature");
382 CmdArgs.push_back(Feature.data());
387 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
388 const llvm::Triple &Triple) {
389 // We use the zero-cost exception tables for Objective-C if the non-fragile
390 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
392 if (runtime.isNonFragile())
395 if (!Triple.isMacOSX())
398 return (!Triple.isMacOSXVersionLT(10, 5) &&
399 (Triple.getArch() == llvm::Triple::x86_64 ||
400 Triple.getArch() == llvm::Triple::arm));
403 /// Adds exception related arguments to the driver command arguments. There's a
404 /// master flag, -fexceptions and also language specific flags to enable/disable
405 /// C++ and Objective-C exceptions. This makes it possible to for example
406 /// disable C++ exceptions but enable Objective-C exceptions.
407 static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
408 const ToolChain &TC, bool KernelOrKext,
409 const ObjCRuntime &objcRuntime,
410 ArgStringList &CmdArgs) {
411 const llvm::Triple &Triple = TC.getTriple();
414 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
415 // arguments now to avoid warnings about unused arguments.
416 Args.ClaimAllArgs(options::OPT_fexceptions);
417 Args.ClaimAllArgs(options::OPT_fno_exceptions);
418 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
419 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
420 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
421 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
422 Args.ClaimAllArgs(options::OPT_fasync_exceptions);
423 Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
427 // See if the user explicitly enabled exceptions.
428 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
431 bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
432 options::OPT_fno_async_exceptions, false);
434 CmdArgs.push_back("-fasync-exceptions");
438 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
439 // is not necessarily sensible, but follows GCC.
440 if (types::isObjC(InputType) &&
441 Args.hasFlag(options::OPT_fobjc_exceptions,
442 options::OPT_fno_objc_exceptions, true)) {
443 CmdArgs.push_back("-fobjc-exceptions");
445 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
448 if (types::isCXX(InputType)) {
449 // Disable C++ EH by default on XCore and PS4.
450 bool CXXExceptionsEnabled =
451 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
452 Arg *ExceptionArg = Args.getLastArg(
453 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
454 options::OPT_fexceptions, options::OPT_fno_exceptions);
456 CXXExceptionsEnabled =
457 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
458 ExceptionArg->getOption().matches(options::OPT_fexceptions);
460 if (CXXExceptionsEnabled) {
461 CmdArgs.push_back("-fcxx-exceptions");
467 // OPT_fignore_exceptions means exception could still be thrown,
468 // but no clean up or catch would happen in current module.
469 // So we do not set EH to false.
470 Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
473 CmdArgs.push_back("-fexceptions");
477 static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
478 const JobAction &JA) {
480 if (TC.getTriple().isOSDarwin()) {
481 // The native darwin assembler doesn't support the linker_option directives,
482 // so we disable them if we think the .s file will be passed to it.
483 Default = TC.useIntegratedAs();
485 // The linker_option directives are intended for host compilation.
486 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
487 JA.isDeviceOffloading(Action::OFK_HIP))
489 return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
493 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
494 // to the corresponding DebugInfoKind.
495 static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
496 assert(A.getOption().matches(options::OPT_gN_Group) &&
497 "Not a -g option that specifies a debug-info level");
498 if (A.getOption().matches(options::OPT_g0) ||
499 A.getOption().matches(options::OPT_ggdb0))
500 return codegenoptions::NoDebugInfo;
501 if (A.getOption().matches(options::OPT_gline_tables_only) ||
502 A.getOption().matches(options::OPT_ggdb1))
503 return codegenoptions::DebugLineTablesOnly;
504 if (A.getOption().matches(options::OPT_gline_directives_only))
505 return codegenoptions::DebugDirectivesOnly;
506 return codegenoptions::DebugInfoConstructor;
509 static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
510 switch (Triple.getArch()){
513 case llvm::Triple::arm:
514 case llvm::Triple::thumb:
515 // ARM Darwin targets require a frame pointer to be always present to aid
516 // offline debugging via backtraces.
517 return Triple.isOSDarwin();
521 static bool useFramePointerForTargetByDefault(const ArgList &Args,
522 const llvm::Triple &Triple) {
523 if (Args.hasArg(options::OPT_pg) && !Args.hasArg(options::OPT_mfentry))
526 switch (Triple.getArch()) {
527 case llvm::Triple::xcore:
528 case llvm::Triple::wasm32:
529 case llvm::Triple::wasm64:
530 case llvm::Triple::msp430:
531 // XCore never wants frame pointers, regardless of OS.
532 // WebAssembly never wants frame pointers.
534 case llvm::Triple::ppc:
535 case llvm::Triple::ppcle:
536 case llvm::Triple::ppc64:
537 case llvm::Triple::ppc64le:
538 case llvm::Triple::riscv32:
539 case llvm::Triple::riscv64:
540 case llvm::Triple::amdgcn:
541 case llvm::Triple::r600:
542 return !areOptimizationsEnabled(Args);
547 if (Triple.isOSNetBSD()) {
548 return !areOptimizationsEnabled(Args);
551 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
553 switch (Triple.getArch()) {
554 // Don't use a frame pointer on linux if optimizing for certain targets.
555 case llvm::Triple::arm:
556 case llvm::Triple::armeb:
557 case llvm::Triple::thumb:
558 case llvm::Triple::thumbeb:
559 if (Triple.isAndroid())
562 case llvm::Triple::mips64:
563 case llvm::Triple::mips64el:
564 case llvm::Triple::mips:
565 case llvm::Triple::mipsel:
566 case llvm::Triple::systemz:
567 case llvm::Triple::x86:
568 case llvm::Triple::x86_64:
569 return !areOptimizationsEnabled(Args);
575 if (Triple.isOSWindows()) {
576 switch (Triple.getArch()) {
577 case llvm::Triple::x86:
578 return !areOptimizationsEnabled(Args);
579 case llvm::Triple::x86_64:
580 return Triple.isOSBinFormatMachO();
581 case llvm::Triple::arm:
582 case llvm::Triple::thumb:
583 // Windows on ARM builds with FPO disabled to aid fast stack walking
586 // All other supported Windows ISAs use xdata unwind information, so frame
587 // pointers are not generally useful.
595 static CodeGenOptions::FramePointerKind
596 getFramePointerKind(const ArgList &Args, const llvm::Triple &Triple) {
599 // 00) leaf retained, non-leaf retained
600 // 01) leaf retained, non-leaf omitted (this is invalid)
601 // 10) leaf omitted, non-leaf retained
602 // (what -momit-leaf-frame-pointer was designed for)
603 // 11) leaf omitted, non-leaf omitted
605 // "omit" options taking precedence over "no-omit" options is the only way
606 // to make 3 valid states representable
607 Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
608 options::OPT_fno_omit_frame_pointer);
609 bool OmitFP = A && A->getOption().matches(options::OPT_fomit_frame_pointer);
611 A && A->getOption().matches(options::OPT_fno_omit_frame_pointer);
612 bool OmitLeafFP = Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
613 options::OPT_mno_omit_leaf_frame_pointer,
614 Triple.isAArch64() || Triple.isPS4CPU());
615 if (NoOmitFP || mustUseNonLeafFramePointerForTarget(Triple) ||
616 (!OmitFP && useFramePointerForTargetByDefault(Args, Triple))) {
618 return CodeGenOptions::FramePointerKind::NonLeaf;
619 return CodeGenOptions::FramePointerKind::All;
621 return CodeGenOptions::FramePointerKind::None;
624 /// Add a CC1 option to specify the debug compilation directory.
625 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs,
626 const llvm::vfs::FileSystem &VFS) {
627 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
628 options::OPT_fdebug_compilation_dir_EQ)) {
629 if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
630 CmdArgs.push_back(Args.MakeArgString(Twine("-fdebug-compilation-dir=") +
633 A->render(Args, CmdArgs);
634 } else if (llvm::ErrorOr<std::string> CWD =
635 VFS.getCurrentWorkingDirectory()) {
636 CmdArgs.push_back(Args.MakeArgString("-fdebug-compilation-dir=" + *CWD));
640 /// Add a CC1 and CC1AS option to specify the debug file path prefix map.
641 static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
642 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
643 options::OPT_fdebug_prefix_map_EQ)) {
644 StringRef Map = A->getValue();
645 if (Map.find('=') == StringRef::npos)
646 D.Diag(diag::err_drv_invalid_argument_to_option)
647 << Map << A->getOption().getName();
649 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
654 /// Add a CC1 and CC1AS option to specify the macro file path prefix map.
655 static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
656 ArgStringList &CmdArgs) {
657 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
658 options::OPT_fmacro_prefix_map_EQ)) {
659 StringRef Map = A->getValue();
660 if (Map.find('=') == StringRef::npos)
661 D.Diag(diag::err_drv_invalid_argument_to_option)
662 << Map << A->getOption().getName();
664 CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
669 /// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
670 static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
671 ArgStringList &CmdArgs) {
672 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
673 options::OPT_fcoverage_prefix_map_EQ)) {
674 StringRef Map = A->getValue();
675 if (Map.find('=') == StringRef::npos)
676 D.Diag(diag::err_drv_invalid_argument_to_option)
677 << Map << A->getOption().getName();
679 CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
684 /// Vectorize at all optimization levels greater than 1 except for -Oz.
685 /// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
687 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
688 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
689 if (A->getOption().matches(options::OPT_O4) ||
690 A->getOption().matches(options::OPT_Ofast))
693 if (A->getOption().matches(options::OPT_O0))
696 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
699 StringRef S(A->getValue());
703 // Don't vectorize -Oz, unless it's the slp vectorizer.
707 unsigned OptLevel = 0;
708 if (S.getAsInteger(10, OptLevel))
717 /// Add -x lang to \p CmdArgs for \p Input.
718 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
719 ArgStringList &CmdArgs) {
720 // When using -verify-pch, we don't want to provide the type
721 // 'precompiled-header' if it was inferred from the file extension
722 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
725 CmdArgs.push_back("-x");
726 if (Args.hasArg(options::OPT_rewrite_objc))
727 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
729 // Map the driver type to the frontend type. This is mostly an identity
730 // mapping, except that the distinction between module interface units
731 // and other source files does not exist at the frontend layer.
732 const char *ClangType;
733 switch (Input.getType()) {
734 case types::TY_CXXModule:
737 case types::TY_PP_CXXModule:
738 ClangType = "c++-cpp-output";
741 ClangType = types::getTypeName(Input.getType());
744 CmdArgs.push_back(ClangType);
748 static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
749 const Driver &D, const InputInfo &Output,
751 ArgStringList &CmdArgs) {
753 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
754 options::OPT_fprofile_generate_EQ,
755 options::OPT_fno_profile_generate);
756 if (PGOGenerateArg &&
757 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
758 PGOGenerateArg = nullptr;
760 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
761 options::OPT_fcs_profile_generate_EQ,
762 options::OPT_fno_profile_generate);
763 if (CSPGOGenerateArg &&
764 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
765 CSPGOGenerateArg = nullptr;
767 auto *ProfileGenerateArg = Args.getLastArg(
768 options::OPT_fprofile_instr_generate,
769 options::OPT_fprofile_instr_generate_EQ,
770 options::OPT_fno_profile_instr_generate);
771 if (ProfileGenerateArg &&
772 ProfileGenerateArg->getOption().matches(
773 options::OPT_fno_profile_instr_generate))
774 ProfileGenerateArg = nullptr;
776 if (PGOGenerateArg && ProfileGenerateArg)
777 D.Diag(diag::err_drv_argument_not_allowed_with)
778 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
780 auto *ProfileUseArg = getLastProfileUseArg(Args);
782 if (PGOGenerateArg && ProfileUseArg)
783 D.Diag(diag::err_drv_argument_not_allowed_with)
784 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
786 if (ProfileGenerateArg && ProfileUseArg)
787 D.Diag(diag::err_drv_argument_not_allowed_with)
788 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
790 if (CSPGOGenerateArg && PGOGenerateArg) {
791 D.Diag(diag::err_drv_argument_not_allowed_with)
792 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
793 PGOGenerateArg = nullptr;
796 if (TC.getTriple().isOSAIX()) {
798 if (!D.isUsingLTO(false /*IsDeviceOffloadAction */) ||
799 D.getLTOMode() != LTOK_Full)
800 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
801 << PGOGenerateArg->getSpelling() << "-flto";
802 if (ProfileGenerateArg)
803 D.Diag(diag::err_drv_unsupported_opt_for_target)
804 << ProfileGenerateArg->getSpelling() << TC.getTriple().str();
805 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
806 D.Diag(diag::err_drv_unsupported_opt_for_target)
807 << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
810 if (ProfileGenerateArg) {
811 if (ProfileGenerateArg->getOption().matches(
812 options::OPT_fprofile_instr_generate_EQ))
813 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
814 ProfileGenerateArg->getValue()));
815 // The default is to use Clang Instrumentation.
816 CmdArgs.push_back("-fprofile-instrument=clang");
817 if (TC.getTriple().isWindowsMSVCEnvironment()) {
818 // Add dependent lib for clang_rt.profile
819 CmdArgs.push_back(Args.MakeArgString(
820 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
824 Arg *PGOGenArg = nullptr;
825 if (PGOGenerateArg) {
826 assert(!CSPGOGenerateArg);
827 PGOGenArg = PGOGenerateArg;
828 CmdArgs.push_back("-fprofile-instrument=llvm");
830 if (CSPGOGenerateArg) {
831 assert(!PGOGenerateArg);
832 PGOGenArg = CSPGOGenerateArg;
833 CmdArgs.push_back("-fprofile-instrument=csllvm");
836 if (TC.getTriple().isWindowsMSVCEnvironment()) {
837 // Add dependent lib for clang_rt.profile
838 CmdArgs.push_back(Args.MakeArgString(
839 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
841 if (PGOGenArg->getOption().matches(
842 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
843 : options::OPT_fcs_profile_generate_EQ)) {
844 SmallString<128> Path(PGOGenArg->getValue());
845 llvm::sys::path::append(Path, "default_%m.profraw");
847 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
852 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
853 CmdArgs.push_back(Args.MakeArgString(
854 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
855 else if ((ProfileUseArg->getOption().matches(
856 options::OPT_fprofile_use_EQ) ||
857 ProfileUseArg->getOption().matches(
858 options::OPT_fprofile_instr_use))) {
859 SmallString<128> Path(
860 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
861 if (Path.empty() || llvm::sys::fs::is_directory(Path))
862 llvm::sys::path::append(Path, "default.profdata");
864 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
868 bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
869 options::OPT_fno_test_coverage, false) ||
870 Args.hasArg(options::OPT_coverage);
871 bool EmitCovData = TC.needsGCovInstrumentation(Args);
873 CmdArgs.push_back("-ftest-coverage");
875 CmdArgs.push_back("-fprofile-arcs");
877 if (Args.hasFlag(options::OPT_fcoverage_mapping,
878 options::OPT_fno_coverage_mapping, false)) {
879 if (!ProfileGenerateArg)
880 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
881 << "-fcoverage-mapping"
882 << "-fprofile-instr-generate";
884 CmdArgs.push_back("-fcoverage-mapping");
887 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
888 options::OPT_fcoverage_compilation_dir_EQ)) {
889 if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
890 CmdArgs.push_back(Args.MakeArgString(
891 Twine("-fcoverage-compilation-dir=") + A->getValue()));
893 A->render(Args, CmdArgs);
894 } else if (llvm::ErrorOr<std::string> CWD =
895 D.getVFS().getCurrentWorkingDirectory()) {
896 CmdArgs.push_back(Args.MakeArgString("-fcoverage-compilation-dir=" + *CWD));
899 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
900 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
901 if (!Args.hasArg(options::OPT_coverage))
902 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
903 << "-fprofile-exclude-files="
906 StringRef v = Arg->getValue();
908 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
911 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
912 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
913 if (!Args.hasArg(options::OPT_coverage))
914 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
915 << "-fprofile-filter-files="
918 StringRef v = Arg->getValue();
919 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
922 if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
923 StringRef Val = A->getValue();
924 if (Val == "atomic" || Val == "prefer-atomic")
925 CmdArgs.push_back("-fprofile-update=atomic");
926 else if (Val != "single")
927 D.Diag(diag::err_drv_unsupported_option_argument)
928 << A->getOption().getName() << Val;
929 } else if (TC.getSanitizerArgs().needsTsanRt()) {
930 CmdArgs.push_back("-fprofile-update=atomic");
933 // Leave -fprofile-dir= an unused argument unless .gcda emission is
934 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
935 // the flag used. There is no -fno-profile-dir, so the user has no
936 // targeted way to suppress the warning.
937 Arg *FProfileDir = nullptr;
938 if (Args.hasArg(options::OPT_fprofile_arcs) ||
939 Args.hasArg(options::OPT_coverage))
940 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
942 // Put the .gcno and .gcda files (if needed) next to the object file or
943 // bitcode file in the case of LTO.
944 // FIXME: There should be a simpler way to find the object file for this
945 // input, and this code probably does the wrong thing for commands that
946 // compile and link all at once.
947 if ((Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) &&
948 (EmitCovNotes || EmitCovData) && Output.isFilename()) {
949 SmallString<128> OutputFilename;
950 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT__SLASH_Fo))
951 OutputFilename = FinalOutput->getValue();
952 else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
953 OutputFilename = FinalOutput->getValue();
955 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
956 SmallString<128> CoverageFilename = OutputFilename;
957 if (llvm::sys::path::is_relative(CoverageFilename))
958 (void)D.getVFS().makeAbsolute(CoverageFilename);
959 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
961 CmdArgs.push_back("-coverage-notes-file");
962 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
966 CoverageFilename = FProfileDir->getValue();
967 llvm::sys::path::append(CoverageFilename, OutputFilename);
969 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
970 CmdArgs.push_back("-coverage-data-file");
971 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
976 /// Check whether the given input tree contains any compilation actions.
977 static bool ContainsCompileAction(const Action *A) {
978 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
981 for (const auto &AI : A->inputs())
982 if (ContainsCompileAction(AI))
988 /// Check if -relax-all should be passed to the internal assembler.
989 /// This is done by default when compiling non-assembler source with -O0.
990 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
991 bool RelaxDefault = true;
993 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
994 RelaxDefault = A->getOption().matches(options::OPT_O0);
997 RelaxDefault = false;
998 for (const auto &Act : C.getActions()) {
999 if (ContainsCompileAction(Act)) {
1000 RelaxDefault = true;
1006 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
1010 // Extract the integer N from a string spelled "-dwarf-N", returning 0
1011 // on mismatch. The StringRef input (rather than an Arg) allows
1012 // for use by the "-Xassembler" option parser.
1013 static unsigned DwarfVersionNum(StringRef ArgValue) {
1014 return llvm::StringSwitch<unsigned>(ArgValue)
1015 .Case("-gdwarf-2", 2)
1016 .Case("-gdwarf-3", 3)
1017 .Case("-gdwarf-4", 4)
1018 .Case("-gdwarf-5", 5)
1022 // Find a DWARF format version option.
1023 // This function is a complementary for DwarfVersionNum().
1024 static const Arg *getDwarfNArg(const ArgList &Args) {
1025 return Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
1026 options::OPT_gdwarf_4, options::OPT_gdwarf_5,
1027 options::OPT_gdwarf);
1030 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
1031 codegenoptions::DebugInfoKind DebugInfoKind,
1032 unsigned DwarfVersion,
1033 llvm::DebuggerKind DebuggerTuning) {
1034 switch (DebugInfoKind) {
1035 case codegenoptions::DebugDirectivesOnly:
1036 CmdArgs.push_back("-debug-info-kind=line-directives-only");
1038 case codegenoptions::DebugLineTablesOnly:
1039 CmdArgs.push_back("-debug-info-kind=line-tables-only");
1041 case codegenoptions::DebugInfoConstructor:
1042 CmdArgs.push_back("-debug-info-kind=constructor");
1044 case codegenoptions::LimitedDebugInfo:
1045 CmdArgs.push_back("-debug-info-kind=limited");
1047 case codegenoptions::FullDebugInfo:
1048 CmdArgs.push_back("-debug-info-kind=standalone");
1050 case codegenoptions::UnusedTypeInfo:
1051 CmdArgs.push_back("-debug-info-kind=unused-types");
1056 if (DwarfVersion > 0)
1058 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
1059 switch (DebuggerTuning) {
1060 case llvm::DebuggerKind::GDB:
1061 CmdArgs.push_back("-debugger-tuning=gdb");
1063 case llvm::DebuggerKind::LLDB:
1064 CmdArgs.push_back("-debugger-tuning=lldb");
1066 case llvm::DebuggerKind::SCE:
1067 CmdArgs.push_back("-debugger-tuning=sce");
1069 case llvm::DebuggerKind::DBX:
1070 CmdArgs.push_back("-debugger-tuning=dbx");
1077 static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
1078 const Driver &D, const ToolChain &TC) {
1079 assert(A && "Expected non-nullptr argument.");
1080 if (TC.supportsDebugInfoOption(A))
1082 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
1083 << A->getAsString(Args) << TC.getTripleString();
1087 static void RenderDebugInfoCompressionArgs(const ArgList &Args,
1088 ArgStringList &CmdArgs,
1090 const ToolChain &TC) {
1091 const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
1094 if (checkDebugInfoOption(A, Args, D, TC)) {
1095 StringRef Value = A->getValue();
1096 if (Value == "none") {
1097 CmdArgs.push_back("--compress-debug-sections=none");
1098 } else if (Value == "zlib" || Value == "zlib-gnu") {
1099 if (llvm::zlib::isAvailable()) {
1101 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
1103 D.Diag(diag::warn_debug_compression_unavailable);
1106 D.Diag(diag::err_drv_unsupported_option_argument)
1107 << A->getOption().getName() << Value;
1112 static const char *RelocationModelName(llvm::Reloc::Model Model) {
1114 case llvm::Reloc::Static:
1116 case llvm::Reloc::PIC_:
1118 case llvm::Reloc::DynamicNoPIC:
1119 return "dynamic-no-pic";
1120 case llvm::Reloc::ROPI:
1122 case llvm::Reloc::RWPI:
1124 case llvm::Reloc::ROPI_RWPI:
1127 llvm_unreachable("Unknown Reloc::Model kind");
1129 static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
1130 const ArgList &Args,
1131 ArgStringList &CmdArgs) {
1132 // If no version was requested by the user, use the default value from the
1133 // back end. This is consistent with the value returned from
1134 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
1135 // requiring the corresponding llvm to have the AMDGPU target enabled,
1136 // provided the user (e.g. front end tests) can use the default.
1137 if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
1138 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
1139 CmdArgs.insert(CmdArgs.begin() + 1,
1140 Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
1141 Twine(CodeObjVer)));
1142 CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
1146 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1147 const Driver &D, const ArgList &Args,
1148 ArgStringList &CmdArgs,
1149 const InputInfo &Output,
1150 const InputInfoList &Inputs) const {
1151 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1153 CheckPreprocessingOptions(D, Args);
1155 Args.AddLastArg(CmdArgs, options::OPT_C);
1156 Args.AddLastArg(CmdArgs, options::OPT_CC);
1158 // Handle dependency file generation.
1159 Arg *ArgM = Args.getLastArg(options::OPT_MM);
1161 ArgM = Args.getLastArg(options::OPT_M);
1162 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
1164 ArgMD = Args.getLastArg(options::OPT_MD);
1166 // -M and -MM imply -w.
1168 CmdArgs.push_back("-w");
1173 // Determine the output location.
1174 const char *DepFile;
1175 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1176 DepFile = MF->getValue();
1177 C.addFailureResultFile(DepFile, &JA);
1178 } else if (Output.getType() == types::TY_Dependencies) {
1179 DepFile = Output.getFilename();
1180 } else if (!ArgMD) {
1183 DepFile = getDependencyFileName(Args, Inputs);
1184 C.addFailureResultFile(DepFile, &JA);
1186 CmdArgs.push_back("-dependency-file");
1187 CmdArgs.push_back(DepFile);
1189 bool HasTarget = false;
1190 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1193 if (A->getOption().matches(options::OPT_MT)) {
1194 A->render(Args, CmdArgs);
1196 CmdArgs.push_back("-MT");
1197 SmallString<128> Quoted;
1198 QuoteTarget(A->getValue(), Quoted);
1199 CmdArgs.push_back(Args.MakeArgString(Quoted));
1203 // Add a default target if one wasn't specified.
1205 const char *DepTarget;
1207 // If user provided -o, that is the dependency target, except
1208 // when we are only generating a dependency file.
1209 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1210 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1211 DepTarget = OutputOpt->getValue();
1213 // Otherwise derive from the base input.
1215 // FIXME: This should use the computed output file location.
1216 SmallString<128> P(Inputs[0].getBaseInput());
1217 llvm::sys::path::replace_extension(P, "o");
1218 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1221 CmdArgs.push_back("-MT");
1222 SmallString<128> Quoted;
1223 QuoteTarget(DepTarget, Quoted);
1224 CmdArgs.push_back(Args.MakeArgString(Quoted));
1227 if (ArgM->getOption().matches(options::OPT_M) ||
1228 ArgM->getOption().matches(options::OPT_MD))
1229 CmdArgs.push_back("-sys-header-deps");
1230 if ((isa<PrecompileJobAction>(JA) &&
1231 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1232 Args.hasArg(options::OPT_fmodule_file_deps))
1233 CmdArgs.push_back("-module-file-deps");
1236 if (Args.hasArg(options::OPT_MG)) {
1237 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1238 ArgM->getOption().matches(options::OPT_MMD))
1239 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1240 CmdArgs.push_back("-MG");
1243 Args.AddLastArg(CmdArgs, options::OPT_MP);
1244 Args.AddLastArg(CmdArgs, options::OPT_MV);
1246 // Add offload include arguments specific for CUDA/HIP. This must happen
1247 // before we -I or -include anything else, because we must pick up the
1248 // CUDA/HIP headers from the particular CUDA/ROCm installation, rather than
1249 // from e.g. /usr/local/include.
1250 if (JA.isOffloading(Action::OFK_Cuda))
1251 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1252 if (JA.isOffloading(Action::OFK_HIP))
1253 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
1255 // If we are offloading to a target via OpenMP we need to include the
1256 // openmp_wrappers folder which contains alternative system headers.
1257 if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
1258 getToolChain().getTriple().isNVPTX()){
1259 if (!Args.hasArg(options::OPT_nobuiltininc)) {
1260 // Add openmp_wrappers/* to our system include path. This lets us wrap
1261 // standard library headers.
1262 SmallString<128> P(D.ResourceDir);
1263 llvm::sys::path::append(P, "include");
1264 llvm::sys::path::append(P, "openmp_wrappers");
1265 CmdArgs.push_back("-internal-isystem");
1266 CmdArgs.push_back(Args.MakeArgString(P));
1269 CmdArgs.push_back("-include");
1270 CmdArgs.push_back("__clang_openmp_device_functions.h");
1273 // Add -i* options, and automatically translate to
1274 // -include-pch/-include-pth for transparent PCH support. It's
1275 // wonky, but we include looking for .gch so we can support seamless
1276 // replacement into a build system already set up to be generating
1279 if (getToolChain().getDriver().IsCLMode()) {
1280 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1281 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1282 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1283 JA.getKind() <= Action::AssembleJobClass) {
1284 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1285 // -fpch-instantiate-templates is the default when creating
1286 // precomp using /Yc
1287 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1288 options::OPT_fno_pch_instantiate_templates, true))
1289 CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1291 if (YcArg || YuArg) {
1292 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1293 if (!isa<PrecompileJobAction>(JA)) {
1294 CmdArgs.push_back("-include-pch");
1295 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1296 C, !ThroughHeader.empty()
1298 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1301 if (ThroughHeader.empty()) {
1302 CmdArgs.push_back(Args.MakeArgString(
1303 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1306 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1311 bool RenderedImplicitInclude = false;
1312 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1313 if (A->getOption().matches(options::OPT_include)) {
1314 // Handling of gcc-style gch precompiled headers.
1315 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1316 RenderedImplicitInclude = true;
1318 bool FoundPCH = false;
1319 SmallString<128> P(A->getValue());
1320 // We want the files to have a name like foo.h.pch. Add a dummy extension
1321 // so that replace_extension does the right thing.
1323 llvm::sys::path::replace_extension(P, "pch");
1324 if (llvm::sys::fs::exists(P))
1328 llvm::sys::path::replace_extension(P, "gch");
1329 if (llvm::sys::fs::exists(P)) {
1335 if (IsFirstImplicitInclude) {
1337 CmdArgs.push_back("-include-pch");
1338 CmdArgs.push_back(Args.MakeArgString(P));
1341 // Ignore the PCH if not first on command line and emit warning.
1342 D.Diag(diag::warn_drv_pch_not_first_include) << P
1343 << A->getAsString(Args);
1346 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1347 // Handling of paths which must come late. These entries are handled by
1348 // the toolchain itself after the resource dir is inserted in the right
1350 // Do not claim the argument so that the use of the argument does not
1351 // silently go unnoticed on toolchains which do not honour the option.
1353 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1354 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1358 // Not translated, render as usual.
1360 A->render(Args, CmdArgs);
1363 Args.AddAllArgs(CmdArgs,
1364 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1365 options::OPT_F, options::OPT_index_header_map});
1367 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1369 // FIXME: There is a very unfortunate problem here, some troubled
1370 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1371 // really support that we would have to parse and then translate
1372 // those options. :(
1373 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1374 options::OPT_Xpreprocessor);
1376 // -I- is a deprecated GCC feature, reject it.
1377 if (Arg *A = Args.getLastArg(options::OPT_I_))
1378 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1380 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1381 // -isysroot to the CC1 invocation.
1382 StringRef sysroot = C.getSysRoot();
1383 if (sysroot != "") {
1384 if (!Args.hasArg(options::OPT_isysroot)) {
1385 CmdArgs.push_back("-isysroot");
1386 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1390 // Parse additional include paths from environment variables.
1391 // FIXME: We should probably sink the logic for handling these from the
1392 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1393 // CPATH - included following the user specified includes (but prior to
1394 // builtin and standard includes).
1395 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1396 // C_INCLUDE_PATH - system includes enabled when compiling C.
1397 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1398 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1399 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1400 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1401 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1402 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1403 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1405 // While adding the include arguments, we also attempt to retrieve the
1406 // arguments of related offloading toolchains or arguments that are specific
1407 // of an offloading programming model.
1409 // Add C++ include arguments, if needed.
1410 if (types::isCXX(Inputs[0].getType())) {
1411 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1412 forAllAssociatedToolChains(
1413 C, JA, getToolChain(),
1414 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1415 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1416 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1420 // Add system include arguments for all targets but IAMCU.
1422 forAllAssociatedToolChains(C, JA, getToolChain(),
1423 [&Args, &CmdArgs](const ToolChain &TC) {
1424 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1427 // For IAMCU add special include arguments.
1428 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1431 addMacroPrefixMapArg(D, Args, CmdArgs);
1432 addCoveragePrefixMapArg(D, Args, CmdArgs);
1435 // FIXME: Move to target hook.
1436 static bool isSignedCharDefault(const llvm::Triple &Triple) {
1437 switch (Triple.getArch()) {
1441 case llvm::Triple::aarch64:
1442 case llvm::Triple::aarch64_32:
1443 case llvm::Triple::aarch64_be:
1444 case llvm::Triple::arm:
1445 case llvm::Triple::armeb:
1446 case llvm::Triple::thumb:
1447 case llvm::Triple::thumbeb:
1448 if (Triple.isOSDarwin() || Triple.isOSWindows())
1452 case llvm::Triple::ppc:
1453 case llvm::Triple::ppc64:
1454 if (Triple.isOSDarwin())
1458 case llvm::Triple::hexagon:
1459 case llvm::Triple::ppcle:
1460 case llvm::Triple::ppc64le:
1461 case llvm::Triple::riscv32:
1462 case llvm::Triple::riscv64:
1463 case llvm::Triple::systemz:
1464 case llvm::Triple::xcore:
1469 static bool hasMultipleInvocations(const llvm::Triple &Triple,
1470 const ArgList &Args) {
1471 // Supported only on Darwin where we invoke the compiler multiple times
1472 // followed by an invocation to lipo.
1473 if (!Triple.isOSDarwin())
1475 // If more than one "-arch <arch>" is specified, we're targeting multiple
1476 // architectures resulting in a fat binary.
1477 return Args.getAllArgValues(options::OPT_arch).size() > 1;
1480 static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1481 const llvm::Triple &Triple) {
1482 // When enabling remarks, we need to error if:
1483 // * The remark file is specified but we're targeting multiple architectures,
1484 // which means more than one remark file is being generated.
1485 bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1486 bool hasExplicitOutputFile =
1487 Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1488 if (hasMultipleInvocations && hasExplicitOutputFile) {
1489 D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1490 << "-foptimization-record-file";
1496 static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1497 const llvm::Triple &Triple,
1498 const InputInfo &Input,
1499 const InputInfo &Output, const JobAction &JA) {
1500 StringRef Format = "yaml";
1501 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1502 Format = A->getValue();
1504 CmdArgs.push_back("-opt-record-file");
1506 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1508 CmdArgs.push_back(A->getValue());
1510 bool hasMultipleArchs =
1511 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1512 Args.getAllArgValues(options::OPT_arch).size() > 1;
1516 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1517 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1518 F = FinalOutput->getValue();
1520 if (Format != "yaml" && // For YAML, keep the original behavior.
1521 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1522 Output.isFilename())
1523 F = Output.getFilename();
1527 // Use the input filename.
1528 F = llvm::sys::path::stem(Input.getBaseInput());
1530 // If we're compiling for an offload architecture (i.e. a CUDA device),
1531 // we need to make the file name for the device compilation different
1532 // from the host compilation.
1533 if (!JA.isDeviceOffloading(Action::OFK_None) &&
1534 !JA.isDeviceOffloading(Action::OFK_Host)) {
1535 llvm::sys::path::replace_extension(F, "");
1536 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
1537 Triple.normalize());
1539 F += JA.getOffloadingArch();
1543 // If we're having more than one "-arch", we should name the files
1544 // differently so that every cc1 invocation writes to a different file.
1545 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1546 // name from the triple.
1547 if (hasMultipleArchs) {
1548 // First, remember the extension.
1549 SmallString<64> OldExtension = llvm::sys::path::extension(F);
1551 llvm::sys::path::replace_extension(F, "");
1552 // attach -<arch> to it.
1554 F += Triple.getArchName();
1555 // put back the extension.
1556 llvm::sys::path::replace_extension(F, OldExtension);
1559 SmallString<32> Extension;
1560 Extension += "opt.";
1561 Extension += Format;
1563 llvm::sys::path::replace_extension(F, Extension);
1564 CmdArgs.push_back(Args.MakeArgString(F));
1568 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1569 CmdArgs.push_back("-opt-record-passes");
1570 CmdArgs.push_back(A->getValue());
1573 if (!Format.empty()) {
1574 CmdArgs.push_back("-opt-record-format");
1575 CmdArgs.push_back(Format.data());
1579 void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1580 if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1581 options::OPT_fno_aapcs_bitfield_width, true))
1582 CmdArgs.push_back("-fno-aapcs-bitfield-width");
1584 if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1585 CmdArgs.push_back("-faapcs-bitfield-load");
1589 void RenderARMABI(const llvm::Triple &Triple, const ArgList &Args,
1590 ArgStringList &CmdArgs) {
1591 // Select the ABI to use.
1592 // FIXME: Support -meabi.
1593 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1594 const char *ABIName = nullptr;
1595 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1596 ABIName = A->getValue();
1598 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
1599 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1602 CmdArgs.push_back("-target-abi");
1603 CmdArgs.push_back(ABIName);
1607 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1608 ArgStringList &CmdArgs, bool KernelOrKext) const {
1609 RenderARMABI(Triple, Args, CmdArgs);
1611 // Determine floating point ABI from the options & target defaults.
1612 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1613 if (ABI == arm::FloatABI::Soft) {
1614 // Floating point operations and argument passing are soft.
1615 // FIXME: This changes CPP defines, we need -target-soft-float.
1616 CmdArgs.push_back("-msoft-float");
1617 CmdArgs.push_back("-mfloat-abi");
1618 CmdArgs.push_back("soft");
1619 } else if (ABI == arm::FloatABI::SoftFP) {
1620 // Floating point operations are hard, but argument passing is soft.
1621 CmdArgs.push_back("-mfloat-abi");
1622 CmdArgs.push_back("soft");
1624 // Floating point operations and argument passing are hard.
1625 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1626 CmdArgs.push_back("-mfloat-abi");
1627 CmdArgs.push_back("hard");
1630 // Forward the -mglobal-merge option for explicit control over the pass.
1631 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1632 options::OPT_mno_global_merge)) {
1633 CmdArgs.push_back("-mllvm");
1634 if (A->getOption().matches(options::OPT_mno_global_merge))
1635 CmdArgs.push_back("-arm-global-merge=false");
1637 CmdArgs.push_back("-arm-global-merge=true");
1640 if (!Args.hasFlag(options::OPT_mimplicit_float,
1641 options::OPT_mno_implicit_float, true))
1642 CmdArgs.push_back("-no-implicit-float");
1644 if (Args.getLastArg(options::OPT_mcmse))
1645 CmdArgs.push_back("-mcmse");
1647 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1650 void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1651 const ArgList &Args, bool KernelOrKext,
1652 ArgStringList &CmdArgs) const {
1653 const ToolChain &TC = getToolChain();
1655 // Add the target features
1656 getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1658 // Add target specific flags.
1659 switch (TC.getArch()) {
1663 case llvm::Triple::arm:
1664 case llvm::Triple::armeb:
1665 case llvm::Triple::thumb:
1666 case llvm::Triple::thumbeb:
1667 // Use the effective triple, which takes into account the deployment target.
1668 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1669 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1672 case llvm::Triple::aarch64:
1673 case llvm::Triple::aarch64_32:
1674 case llvm::Triple::aarch64_be:
1675 AddAArch64TargetArgs(Args, CmdArgs);
1676 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1679 case llvm::Triple::mips:
1680 case llvm::Triple::mipsel:
1681 case llvm::Triple::mips64:
1682 case llvm::Triple::mips64el:
1683 AddMIPSTargetArgs(Args, CmdArgs);
1686 case llvm::Triple::ppc:
1687 case llvm::Triple::ppcle:
1688 case llvm::Triple::ppc64:
1689 case llvm::Triple::ppc64le:
1690 AddPPCTargetArgs(Args, CmdArgs);
1693 case llvm::Triple::riscv32:
1694 case llvm::Triple::riscv64:
1695 AddRISCVTargetArgs(Args, CmdArgs);
1698 case llvm::Triple::sparc:
1699 case llvm::Triple::sparcel:
1700 case llvm::Triple::sparcv9:
1701 AddSparcTargetArgs(Args, CmdArgs);
1704 case llvm::Triple::systemz:
1705 AddSystemZTargetArgs(Args, CmdArgs);
1708 case llvm::Triple::x86:
1709 case llvm::Triple::x86_64:
1710 AddX86TargetArgs(Args, CmdArgs);
1713 case llvm::Triple::lanai:
1714 AddLanaiTargetArgs(Args, CmdArgs);
1717 case llvm::Triple::hexagon:
1718 AddHexagonTargetArgs(Args, CmdArgs);
1721 case llvm::Triple::wasm32:
1722 case llvm::Triple::wasm64:
1723 AddWebAssemblyTargetArgs(Args, CmdArgs);
1726 case llvm::Triple::ve:
1727 AddVETargetArgs(Args, CmdArgs);
1733 void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1734 ArgStringList &CmdArgs) {
1735 const char *ABIName = nullptr;
1736 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1737 ABIName = A->getValue();
1738 else if (Triple.isOSDarwin())
1739 ABIName = "darwinpcs";
1743 CmdArgs.push_back("-target-abi");
1744 CmdArgs.push_back(ABIName);
1748 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1749 ArgStringList &CmdArgs) const {
1750 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1752 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1753 Args.hasArg(options::OPT_mkernel) ||
1754 Args.hasArg(options::OPT_fapple_kext))
1755 CmdArgs.push_back("-disable-red-zone");
1757 if (!Args.hasFlag(options::OPT_mimplicit_float,
1758 options::OPT_mno_implicit_float, true))
1759 CmdArgs.push_back("-no-implicit-float");
1761 RenderAArch64ABI(Triple, Args, CmdArgs);
1763 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1764 options::OPT_mno_fix_cortex_a53_835769)) {
1765 CmdArgs.push_back("-mllvm");
1766 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1767 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1769 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1770 } else if (Triple.isAndroid()) {
1771 // Enabled A53 errata (835769) workaround by default on android
1772 CmdArgs.push_back("-mllvm");
1773 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1776 // Forward the -mglobal-merge option for explicit control over the pass.
1777 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1778 options::OPT_mno_global_merge)) {
1779 CmdArgs.push_back("-mllvm");
1780 if (A->getOption().matches(options::OPT_mno_global_merge))
1781 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1783 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1786 // Enable/disable return address signing and indirect branch targets.
1787 if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ,
1788 options::OPT_mbranch_protection_EQ)) {
1790 const Driver &D = getToolChain().getDriver();
1792 StringRef Scope, Key;
1793 bool IndirectBranches;
1795 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1796 Scope = A->getValue();
1797 if (!Scope.equals("none") && !Scope.equals("non-leaf") &&
1798 !Scope.equals("all"))
1799 D.Diag(diag::err_invalid_branch_protection)
1800 << Scope << A->getAsString(Args);
1802 IndirectBranches = false;
1805 llvm::AArch64::ParsedBranchProtection PBP;
1806 if (!llvm::AArch64::parseBranchProtection(A->getValue(), PBP, Err))
1807 D.Diag(diag::err_invalid_branch_protection)
1808 << Err << A->getAsString(Args);
1811 IndirectBranches = PBP.BranchTargetEnforcement;
1815 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1817 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1818 if (IndirectBranches)
1819 CmdArgs.push_back("-mbranch-target-enforce");
1822 // Handle -msve_vector_bits=<bits>
1823 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
1824 StringRef Val = A->getValue();
1825 const Driver &D = getToolChain().getDriver();
1826 if (Val.equals("128") || Val.equals("256") || Val.equals("512") ||
1827 Val.equals("1024") || Val.equals("2048"))
1829 Args.MakeArgString(llvm::Twine("-msve-vector-bits=") + Val));
1830 // Silently drop requests for vector-length agnostic code as it's implied.
1831 else if (!Val.equals("scalable"))
1832 // Handle the unsupported values passed to msve-vector-bits.
1833 D.Diag(diag::err_drv_unsupported_option_argument)
1834 << A->getOption().getName() << Val;
1837 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1840 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1841 ArgStringList &CmdArgs) const {
1842 const Driver &D = getToolChain().getDriver();
1845 const llvm::Triple &Triple = getToolChain().getTriple();
1846 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1848 CmdArgs.push_back("-target-abi");
1849 CmdArgs.push_back(ABIName.data());
1851 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1852 if (ABI == mips::FloatABI::Soft) {
1853 // Floating point operations and argument passing are soft.
1854 CmdArgs.push_back("-msoft-float");
1855 CmdArgs.push_back("-mfloat-abi");
1856 CmdArgs.push_back("soft");
1858 // Floating point operations and argument passing are hard.
1859 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1860 CmdArgs.push_back("-mfloat-abi");
1861 CmdArgs.push_back("hard");
1864 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1865 options::OPT_mno_ldc1_sdc1)) {
1866 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1867 CmdArgs.push_back("-mllvm");
1868 CmdArgs.push_back("-mno-ldc1-sdc1");
1872 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1873 options::OPT_mno_check_zero_division)) {
1874 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1875 CmdArgs.push_back("-mllvm");
1876 CmdArgs.push_back("-mno-check-zero-division");
1880 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1881 StringRef v = A->getValue();
1882 CmdArgs.push_back("-mllvm");
1883 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1887 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1889 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1891 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1892 // -mgpopt is the default for static, -fno-pic environments but these two
1893 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1894 // the only case where -mllvm -mgpopt is passed.
1895 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1896 // passed explicitly when compiling something with -mabicalls
1897 // (implictly) in affect. Currently the warning is in the backend.
1899 // When the ABI in use is N64, we also need to determine the PIC mode that
1900 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1902 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1904 llvm::Reloc::Model RelocationModel;
1907 std::tie(RelocationModel, PICLevel, IsPIE) =
1908 ParsePICArgs(getToolChain(), Args);
1910 NoABICalls = NoABICalls ||
1911 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1913 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1914 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1915 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1916 CmdArgs.push_back("-mllvm");
1917 CmdArgs.push_back("-mgpopt");
1919 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1920 options::OPT_mno_local_sdata);
1921 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1922 options::OPT_mno_extern_sdata);
1923 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1924 options::OPT_mno_embedded_data);
1926 CmdArgs.push_back("-mllvm");
1927 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1928 CmdArgs.push_back("-mlocal-sdata=1");
1930 CmdArgs.push_back("-mlocal-sdata=0");
1932 LocalSData->claim();
1936 CmdArgs.push_back("-mllvm");
1937 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1938 CmdArgs.push_back("-mextern-sdata=1");
1940 CmdArgs.push_back("-mextern-sdata=0");
1942 ExternSData->claim();
1946 CmdArgs.push_back("-mllvm");
1947 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1948 CmdArgs.push_back("-membedded-data=1");
1950 CmdArgs.push_back("-membedded-data=0");
1952 EmbeddedData->claim();
1955 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1956 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1961 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1962 StringRef Val = StringRef(A->getValue());
1963 if (mips::hasCompactBranches(CPUName)) {
1964 if (Val == "never" || Val == "always" || Val == "optimal") {
1965 CmdArgs.push_back("-mllvm");
1966 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1968 D.Diag(diag::err_drv_unsupported_option_argument)
1969 << A->getOption().getName() << Val;
1971 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1974 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1975 options::OPT_mno_relax_pic_calls)) {
1976 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1977 CmdArgs.push_back("-mllvm");
1978 CmdArgs.push_back("-mips-jalr-reloc=0");
1983 void Clang::AddPPCTargetArgs(const ArgList &Args,
1984 ArgStringList &CmdArgs) const {
1985 // Select the ABI to use.
1986 const char *ABIName = nullptr;
1987 const llvm::Triple &T = getToolChain().getTriple();
1988 if (T.isOSBinFormatELF()) {
1989 switch (getToolChain().getArch()) {
1990 case llvm::Triple::ppc64: {
1991 if ((T.isOSFreeBSD() && T.getOSMajorVersion() >= 13) ||
1992 T.isOSOpenBSD() || T.isMusl())
1998 case llvm::Triple::ppc64le:
2006 bool IEEELongDouble = false;
2007 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
2008 StringRef V = A->getValue();
2009 if (V == "ieeelongdouble")
2010 IEEELongDouble = true;
2011 else if (V == "ibmlongdouble")
2012 IEEELongDouble = false;
2013 else if (V != "altivec")
2014 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2015 // the option if given as we don't have backend support for any targets
2016 // that don't use the altivec abi.
2017 ABIName = A->getValue();
2020 CmdArgs.push_back("-mabi=ieeelongdouble");
2022 ppc::FloatABI FloatABI =
2023 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
2025 if (FloatABI == ppc::FloatABI::Soft) {
2026 // Floating point operations and argument passing are soft.
2027 CmdArgs.push_back("-msoft-float");
2028 CmdArgs.push_back("-mfloat-abi");
2029 CmdArgs.push_back("soft");
2031 // Floating point operations and argument passing are hard.
2032 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2033 CmdArgs.push_back("-mfloat-abi");
2034 CmdArgs.push_back("hard");
2038 CmdArgs.push_back("-target-abi");
2039 CmdArgs.push_back(ABIName);
2043 static void SetRISCVSmallDataLimit(const ToolChain &TC, const ArgList &Args,
2044 ArgStringList &CmdArgs) {
2045 const Driver &D = TC.getDriver();
2046 const llvm::Triple &Triple = TC.getTriple();
2047 // Default small data limitation is eight.
2048 const char *SmallDataLimit = "8";
2049 // Get small data limitation.
2050 if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
2051 options::OPT_fPIC)) {
2052 // Not support linker relaxation for PIC.
2053 SmallDataLimit = "0";
2054 if (Args.hasArg(options::OPT_G)) {
2055 D.Diag(diag::warn_drv_unsupported_sdata);
2057 } else if (Args.getLastArgValue(options::OPT_mcmodel_EQ)
2058 .equals_insensitive("large") &&
2059 (Triple.getArch() == llvm::Triple::riscv64)) {
2060 // Not support linker relaxation for RV64 with large code model.
2061 SmallDataLimit = "0";
2062 if (Args.hasArg(options::OPT_G)) {
2063 D.Diag(diag::warn_drv_unsupported_sdata);
2065 } else if (Arg *A = Args.getLastArg(options::OPT_G)) {
2066 SmallDataLimit = A->getValue();
2068 // Forward the -msmall-data-limit= option.
2069 CmdArgs.push_back("-msmall-data-limit");
2070 CmdArgs.push_back(SmallDataLimit);
2073 void Clang::AddRISCVTargetArgs(const ArgList &Args,
2074 ArgStringList &CmdArgs) const {
2075 const llvm::Triple &Triple = getToolChain().getTriple();
2076 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2078 CmdArgs.push_back("-target-abi");
2079 CmdArgs.push_back(ABIName.data());
2081 SetRISCVSmallDataLimit(getToolChain(), Args, CmdArgs);
2083 std::string TuneCPU;
2085 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2086 StringRef Name = A->getValue();
2088 Name = llvm::RISCV::resolveTuneCPUAlias(Name, Triple.isArch64Bit());
2089 TuneCPU = std::string(Name);
2092 if (!TuneCPU.empty()) {
2093 CmdArgs.push_back("-tune-cpu");
2094 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2098 void Clang::AddSparcTargetArgs(const ArgList &Args,
2099 ArgStringList &CmdArgs) const {
2100 sparc::FloatABI FloatABI =
2101 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2103 if (FloatABI == sparc::FloatABI::Soft) {
2104 // Floating point operations and argument passing are soft.
2105 CmdArgs.push_back("-msoft-float");
2106 CmdArgs.push_back("-mfloat-abi");
2107 CmdArgs.push_back("soft");
2109 // Floating point operations and argument passing are hard.
2110 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2111 CmdArgs.push_back("-mfloat-abi");
2112 CmdArgs.push_back("hard");
2116 void Clang::AddSystemZTargetArgs(const ArgList &Args,
2117 ArgStringList &CmdArgs) const {
2118 bool HasBackchain = Args.hasFlag(options::OPT_mbackchain,
2119 options::OPT_mno_backchain, false);
2120 bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2121 options::OPT_mno_packed_stack, false);
2122 systemz::FloatABI FloatABI =
2123 systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2124 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2125 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2126 const Driver &D = getToolChain().getDriver();
2127 D.Diag(diag::err_drv_unsupported_opt)
2128 << "-mpacked-stack -mbackchain -mhard-float";
2131 CmdArgs.push_back("-mbackchain");
2133 CmdArgs.push_back("-mpacked-stack");
2135 // Floating point operations and argument passing are soft.
2136 CmdArgs.push_back("-msoft-float");
2137 CmdArgs.push_back("-mfloat-abi");
2138 CmdArgs.push_back("soft");
2142 void Clang::AddX86TargetArgs(const ArgList &Args,
2143 ArgStringList &CmdArgs) const {
2144 const Driver &D = getToolChain().getDriver();
2145 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2147 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2148 Args.hasArg(options::OPT_mkernel) ||
2149 Args.hasArg(options::OPT_fapple_kext))
2150 CmdArgs.push_back("-disable-red-zone");
2152 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2153 options::OPT_mno_tls_direct_seg_refs, true))
2154 CmdArgs.push_back("-mno-tls-direct-seg-refs");
2156 // Default to avoid implicit floating-point for kernel/kext code, but allow
2157 // that to be overridden with -mno-soft-float.
2158 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2159 Args.hasArg(options::OPT_fapple_kext));
2160 if (Arg *A = Args.getLastArg(
2161 options::OPT_msoft_float, options::OPT_mno_soft_float,
2162 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2163 const Option &O = A->getOption();
2164 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2165 O.matches(options::OPT_msoft_float));
2167 if (NoImplicitFloat)
2168 CmdArgs.push_back("-no-implicit-float");
2170 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2171 StringRef Value = A->getValue();
2172 if (Value == "intel" || Value == "att") {
2173 CmdArgs.push_back("-mllvm");
2174 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2176 D.Diag(diag::err_drv_unsupported_option_argument)
2177 << A->getOption().getName() << Value;
2179 } else if (D.IsCLMode()) {
2180 CmdArgs.push_back("-mllvm");
2181 CmdArgs.push_back("-x86-asm-syntax=intel");
2184 // Set flags to support MCU ABI.
2185 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2186 CmdArgs.push_back("-mfloat-abi");
2187 CmdArgs.push_back("soft");
2188 CmdArgs.push_back("-mstack-alignment=4");
2193 // Default to "generic" unless -march is present or targetting the PS4.
2194 std::string TuneCPU;
2195 if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
2196 !getToolChain().getTriple().isPS4CPU())
2197 TuneCPU = "generic";
2199 // Override based on -mtune.
2200 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2201 StringRef Name = A->getValue();
2203 if (Name == "native") {
2204 Name = llvm::sys::getHostCPUName();
2206 TuneCPU = std::string(Name);
2208 TuneCPU = std::string(Name);
2211 if (!TuneCPU.empty()) {
2212 CmdArgs.push_back("-tune-cpu");
2213 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2217 void Clang::AddHexagonTargetArgs(const ArgList &Args,
2218 ArgStringList &CmdArgs) const {
2219 CmdArgs.push_back("-mqdsp6-compat");
2220 CmdArgs.push_back("-Wreturn-type");
2222 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2223 CmdArgs.push_back("-mllvm");
2224 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
2225 Twine(G.getValue())));
2228 if (!Args.hasArg(options::OPT_fno_short_enums))
2229 CmdArgs.push_back("-fshort-enums");
2230 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2231 CmdArgs.push_back("-mllvm");
2232 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2234 CmdArgs.push_back("-mllvm");
2235 CmdArgs.push_back("-machine-sink-split=0");
2238 void Clang::AddLanaiTargetArgs(const ArgList &Args,
2239 ArgStringList &CmdArgs) const {
2240 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2241 StringRef CPUName = A->getValue();
2243 CmdArgs.push_back("-target-cpu");
2244 CmdArgs.push_back(Args.MakeArgString(CPUName));
2246 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2247 StringRef Value = A->getValue();
2248 // Only support mregparm=4 to support old usage. Report error for all other
2251 if (Value.getAsInteger(10, Mregparm)) {
2252 if (Mregparm != 4) {
2253 getToolChain().getDriver().Diag(
2254 diag::err_drv_unsupported_option_argument)
2255 << A->getOption().getName() << Value;
2261 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2262 ArgStringList &CmdArgs) const {
2263 // Default to "hidden" visibility.
2264 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2265 options::OPT_fvisibility_ms_compat)) {
2266 CmdArgs.push_back("-fvisibility");
2267 CmdArgs.push_back("hidden");
2271 void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2272 // Floating point operations and argument passing are hard.
2273 CmdArgs.push_back("-mfloat-abi");
2274 CmdArgs.push_back("hard");
2277 void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2278 StringRef Target, const InputInfo &Output,
2279 const InputInfo &Input, const ArgList &Args) const {
2280 // If this is a dry run, do not create the compilation database file.
2281 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2284 using llvm::yaml::escape;
2285 const Driver &D = getToolChain().getDriver();
2287 if (!CompilationDatabase) {
2289 auto File = std::make_unique<llvm::raw_fd_ostream>(
2290 Filename, EC, llvm::sys::fs::OF_TextWithCRLF);
2292 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2296 CompilationDatabase = std::move(File);
2298 auto &CDB = *CompilationDatabase;
2299 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2302 CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2303 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2304 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2305 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2306 SmallString<128> Buf;
2308 Buf += types::getTypeName(Input.getType());
2309 CDB << ", \"" << escape(Buf) << "\"";
2310 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2313 CDB << ", \"" << escape(Buf) << "\"";
2315 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2316 for (auto &A: Args) {
2317 auto &O = A->getOption();
2318 // Skip language selection, which is positional.
2319 if (O.getID() == options::OPT_x)
2321 // Skip writing dependency output and the compilation database itself.
2322 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2324 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2327 if (O.getKind() == Option::InputClass)
2329 // All other arguments are quoted and appended.
2331 A->render(Args, ASL);
2333 CDB << ", \"" << escape(it) << "\"";
2337 CDB << ", \"" << escape(Buf) << "\"]},\n";
2340 void Clang::DumpCompilationDatabaseFragmentToDir(
2341 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2342 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2343 // If this is a dry run, do not create the compilation database file.
2344 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2347 if (CompilationDatabase)
2348 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2350 SmallString<256> Path = Dir;
2351 const auto &Driver = C.getDriver();
2352 Driver.getVFS().makeAbsolute(Path);
2353 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2355 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2359 llvm::sys::path::append(
2361 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2363 SmallString<256> TempPath;
2364 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2365 llvm::sys::fs::OF_Text);
2367 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2370 CompilationDatabase =
2371 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2372 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2375 static bool CheckARMImplicitITArg(StringRef Value) {
2376 return Value == "always" || Value == "never" || Value == "arm" ||
2380 static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2382 CmdArgs.push_back("-mllvm");
2383 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2386 static void CollectArgsForIntegratedAssembler(Compilation &C,
2387 const ArgList &Args,
2388 ArgStringList &CmdArgs,
2390 if (UseRelaxAll(C, Args))
2391 CmdArgs.push_back("-mrelax-all");
2393 // Only default to -mincremental-linker-compatible if we think we are
2394 // targeting the MSVC linker.
2395 bool DefaultIncrementalLinkerCompatible =
2396 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2397 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2398 options::OPT_mno_incremental_linker_compatible,
2399 DefaultIncrementalLinkerCompatible))
2400 CmdArgs.push_back("-mincremental-linker-compatible");
2402 // If you add more args here, also add them to the block below that
2403 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2405 // When passing -I arguments to the assembler we sometimes need to
2406 // unconditionally take the next argument. For example, when parsing
2407 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2408 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2409 // arg after parsing the '-I' arg.
2410 bool TakeNextArg = false;
2412 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2413 bool UseNoExecStack = C.getDefaultToolChain().isNoExecStackDefault();
2414 const char *MipsTargetFeature = nullptr;
2415 StringRef ImplicitIt;
2417 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2418 options::OPT_mimplicit_it_EQ)) {
2421 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2422 switch (C.getDefaultToolChain().getArch()) {
2423 case llvm::Triple::arm:
2424 case llvm::Triple::armeb:
2425 case llvm::Triple::thumb:
2426 case llvm::Triple::thumbeb:
2427 // Only store the value; the last value set takes effect.
2428 ImplicitIt = A->getValue();
2429 if (!CheckARMImplicitITArg(ImplicitIt))
2430 D.Diag(diag::err_drv_unsupported_option_argument)
2431 << A->getOption().getName() << ImplicitIt;
2438 for (StringRef Value : A->getValues()) {
2440 CmdArgs.push_back(Value.data());
2441 TakeNextArg = false;
2445 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2446 Value == "-mbig-obj")
2447 continue; // LLVM handles bigobj automatically
2449 switch (C.getDefaultToolChain().getArch()) {
2452 case llvm::Triple::thumb:
2453 case llvm::Triple::thumbeb:
2454 case llvm::Triple::arm:
2455 case llvm::Triple::armeb:
2456 if (Value.startswith("-mimplicit-it=")) {
2457 // Only store the value; the last value set takes effect.
2458 ImplicitIt = Value.split("=").second;
2459 if (CheckARMImplicitITArg(ImplicitIt))
2462 if (Value == "-mthumb")
2463 // -mthumb has already been processed in ComputeLLVMTriple()
2464 // recognize but skip over here.
2467 case llvm::Triple::mips:
2468 case llvm::Triple::mipsel:
2469 case llvm::Triple::mips64:
2470 case llvm::Triple::mips64el:
2471 if (Value == "--trap") {
2472 CmdArgs.push_back("-target-feature");
2473 CmdArgs.push_back("+use-tcc-in-div");
2476 if (Value == "--break") {
2477 CmdArgs.push_back("-target-feature");
2478 CmdArgs.push_back("-use-tcc-in-div");
2481 if (Value.startswith("-msoft-float")) {
2482 CmdArgs.push_back("-target-feature");
2483 CmdArgs.push_back("+soft-float");
2486 if (Value.startswith("-mhard-float")) {
2487 CmdArgs.push_back("-target-feature");
2488 CmdArgs.push_back("-soft-float");
2492 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2493 .Case("-mips1", "+mips1")
2494 .Case("-mips2", "+mips2")
2495 .Case("-mips3", "+mips3")
2496 .Case("-mips4", "+mips4")
2497 .Case("-mips5", "+mips5")
2498 .Case("-mips32", "+mips32")
2499 .Case("-mips32r2", "+mips32r2")
2500 .Case("-mips32r3", "+mips32r3")
2501 .Case("-mips32r5", "+mips32r5")
2502 .Case("-mips32r6", "+mips32r6")
2503 .Case("-mips64", "+mips64")
2504 .Case("-mips64r2", "+mips64r2")
2505 .Case("-mips64r3", "+mips64r3")
2506 .Case("-mips64r5", "+mips64r5")
2507 .Case("-mips64r6", "+mips64r6")
2509 if (MipsTargetFeature)
2513 if (Value == "-force_cpusubtype_ALL") {
2514 // Do nothing, this is the default and we don't support anything else.
2515 } else if (Value == "-L") {
2516 CmdArgs.push_back("-msave-temp-labels");
2517 } else if (Value == "--fatal-warnings") {
2518 CmdArgs.push_back("-massembler-fatal-warnings");
2519 } else if (Value == "--no-warn" || Value == "-W") {
2520 CmdArgs.push_back("-massembler-no-warn");
2521 } else if (Value == "--noexecstack") {
2522 UseNoExecStack = true;
2523 } else if (Value.startswith("-compress-debug-sections") ||
2524 Value.startswith("--compress-debug-sections") ||
2525 Value == "-nocompress-debug-sections" ||
2526 Value == "--nocompress-debug-sections") {
2527 CmdArgs.push_back(Value.data());
2528 } else if (Value == "-mrelax-relocations=yes" ||
2529 Value == "--mrelax-relocations=yes") {
2530 UseRelaxRelocations = true;
2531 } else if (Value == "-mrelax-relocations=no" ||
2532 Value == "--mrelax-relocations=no") {
2533 UseRelaxRelocations = false;
2534 } else if (Value.startswith("-I")) {
2535 CmdArgs.push_back(Value.data());
2536 // We need to consume the next argument if the current arg is a plain
2537 // -I. The next arg will be the include directory.
2540 } else if (Value.startswith("-gdwarf-")) {
2541 // "-gdwarf-N" options are not cc1as options.
2542 unsigned DwarfVersion = DwarfVersionNum(Value);
2543 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2544 CmdArgs.push_back(Value.data());
2546 RenderDebugEnablingArgs(Args, CmdArgs,
2547 codegenoptions::DebugInfoConstructor,
2548 DwarfVersion, llvm::DebuggerKind::Default);
2550 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2551 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2552 // Do nothing, we'll validate it later.
2553 } else if (Value == "-defsym") {
2554 if (A->getNumValues() != 2) {
2555 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2558 const char *S = A->getValue(1);
2559 auto Pair = StringRef(S).split('=');
2560 auto Sym = Pair.first;
2561 auto SVal = Pair.second;
2563 if (Sym.empty() || SVal.empty()) {
2564 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2568 if (SVal.getAsInteger(0, IVal)) {
2569 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2572 CmdArgs.push_back(Value.data());
2574 } else if (Value == "-fdebug-compilation-dir") {
2575 CmdArgs.push_back("-fdebug-compilation-dir");
2577 } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2578 // The flag is a -Wa / -Xassembler argument and Options doesn't
2579 // parse the argument, so this isn't automatically aliased to
2580 // -fdebug-compilation-dir (without '=') here.
2581 CmdArgs.push_back("-fdebug-compilation-dir");
2582 CmdArgs.push_back(Value.data());
2583 } else if (Value == "--version") {
2584 D.PrintVersion(C, llvm::outs());
2586 D.Diag(diag::err_drv_unsupported_option_argument)
2587 << A->getOption().getName() << Value;
2591 if (ImplicitIt.size())
2592 AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2593 if (UseRelaxRelocations)
2594 CmdArgs.push_back("--mrelax-relocations");
2596 CmdArgs.push_back("-mnoexecstack");
2597 if (MipsTargetFeature != nullptr) {
2598 CmdArgs.push_back("-target-feature");
2599 CmdArgs.push_back(MipsTargetFeature);
2602 // forward -fembed-bitcode to assmebler
2603 if (C.getDriver().embedBitcodeEnabled() ||
2604 C.getDriver().embedBitcodeMarkerOnly())
2605 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2608 static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2609 bool OFastEnabled, const ArgList &Args,
2610 ArgStringList &CmdArgs,
2611 const JobAction &JA) {
2612 // Handle various floating point optimization flags, mapping them to the
2613 // appropriate LLVM code generation flags. This is complicated by several
2614 // "umbrella" flags, so we do this by stepping through the flags incrementally
2615 // adjusting what we think is enabled/disabled, then at the end setting the
2616 // LLVM flags based on the final state.
2617 bool HonorINFs = true;
2618 bool HonorNaNs = true;
2619 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2620 bool MathErrno = TC.IsMathErrnoDefault();
2621 bool AssociativeMath = false;
2622 bool ReciprocalMath = false;
2623 bool SignedZeros = true;
2624 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2625 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2626 // overriden by ffp-exception-behavior?
2627 bool RoundingFPMath = false;
2628 bool RoundingMathPresent = false; // Is rounding-math in args?
2629 // -ffp-model values: strict, fast, precise
2630 StringRef FPModel = "";
2631 // -ffp-exception-behavior options: strict, maytrap, ignore
2632 StringRef FPExceptionBehavior = "";
2633 const llvm::DenormalMode DefaultDenormalFPMath =
2634 TC.getDefaultDenormalModeForType(Args, JA);
2635 const llvm::DenormalMode DefaultDenormalFP32Math =
2636 TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2638 llvm::DenormalMode DenormalFPMath = DefaultDenormalFPMath;
2639 llvm::DenormalMode DenormalFP32Math = DefaultDenormalFP32Math;
2640 StringRef FPContract = "";
2641 bool StrictFPModel = false;
2644 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2645 CmdArgs.push_back("-mlimit-float-precision");
2646 CmdArgs.push_back(A->getValue());
2649 for (const Arg *A : Args) {
2650 auto optID = A->getOption().getID();
2651 bool PreciseFPModel = false;
2655 case options::OPT_ffp_model_EQ: {
2656 // If -ffp-model= is seen, reset to fno-fast-math
2659 // Turning *off* -ffast-math restores the toolchain default.
2660 MathErrno = TC.IsMathErrnoDefault();
2661 AssociativeMath = false;
2662 ReciprocalMath = false;
2664 // -fno_fast_math restores default denormal and fpcontract handling
2666 DenormalFPMath = llvm::DenormalMode::getIEEE();
2668 // FIXME: The target may have picked a non-IEEE default mode here based on
2669 // -cl-denorms-are-zero. Should the target consider -fp-model interaction?
2670 DenormalFP32Math = llvm::DenormalMode::getIEEE();
2672 StringRef Val = A->getValue();
2673 if (OFastEnabled && !Val.equals("fast")) {
2674 // Only -ffp-model=fast is compatible with OFast, ignore.
2675 D.Diag(clang::diag::warn_drv_overriding_flag_option)
2676 << Args.MakeArgString("-ffp-model=" + Val)
2680 StrictFPModel = false;
2681 PreciseFPModel = true;
2682 // ffp-model= is a Driver option, it is entirely rewritten into more
2683 // granular options before being passed into cc1.
2684 // Use the gcc option in the switch below.
2685 if (!FPModel.empty() && !FPModel.equals(Val)) {
2686 D.Diag(clang::diag::warn_drv_overriding_flag_option)
2687 << Args.MakeArgString("-ffp-model=" + FPModel)
2688 << Args.MakeArgString("-ffp-model=" + Val);
2691 if (Val.equals("fast")) {
2692 optID = options::OPT_ffast_math;
2694 FPContract = "fast";
2695 } else if (Val.equals("precise")) {
2696 optID = options::OPT_ffp_contract;
2698 FPContract = "fast";
2699 PreciseFPModel = true;
2700 } else if (Val.equals("strict")) {
2701 StrictFPModel = true;
2702 optID = options::OPT_frounding_math;
2703 FPExceptionBehavior = "strict";
2706 TrappingMath = true;
2708 D.Diag(diag::err_drv_unsupported_option_argument)
2709 << A->getOption().getName() << Val;
2715 // If this isn't an FP option skip the claim below
2718 // Options controlling individual features
2719 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2720 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2721 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2722 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2723 case options::OPT_fmath_errno: MathErrno = true; break;
2724 case options::OPT_fno_math_errno: MathErrno = false; break;
2725 case options::OPT_fassociative_math: AssociativeMath = true; break;
2726 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2727 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2728 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2729 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2730 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2731 case options::OPT_ftrapping_math:
2732 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2733 !FPExceptionBehavior.equals("strict"))
2734 // Warn that previous value of option is overridden.
2735 D.Diag(clang::diag::warn_drv_overriding_flag_option)
2736 << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2737 << "-ftrapping-math";
2738 TrappingMath = true;
2739 TrappingMathPresent = true;
2740 FPExceptionBehavior = "strict";
2742 case options::OPT_fno_trapping_math:
2743 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2744 !FPExceptionBehavior.equals("ignore"))
2745 // Warn that previous value of option is overridden.
2746 D.Diag(clang::diag::warn_drv_overriding_flag_option)
2747 << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2748 << "-fno-trapping-math";
2749 TrappingMath = false;
2750 TrappingMathPresent = true;
2751 FPExceptionBehavior = "ignore";
2754 case options::OPT_frounding_math:
2755 RoundingFPMath = true;
2756 RoundingMathPresent = true;
2759 case options::OPT_fno_rounding_math:
2760 RoundingFPMath = false;
2761 RoundingMathPresent = false;
2764 case options::OPT_fdenormal_fp_math_EQ:
2765 DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
2766 if (!DenormalFPMath.isValid()) {
2767 D.Diag(diag::err_drv_invalid_value)
2768 << A->getAsString(Args) << A->getValue();
2772 case options::OPT_fdenormal_fp_math_f32_EQ:
2773 DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
2774 if (!DenormalFP32Math.isValid()) {
2775 D.Diag(diag::err_drv_invalid_value)
2776 << A->getAsString(Args) << A->getValue();
2780 // Validate and pass through -ffp-contract option.
2781 case options::OPT_ffp_contract: {
2782 StringRef Val = A->getValue();
2783 if (PreciseFPModel) {
2784 // -ffp-model=precise enables ffp-contract=fast as a side effect
2785 // the FPContract value has already been set to a string literal
2786 // and the Val string isn't a pertinent value.
2788 } else if (Val.equals("fast") || Val.equals("on") || Val.equals("off"))
2791 D.Diag(diag::err_drv_unsupported_option_argument)
2792 << A->getOption().getName() << Val;
2796 // Validate and pass through -ffp-model option.
2797 case options::OPT_ffp_model_EQ:
2798 // This should only occur in the error case
2799 // since the optID has been replaced by a more granular
2800 // floating point option.
2803 // Validate and pass through -ffp-exception-behavior option.
2804 case options::OPT_ffp_exception_behavior_EQ: {
2805 StringRef Val = A->getValue();
2806 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2807 !FPExceptionBehavior.equals(Val))
2808 // Warn that previous value of option is overridden.
2809 D.Diag(clang::diag::warn_drv_overriding_flag_option)
2810 << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2811 << Args.MakeArgString("-ffp-exception-behavior=" + Val);
2812 TrappingMath = TrappingMathPresent = false;
2813 if (Val.equals("ignore") || Val.equals("maytrap"))
2814 FPExceptionBehavior = Val;
2815 else if (Val.equals("strict")) {
2816 FPExceptionBehavior = Val;
2817 TrappingMath = TrappingMathPresent = true;
2819 D.Diag(diag::err_drv_unsupported_option_argument)
2820 << A->getOption().getName() << Val;
2824 case options::OPT_ffinite_math_only:
2828 case options::OPT_fno_finite_math_only:
2833 case options::OPT_funsafe_math_optimizations:
2834 AssociativeMath = true;
2835 ReciprocalMath = true;
2836 SignedZeros = false;
2837 TrappingMath = false;
2838 FPExceptionBehavior = "";
2840 case options::OPT_fno_unsafe_math_optimizations:
2841 AssociativeMath = false;
2842 ReciprocalMath = false;
2844 TrappingMath = true;
2845 FPExceptionBehavior = "strict";
2847 // The target may have opted to flush by default, so force IEEE.
2848 DenormalFPMath = llvm::DenormalMode::getIEEE();
2849 DenormalFP32Math = llvm::DenormalMode::getIEEE();
2852 case options::OPT_Ofast:
2853 // If -Ofast is the optimization level, then -ffast-math should be enabled
2857 case options::OPT_ffast_math:
2861 AssociativeMath = true;
2862 ReciprocalMath = true;
2863 SignedZeros = false;
2864 TrappingMath = false;
2865 RoundingFPMath = false;
2866 // If fast-math is set then set the fp-contract mode to fast.
2867 FPContract = "fast";
2869 case options::OPT_fno_fast_math:
2872 // Turning on -ffast-math (with either flag) removes the need for
2873 // MathErrno. However, turning *off* -ffast-math merely restores the
2874 // toolchain default (which may be false).
2875 MathErrno = TC.IsMathErrnoDefault();
2876 AssociativeMath = false;
2877 ReciprocalMath = false;
2879 TrappingMath = false;
2880 RoundingFPMath = false;
2881 // -fno_fast_math restores default denormal and fpcontract handling
2882 DenormalFPMath = DefaultDenormalFPMath;
2883 DenormalFP32Math = llvm::DenormalMode::getIEEE();
2887 if (StrictFPModel) {
2888 // If -ffp-model=strict has been specified on command line but
2889 // subsequent options conflict then emit warning diagnostic.
2890 if (HonorINFs && HonorNaNs &&
2891 !AssociativeMath && !ReciprocalMath &&
2892 SignedZeros && TrappingMath && RoundingFPMath &&
2893 (FPContract.equals("off") || FPContract.empty()) &&
2894 DenormalFPMath == llvm::DenormalMode::getIEEE() &&
2895 DenormalFP32Math == llvm::DenormalMode::getIEEE())
2896 // OK: Current Arg doesn't conflict with -ffp-model=strict
2899 StrictFPModel = false;
2901 D.Diag(clang::diag::warn_drv_overriding_flag_option)
2902 << "-ffp-model=strict" <<
2903 ((A->getNumValues() == 0) ? A->getSpelling()
2904 : Args.MakeArgString(A->getSpelling() + A->getValue()));
2908 // If we handled this option claim it
2913 CmdArgs.push_back("-menable-no-infs");
2916 CmdArgs.push_back("-menable-no-nans");
2919 CmdArgs.push_back("-fmath-errno");
2921 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2923 CmdArgs.push_back("-menable-unsafe-fp-math");
2926 CmdArgs.push_back("-fno-signed-zeros");
2928 if (AssociativeMath && !SignedZeros && !TrappingMath)
2929 CmdArgs.push_back("-mreassociate");
2932 CmdArgs.push_back("-freciprocal-math");
2935 // FP Exception Behavior is also set to strict
2936 assert(FPExceptionBehavior.equals("strict"));
2939 // The default is IEEE.
2940 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
2941 llvm::SmallString<64> DenormFlag;
2942 llvm::raw_svector_ostream ArgStr(DenormFlag);
2943 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
2944 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
2947 // Add f32 specific denormal mode flag if it's different.
2948 if (DenormalFP32Math != DenormalFPMath) {
2949 llvm::SmallString<64> DenormFlag;
2950 llvm::raw_svector_ostream ArgStr(DenormFlag);
2951 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
2952 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
2955 if (!FPContract.empty())
2956 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2958 if (!RoundingFPMath)
2959 CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
2961 if (RoundingFPMath && RoundingMathPresent)
2962 CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
2964 if (!FPExceptionBehavior.empty())
2965 CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
2966 FPExceptionBehavior));
2968 ParseMRecip(D, Args, CmdArgs);
2970 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2971 // individual features enabled by -ffast-math instead of the option itself as
2972 // that's consistent with gcc's behaviour.
2973 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2974 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath) {
2975 CmdArgs.push_back("-ffast-math");
2976 if (FPModel.equals("fast")) {
2977 if (FPContract.equals("fast"))
2978 // All set, do nothing.
2980 else if (FPContract.empty())
2981 // Enable -ffp-contract=fast
2982 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
2984 D.Diag(clang::diag::warn_drv_overriding_flag_option)
2985 << "-ffp-model=fast"
2986 << Args.MakeArgString("-ffp-contract=" + FPContract);
2990 // Handle __FINITE_MATH_ONLY__ similarly.
2991 if (!HonorINFs && !HonorNaNs)
2992 CmdArgs.push_back("-ffinite-math-only");
2994 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2995 CmdArgs.push_back("-mfpmath");
2996 CmdArgs.push_back(A->getValue());
2999 // Disable a codegen optimization for floating-point casts.
3000 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3001 options::OPT_fstrict_float_cast_overflow, false))
3002 CmdArgs.push_back("-fno-strict-float-cast-overflow");
3005 static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3006 const llvm::Triple &Triple,
3007 const InputInfo &Input) {
3008 // Enable region store model by default.
3009 CmdArgs.push_back("-analyzer-store=region");
3011 // Treat blocks as analysis entry points.
3012 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
3014 // Add default argument set.
3015 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3016 CmdArgs.push_back("-analyzer-checker=core");
3017 CmdArgs.push_back("-analyzer-checker=apiModeling");
3019 if (!Triple.isWindowsMSVCEnvironment()) {
3020 CmdArgs.push_back("-analyzer-checker=unix");
3022 // Enable "unix" checkers that also work on Windows.
3023 CmdArgs.push_back("-analyzer-checker=unix.API");
3024 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3025 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3026 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3027 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3028 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3031 // Disable some unix checkers for PS4.
3032 if (Triple.isPS4CPU()) {
3033 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3034 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3037 if (Triple.isOSDarwin()) {
3038 CmdArgs.push_back("-analyzer-checker=osx");
3040 "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3042 else if (Triple.isOSFuchsia())
3043 CmdArgs.push_back("-analyzer-checker=fuchsia");
3045 CmdArgs.push_back("-analyzer-checker=deadcode");
3047 if (types::isCXX(Input.getType()))
3048 CmdArgs.push_back("-analyzer-checker=cplusplus");
3050 if (!Triple.isPS4CPU()) {
3051 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3052 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3053 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3054 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3055 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3056 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3059 // Default nullability checks.
3060 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3061 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3064 // Set the output format. The default is plist, for (lame) historical reasons.
3065 CmdArgs.push_back("-analyzer-output");
3066 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3067 CmdArgs.push_back(A->getValue());
3069 CmdArgs.push_back("plist");
3071 // Disable the presentation of standard compiler warnings when using
3072 // --analyze. We only want to show static analyzer diagnostics or frontend
3074 CmdArgs.push_back("-w");
3076 // Add -Xanalyzer arguments when running as analyzer.
3077 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3080 static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3081 const ArgList &Args, ArgStringList &CmdArgs,
3082 bool KernelOrKext) {
3083 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3085 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3086 // doesn't even have a stack!
3087 if (EffectiveTriple.isNVPTX())
3090 // -stack-protector=0 is default.
3091 LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3092 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3093 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3095 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3096 options::OPT_fstack_protector_all,
3097 options::OPT_fstack_protector_strong,
3098 options::OPT_fstack_protector)) {
3099 if (A->getOption().matches(options::OPT_fstack_protector))
3100 StackProtectorLevel =
3101 std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3102 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3103 StackProtectorLevel = LangOptions::SSPStrong;
3104 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3105 StackProtectorLevel = LangOptions::SSPReq;
3107 StackProtectorLevel = DefaultStackProtectorLevel;
3110 if (StackProtectorLevel) {
3111 CmdArgs.push_back("-stack-protector");
3112 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3115 // --param ssp-buffer-size=
3116 for (const Arg *A : Args.filtered(options::OPT__param)) {
3117 StringRef Str(A->getValue());
3118 if (Str.startswith("ssp-buffer-size=")) {
3119 if (StackProtectorLevel) {
3120 CmdArgs.push_back("-stack-protector-buffer-size");
3121 // FIXME: Verify the argument is a valid integer.
3122 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3128 const std::string &TripleStr = EffectiveTriple.getTriple();
3129 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3130 StringRef Value = A->getValue();
3131 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
3132 D.Diag(diag::err_drv_unsupported_opt_for_target)
3133 << A->getAsString(Args) << TripleStr;
3134 if (EffectiveTriple.isX86() && Value != "tls" && Value != "global") {
3135 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3136 << A->getOption().getName() << Value << "tls global";
3139 if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3140 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3141 << A->getOption().getName() << Value << "sysreg global";
3144 A->render(Args, CmdArgs);
3147 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3148 StringRef Value = A->getValue();
3149 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
3150 D.Diag(diag::err_drv_unsupported_opt_for_target)
3151 << A->getAsString(Args) << TripleStr;
3153 if (Value.getAsInteger(10, Offset)) {
3154 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3157 A->render(Args, CmdArgs);
3160 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3161 StringRef Value = A->getValue();
3162 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64())
3163 D.Diag(diag::err_drv_unsupported_opt_for_target)
3164 << A->getAsString(Args) << TripleStr;
3165 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3166 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3167 << A->getOption().getName() << Value << "fs gs";
3170 if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3171 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3174 A->render(Args, CmdArgs);
3178 static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3179 ArgStringList &CmdArgs) {
3180 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3182 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux())
3185 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3186 !EffectiveTriple.isPPC64())
3189 if (Args.hasFlag(options::OPT_fstack_clash_protection,
3190 options::OPT_fno_stack_clash_protection, false))
3191 CmdArgs.push_back("-fstack-clash-protection");
3194 static void RenderTrivialAutoVarInitOptions(const Driver &D,
3195 const ToolChain &TC,
3196 const ArgList &Args,
3197 ArgStringList &CmdArgs) {
3198 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3199 StringRef TrivialAutoVarInit = "";
3201 for (const Arg *A : Args) {
3202 switch (A->getOption().getID()) {
3205 case options::OPT_ftrivial_auto_var_init: {
3207 StringRef Val = A->getValue();
3208 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3209 TrivialAutoVarInit = Val;
3211 D.Diag(diag::err_drv_unsupported_option_argument)
3212 << A->getOption().getName() << Val;
3218 if (TrivialAutoVarInit.empty())
3219 switch (DefaultTrivialAutoVarInit) {
3220 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3222 case LangOptions::TrivialAutoVarInitKind::Pattern:
3223 TrivialAutoVarInit = "pattern";
3225 case LangOptions::TrivialAutoVarInitKind::Zero:
3226 TrivialAutoVarInit = "zero";
3230 if (!TrivialAutoVarInit.empty()) {
3231 if (TrivialAutoVarInit == "zero" && !Args.hasArg(options::OPT_enable_trivial_var_init_zero))
3232 D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled);
3234 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3238 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3239 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3241 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3243 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3245 StringRef Val = A->getValue();
3246 if (std::stoi(Val.str()) <= 0)
3247 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3249 Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3253 static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3254 types::ID InputType) {
3255 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3256 // for denormal flushing handling based on the target.
3257 const unsigned ForwardedArguments[] = {
3258 options::OPT_cl_opt_disable,
3259 options::OPT_cl_strict_aliasing,
3260 options::OPT_cl_single_precision_constant,
3261 options::OPT_cl_finite_math_only,
3262 options::OPT_cl_kernel_arg_info,
3263 options::OPT_cl_unsafe_math_optimizations,
3264 options::OPT_cl_fast_relaxed_math,
3265 options::OPT_cl_mad_enable,
3266 options::OPT_cl_no_signed_zeros,
3267 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3268 options::OPT_cl_uniform_work_group_size
3271 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3272 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3273 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3276 for (const auto &Arg : ForwardedArguments)
3277 if (const auto *A = Args.getLastArg(Arg))
3278 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3280 // Only add the default headers if we are compiling OpenCL sources.
3281 if ((types::isOpenCL(InputType) ||
3282 (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3283 !Args.hasArg(options::OPT_cl_no_stdinc)) {
3284 CmdArgs.push_back("-finclude-default-header");
3285 CmdArgs.push_back("-fdeclare-opencl-builtins");
3289 static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
3290 ArgStringList &CmdArgs) {
3291 bool ARCMTEnabled = false;
3292 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3293 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3294 options::OPT_ccc_arcmt_modify,
3295 options::OPT_ccc_arcmt_migrate)) {
3296 ARCMTEnabled = true;
3297 switch (A->getOption().getID()) {
3298 default: llvm_unreachable("missed a case");
3299 case options::OPT_ccc_arcmt_check:
3300 CmdArgs.push_back("-arcmt-action=check");
3302 case options::OPT_ccc_arcmt_modify:
3303 CmdArgs.push_back("-arcmt-action=modify");
3305 case options::OPT_ccc_arcmt_migrate:
3306 CmdArgs.push_back("-arcmt-action=migrate");
3307 CmdArgs.push_back("-mt-migrate-directory");
3308 CmdArgs.push_back(A->getValue());
3310 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3311 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3316 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3317 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3318 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3321 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3323 D.Diag(diag::err_drv_argument_not_allowed_with)
3324 << A->getAsString(Args) << "-ccc-arcmt-migrate";
3326 CmdArgs.push_back("-mt-migrate-directory");
3327 CmdArgs.push_back(A->getValue());
3329 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3330 options::OPT_objcmt_migrate_subscripting,
3331 options::OPT_objcmt_migrate_property)) {
3332 // None specified, means enable them all.
3333 CmdArgs.push_back("-objcmt-migrate-literals");
3334 CmdArgs.push_back("-objcmt-migrate-subscripting");
3335 CmdArgs.push_back("-objcmt-migrate-property");
3337 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3338 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3339 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3342 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3343 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3344 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3345 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3346 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3347 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3348 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3349 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3350 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3351 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3352 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3353 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3354 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3355 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3356 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3357 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
3361 static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3362 const ArgList &Args, ArgStringList &CmdArgs) {
3363 // -fbuiltin is default unless -mkernel is used.
3365 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3366 !Args.hasArg(options::OPT_mkernel));
3368 CmdArgs.push_back("-fno-builtin");
3370 // -ffreestanding implies -fno-builtin.
3371 if (Args.hasArg(options::OPT_ffreestanding))
3372 UseBuiltins = false;
3374 // Process the -fno-builtin-* options.
3375 for (const auto &Arg : Args) {
3376 const Option &O = Arg->getOption();
3377 if (!O.matches(options::OPT_fno_builtin_))
3382 // If -fno-builtin is specified, then there's no need to pass the option to
3387 StringRef FuncName = Arg->getValue();
3388 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
3391 // le32-specific flags:
3392 // -fno-math-builtin: clang should not convert math builtins to intrinsics
3394 if (TC.getArch() == llvm::Triple::le32)
3395 CmdArgs.push_back("-fno-math-builtin");
3398 bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
3399 if (llvm::sys::path::cache_directory(Result)) {
3400 llvm::sys::path::append(Result, "clang");
3401 llvm::sys::path::append(Result, "ModuleCache");
3407 static void RenderModulesOptions(Compilation &C, const Driver &D,
3408 const ArgList &Args, const InputInfo &Input,
3409 const InputInfo &Output,
3410 ArgStringList &CmdArgs, bool &HaveModules) {
3411 // -fmodules enables the use of precompiled modules (off by default).
3412 // Users can pass -fno-cxx-modules to turn off modules support for
3413 // C++/Objective-C++ programs.
3414 bool HaveClangModules = false;
3415 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3416 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3417 options::OPT_fno_cxx_modules, true);
3418 if (AllowedInCXX || !types::isCXX(Input.getType())) {
3419 CmdArgs.push_back("-fmodules");
3420 HaveClangModules = true;
3424 HaveModules |= HaveClangModules;
3425 if (Args.hasArg(options::OPT_fmodules_ts)) {
3426 CmdArgs.push_back("-fmodules-ts");
3430 // -fmodule-maps enables implicit reading of module map files. By default,
3431 // this is enabled if we are using Clang's flavor of precompiled modules.
3432 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3433 options::OPT_fno_implicit_module_maps, HaveClangModules))
3434 CmdArgs.push_back("-fimplicit-module-maps");
3436 // -fmodules-decluse checks that modules used are declared so (off by default)
3437 if (Args.hasFlag(options::OPT_fmodules_decluse,
3438 options::OPT_fno_modules_decluse, false))
3439 CmdArgs.push_back("-fmodules-decluse");
3441 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3442 // all #included headers are part of modules.
3443 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3444 options::OPT_fno_modules_strict_decluse, false))
3445 CmdArgs.push_back("-fmodules-strict-decluse");
3447 // -fno-implicit-modules turns off implicitly compiling modules on demand.
3448 bool ImplicitModules = false;
3449 if (!Args.hasFlag(options::OPT_fimplicit_modules,
3450 options::OPT_fno_implicit_modules, HaveClangModules)) {
3452 CmdArgs.push_back("-fno-implicit-modules");
3453 } else if (HaveModules) {
3454 ImplicitModules = true;
3455 // -fmodule-cache-path specifies where our implicitly-built module files
3456 // should be written.
3457 SmallString<128> Path;
3458 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3459 Path = A->getValue();
3461 bool HasPath = true;
3462 if (C.isForDiagnostics()) {
3463 // When generating crash reports, we want to emit the modules along with
3464 // the reproduction sources, so we ignore any provided module path.
3465 Path = Output.getFilename();
3466 llvm::sys::path::replace_extension(Path, ".cache");
3467 llvm::sys::path::append(Path, "modules");
3468 } else if (Path.empty()) {
3469 // No module path was provided: use the default.
3470 HasPath = Driver::getDefaultModuleCachePath(Path);
3473 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3474 // That being said, that failure is unlikely and not caching is harmless.
3476 const char Arg[] = "-fmodules-cache-path=";
3477 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3478 CmdArgs.push_back(Args.MakeArgString(Path));
3483 // -fprebuilt-module-path specifies where to load the prebuilt module files.
3484 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
3485 CmdArgs.push_back(Args.MakeArgString(
3486 std::string("-fprebuilt-module-path=") + A->getValue()));
3489 if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
3490 options::OPT_fno_prebuilt_implicit_modules, false))
3491 CmdArgs.push_back("-fprebuilt-implicit-modules");
3492 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
3493 options::OPT_fno_modules_validate_input_files_content,
3495 CmdArgs.push_back("-fvalidate-ast-input-files-content");
3498 // -fmodule-name specifies the module that is currently being built (or
3499 // used for header checking by -fmodule-maps).
3500 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3502 // -fmodule-map-file can be used to specify files containing module
3504 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3506 // -fbuiltin-module-map can be used to load the clang
3507 // builtin headers modulemap file.
3508 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
3509 SmallString<128> BuiltinModuleMap(D.ResourceDir);
3510 llvm::sys::path::append(BuiltinModuleMap, "include");
3511 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
3512 if (llvm::sys::fs::exists(BuiltinModuleMap))
3514 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
3517 // The -fmodule-file=<name>=<file> form specifies the mapping of module
3518 // names to precompiled module files (the module is loaded only if used).
3519 // The -fmodule-file=<file> form can be used to unconditionally load
3520 // precompiled module files (whether used or not).
3522 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
3524 Args.ClaimAllArgs(options::OPT_fmodule_file);
3526 // When building modules and generating crashdumps, we need to dump a module
3527 // dependency VFS alongside the output.
3528 if (HaveClangModules && C.isForDiagnostics()) {
3529 SmallString<128> VFSDir(Output.getFilename());
3530 llvm::sys::path::replace_extension(VFSDir, ".cache");
3531 // Add the cache directory as a temp so the crash diagnostics pick it up.
3532 C.addTempFile(Args.MakeArgString(VFSDir));
3534 llvm::sys::path::append(VFSDir, "vfs");
3535 CmdArgs.push_back("-module-dependency-dir");
3536 CmdArgs.push_back(Args.MakeArgString(VFSDir));
3539 if (HaveClangModules)
3540 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
3542 // Pass through all -fmodules-ignore-macro arguments.
3543 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3544 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3545 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3547 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3549 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
3550 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
3551 D.Diag(diag::err_drv_argument_not_allowed_with)
3552 << A->getAsString(Args) << "-fbuild-session-timestamp";
3554 llvm::sys::fs::file_status Status;
3555 if (llvm::sys::fs::status(A->getValue(), Status))
3556 D.Diag(diag::err_drv_no_such_file) << A->getValue();
3558 Args.MakeArgString("-fbuild-session-timestamp=" +
3559 Twine((uint64_t)Status.getLastModificationTime()
3564 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
3565 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
3566 options::OPT_fbuild_session_file))
3567 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
3569 Args.AddLastArg(CmdArgs,
3570 options::OPT_fmodules_validate_once_per_build_session);
3573 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
3574 options::OPT_fno_modules_validate_system_headers,
3576 CmdArgs.push_back("-fmodules-validate-system-headers");
3578 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
3581 static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
3582 ArgStringList &CmdArgs) {
3583 // -fsigned-char is default.
3584 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
3585 options::OPT_fno_signed_char,
3586 options::OPT_funsigned_char,
3587 options::OPT_fno_unsigned_char)) {
3588 if (A->getOption().matches(options::OPT_funsigned_char) ||
3589 A->getOption().matches(options::OPT_fno_signed_char)) {
3590 CmdArgs.push_back("-fno-signed-char");
3592 } else if (!isSignedCharDefault(T)) {
3593 CmdArgs.push_back("-fno-signed-char");
3596 // The default depends on the language standard.
3597 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
3599 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
3600 options::OPT_fno_short_wchar)) {
3601 if (A->getOption().matches(options::OPT_fshort_wchar)) {
3602 CmdArgs.push_back("-fwchar-type=short");
3603 CmdArgs.push_back("-fno-signed-wchar");
3605 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
3606 CmdArgs.push_back("-fwchar-type=int");
3608 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
3609 CmdArgs.push_back("-fno-signed-wchar");
3611 CmdArgs.push_back("-fsigned-wchar");
3616 static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
3617 const llvm::Triple &T, const ArgList &Args,
3618 ObjCRuntime &Runtime, bool InferCovariantReturns,
3619 const InputInfo &Input, ArgStringList &CmdArgs) {
3620 const llvm::Triple::ArchType Arch = TC.getArch();
3622 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
3623 // is the default. Except for deployment target of 10.5, next runtime is
3624 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
3625 if (Runtime.isNonFragile()) {
3626 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3627 options::OPT_fno_objc_legacy_dispatch,
3628 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
3629 if (TC.UseObjCMixedDispatch())
3630 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3632 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3636 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
3637 // to do Array/Dictionary subscripting by default.
3638 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
3639 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
3640 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3642 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3643 // NOTE: This logic is duplicated in ToolChains.cpp.
3644 if (isObjCAutoRefCount(Args)) {
3647 CmdArgs.push_back("-fobjc-arc");
3649 // FIXME: It seems like this entire block, and several around it should be
3650 // wrapped in isObjC, but for now we just use it here as this is where it
3651 // was being used previously.
3652 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
3653 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3654 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3656 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3659 // Allow the user to enable full exceptions code emission.
3660 // We default off for Objective-C, on for Objective-C++.
3661 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
3662 options::OPT_fno_objc_arc_exceptions,
3663 /*Default=*/types::isCXX(Input.getType())))
3664 CmdArgs.push_back("-fobjc-arc-exceptions");
3667 // Silence warning for full exception code emission options when explicitly
3668 // set to use no ARC.
3669 if (Args.hasArg(options::OPT_fno_objc_arc)) {
3670 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
3671 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
3674 // Allow the user to control whether messages can be converted to runtime
3676 if (types::isObjC(Input.getType())) {
3677 auto *Arg = Args.getLastArg(
3678 options::OPT_fobjc_convert_messages_to_runtime_calls,
3679 options::OPT_fno_objc_convert_messages_to_runtime_calls);
3681 Arg->getOption().matches(
3682 options::OPT_fno_objc_convert_messages_to_runtime_calls))
3683 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
3686 // -fobjc-infer-related-result-type is the default, except in the Objective-C
3688 if (InferCovariantReturns)
3689 CmdArgs.push_back("-fno-objc-infer-related-result-type");
3691 // Pass down -fobjc-weak or -fno-objc-weak if present.
3692 if (types::isObjC(Input.getType())) {
3694 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
3697 } else if (!Runtime.allowsWeak()) {
3698 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
3699 D.Diag(diag::err_objc_weak_unsupported);
3701 WeakArg->render(Args, CmdArgs);
3705 if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
3706 CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
3709 static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
3710 ArgStringList &CmdArgs) {
3711 bool CaretDefault = true;
3712 bool ColumnDefault = true;
3714 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
3715 options::OPT__SLASH_diagnostics_column,
3716 options::OPT__SLASH_diagnostics_caret)) {
3717 switch (A->getOption().getID()) {
3718 case options::OPT__SLASH_diagnostics_caret:
3719 CaretDefault = true;
3720 ColumnDefault = true;
3722 case options::OPT__SLASH_diagnostics_column:
3723 CaretDefault = false;
3724 ColumnDefault = true;
3726 case options::OPT__SLASH_diagnostics_classic:
3727 CaretDefault = false;
3728 ColumnDefault = false;
3733 // -fcaret-diagnostics is default.
3734 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3735 options::OPT_fno_caret_diagnostics, CaretDefault))
3736 CmdArgs.push_back("-fno-caret-diagnostics");
3738 // -fdiagnostics-fixit-info is default, only pass non-default.
3739 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
3740 options::OPT_fno_diagnostics_fixit_info))
3741 CmdArgs.push_back("-fno-diagnostics-fixit-info");
3743 // Enable -fdiagnostics-show-option by default.
3744 if (!Args.hasFlag(options::OPT_fdiagnostics_show_option,
3745 options::OPT_fno_diagnostics_show_option, true))
3746 CmdArgs.push_back("-fno-diagnostics-show-option");
3749 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3750 CmdArgs.push_back("-fdiagnostics-show-category");
3751 CmdArgs.push_back(A->getValue());
3754 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
3755 options::OPT_fno_diagnostics_show_hotness, false))
3756 CmdArgs.push_back("-fdiagnostics-show-hotness");
3759 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
3761 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
3762 CmdArgs.push_back(Args.MakeArgString(Opt));
3765 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3766 CmdArgs.push_back("-fdiagnostics-format");
3767 CmdArgs.push_back(A->getValue());
3770 if (const Arg *A = Args.getLastArg(
3771 options::OPT_fdiagnostics_show_note_include_stack,
3772 options::OPT_fno_diagnostics_show_note_include_stack)) {
3773 const Option &O = A->getOption();
3774 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
3775 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3777 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3780 // Color diagnostics are parsed by the driver directly from argv and later
3781 // re-parsed to construct this job; claim any possible color diagnostic here
3782 // to avoid warn_drv_unused_argument and diagnose bad
3783 // OPT_fdiagnostics_color_EQ values.
3784 for (const Arg *A : Args) {
3785 const Option &O = A->getOption();
3786 if (!O.matches(options::OPT_fcolor_diagnostics) &&
3787 !O.matches(options::OPT_fdiagnostics_color) &&
3788 !O.matches(options::OPT_fno_color_diagnostics) &&
3789 !O.matches(options::OPT_fno_diagnostics_color) &&
3790 !O.matches(options::OPT_fdiagnostics_color_EQ))
3793 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
3794 StringRef Value(A->getValue());
3795 if (Value != "always" && Value != "never" && Value != "auto")
3796 D.Diag(diag::err_drv_clang_unsupported)
3797 << ("-fdiagnostics-color=" + Value).str();
3802 if (D.getDiags().getDiagnosticOptions().ShowColors)
3803 CmdArgs.push_back("-fcolor-diagnostics");
3805 if (Args.hasArg(options::OPT_fansi_escape_codes))
3806 CmdArgs.push_back("-fansi-escape-codes");
3808 if (!Args.hasFlag(options::OPT_fshow_source_location,
3809 options::OPT_fno_show_source_location))
3810 CmdArgs.push_back("-fno-show-source-location");
3812 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
3813 CmdArgs.push_back("-fdiagnostics-absolute-paths");
3815 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
3817 CmdArgs.push_back("-fno-show-column");
3819 if (!Args.hasFlag(options::OPT_fspell_checking,
3820 options::OPT_fno_spell_checking))
3821 CmdArgs.push_back("-fno-spell-checking");
3824 enum class DwarfFissionKind { None, Split, Single };
3826 static DwarfFissionKind getDebugFissionKind(const Driver &D,
3827 const ArgList &Args, Arg *&Arg) {
3828 Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
3829 options::OPT_gno_split_dwarf);
3830 if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf))
3831 return DwarfFissionKind::None;
3833 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
3834 return DwarfFissionKind::Split;
3836 StringRef Value = Arg->getValue();
3837 if (Value == "split")
3838 return DwarfFissionKind::Split;
3839 if (Value == "single")
3840 return DwarfFissionKind::Single;
3842 D.Diag(diag::err_drv_unsupported_option_argument)
3843 << Arg->getOption().getName() << Arg->getValue();
3844 return DwarfFissionKind::None;
3847 static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
3848 const ArgList &Args, ArgStringList &CmdArgs,
3849 unsigned DwarfVersion) {
3850 auto *DwarfFormatArg =
3851 Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
3852 if (!DwarfFormatArg)
3855 if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
3856 if (DwarfVersion < 3)
3857 D.Diag(diag::err_drv_argument_only_allowed_with)
3858 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
3859 else if (!T.isArch64Bit())
3860 D.Diag(diag::err_drv_argument_only_allowed_with)
3861 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
3862 else if (!T.isOSBinFormatELF())
3863 D.Diag(diag::err_drv_argument_only_allowed_with)
3864 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
3867 DwarfFormatArg->render(Args, CmdArgs);
3870 static void renderDebugOptions(const ToolChain &TC, const Driver &D,
3871 const llvm::Triple &T, const ArgList &Args,
3872 bool EmitCodeView, bool IRInput,
3873 ArgStringList &CmdArgs,
3874 codegenoptions::DebugInfoKind &DebugInfoKind,
3875 DwarfFissionKind &DwarfFission) {
3876 // These two forms of profiling info can't be used together.
3877 if (const Arg *A1 = Args.getLastArg(options::OPT_fpseudo_probe_for_profiling))
3878 if (const Arg *A2 = Args.getLastArg(options::OPT_fdebug_info_for_profiling))
3879 D.Diag(diag::err_drv_argument_not_allowed_with)
3880 << A1->getAsString(Args) << A2->getAsString(Args);
3882 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
3883 options::OPT_fno_debug_info_for_profiling, false) &&
3884 checkDebugInfoOption(
3885 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
3886 CmdArgs.push_back("-fdebug-info-for-profiling");
3888 // The 'g' groups options involve a somewhat intricate sequence of decisions
3889 // about what to pass from the driver to the frontend, but by the time they
3890 // reach cc1 they've been factored into three well-defined orthogonal choices:
3891 // * what level of debug info to generate
3892 // * what dwarf version to write
3893 // * what debugger tuning to use
3894 // This avoids having to monkey around further in cc1 other than to disable
3895 // codeview if not running in a Windows environment. Perhaps even that
3896 // decision should be made in the driver as well though.
3897 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
3899 bool SplitDWARFInlining =
3900 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
3901 options::OPT_fno_split_dwarf_inlining, false);
3903 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
3904 // object file generation and no IR generation, -gN should not be needed. So
3905 // allow -gsplit-dwarf with either -gN or IR input.
3906 if (IRInput || Args.hasArg(options::OPT_g_Group)) {
3908 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
3909 if (DwarfFission != DwarfFissionKind::None &&
3910 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
3911 DwarfFission = DwarfFissionKind::None;
3912 SplitDWARFInlining = false;
3915 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
3916 DebugInfoKind = codegenoptions::DebugInfoConstructor;
3918 // If the last option explicitly specified a debug-info level, use it.
3919 if (checkDebugInfoOption(A, Args, D, TC) &&
3920 A->getOption().matches(options::OPT_gN_Group)) {
3921 DebugInfoKind = DebugLevelToInfoKind(*A);
3922 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
3923 // complicated if you've disabled inline info in the skeleton CUs
3924 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
3925 // line-tables-only, so let those compose naturally in that case.
3926 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
3927 DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
3928 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
3929 SplitDWARFInlining))
3930 DwarfFission = DwarfFissionKind::None;
3934 // If a debugger tuning argument appeared, remember it.
3936 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
3937 if (checkDebugInfoOption(A, Args, D, TC)) {
3938 if (A->getOption().matches(options::OPT_glldb))
3939 DebuggerTuning = llvm::DebuggerKind::LLDB;
3940 else if (A->getOption().matches(options::OPT_gsce))
3941 DebuggerTuning = llvm::DebuggerKind::SCE;
3942 else if (A->getOption().matches(options::OPT_gdbx))
3943 DebuggerTuning = llvm::DebuggerKind::DBX;
3945 DebuggerTuning = llvm::DebuggerKind::GDB;
3949 // If a -gdwarf argument appeared, remember it.
3950 const Arg *GDwarfN = getDwarfNArg(Args);
3951 bool EmitDwarf = false;
3953 if (checkDebugInfoOption(GDwarfN, Args, D, TC))
3959 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
3960 if (checkDebugInfoOption(A, Args, D, TC))
3961 EmitCodeView = true;
3964 // If the user asked for debug info but did not explicitly specify -gcodeview
3965 // or -gdwarf, ask the toolchain for the default format.
3966 if (!EmitCodeView && !EmitDwarf &&
3967 DebugInfoKind != codegenoptions::NoDebugInfo) {
3968 switch (TC.getDefaultDebugFormat()) {
3969 case codegenoptions::DIF_CodeView:
3970 EmitCodeView = true;
3972 case codegenoptions::DIF_DWARF:
3978 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
3979 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
3980 // be lower than what the user wanted.
3981 unsigned DefaultDWARFVersion = ParseDebugDefaultVersion(TC, Args);
3983 // Start with the platform default DWARF version
3984 RequestedDWARFVersion = TC.GetDefaultDwarfVersion();
3985 assert(RequestedDWARFVersion &&
3986 "toolchain default DWARF version must be nonzero");
3988 // If the user specified a default DWARF version, that takes precedence
3989 // over the platform default.
3990 if (DefaultDWARFVersion)
3991 RequestedDWARFVersion = DefaultDWARFVersion;
3993 // Override with a user-specified DWARF version
3995 if (auto ExplicitVersion = DwarfVersionNum(GDwarfN->getSpelling()))
3996 RequestedDWARFVersion = ExplicitVersion;
3997 // Clamp effective DWARF version to the max supported by the toolchain.
3998 EffectiveDWARFVersion =
3999 std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4002 // -gline-directives-only supported only for the DWARF debug info.
4003 if (RequestedDWARFVersion == 0 &&
4004 DebugInfoKind == codegenoptions::DebugDirectivesOnly)
4005 DebugInfoKind = codegenoptions::NoDebugInfo;
4007 // strict DWARF is set to false by default. But for DBX, we need it to be set
4008 // as true by default.
4009 if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4010 (void)checkDebugInfoOption(A, Args, D, TC);
4011 if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4012 DebuggerTuning == llvm::DebuggerKind::DBX))
4013 CmdArgs.push_back("-gstrict-dwarf");
4015 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4016 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4018 // Column info is included by default for everything except SCE and
4019 // CodeView. Clang doesn't track end columns, just starting columns, which,
4020 // in theory, is fine for CodeView (and PDB). In practice, however, the
4021 // Microsoft debuggers don't handle missing end columns well, and the AIX
4022 // debugger DBX also doesn't handle the columns well, so it's better not to
4023 // include any column info.
4024 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4025 (void)checkDebugInfoOption(A, Args, D, TC);
4026 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4028 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4029 DebuggerTuning != llvm::DebuggerKind::DBX)))
4030 CmdArgs.push_back("-gno-column-info");
4032 // FIXME: Move backend command line options to the module.
4033 // If -gline-tables-only or -gline-directives-only is the last option it wins.
4034 if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
4035 if (checkDebugInfoOption(A, Args, D, TC)) {
4036 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
4037 DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
4038 DebugInfoKind = codegenoptions::DebugInfoConstructor;
4039 CmdArgs.push_back("-dwarf-ext-refs");
4040 CmdArgs.push_back("-fmodule-format=obj");
4044 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4045 CmdArgs.push_back("-fsplit-dwarf-inlining");
4047 // After we've dealt with all combinations of things that could
4048 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4049 // figure out if we need to "upgrade" it to standalone debug info.
4050 // We parse these two '-f' options whether or not they will be used,
4051 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4052 bool NeedFullDebug = Args.hasFlag(
4053 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4054 DebuggerTuning == llvm::DebuggerKind::LLDB ||
4055 TC.GetDefaultStandaloneDebug());
4056 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4057 (void)checkDebugInfoOption(A, Args, D, TC);
4059 if (DebugInfoKind == codegenoptions::LimitedDebugInfo ||
4060 DebugInfoKind == codegenoptions::DebugInfoConstructor) {
4061 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4062 options::OPT_feliminate_unused_debug_types, false))
4063 DebugInfoKind = codegenoptions::UnusedTypeInfo;
4064 else if (NeedFullDebug)
4065 DebugInfoKind = codegenoptions::FullDebugInfo;
4068 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4070 // Source embedding is a vendor extension to DWARF v5. By now we have
4071 // checked if a DWARF version was stated explicitly, and have otherwise
4072 // fallen back to the target default, so if this is still not at least 5
4073 // we emit an error.
4074 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4075 if (RequestedDWARFVersion < 5)
4076 D.Diag(diag::err_drv_argument_only_allowed_with)
4077 << A->getAsString(Args) << "-gdwarf-5";
4078 else if (EffectiveDWARFVersion < 5)
4079 // The toolchain has reduced allowed dwarf version, so we can't enable
4081 D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4082 << A->getAsString(Args) << TC.getTripleString() << 5
4083 << EffectiveDWARFVersion;
4084 else if (checkDebugInfoOption(A, Args, D, TC))
4085 CmdArgs.push_back("-gembed-source");
4089 CmdArgs.push_back("-gcodeview");
4091 // Emit codeview type hashes if requested.
4092 if (Args.hasFlag(options::OPT_gcodeview_ghash,
4093 options::OPT_gno_codeview_ghash, false)) {
4094 CmdArgs.push_back("-gcodeview-ghash");
4098 // Omit inline line tables if requested.
4099 if (Args.hasFlag(options::OPT_gno_inline_line_tables,
4100 options::OPT_ginline_line_tables, false)) {
4101 CmdArgs.push_back("-gno-inline-line-tables");
4104 // When emitting remarks, we need at least debug lines in the output.
4105 if (willEmitRemarks(Args) &&
4106 DebugInfoKind <= codegenoptions::DebugDirectivesOnly)
4107 DebugInfoKind = codegenoptions::DebugLineTablesOnly;
4109 // Adjust the debug info kind for the given toolchain.
4110 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4112 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4115 // -fdebug-macro turns on macro debug info generation.
4116 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4118 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4120 CmdArgs.push_back("-debug-info-macro");
4122 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4123 const auto *PubnamesArg =
4124 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4125 options::OPT_gpubnames, options::OPT_gno_pubnames);
4126 if (DwarfFission != DwarfFissionKind::None ||
4127 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
4129 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4130 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
4131 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4132 options::OPT_gpubnames)
4134 : "-ggnu-pubnames");
4136 if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
4137 options::OPT_fno_debug_ranges_base_address, false)) {
4138 CmdArgs.push_back("-fdebug-ranges-base-address");
4141 // -gdwarf-aranges turns on the emission of the aranges section in the
4143 // Always enabled for SCE tuning.
4144 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
4145 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
4146 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
4148 CmdArgs.push_back("-mllvm");
4149 CmdArgs.push_back("-generate-arange-section");
4152 if (Args.hasFlag(options::OPT_fforce_dwarf_frame,
4153 options::OPT_fno_force_dwarf_frame, false))
4154 CmdArgs.push_back("-fforce-dwarf-frame");
4156 if (Args.hasFlag(options::OPT_fdebug_types_section,
4157 options::OPT_fno_debug_types_section, false)) {
4158 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4159 D.Diag(diag::err_drv_unsupported_opt_for_target)
4160 << Args.getLastArg(options::OPT_fdebug_types_section)
4163 } else if (checkDebugInfoOption(
4164 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4166 CmdArgs.push_back("-mllvm");
4167 CmdArgs.push_back("-generate-type-units");
4171 // To avoid join/split of directory+filename, the integrated assembler prefers
4172 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4173 // form before DWARF v5.
4174 if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4175 options::OPT_fno_dwarf_directory_asm,
4176 TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4177 CmdArgs.push_back("-fno-dwarf-directory-asm");
4179 // Decide how to render forward declarations of template instantiations.
4180 // SCE wants full descriptions, others just get them in the name.
4181 if (DebuggerTuning == llvm::DebuggerKind::SCE)
4182 CmdArgs.push_back("-debug-forward-template-params");
4184 // Do we need to explicitly import anonymous namespaces into the parent
4186 if (DebuggerTuning == llvm::DebuggerKind::SCE)
4187 CmdArgs.push_back("-dwarf-explicit-import");
4189 renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
4190 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4193 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
4194 const InputInfo &Output, const InputInfoList &Inputs,
4195 const ArgList &Args, const char *LinkingOutput) const {
4196 const auto &TC = getToolChain();
4197 const llvm::Triple &RawTriple = TC.getTriple();
4198 const llvm::Triple &Triple = TC.getEffectiveTriple();
4199 const std::string &TripleStr = Triple.getTriple();
4202 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
4203 const Driver &D = TC.getDriver();
4204 ArgStringList CmdArgs;
4206 // Check number of inputs for sanity. We need at least one input.
4207 assert(Inputs.size() >= 1 && "Must have at least one input.");
4208 // CUDA/HIP compilation may have multiple inputs (source file + results of
4209 // device-side compilations). OpenMP device jobs also take the host IR as a
4210 // second input. Module precompilation accepts a list of header files to
4211 // include as part of the module. All other jobs are expected to have exactly
4213 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
4214 bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
4215 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
4216 bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
4217 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
4218 bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
4219 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
4220 JA.isDeviceOffloading(Action::OFK_Host));
4221 bool IsUsingLTO = D.isUsingLTO(IsDeviceOffloadAction);
4222 auto LTOMode = D.getLTOMode(IsDeviceOffloadAction);
4224 // A header module compilation doesn't have a main input file, so invent a
4225 // fake one as a placeholder.
4226 const char *ModuleName = [&]{
4227 auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
4228 return ModuleNameArg ? ModuleNameArg->getValue() : "";
4230 InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
4232 const InputInfo &Input =
4233 IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
4235 InputInfoList ModuleHeaderInputs;
4236 const InputInfo *CudaDeviceInput = nullptr;
4237 const InputInfo *OpenMPDeviceInput = nullptr;
4238 for (const InputInfo &I : Inputs) {
4240 // This is the primary input.
4241 } else if (IsHeaderModulePrecompile &&
4242 types::getPrecompiledType(I.getType()) == types::TY_PCH) {
4243 types::ID Expected = HeaderModuleInput.getType();
4244 if (I.getType() != Expected) {
4245 D.Diag(diag::err_drv_module_header_wrong_kind)
4246 << I.getFilename() << types::getTypeName(I.getType())
4247 << types::getTypeName(Expected);
4249 ModuleHeaderInputs.push_back(I);
4250 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
4251 CudaDeviceInput = &I;
4252 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
4253 OpenMPDeviceInput = &I;
4255 llvm_unreachable("unexpectedly given multiple inputs");
4259 const llvm::Triple *AuxTriple =
4260 (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
4261 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
4262 bool IsIAMCU = RawTriple.isOSIAMCU();
4264 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
4265 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
4266 // Windows), we need to pass Windows-specific flags to cc1.
4267 if (IsCuda || IsHIP)
4268 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
4270 // C++ is not supported for IAMCU.
4271 if (IsIAMCU && types::isCXX(Input.getType()))
4272 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
4274 // Invoke ourselves in -cc1 mode.
4276 // FIXME: Implement custom jobs for internal actions.
4277 CmdArgs.push_back("-cc1");
4279 // Add the "effective" target triple.
4280 CmdArgs.push_back("-triple");
4281 CmdArgs.push_back(Args.MakeArgString(TripleStr));
4283 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
4284 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
4285 Args.ClaimAllArgs(options::OPT_MJ);
4286 } else if (const Arg *GenCDBFragment =
4287 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
4288 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
4289 TripleStr, Output, Input, Args);
4290 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
4293 if (IsCuda || IsHIP) {
4294 // We have to pass the triple of the host if compiling for a CUDA/HIP device
4296 std::string NormalizedTriple;
4297 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
4298 JA.isDeviceOffloading(Action::OFK_HIP))
4299 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
4303 // Host-side compilation.
4305 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
4306 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
4310 // We need to figure out which CUDA version we're compiling for, as that
4311 // determines how we load and launch GPU kernels.
4312 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
4313 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
4314 assert(CTC && "Expected valid CUDA Toolchain.");
4315 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
4316 CmdArgs.push_back(Args.MakeArgString(
4317 Twine("-target-sdk-version=") +
4318 CudaVersionToString(CTC->CudaInstallation.version())));
4321 CmdArgs.push_back("-aux-triple");
4322 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4325 if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) {
4326 CmdArgs.push_back("-fsycl-is-device");
4328 if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) {
4329 A->render(Args, CmdArgs);
4331 // Ensure the default version in SYCL mode is 2020.
4332 CmdArgs.push_back("-sycl-std=2020");
4336 if (IsOpenMPDevice) {
4337 // We have to pass the triple of the host if compiling for an OpenMP device.
4338 std::string NormalizedTriple =
4339 C.getSingleOffloadToolChain<Action::OFK_Host>()
4342 CmdArgs.push_back("-aux-triple");
4343 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4346 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
4347 Triple.getArch() == llvm::Triple::thumb)) {
4348 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
4349 unsigned Version = 0;
4351 Triple.getArchName().substr(Offset).consumeInteger(10, Version);
4352 if (Failure || Version < 7)
4353 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
4357 // Push all default warning arguments that are specific to
4358 // the given target. These come before user provided warning options
4360 TC.addClangWarningOptions(CmdArgs);
4362 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
4363 if (Triple.isSPIR())
4364 CmdArgs.push_back("-Wspir-compat");
4366 // Select the appropriate action.
4367 RewriteKind rewriteKind = RK_None;
4369 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
4370 // it claims when not running an assembler. Otherwise, clang would emit
4371 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
4372 // flags while debugging something. That'd be somewhat inconvenient, and it's
4373 // also inconsistent with most other flags -- we don't warn on
4374 // -ffunction-sections not being used in -E mode either for example, even
4375 // though it's not really used either.
4376 if (!isa<AssembleJobAction>(JA)) {
4377 // The args claimed here should match the args used in
4378 // CollectArgsForIntegratedAssembler().
4379 if (TC.useIntegratedAs()) {
4380 Args.ClaimAllArgs(options::OPT_mrelax_all);
4381 Args.ClaimAllArgs(options::OPT_mno_relax_all);
4382 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
4383 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
4384 switch (C.getDefaultToolChain().getArch()) {
4385 case llvm::Triple::arm:
4386 case llvm::Triple::armeb:
4387 case llvm::Triple::thumb:
4388 case llvm::Triple::thumbeb:
4389 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
4395 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
4396 Args.ClaimAllArgs(options::OPT_Xassembler);
4399 if (isa<AnalyzeJobAction>(JA)) {
4400 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
4401 CmdArgs.push_back("-analyze");
4402 } else if (isa<MigrateJobAction>(JA)) {
4403 CmdArgs.push_back("-migrate");
4404 } else if (isa<PreprocessJobAction>(JA)) {
4405 if (Output.getType() == types::TY_Dependencies)
4406 CmdArgs.push_back("-Eonly");
4408 CmdArgs.push_back("-E");
4409 if (Args.hasArg(options::OPT_rewrite_objc) &&
4410 !Args.hasArg(options::OPT_g_Group))
4411 CmdArgs.push_back("-P");
4413 } else if (isa<AssembleJobAction>(JA)) {
4414 CmdArgs.push_back("-emit-obj");
4416 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
4418 // Also ignore explicit -force_cpusubtype_ALL option.
4419 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
4420 } else if (isa<PrecompileJobAction>(JA)) {
4421 if (JA.getType() == types::TY_Nothing)
4422 CmdArgs.push_back("-fsyntax-only");
4423 else if (JA.getType() == types::TY_ModuleFile)
4424 CmdArgs.push_back(IsHeaderModulePrecompile
4425 ? "-emit-header-module"
4426 : "-emit-module-interface");
4428 CmdArgs.push_back("-emit-pch");
4429 } else if (isa<VerifyPCHJobAction>(JA)) {
4430 CmdArgs.push_back("-verify-pch");
4432 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
4433 "Invalid action for clang tool.");
4434 if (JA.getType() == types::TY_Nothing) {
4435 CmdArgs.push_back("-fsyntax-only");
4436 } else if (JA.getType() == types::TY_LLVM_IR ||
4437 JA.getType() == types::TY_LTO_IR) {
4438 CmdArgs.push_back("-emit-llvm");
4439 } else if (JA.getType() == types::TY_LLVM_BC ||
4440 JA.getType() == types::TY_LTO_BC) {
4441 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
4442 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
4443 Args.hasArg(options::OPT_emit_llvm)) {
4444 CmdArgs.push_back("-emit-llvm");
4446 CmdArgs.push_back("-emit-llvm-bc");
4448 } else if (JA.getType() == types::TY_IFS ||
4449 JA.getType() == types::TY_IFS_CPP) {
4451 Args.hasArg(options::OPT_interface_stub_version_EQ)
4452 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
4454 CmdArgs.push_back("-emit-interface-stubs");
4456 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
4457 } else if (JA.getType() == types::TY_PP_Asm) {
4458 CmdArgs.push_back("-S");
4459 } else if (JA.getType() == types::TY_AST) {
4460 CmdArgs.push_back("-emit-pch");
4461 } else if (JA.getType() == types::TY_ModuleFile) {
4462 CmdArgs.push_back("-module-file-info");
4463 } else if (JA.getType() == types::TY_RewrittenObjC) {
4464 CmdArgs.push_back("-rewrite-objc");
4465 rewriteKind = RK_NonFragile;
4466 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
4467 CmdArgs.push_back("-rewrite-objc");
4468 rewriteKind = RK_Fragile;
4470 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
4473 // Preserve use-list order by default when emitting bitcode, so that
4474 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
4475 // same result as running passes here. For LTO, we don't need to preserve
4476 // the use-list order, since serialization to bitcode is part of the flow.
4477 if (JA.getType() == types::TY_LLVM_BC)
4478 CmdArgs.push_back("-emit-llvm-uselists");
4481 if (!IsDeviceOffloadAction) {
4482 if (Args.hasArg(options::OPT_flto))
4483 CmdArgs.push_back("-flto");
4485 if (D.getLTOMode() == LTOK_Thin)
4486 CmdArgs.push_back("-flto=thin");
4488 CmdArgs.push_back("-flto=full");
4490 CmdArgs.push_back("-flto-unit");
4491 } else if (Triple.isAMDGPU()) {
4492 // Only AMDGPU supports device-side LTO
4493 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
4494 CmdArgs.push_back(Args.MakeArgString(
4495 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
4496 CmdArgs.push_back("-flto-unit");
4498 D.Diag(diag::err_drv_unsupported_opt_for_target)
4499 << Args.getLastArg(options::OPT_foffload_lto,
4500 options::OPT_foffload_lto_EQ)
4502 << Triple.getTriple();
4507 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
4508 if (!types::isLLVMIR(Input.getType()))
4509 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
4510 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
4513 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
4514 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
4516 if (Args.getLastArg(options::OPT_save_temps_EQ))
4517 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
4519 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
4520 options::OPT_fmemory_profile_EQ,
4521 options::OPT_fno_memory_profile);
4523 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
4524 MemProfArg->render(Args, CmdArgs);
4526 // Embed-bitcode option.
4527 // Only white-listed flags below are allowed to be embedded.
4528 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
4529 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
4530 // Add flags implied by -fembed-bitcode.
4531 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
4532 // Disable all llvm IR level optimizations.
4533 CmdArgs.push_back("-disable-llvm-passes");
4535 // Render target options.
4536 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
4538 // reject options that shouldn't be supported in bitcode
4539 // also reject kernel/kext
4540 static const constexpr unsigned kBitcodeOptionBlacklist[] = {
4541 options::OPT_mkernel,
4542 options::OPT_fapple_kext,
4543 options::OPT_ffunction_sections,
4544 options::OPT_fno_function_sections,
4545 options::OPT_fdata_sections,
4546 options::OPT_fno_data_sections,
4547 options::OPT_fbasic_block_sections_EQ,
4548 options::OPT_funique_internal_linkage_names,
4549 options::OPT_fno_unique_internal_linkage_names,
4550 options::OPT_funique_section_names,
4551 options::OPT_fno_unique_section_names,
4552 options::OPT_funique_basic_block_section_names,
4553 options::OPT_fno_unique_basic_block_section_names,
4554 options::OPT_mrestrict_it,
4555 options::OPT_mno_restrict_it,
4556 options::OPT_mstackrealign,
4557 options::OPT_mno_stackrealign,
4558 options::OPT_mstack_alignment,
4559 options::OPT_mcmodel_EQ,
4560 options::OPT_mlong_calls,
4561 options::OPT_mno_long_calls,
4562 options::OPT_ggnu_pubnames,
4563 options::OPT_gdwarf_aranges,
4564 options::OPT_fdebug_types_section,
4565 options::OPT_fno_debug_types_section,
4566 options::OPT_fdwarf_directory_asm,
4567 options::OPT_fno_dwarf_directory_asm,
4568 options::OPT_mrelax_all,
4569 options::OPT_mno_relax_all,
4570 options::OPT_ftrap_function_EQ,
4571 options::OPT_ffixed_r9,
4572 options::OPT_mfix_cortex_a53_835769,
4573 options::OPT_mno_fix_cortex_a53_835769,
4574 options::OPT_ffixed_x18,
4575 options::OPT_mglobal_merge,
4576 options::OPT_mno_global_merge,
4577 options::OPT_mred_zone,
4578 options::OPT_mno_red_zone,
4579 options::OPT_Wa_COMMA,
4580 options::OPT_Xassembler,
4583 for (const auto &A : Args)
4584 if (llvm::find(kBitcodeOptionBlacklist, A->getOption().getID()) !=
4585 std::end(kBitcodeOptionBlacklist))
4586 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
4588 // Render the CodeGen options that need to be passed.
4589 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4590 options::OPT_fno_optimize_sibling_calls))
4591 CmdArgs.push_back("-mdisable-tail-calls");
4593 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
4596 // Render ABI arguments
4597 switch (TC.getArch()) {
4599 case llvm::Triple::arm:
4600 case llvm::Triple::armeb:
4601 case llvm::Triple::thumbeb:
4602 RenderARMABI(Triple, Args, CmdArgs);
4604 case llvm::Triple::aarch64:
4605 case llvm::Triple::aarch64_32:
4606 case llvm::Triple::aarch64_be:
4607 RenderAArch64ABI(Triple, Args, CmdArgs);
4611 // Optimization level for CodeGen.
4612 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4613 if (A->getOption().matches(options::OPT_O4)) {
4614 CmdArgs.push_back("-O3");
4615 D.Diag(diag::warn_O4_is_O3);
4617 A->render(Args, CmdArgs);
4621 // Input/Output file.
4622 if (Output.getType() == types::TY_Dependencies) {
4623 // Handled with other dependency code.
4624 } else if (Output.isFilename()) {
4625 CmdArgs.push_back("-o");
4626 CmdArgs.push_back(Output.getFilename());
4628 assert(Output.isNothing() && "Input output.");
4631 for (const auto &II : Inputs) {
4632 addDashXForInput(Args, II, CmdArgs);
4633 if (II.isFilename())
4634 CmdArgs.push_back(II.getFilename());
4636 II.getInputArg().renderAsInput(Args, CmdArgs);
4639 C.addCommand(std::make_unique<Command>(
4640 JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(),
4641 CmdArgs, Inputs, Output));
4645 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
4646 CmdArgs.push_back("-fembed-bitcode=marker");
4648 // We normally speed up the clang process a bit by skipping destructors at
4649 // exit, but when we're generating diagnostics we can rely on some of the
4651 if (!C.isForDiagnostics())
4652 CmdArgs.push_back("-disable-free");
4655 const bool IsAssertBuild = false;
4657 const bool IsAssertBuild = true;
4660 // Disable the verification pass in -asserts builds.
4662 CmdArgs.push_back("-disable-llvm-verifier");
4664 // Discard value names in assert builds unless otherwise specified.
4665 if (Args.hasFlag(options::OPT_fdiscard_value_names,
4666 options::OPT_fno_discard_value_names, !IsAssertBuild)) {
4667 if (Args.hasArg(options::OPT_fdiscard_value_names) &&
4668 (std::any_of(Inputs.begin(), Inputs.end(),
4669 [](const clang::driver::InputInfo &II) {
4670 return types::isLLVMIR(II.getType());
4672 D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
4674 CmdArgs.push_back("-discard-value-names");
4677 // Set the main file name, so that debug info works even with
4679 CmdArgs.push_back("-main-file-name");
4680 CmdArgs.push_back(getBaseInputName(Args, Input));
4682 // Some flags which affect the language (via preprocessor
4684 if (Args.hasArg(options::OPT_static))
4685 CmdArgs.push_back("-static-define");
4687 if (Args.hasArg(options::OPT_municode))
4688 CmdArgs.push_back("-DUNICODE");
4690 if (isa<AnalyzeJobAction>(JA))
4691 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
4693 if (isa<AnalyzeJobAction>(JA) ||
4694 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
4695 CmdArgs.push_back("-setup-static-analyzer");
4697 // Enable compatilibily mode to avoid analyzer-config related errors.
4698 // Since we can't access frontend flags through hasArg, let's manually iterate
4700 bool FoundAnalyzerConfig = false;
4701 for (auto Arg : Args.filtered(options::OPT_Xclang))
4702 if (StringRef(Arg->getValue()) == "-analyzer-config") {
4703 FoundAnalyzerConfig = true;
4706 if (!FoundAnalyzerConfig)
4707 for (auto Arg : Args.filtered(options::OPT_Xanalyzer))
4708 if (StringRef(Arg->getValue()) == "-analyzer-config") {
4709 FoundAnalyzerConfig = true;
4712 if (FoundAnalyzerConfig)
4713 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
4715 CheckCodeGenerationOptions(D, Args);
4717 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
4718 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
4719 if (FunctionAlignment) {
4720 CmdArgs.push_back("-function-alignment");
4721 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
4724 llvm::Reloc::Model RelocationModel;
4727 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
4729 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
4730 RelocationModel == llvm::Reloc::ROPI_RWPI;
4731 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
4732 RelocationModel == llvm::Reloc::ROPI_RWPI;
4734 if (Args.hasArg(options::OPT_mcmse) &&
4735 !Args.hasArg(options::OPT_fallow_unsupported)) {
4737 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
4739 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
4742 if (IsROPI && types::isCXX(Input.getType()) &&
4743 !Args.hasArg(options::OPT_fallow_unsupported))
4744 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
4746 const char *RMName = RelocationModelName(RelocationModel);
4748 CmdArgs.push_back("-mrelocation-model");
4749 CmdArgs.push_back(RMName);
4752 CmdArgs.push_back("-pic-level");
4753 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
4755 CmdArgs.push_back("-pic-is-pie");
4758 if (RelocationModel == llvm::Reloc::ROPI ||
4759 RelocationModel == llvm::Reloc::ROPI_RWPI)
4760 CmdArgs.push_back("-fropi");
4761 if (RelocationModel == llvm::Reloc::RWPI ||
4762 RelocationModel == llvm::Reloc::ROPI_RWPI)
4763 CmdArgs.push_back("-frwpi");
4765 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
4766 CmdArgs.push_back("-meabi");
4767 CmdArgs.push_back(A->getValue());
4770 // -fsemantic-interposition is forwarded to CC1: set the
4771 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
4772 // make default visibility external linkage definitions dso_preemptable.
4774 // -fno-semantic-interposition: if the target supports .Lfoo$local local
4775 // aliases (make default visibility external linkage definitions dso_local).
4776 // This is the CC1 default for ELF to match COFF/Mach-O.
4778 // Otherwise use Clang's traditional behavior: like
4779 // -fno-semantic-interposition but local aliases are not used. So references
4780 // can be interposed if not optimized out.
4781 if (Triple.isOSBinFormatELF()) {
4782 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
4783 options::OPT_fno_semantic_interposition);
4784 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
4785 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
4786 bool SupportsLocalAlias =
4787 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
4789 CmdArgs.push_back("-fhalf-no-semantic-interposition");
4790 else if (A->getOption().matches(options::OPT_fsemantic_interposition))
4791 A->render(Args, CmdArgs);
4792 else if (!SupportsLocalAlias)
4793 CmdArgs.push_back("-fhalf-no-semantic-interposition");
4799 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
4800 if (!TC.isThreadModelSupported(A->getValue()))
4801 D.Diag(diag::err_drv_invalid_thread_model_for_target)
4802 << A->getValue() << A->getAsString(Args);
4803 Model = A->getValue();
4805 Model = TC.getThreadModel();
4806 if (Model != "posix") {
4807 CmdArgs.push_back("-mthread-model");
4808 CmdArgs.push_back(Args.MakeArgString(Model));
4812 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
4814 if (Args.hasFlag(options::OPT_fmerge_all_constants,
4815 options::OPT_fno_merge_all_constants, false))
4816 CmdArgs.push_back("-fmerge-all-constants");
4818 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
4819 options::OPT_fdelete_null_pointer_checks, false))
4820 CmdArgs.push_back("-fno-delete-null-pointer-checks");
4822 // LLVM Code Generator Options.
4824 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file_EQ)) {
4825 StringRef Map = A->getValue();
4826 if (!llvm::sys::fs::exists(Map)) {
4827 D.Diag(diag::err_drv_no_such_file) << Map;
4829 A->render(Args, CmdArgs);
4834 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_vec_extabi,
4835 options::OPT_mabi_EQ_vec_default)) {
4836 if (!Triple.isOSAIX())
4837 D.Diag(diag::err_drv_unsupported_opt_for_target)
4838 << A->getSpelling() << RawTriple.str();
4839 if (A->getOption().getID() == options::OPT_mabi_EQ_vec_extabi)
4840 CmdArgs.push_back("-mabi=vec-extabi");
4842 CmdArgs.push_back("-mabi=vec-default");
4845 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
4846 // Emit the unsupported option error until the Clang's library integration
4847 // support for 128-bit long double is available for AIX.
4848 if (Triple.isOSAIX())
4849 D.Diag(diag::err_drv_unsupported_opt_for_target)
4850 << A->getSpelling() << RawTriple.str();
4853 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
4854 StringRef v = A->getValue();
4855 // FIXME: Validate the argument here so we don't produce meaningless errors
4856 // about -fwarn-stack-size=.
4858 D.Diag(diag::err_drv_missing_argument) << A->getSpelling() << 1;
4860 CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + v));
4864 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
4866 CmdArgs.push_back("-fno-jump-tables");
4868 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
4869 options::OPT_fno_profile_sample_accurate, false))
4870 CmdArgs.push_back("-fprofile-sample-accurate");
4872 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
4873 options::OPT_fno_preserve_as_comments, true))
4874 CmdArgs.push_back("-fno-preserve-as-comments");
4876 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
4877 CmdArgs.push_back("-mregparm");
4878 CmdArgs.push_back(A->getValue());
4881 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
4882 options::OPT_msvr4_struct_return)) {
4883 if (!TC.getTriple().isPPC32()) {
4884 D.Diag(diag::err_drv_unsupported_opt_for_target)
4885 << A->getSpelling() << RawTriple.str();
4886 } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
4887 CmdArgs.push_back("-maix-struct-return");
4889 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
4890 CmdArgs.push_back("-msvr4-struct-return");
4894 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
4895 options::OPT_freg_struct_return)) {
4896 if (TC.getArch() != llvm::Triple::x86) {
4897 D.Diag(diag::err_drv_unsupported_opt_for_target)
4898 << A->getSpelling() << RawTriple.str();
4899 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
4900 CmdArgs.push_back("-fpcc-struct-return");
4902 assert(A->getOption().matches(options::OPT_freg_struct_return));
4903 CmdArgs.push_back("-freg-struct-return");
4907 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
4908 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
4910 if (Args.hasArg(options::OPT_fenable_matrix)) {
4911 // enable-matrix is needed by both the LangOpts and by LLVM.
4912 CmdArgs.push_back("-fenable-matrix");
4913 CmdArgs.push_back("-mllvm");
4914 CmdArgs.push_back("-enable-matrix");
4917 CodeGenOptions::FramePointerKind FPKeepKind =
4918 getFramePointerKind(Args, RawTriple);
4919 const char *FPKeepKindStr = nullptr;
4920 switch (FPKeepKind) {
4921 case CodeGenOptions::FramePointerKind::None:
4922 FPKeepKindStr = "-mframe-pointer=none";
4924 case CodeGenOptions::FramePointerKind::NonLeaf:
4925 FPKeepKindStr = "-mframe-pointer=non-leaf";
4927 case CodeGenOptions::FramePointerKind::All:
4928 FPKeepKindStr = "-mframe-pointer=all";
4931 assert(FPKeepKindStr && "unknown FramePointerKind");
4932 CmdArgs.push_back(FPKeepKindStr);
4934 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
4935 options::OPT_fno_zero_initialized_in_bss, true))
4936 CmdArgs.push_back("-fno-zero-initialized-in-bss");
4938 bool OFastEnabled = isOptimizationLevelFast(Args);
4939 // If -Ofast is the optimization level, then -fstrict-aliasing should be
4940 // enabled. This alias option is being used to simplify the hasFlag logic.
4941 OptSpecifier StrictAliasingAliasOption =
4942 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
4943 // We turn strict aliasing off by default if we're in CL mode, since MSVC
4944 // doesn't do any TBAA.
4945 bool TBAAOnByDefault = !D.IsCLMode();
4946 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
4947 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
4948 CmdArgs.push_back("-relaxed-aliasing");
4949 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
4950 options::OPT_fno_struct_path_tbaa))
4951 CmdArgs.push_back("-no-struct-path-tbaa");
4952 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
4954 CmdArgs.push_back("-fstrict-enums");
4955 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
4957 CmdArgs.push_back("-fno-strict-return");
4958 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
4959 options::OPT_fno_allow_editor_placeholders, false))
4960 CmdArgs.push_back("-fallow-editor-placeholders");
4961 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
4962 options::OPT_fno_strict_vtable_pointers,
4964 CmdArgs.push_back("-fstrict-vtable-pointers");
4965 if (Args.hasFlag(options::OPT_fforce_emit_vtables,
4966 options::OPT_fno_force_emit_vtables,
4968 CmdArgs.push_back("-fforce-emit-vtables");
4969 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4970 options::OPT_fno_optimize_sibling_calls))
4971 CmdArgs.push_back("-mdisable-tail-calls");
4972 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
4973 options::OPT_fescaping_block_tail_calls, false))
4974 CmdArgs.push_back("-fno-escaping-block-tail-calls");
4976 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
4977 options::OPT_fno_fine_grained_bitfield_accesses);
4979 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
4980 options::OPT_fno_experimental_relative_cxx_abi_vtables);
4982 // Handle segmented stacks.
4983 if (Args.hasFlag(options::OPT_fsplit_stack, options::OPT_fno_split_stack,
4985 CmdArgs.push_back("-fsplit-stack");
4987 // -fprotect-parens=0 is default.
4988 if (Args.hasFlag(options::OPT_fprotect_parens,
4989 options::OPT_fno_protect_parens, false))
4990 CmdArgs.push_back("-fprotect-parens");
4992 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
4994 if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
4995 const llvm::Triple::ArchType Arch = TC.getArch();
4996 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
4997 StringRef V = A->getValue();
4999 CmdArgs.push_back("-fextend-arguments=64");
5001 D.Diag(diag::err_drv_invalid_argument_to_option)
5002 << A->getValue() << A->getOption().getName();
5004 D.Diag(diag::err_drv_unsupported_opt_for_target)
5005 << A->getOption().getName() << TripleStr;
5008 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
5009 if (TC.getArch() == llvm::Triple::avr)
5010 A->render(Args, CmdArgs);
5012 D.Diag(diag::err_drv_unsupported_opt_for_target)
5013 << A->getAsString(Args) << TripleStr;
5016 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
5017 if (TC.getTriple().isX86())
5018 A->render(Args, CmdArgs);
5019 else if (TC.getTriple().isPPC() &&
5020 (A->getOption().getID() != options::OPT_mlong_double_80))
5021 A->render(Args, CmdArgs);
5023 D.Diag(diag::err_drv_unsupported_opt_for_target)
5024 << A->getAsString(Args) << TripleStr;
5027 // Decide whether to use verbose asm. Verbose assembly is the default on
5028 // toolchains which have the integrated assembler on by default.
5029 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
5030 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
5031 IsIntegratedAssemblerDefault))
5032 CmdArgs.push_back("-fno-verbose-asm");
5034 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5035 // use that to indicate the MC default in the backend.
5036 if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
5037 StringRef V = A->getValue();
5040 A->render(Args, CmdArgs);
5041 else if (!V.consumeInteger(10, Num) && Num > 0 &&
5042 (V.empty() || (V.consume_front(".") &&
5043 !V.consumeInteger(10, Num) && V.empty())))
5044 A->render(Args, CmdArgs);
5046 D.Diag(diag::err_drv_invalid_argument_to_option)
5047 << A->getValue() << A->getOption().getName();
5050 // If toolchain choose to use MCAsmParser for inline asm don't pass the
5051 // option to disable integrated-as explictly.
5052 if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
5053 CmdArgs.push_back("-no-integrated-as");
5055 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
5056 CmdArgs.push_back("-mdebug-pass");
5057 CmdArgs.push_back("Structure");
5059 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
5060 CmdArgs.push_back("-mdebug-pass");
5061 CmdArgs.push_back("Arguments");
5064 // Enable -mconstructor-aliases except on darwin, where we have to work around
5065 // a linker bug (see <rdar://problem/7651567>), and CUDA/AMDGPU device code,
5066 // where aliases aren't supported.
5067 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX() && !RawTriple.isAMDGPU())
5068 CmdArgs.push_back("-mconstructor-aliases");
5070 // Darwin's kernel doesn't support guard variables; just die if we
5072 if (KernelOrKext && RawTriple.isOSDarwin())
5073 CmdArgs.push_back("-fforbid-guard-variables");
5075 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
5076 Triple.isWindowsGNUEnvironment())) {
5077 CmdArgs.push_back("-mms-bitfields");
5080 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
5081 // defaults to -fno-direct-access-external-data. Pass the option if different
5082 // from the default.
5083 if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
5084 options::OPT_fno_direct_access_external_data))
5085 if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
5087 A->render(Args, CmdArgs);
5089 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
5090 CmdArgs.push_back("-fno-plt");
5093 // -fhosted is default.
5094 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
5095 // use Freestanding.
5097 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
5100 CmdArgs.push_back("-ffreestanding");
5102 // This is a coarse approximation of what llvm-gcc actually does, both
5103 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
5104 // complicated ways.
5106 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
5107 options::OPT_fno_asynchronous_unwind_tables,
5108 (TC.IsUnwindTablesDefault(Args) ||
5109 TC.getSanitizerArgs().needsUnwindTables()) &&
5111 UnwindTables = Args.hasFlag(options::OPT_funwind_tables,
5112 options::OPT_fno_unwind_tables, UnwindTables);
5114 CmdArgs.push_back("-munwind-tables");
5116 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
5117 // `--gpu-use-aux-triple-only` is specified.
5118 if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
5119 (IsCudaDevice || IsHIPDevice)) {
5120 const ArgList &HostArgs =
5121 C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
5122 std::string HostCPU =
5123 getCPUName(HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
5124 if (!HostCPU.empty()) {
5125 CmdArgs.push_back("-aux-target-cpu");
5126 CmdArgs.push_back(Args.MakeArgString(HostCPU));
5128 getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
5129 /*ForAS*/ false, /*IsAux*/ true);
5132 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5134 // FIXME: Handle -mtune=.
5135 (void)Args.hasArg(options::OPT_mtune_EQ);
5137 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
5138 StringRef CM = A->getValue();
5139 if (CM == "small" || CM == "kernel" || CM == "medium" || CM == "large" ||
5141 if (Triple.isOSAIX() && CM == "medium")
5142 CmdArgs.push_back("-mcmodel=large");
5144 A->render(Args, CmdArgs);
5146 D.Diag(diag::err_drv_invalid_argument_to_option)
5147 << CM << A->getOption().getName();
5151 if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
5152 StringRef Value = A->getValue();
5153 unsigned TLSSize = 0;
5154 Value.getAsInteger(10, TLSSize);
5155 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
5156 D.Diag(diag::err_drv_unsupported_opt_for_target)
5157 << A->getOption().getName() << TripleStr;
5158 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
5159 D.Diag(diag::err_drv_invalid_int_value)
5160 << A->getOption().getName() << Value;
5161 Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
5164 // Add the target cpu
5165 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
5167 CmdArgs.push_back("-target-cpu");
5168 CmdArgs.push_back(Args.MakeArgString(CPU));
5171 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
5173 // FIXME: For now we want to demote any errors to warnings, when they have
5174 // been raised for asking the wrong question of scalable vectors, such as
5175 // asking for the fixed number of elements. This may happen because code that
5176 // is not yet ported to work for scalable vectors uses the wrong interfaces,
5177 // whereas the behaviour is actually correct. Emitting a warning helps bring
5178 // up scalable vector support in an incremental way. When scalable vector
5179 // support is stable enough, all uses of wrong interfaces should be considered
5180 // as errors, but until then, we can live with a warning being emitted by the
5181 // compiler. This way, Clang can be used to compile code with scalable vectors
5182 // and identify possible issues.
5183 if (isa<BackendJobAction>(JA)) {
5184 CmdArgs.push_back("-mllvm");
5185 CmdArgs.push_back("-treat-scalable-fixed-error-as-warning");
5188 // These two are potentially updated by AddClangCLArgs.
5189 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
5190 bool EmitCodeView = false;
5192 // Add clang-cl arguments.
5193 types::ID InputType = Input.getType();
5195 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
5197 DwarfFissionKind DwarfFission = DwarfFissionKind::None;
5198 renderDebugOptions(TC, D, RawTriple, Args, EmitCodeView,
5199 types::isLLVMIR(InputType), CmdArgs, DebugInfoKind,
5202 // Add the split debug info name to the command lines here so we
5203 // can propagate it to the backend.
5204 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
5205 (TC.getTriple().isOSBinFormatELF() ||
5206 TC.getTriple().isOSBinFormatWasm()) &&
5207 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
5208 isa<BackendJobAction>(JA));
5210 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
5211 CmdArgs.push_back("-split-dwarf-file");
5212 CmdArgs.push_back(SplitDWARFOut);
5213 if (DwarfFission == DwarfFissionKind::Split) {
5214 CmdArgs.push_back("-split-dwarf-output");
5215 CmdArgs.push_back(SplitDWARFOut);
5219 // Pass the linker version in use.
5220 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
5221 CmdArgs.push_back("-target-linker-version");
5222 CmdArgs.push_back(A->getValue());
5225 // Explicitly error on some things we know we don't support and can't just
5227 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
5229 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
5230 TC.getArch() == llvm::Triple::x86) {
5231 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
5232 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
5233 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
5234 << Unsupported->getOption().getName();
5236 // The faltivec option has been superseded by the maltivec option.
5237 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
5238 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5239 << Unsupported->getOption().getName()
5240 << "please use -maltivec and include altivec.h explicitly";
5241 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
5242 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
5243 << Unsupported->getOption().getName() << "please use -mno-altivec";
5246 Args.AddAllArgs(CmdArgs, options::OPT_v);
5248 if (Args.getLastArg(options::OPT_H)) {
5249 CmdArgs.push_back("-H");
5250 CmdArgs.push_back("-sys-header-deps");
5252 Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
5254 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
5255 CmdArgs.push_back("-header-include-file");
5256 CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
5257 ? D.CCPrintHeadersFilename.c_str()
5259 CmdArgs.push_back("-sys-header-deps");
5261 Args.AddLastArg(CmdArgs, options::OPT_P);
5262 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
5264 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
5265 CmdArgs.push_back("-diagnostic-log-file");
5266 CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
5267 ? D.CCLogDiagnosticsFilename.c_str()
5271 // Give the gen diagnostics more chances to succeed, by avoiding intentional
5273 if (D.CCGenDiagnostics)
5274 CmdArgs.push_back("-disable-pragma-debug-crash");
5276 // Allow backend to put its diagnostic files in the same place as frontend
5277 // crash diagnostics files.
5278 if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
5279 StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
5280 CmdArgs.push_back("-mllvm");
5281 CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
5284 bool UseSeparateSections = isUseSeparateSections(Triple);
5286 if (Args.hasFlag(options::OPT_ffunction_sections,
5287 options::OPT_fno_function_sections, UseSeparateSections)) {
5288 CmdArgs.push_back("-ffunction-sections");
5291 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
5292 StringRef Val = A->getValue();
5293 if (Triple.isX86() && Triple.isOSBinFormatELF()) {
5294 if (Val != "all" && Val != "labels" && Val != "none" &&
5295 !Val.startswith("list="))
5296 D.Diag(diag::err_drv_invalid_value)
5297 << A->getAsString(Args) << A->getValue();
5299 A->render(Args, CmdArgs);
5300 } else if (Triple.isNVPTX()) {
5301 // Do not pass the option to the GPU compilation. We still want it enabled
5302 // for the host-side compilation, so seeing it here is not an error.
5303 } else if (Val != "none") {
5304 // =none is allowed everywhere. It's useful for overriding the option
5305 // and is the same as not specifying the option.
5306 D.Diag(diag::err_drv_unsupported_opt_for_target)
5307 << A->getAsString(Args) << TripleStr;
5311 bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
5312 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
5313 UseSeparateSections || HasDefaultDataSections)) {
5314 CmdArgs.push_back("-fdata-sections");
5317 if (!Args.hasFlag(options::OPT_funique_section_names,
5318 options::OPT_fno_unique_section_names, true))
5319 CmdArgs.push_back("-fno-unique-section-names");
5321 if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
5322 options::OPT_fno_unique_internal_linkage_names, false))
5323 CmdArgs.push_back("-funique-internal-linkage-names");
5325 if (Args.hasFlag(options::OPT_funique_basic_block_section_names,
5326 options::OPT_fno_unique_basic_block_section_names, false))
5327 CmdArgs.push_back("-funique-basic-block-section-names");
5329 if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
5330 options::OPT_fno_split_machine_functions)) {
5331 // This codegen pass is only available on x86-elf targets.
5332 if (Triple.isX86() && Triple.isOSBinFormatELF()) {
5333 if (A->getOption().matches(options::OPT_fsplit_machine_functions))
5334 A->render(Args, CmdArgs);
5336 D.Diag(diag::err_drv_unsupported_opt_for_target)
5337 << A->getAsString(Args) << TripleStr;
5341 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
5342 options::OPT_finstrument_functions_after_inlining,
5343 options::OPT_finstrument_function_entry_bare);
5345 // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support
5346 // for sampling, overhead of call arc collection is way too high and there's
5347 // no way to collect the output.
5348 if (!Triple.isNVPTX() && !Triple.isAMDGCN())
5349 addPGOAndCoverageFlags(TC, C, D, Output, Args, CmdArgs);
5351 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
5353 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
5354 if (RawTriple.isPS4CPU() &&
5355 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
5356 PS4cpu::addProfileRTArgs(TC, Args, CmdArgs);
5357 PS4cpu::addSanitizerArgs(TC, CmdArgs);
5360 // Pass options for controlling the default header search paths.
5361 if (Args.hasArg(options::OPT_nostdinc)) {
5362 CmdArgs.push_back("-nostdsysteminc");
5363 CmdArgs.push_back("-nobuiltininc");
5365 if (Args.hasArg(options::OPT_nostdlibinc))
5366 CmdArgs.push_back("-nostdsysteminc");
5367 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
5368 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
5371 // Pass the path to compiler resource files.
5372 CmdArgs.push_back("-resource-dir");
5373 CmdArgs.push_back(D.ResourceDir.c_str());
5375 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
5377 RenderARCMigrateToolOptions(D, Args, CmdArgs);
5379 // Add preprocessing options like -I, -D, etc. if we are using the
5382 // FIXME: Support -fpreprocessed
5383 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
5384 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
5386 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
5387 // that "The compiler can only warn and ignore the option if not recognized".
5388 // When building with ccache, it will pass -D options to clang even on
5389 // preprocessed inputs and configure concludes that -fPIC is not supported.
5390 Args.ClaimAllArgs(options::OPT_D);
5392 // Manually translate -O4 to -O3; let clang reject others.
5393 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5394 if (A->getOption().matches(options::OPT_O4)) {
5395 CmdArgs.push_back("-O3");
5396 D.Diag(diag::warn_O4_is_O3);
5398 A->render(Args, CmdArgs);
5402 // Warn about ignored options to clang.
5404 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
5405 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
5410 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
5411 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
5415 claimNoWarnArgs(Args);
5417 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
5419 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
5420 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
5421 CmdArgs.push_back("-pedantic");
5422 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
5423 Args.AddLastArg(CmdArgs, options::OPT_w);
5425 // Fixed point flags
5426 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
5428 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
5430 if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
5431 A->render(Args, CmdArgs);
5433 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
5434 options::OPT_fno_experimental_relative_cxx_abi_vtables);
5436 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
5437 // (-ansi is equivalent to -std=c89 or -std=c++98).
5439 // If a std is supplied, only add -trigraphs if it follows the
5441 bool ImplyVCPPCVer = false;
5442 bool ImplyVCPPCXXVer = false;
5443 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
5445 if (Std->getOption().matches(options::OPT_ansi))
5446 if (types::isCXX(InputType))
5447 CmdArgs.push_back("-std=c++98");
5449 CmdArgs.push_back("-std=c89");
5451 Std->render(Args, CmdArgs);
5453 // If -f(no-)trigraphs appears after the language standard flag, honor it.
5454 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
5455 options::OPT_ftrigraphs,
5456 options::OPT_fno_trigraphs))
5458 A->render(Args, CmdArgs);
5460 // Honor -std-default.
5462 // FIXME: Clang doesn't correctly handle -std= when the input language
5463 // doesn't match. For the time being just ignore this for C++ inputs;
5464 // eventually we want to do all the standard defaulting here instead of
5465 // splitting it between the driver and clang -cc1.
5466 if (!types::isCXX(InputType)) {
5467 if (!Args.hasArg(options::OPT__SLASH_std)) {
5468 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
5471 ImplyVCPPCVer = true;
5473 else if (IsWindowsMSVC)
5474 ImplyVCPPCXXVer = true;
5476 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
5477 options::OPT_fno_trigraphs);
5479 // HIP headers has minimum C++ standard requirements. Therefore set the
5480 // default language standard.
5482 CmdArgs.push_back(IsWindowsMSVC ? "-std=c++14" : "-std=c++11");
5485 // GCC's behavior for -Wwrite-strings is a bit strange:
5486 // * In C, this "warning flag" changes the types of string literals from
5487 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
5488 // for the discarded qualifier.
5489 // * In C++, this is just a normal warning flag.
5491 // Implementing this warning correctly in C is hard, so we follow GCC's
5492 // behavior for now. FIXME: Directly diagnose uses of a string literal as
5493 // a non-const char* in C, rather than using this crude hack.
5494 if (!types::isCXX(InputType)) {
5495 // FIXME: This should behave just like a warning flag, and thus should also
5496 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
5498 Args.getLastArg(options::OPT_Wwrite_strings,
5499 options::OPT_Wno_write_strings, options::OPT_w);
5501 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
5502 CmdArgs.push_back("-fconst-strings");
5505 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
5506 // during C++ compilation, which it is by default. GCC keeps this define even
5507 // in the presence of '-w', match this behavior bug-for-bug.
5508 if (types::isCXX(InputType) &&
5509 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
5511 CmdArgs.push_back("-fdeprecated-macro");
5514 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
5515 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
5516 if (Asm->getOption().matches(options::OPT_fasm))
5517 CmdArgs.push_back("-fgnu-keywords");
5519 CmdArgs.push_back("-fno-gnu-keywords");
5522 if (!ShouldEnableAutolink(Args, TC, JA))
5523 CmdArgs.push_back("-fno-autolink");
5525 // Add in -fdebug-compilation-dir if necessary.
5526 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
5528 addDebugPrefixMapArg(D, Args, CmdArgs);
5530 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
5531 options::OPT_ftemplate_depth_EQ)) {
5532 CmdArgs.push_back("-ftemplate-depth");
5533 CmdArgs.push_back(A->getValue());
5536 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
5537 CmdArgs.push_back("-foperator-arrow-depth");
5538 CmdArgs.push_back(A->getValue());
5541 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
5542 CmdArgs.push_back("-fconstexpr-depth");
5543 CmdArgs.push_back(A->getValue());
5546 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
5547 CmdArgs.push_back("-fconstexpr-steps");
5548 CmdArgs.push_back(A->getValue());
5551 if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
5552 CmdArgs.push_back("-fexperimental-new-constant-interpreter");
5554 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
5555 CmdArgs.push_back("-fbracket-depth");
5556 CmdArgs.push_back(A->getValue());
5559 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
5560 options::OPT_Wlarge_by_value_copy_def)) {
5561 if (A->getNumValues()) {
5562 StringRef bytes = A->getValue();
5563 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
5565 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
5568 if (Args.hasArg(options::OPT_relocatable_pch))
5569 CmdArgs.push_back("-relocatable-pch");
5571 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
5572 static const char *kCFABIs[] = {
5573 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
5576 if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs))
5577 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
5579 A->render(Args, CmdArgs);
5582 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
5583 CmdArgs.push_back("-fconstant-string-class");
5584 CmdArgs.push_back(A->getValue());
5587 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
5588 CmdArgs.push_back("-ftabstop");
5589 CmdArgs.push_back(A->getValue());
5592 if (Args.hasFlag(options::OPT_fstack_size_section,
5593 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
5594 CmdArgs.push_back("-fstack-size-section");
5596 if (Args.hasArg(options::OPT_fstack_usage)) {
5597 CmdArgs.push_back("-stack-usage-file");
5599 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5600 SmallString<128> OutputFilename(OutputOpt->getValue());
5601 llvm::sys::path::replace_extension(OutputFilename, "su");
5602 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
5605 Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
5608 CmdArgs.push_back("-ferror-limit");
5609 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
5610 CmdArgs.push_back(A->getValue());
5612 CmdArgs.push_back("19");
5614 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
5615 CmdArgs.push_back("-fmacro-backtrace-limit");
5616 CmdArgs.push_back(A->getValue());
5619 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
5620 CmdArgs.push_back("-ftemplate-backtrace-limit");
5621 CmdArgs.push_back(A->getValue());
5624 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
5625 CmdArgs.push_back("-fconstexpr-backtrace-limit");
5626 CmdArgs.push_back(A->getValue());
5629 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
5630 CmdArgs.push_back("-fspell-checking-limit");
5631 CmdArgs.push_back(A->getValue());
5634 // Pass -fmessage-length=.
5635 unsigned MessageLength = 0;
5636 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
5637 StringRef V(A->getValue());
5638 if (V.getAsInteger(0, MessageLength))
5639 D.Diag(diag::err_drv_invalid_argument_to_option)
5640 << V << A->getOption().getName();
5642 // If -fmessage-length=N was not specified, determine whether this is a
5643 // terminal and, if so, implicitly define -fmessage-length appropriately.
5644 MessageLength = llvm::sys::Process::StandardErrColumns();
5646 if (MessageLength != 0)
5648 Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
5650 // -fvisibility= and -fvisibility-ms-compat are of a piece.
5651 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
5652 options::OPT_fvisibility_ms_compat)) {
5653 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
5654 CmdArgs.push_back("-fvisibility");
5655 CmdArgs.push_back(A->getValue());
5657 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
5658 CmdArgs.push_back("-fvisibility");
5659 CmdArgs.push_back("hidden");
5660 CmdArgs.push_back("-ftype-visibility");
5661 CmdArgs.push_back("default");
5665 if (!RawTriple.isPS4())
5667 Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
5668 options::OPT_fno_visibility_from_dllstorageclass)) {
5669 if (A->getOption().matches(
5670 options::OPT_fvisibility_from_dllstorageclass)) {
5671 CmdArgs.push_back("-fvisibility-from-dllstorageclass");
5672 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
5673 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
5674 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
5675 Args.AddLastArg(CmdArgs,
5676 options::OPT_fvisibility_externs_nodllstorageclass_EQ);
5680 if (const Arg *A = Args.getLastArg(options::OPT_mignore_xcoff_visibility)) {
5681 if (Triple.isOSAIX())
5682 CmdArgs.push_back("-mignore-xcoff-visibility");
5684 D.Diag(diag::err_drv_unsupported_opt_for_target)
5685 << A->getAsString(Args) << TripleStr;
5689 if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
5690 options::OPT_fno_visibility_inlines_hidden, false))
5691 CmdArgs.push_back("-fvisibility-inlines-hidden");
5693 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
5694 options::OPT_fno_visibility_inlines_hidden_static_local_var);
5695 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
5697 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
5699 if (Args.hasFlag(options::OPT_fno_operator_names,
5700 options::OPT_foperator_names, false))
5701 CmdArgs.push_back("-fno-operator-names");
5703 // Forward -f (flag) options which we can pass directly.
5704 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
5705 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
5706 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
5707 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
5708 options::OPT_fno_emulated_tls);
5710 // AltiVec-like language extensions aren't relevant for assembling.
5711 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
5712 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
5714 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
5715 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
5717 // Forward flags for OpenMP. We don't do this if the current action is an
5718 // device offloading action other than OpenMP.
5719 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
5720 options::OPT_fno_openmp, false) &&
5721 (JA.isDeviceOffloading(Action::OFK_None) ||
5722 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
5723 switch (D.getOpenMPRuntime(Args)) {
5724 case Driver::OMPRT_OMP:
5725 case Driver::OMPRT_IOMP5:
5726 // Clang can generate useful OpenMP code for these two runtime libraries.
5727 CmdArgs.push_back("-fopenmp");
5729 // If no option regarding the use of TLS in OpenMP codegeneration is
5730 // given, decide a default based on the target. Otherwise rely on the
5731 // options and pass the right information to the frontend.
5732 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
5733 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
5734 CmdArgs.push_back("-fnoopenmp-use-tls");
5735 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
5736 options::OPT_fno_openmp_simd);
5737 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
5738 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
5739 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
5740 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
5741 Args.AddAllArgs(CmdArgs,
5742 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
5743 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
5744 options::OPT_fno_openmp_optimistic_collapse,
5746 CmdArgs.push_back("-fopenmp-optimistic-collapse");
5748 // When in OpenMP offloading mode with NVPTX target, forward
5750 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
5751 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
5752 CmdArgs.push_back("-fopenmp-cuda-mode");
5754 // When in OpenMP offloading mode with NVPTX target, check if full runtime
5756 if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime,
5757 options::OPT_fno_openmp_cuda_force_full_runtime,
5759 CmdArgs.push_back("-fopenmp-cuda-force-full-runtime");
5762 // By default, if Clang doesn't know how to generate useful OpenMP code
5763 // for a specific runtime library, we just don't pass the '-fopenmp' flag
5764 // down to the actual compilation.
5765 // FIXME: It would be better to have a mode which *only* omits IR
5766 // generation based on the OpenMP support so that we get consistent
5767 // semantic analysis, etc.
5771 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
5772 options::OPT_fno_openmp_simd);
5773 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
5776 const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
5777 Sanitize.addArgs(TC, Args, CmdArgs, InputType);
5779 const XRayArgs &XRay = TC.getXRayArgs();
5780 XRay.addArgs(TC, Args, CmdArgs, InputType);
5782 for (const auto &Filename :
5783 Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
5784 if (D.getVFS().exists(Filename))
5785 CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
5787 D.Diag(clang::diag::err_drv_no_such_file) << Filename;
5790 if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
5791 StringRef S0 = A->getValue(), S = S0;
5792 unsigned Size, Offset = 0;
5793 if (!Triple.isAArch64() && !Triple.isRISCV() && !Triple.isX86())
5794 D.Diag(diag::err_drv_unsupported_opt_for_target)
5795 << A->getAsString(Args) << TripleStr;
5796 else if (S.consumeInteger(10, Size) ||
5797 (!S.empty() && (!S.consume_front(",") ||
5798 S.consumeInteger(10, Offset) || !S.empty())))
5799 D.Diag(diag::err_drv_invalid_argument_to_option)
5800 << S0 << A->getOption().getName();
5801 else if (Size < Offset)
5802 D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
5804 CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
5805 CmdArgs.push_back(Args.MakeArgString(
5806 "-fpatchable-function-entry-offset=" + Twine(Offset)));
5810 if (TC.SupportsProfiling()) {
5811 Args.AddLastArg(CmdArgs, options::OPT_pg);
5813 llvm::Triple::ArchType Arch = TC.getArch();
5814 if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
5815 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
5816 A->render(Args, CmdArgs);
5818 D.Diag(diag::err_drv_unsupported_opt_for_target)
5819 << A->getAsString(Args) << TripleStr;
5821 if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
5822 if (Arch == llvm::Triple::systemz)
5823 A->render(Args, CmdArgs);
5825 D.Diag(diag::err_drv_unsupported_opt_for_target)
5826 << A->getAsString(Args) << TripleStr;
5828 if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
5829 if (Arch == llvm::Triple::systemz)
5830 A->render(Args, CmdArgs);
5832 D.Diag(diag::err_drv_unsupported_opt_for_target)
5833 << A->getAsString(Args) << TripleStr;
5837 if (Args.getLastArg(options::OPT_fapple_kext) ||
5838 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
5839 CmdArgs.push_back("-fapple-kext");
5841 Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
5842 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
5843 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
5844 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
5845 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
5846 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
5847 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
5848 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
5849 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
5850 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
5851 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
5852 Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
5854 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
5855 CmdArgs.push_back("-ftrapv-handler");
5856 CmdArgs.push_back(A->getValue());
5859 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
5861 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
5862 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
5863 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
5864 if (A->getOption().matches(options::OPT_fwrapv))
5865 CmdArgs.push_back("-fwrapv");
5866 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
5867 options::OPT_fno_strict_overflow)) {
5868 if (A->getOption().matches(options::OPT_fno_strict_overflow))
5869 CmdArgs.push_back("-fwrapv");
5872 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
5873 options::OPT_fno_reroll_loops))
5874 if (A->getOption().matches(options::OPT_freroll_loops))
5875 CmdArgs.push_back("-freroll-loops");
5877 Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
5878 options::OPT_fno_finite_loops);
5880 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
5881 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
5882 options::OPT_fno_unroll_loops);
5884 Args.AddLastArg(CmdArgs, options::OPT_pthread);
5886 if (Args.hasFlag(options::OPT_mspeculative_load_hardening,
5887 options::OPT_mno_speculative_load_hardening, false))
5888 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
5890 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
5891 RenderSCPOptions(TC, Args, CmdArgs);
5892 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
5894 // Translate -mstackrealign
5895 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
5897 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
5899 if (Args.hasArg(options::OPT_mstack_alignment)) {
5900 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
5901 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
5904 if (Args.hasArg(options::OPT_mstack_probe_size)) {
5905 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
5908 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
5910 CmdArgs.push_back("-mstack-probe-size=0");
5913 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
5914 options::OPT_mno_stack_arg_probe, true))
5915 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
5917 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
5918 options::OPT_mno_restrict_it)) {
5919 if (A->getOption().matches(options::OPT_mrestrict_it)) {
5920 CmdArgs.push_back("-mllvm");
5921 CmdArgs.push_back("-arm-restrict-it");
5923 CmdArgs.push_back("-mllvm");
5924 CmdArgs.push_back("-arm-no-restrict-it");
5926 } else if (Triple.isOSWindows() &&
5927 (Triple.getArch() == llvm::Triple::arm ||
5928 Triple.getArch() == llvm::Triple::thumb)) {
5929 // Windows on ARM expects restricted IT blocks
5930 CmdArgs.push_back("-mllvm");
5931 CmdArgs.push_back("-arm-restrict-it");
5934 // Forward -cl options to -cc1
5935 RenderOpenCLOptions(Args, CmdArgs, InputType);
5938 if (Args.hasFlag(options::OPT_fhip_new_launch_api,
5939 options::OPT_fno_hip_new_launch_api, true))
5940 CmdArgs.push_back("-fhip-new-launch-api");
5941 if (Args.hasFlag(options::OPT_fgpu_allow_device_init,
5942 options::OPT_fno_gpu_allow_device_init, false))
5943 CmdArgs.push_back("-fgpu-allow-device-init");
5946 if (IsCuda || IsHIP) {
5947 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
5948 CmdArgs.push_back("-fgpu-rdc");
5949 if (Args.hasFlag(options::OPT_fgpu_defer_diag,
5950 options::OPT_fno_gpu_defer_diag, false))
5951 CmdArgs.push_back("-fgpu-defer-diag");
5952 if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
5953 options::OPT_fno_gpu_exclude_wrong_side_overloads,
5955 CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
5956 CmdArgs.push_back("-fgpu-defer-diag");
5960 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
5962 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
5965 // Forward -f options with positive and negative forms; we translate these by
5966 // hand. Do not propagate PGO options to the GPU-side compilations as the
5967 // profile info is for the host-side compilation only.
5968 if (!(IsCudaDevice || IsHIPDevice)) {
5969 if (Arg *A = getLastProfileSampleUseArg(Args)) {
5970 auto *PGOArg = Args.getLastArg(
5971 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
5972 options::OPT_fcs_profile_generate,
5973 options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
5974 options::OPT_fprofile_use_EQ);
5976 D.Diag(diag::err_drv_argument_not_allowed_with)
5977 << "SampleUse with PGO options";
5979 StringRef fname = A->getValue();
5980 if (!llvm::sys::fs::exists(fname))
5981 D.Diag(diag::err_drv_no_such_file) << fname;
5983 A->render(Args, CmdArgs);
5985 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
5987 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
5988 options::OPT_fno_pseudo_probe_for_profiling, false)) {
5989 CmdArgs.push_back("-fpseudo-probe-for-profiling");
5990 // Enforce -funique-internal-linkage-names if it's not explicitly turned
5992 if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
5993 options::OPT_fno_unique_internal_linkage_names, true))
5994 CmdArgs.push_back("-funique-internal-linkage-names");
5997 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
5999 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
6000 options::OPT_fno_assume_sane_operator_new))
6001 CmdArgs.push_back("-fno-assume-sane-operator-new");
6003 // -fblocks=0 is default.
6004 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
6005 TC.IsBlocksDefault()) ||
6006 (Args.hasArg(options::OPT_fgnu_runtime) &&
6007 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
6008 !Args.hasArg(options::OPT_fno_blocks))) {
6009 CmdArgs.push_back("-fblocks");
6011 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
6012 CmdArgs.push_back("-fblocks-runtime-optional");
6015 // -fencode-extended-block-signature=1 is default.
6016 if (TC.IsEncodeExtendedBlockSignatureDefault())
6017 CmdArgs.push_back("-fencode-extended-block-signature");
6019 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
6021 types::isCXX(InputType)) {
6022 CmdArgs.push_back("-fcoroutines-ts");
6025 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
6026 options::OPT_fno_double_square_bracket_attributes);
6028 // -faccess-control is default.
6029 if (Args.hasFlag(options::OPT_fno_access_control,
6030 options::OPT_faccess_control, false))
6031 CmdArgs.push_back("-fno-access-control");
6033 // -felide-constructors is the default.
6034 if (Args.hasFlag(options::OPT_fno_elide_constructors,
6035 options::OPT_felide_constructors, false))
6036 CmdArgs.push_back("-fno-elide-constructors");
6038 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
6040 if (KernelOrKext || (types::isCXX(InputType) &&
6041 (RTTIMode == ToolChain::RM_Disabled)))
6042 CmdArgs.push_back("-fno-rtti");
6044 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
6045 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
6046 TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
6047 CmdArgs.push_back("-fshort-enums");
6049 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
6051 // -fuse-cxa-atexit is default.
6053 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
6054 !RawTriple.isOSAIX() && !RawTriple.isOSWindows() &&
6055 TC.getArch() != llvm::Triple::xcore &&
6056 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
6057 RawTriple.hasEnvironment())) ||
6059 CmdArgs.push_back("-fno-use-cxa-atexit");
6061 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
6062 options::OPT_fno_register_global_dtors_with_atexit,
6063 RawTriple.isOSDarwin() && !KernelOrKext))
6064 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
6066 // -fno-use-line-directives is default.
6067 if (Args.hasFlag(options::OPT_fuse_line_directives,
6068 options::OPT_fno_use_line_directives, false))
6069 CmdArgs.push_back("-fuse-line-directives");
6071 // -fms-extensions=0 is default.
6072 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
6074 CmdArgs.push_back("-fms-extensions");
6076 // -fms-compatibility=0 is default.
6077 bool IsMSVCCompat = Args.hasFlag(
6078 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
6079 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
6080 options::OPT_fno_ms_extensions, true)));
6082 CmdArgs.push_back("-fms-compatibility");
6084 // Handle -fgcc-version, if present.
6085 VersionTuple GNUCVer;
6086 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
6087 // Check that the version has 1 to 3 components and the minor and patch
6088 // versions fit in two decimal digits.
6089 StringRef Val = A->getValue();
6090 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
6091 bool Invalid = GNUCVer.tryParse(Val);
6092 unsigned Minor = GNUCVer.getMinor().getValueOr(0);
6093 unsigned Patch = GNUCVer.getSubminor().getValueOr(0);
6094 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
6095 D.Diag(diag::err_drv_invalid_value)
6096 << A->getAsString(Args) << A->getValue();
6098 } else if (!IsMSVCCompat) {
6099 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
6100 GNUCVer = VersionTuple(4, 2, 1);
6102 if (!GNUCVer.empty()) {
6104 Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
6107 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
6110 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
6112 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
6113 if (ImplyVCPPCVer) {
6114 StringRef LanguageStandard;
6115 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6117 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6118 .Case("c11", "-std=c11")
6119 .Case("c17", "-std=c17")
6121 if (LanguageStandard.empty())
6122 D.Diag(clang::diag::warn_drv_unused_argument)
6123 << StdArg->getAsString(Args);
6125 CmdArgs.push_back(LanguageStandard.data());
6127 if (ImplyVCPPCXXVer) {
6128 StringRef LanguageStandard;
6129 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
6131 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
6132 .Case("c++14", "-std=c++14")
6133 .Case("c++17", "-std=c++17")
6134 .Case("c++20", "-std=c++20")
6135 .Case("c++latest", "-std=c++2b")
6137 if (LanguageStandard.empty())
6138 D.Diag(clang::diag::warn_drv_unused_argument)
6139 << StdArg->getAsString(Args);
6142 if (LanguageStandard.empty()) {
6143 if (IsMSVC2015Compatible)
6144 LanguageStandard = "-std=c++14";
6146 LanguageStandard = "-std=c++11";
6149 CmdArgs.push_back(LanguageStandard.data());
6152 // -fno-borland-extensions is default.
6153 if (Args.hasFlag(options::OPT_fborland_extensions,
6154 options::OPT_fno_borland_extensions, false))
6155 CmdArgs.push_back("-fborland-extensions");
6157 // -fno-declspec is default, except for PS4.
6158 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
6160 CmdArgs.push_back("-fdeclspec");
6161 else if (Args.hasArg(options::OPT_fno_declspec))
6162 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
6164 // -fthreadsafe-static is default, except for MSVC compatibility versions less
6166 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
6167 options::OPT_fno_threadsafe_statics,
6168 !IsWindowsMSVC || IsMSVC2015Compatible))
6169 CmdArgs.push_back("-fno-threadsafe-statics");
6171 // -fno-delayed-template-parsing is default, except when targeting MSVC.
6172 // Many old Windows SDK versions require this to parse.
6173 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
6174 // compiler. We should be able to disable this by default at some point.
6175 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
6176 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
6177 CmdArgs.push_back("-fdelayed-template-parsing");
6179 // -fgnu-keywords default varies depending on language; only pass if
6181 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
6182 options::OPT_fno_gnu_keywords);
6184 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
6186 CmdArgs.push_back("-fgnu89-inline");
6188 if (Args.hasArg(options::OPT_fno_inline))
6189 CmdArgs.push_back("-fno-inline");
6191 Args.AddLastArg(CmdArgs, options::OPT_finline_functions,
6192 options::OPT_finline_hint_functions,
6193 options::OPT_fno_inline_functions);
6195 // FIXME: Find a better way to determine whether the language has modules
6196 // support by default, or just assume that all languages do.
6198 Std && (Std->containsValue("c++2a") || Std->containsValue("c++20") ||
6199 Std->containsValue("c++latest"));
6200 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
6202 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
6203 options::OPT_fno_pch_validate_input_files_content, false))
6204 CmdArgs.push_back("-fvalidate-ast-input-files-content");
6205 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
6206 options::OPT_fno_pch_instantiate_templates, false))
6207 CmdArgs.push_back("-fpch-instantiate-templates");
6208 if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
6210 CmdArgs.push_back("-fmodules-codegen");
6211 if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
6213 CmdArgs.push_back("-fmodules-debuginfo");
6215 Args.AddLastArg(CmdArgs, options::OPT_flegacy_pass_manager,
6216 options::OPT_fno_legacy_pass_manager);
6218 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
6219 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
6222 if (types::isObjC(Input.getType()) &&
6223 Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
6224 options::OPT_fno_objc_encode_cxx_class_template_spec,
6225 !Runtime.isNeXTFamily()))
6226 CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
6228 if (Args.hasFlag(options::OPT_fapplication_extension,
6229 options::OPT_fno_application_extension, false))
6230 CmdArgs.push_back("-fapplication-extension");
6232 // Handle GCC-style exception args.
6234 if (!C.getDriver().IsCLMode())
6235 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
6237 // Handle exception personalities
6238 Arg *A = Args.getLastArg(
6239 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
6240 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
6242 const Option &Opt = A->getOption();
6243 if (Opt.matches(options::OPT_fsjlj_exceptions))
6244 CmdArgs.push_back("-exception-model=sjlj");
6245 if (Opt.matches(options::OPT_fseh_exceptions))
6246 CmdArgs.push_back("-exception-model=seh");
6247 if (Opt.matches(options::OPT_fdwarf_exceptions))
6248 CmdArgs.push_back("-exception-model=dwarf");
6249 if (Opt.matches(options::OPT_fwasm_exceptions))
6250 CmdArgs.push_back("-exception-model=wasm");
6252 switch (TC.GetExceptionModel(Args)) {
6255 case llvm::ExceptionHandling::DwarfCFI:
6256 CmdArgs.push_back("-exception-model=dwarf");
6258 case llvm::ExceptionHandling::SjLj:
6259 CmdArgs.push_back("-exception-model=sjlj");
6261 case llvm::ExceptionHandling::WinEH:
6262 CmdArgs.push_back("-exception-model=seh");
6267 // C++ "sane" operator new.
6268 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
6269 options::OPT_fno_assume_sane_operator_new))
6270 CmdArgs.push_back("-fno-assume-sane-operator-new");
6272 // -frelaxed-template-template-args is off by default, as it is a severe
6273 // breaking change until a corresponding change to template partial ordering
6275 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
6276 options::OPT_fno_relaxed_template_template_args, false))
6277 CmdArgs.push_back("-frelaxed-template-template-args");
6279 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
6281 if (Args.hasFlag(options::OPT_fsized_deallocation,
6282 options::OPT_fno_sized_deallocation, false))
6283 CmdArgs.push_back("-fsized-deallocation");
6285 // -faligned-allocation is on by default in C++17 onwards and otherwise off
6287 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
6288 options::OPT_fno_aligned_allocation,
6289 options::OPT_faligned_new_EQ)) {
6290 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
6291 CmdArgs.push_back("-fno-aligned-allocation");
6293 CmdArgs.push_back("-faligned-allocation");
6296 // The default new alignment can be specified using a dedicated option or via
6297 // a GCC-compatible option that also turns on aligned allocation.
6298 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
6299 options::OPT_faligned_new_EQ))
6301 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
6303 // -fconstant-cfstrings is default, and may be subject to argument translation
6305 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
6306 options::OPT_fno_constant_cfstrings) ||
6307 !Args.hasFlag(options::OPT_mconstant_cfstrings,
6308 options::OPT_mno_constant_cfstrings))
6309 CmdArgs.push_back("-fno-constant-cfstrings");
6311 // -fno-pascal-strings is default, only pass non-default.
6312 if (Args.hasFlag(options::OPT_fpascal_strings,
6313 options::OPT_fno_pascal_strings, false))
6314 CmdArgs.push_back("-fpascal-strings");
6316 // Honor -fpack-struct= and -fpack-struct, if given. Note that
6317 // -fno-pack-struct doesn't apply to -fpack-struct=.
6318 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
6319 std::string PackStructStr = "-fpack-struct=";
6320 PackStructStr += A->getValue();
6321 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
6322 } else if (Args.hasFlag(options::OPT_fpack_struct,
6323 options::OPT_fno_pack_struct, false)) {
6324 CmdArgs.push_back("-fpack-struct=1");
6327 // Handle -fmax-type-align=N and -fno-type-align
6328 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
6329 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
6330 if (!SkipMaxTypeAlign) {
6331 std::string MaxTypeAlignStr = "-fmax-type-align=";
6332 MaxTypeAlignStr += A->getValue();
6333 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
6335 } else if (RawTriple.isOSDarwin()) {
6336 if (!SkipMaxTypeAlign) {
6337 std::string MaxTypeAlignStr = "-fmax-type-align=16";
6338 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
6342 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
6343 CmdArgs.push_back("-Qn");
6345 // -fno-common is the default, set -fcommon only when that flag is set.
6346 if (Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common, false))
6347 CmdArgs.push_back("-fcommon");
6349 // -fsigned-bitfields is default, and clang doesn't yet support
6350 // -funsigned-bitfields.
6351 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
6352 options::OPT_funsigned_bitfields))
6353 D.Diag(diag::warn_drv_clang_unsupported)
6354 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
6356 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
6357 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
6358 D.Diag(diag::err_drv_clang_unsupported)
6359 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
6361 // -finput_charset=UTF-8 is default. Reject others
6362 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
6363 StringRef value = inputCharset->getValue();
6364 if (!value.equals_insensitive("utf-8"))
6365 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
6369 // -fexec_charset=UTF-8 is default. Reject others
6370 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
6371 StringRef value = execCharset->getValue();
6372 if (!value.equals_insensitive("utf-8"))
6373 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
6377 RenderDiagnosticsOptions(D, Args, CmdArgs);
6379 // -fno-asm-blocks is default.
6380 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
6382 CmdArgs.push_back("-fasm-blocks");
6384 // -fgnu-inline-asm is default.
6385 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
6386 options::OPT_fno_gnu_inline_asm, true))
6387 CmdArgs.push_back("-fno-gnu-inline-asm");
6389 // Enable vectorization per default according to the optimization level
6390 // selected. For optimization levels that want vectorization we use the alias
6391 // option to simplify the hasFlag logic.
6392 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
6393 OptSpecifier VectorizeAliasOption =
6394 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
6395 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
6396 options::OPT_fno_vectorize, EnableVec))
6397 CmdArgs.push_back("-vectorize-loops");
6399 // -fslp-vectorize is enabled based on the optimization level selected.
6400 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
6401 OptSpecifier SLPVectAliasOption =
6402 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
6403 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
6404 options::OPT_fno_slp_vectorize, EnableSLPVec))
6405 CmdArgs.push_back("-vectorize-slp");
6407 ParseMPreferVectorWidth(D, Args, CmdArgs);
6409 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
6410 Args.AddLastArg(CmdArgs,
6411 options::OPT_fsanitize_undefined_strip_path_components_EQ);
6413 // -fdollars-in-identifiers default varies depending on platform and
6414 // language; only pass if specified.
6415 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
6416 options::OPT_fno_dollars_in_identifiers)) {
6417 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
6418 CmdArgs.push_back("-fdollars-in-identifiers");
6420 CmdArgs.push_back("-fno-dollars-in-identifiers");
6423 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
6424 // practical purposes.
6425 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
6426 options::OPT_fno_unit_at_a_time)) {
6427 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
6428 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
6431 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
6432 options::OPT_fno_apple_pragma_pack, false))
6433 CmdArgs.push_back("-fapple-pragma-pack");
6435 if (Args.hasFlag(options::OPT_fxl_pragma_pack,
6436 options::OPT_fno_xl_pragma_pack, RawTriple.isOSAIX()))
6437 CmdArgs.push_back("-fxl-pragma-pack");
6439 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
6440 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
6441 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
6443 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
6444 options::OPT_fno_rewrite_imports, false);
6446 CmdArgs.push_back("-frewrite-imports");
6448 // Enable rewrite includes if the user's asked for it or if we're generating
6450 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
6451 // nice to enable this when doing a crashdump for modules as well.
6452 if (Args.hasFlag(options::OPT_frewrite_includes,
6453 options::OPT_fno_rewrite_includes, false) ||
6454 (C.isForDiagnostics() && !HaveModules))
6455 CmdArgs.push_back("-frewrite-includes");
6457 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
6458 if (Arg *A = Args.getLastArg(options::OPT_traditional,
6459 options::OPT_traditional_cpp)) {
6460 if (isa<PreprocessJobAction>(JA))
6461 CmdArgs.push_back("-traditional-cpp");
6463 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
6466 Args.AddLastArg(CmdArgs, options::OPT_dM);
6467 Args.AddLastArg(CmdArgs, options::OPT_dD);
6469 Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
6471 // Handle serialized diagnostics.
6472 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
6473 CmdArgs.push_back("-serialize-diagnostic-file");
6474 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
6477 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
6478 CmdArgs.push_back("-fretain-comments-from-system-headers");
6480 // Forward -fcomment-block-commands to -cc1.
6481 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
6482 // Forward -fparse-all-comments to -cc1.
6483 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
6485 // Turn -fplugin=name.so into -load name.so
6486 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
6487 CmdArgs.push_back("-load");
6488 CmdArgs.push_back(A->getValue());
6492 // Forward -fpass-plugin=name.so to -cc1.
6493 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
6495 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
6499 // Setup statistics file output.
6500 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
6501 if (!StatsFile.empty())
6502 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
6504 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
6506 // -finclude-default-header flag is for preprocessor,
6507 // do not pass it to other cc1 commands when save-temps is enabled
6508 if (C.getDriver().isSaveTempsEnabled() &&
6509 !isa<PreprocessJobAction>(JA)) {
6510 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
6512 if (StringRef(Arg->getValue()) != "-finclude-default-header")
6513 CmdArgs.push_back(Arg->getValue());
6517 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
6519 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
6522 // We translate this by hand to the -cc1 argument, since nightly test uses
6523 // it and developers have been trained to spell it with -mllvm. Both
6524 // spellings are now deprecated and should be removed.
6525 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
6526 CmdArgs.push_back("-disable-llvm-optzns");
6528 A->render(Args, CmdArgs);
6532 // With -save-temps, we want to save the unoptimized bitcode output from the
6533 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
6535 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
6536 // has slightly different breakdown between stages.
6537 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
6538 // pristine IR generated by the frontend. Ideally, a new compile action should
6539 // be added so both IR can be captured.
6540 if ((C.getDriver().isSaveTempsEnabled() ||
6541 JA.isHostOffloading(Action::OFK_OpenMP)) &&
6542 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
6543 isa<CompileJobAction>(JA))
6544 CmdArgs.push_back("-disable-llvm-passes");
6546 Args.AddAllArgs(CmdArgs, options::OPT_undef);
6548 const char *Exec = D.getClangProgramPath();
6550 // Optionally embed the -cc1 level arguments into the debug info or a
6551 // section, for build analysis.
6552 // Also record command line arguments into the debug info if
6553 // -grecord-gcc-switches options is set on.
6554 // By default, -gno-record-gcc-switches is set on and no recording.
6555 auto GRecordSwitches =
6556 Args.hasFlag(options::OPT_grecord_command_line,
6557 options::OPT_gno_record_command_line, false);
6558 auto FRecordSwitches =
6559 Args.hasFlag(options::OPT_frecord_command_line,
6560 options::OPT_fno_record_command_line, false);
6561 if (FRecordSwitches && !Triple.isOSBinFormatELF())
6562 D.Diag(diag::err_drv_unsupported_opt_for_target)
6563 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
6565 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
6566 ArgStringList OriginalArgs;
6567 for (const auto &Arg : Args)
6568 Arg->render(Args, OriginalArgs);
6570 SmallString<256> Flags;
6571 EscapeSpacesAndBackslashes(Exec, Flags);
6572 for (const char *OriginalArg : OriginalArgs) {
6573 SmallString<128> EscapedArg;
6574 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6576 Flags += EscapedArg;
6578 auto FlagsArgString = Args.MakeArgString(Flags);
6579 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
6580 CmdArgs.push_back("-dwarf-debug-flags");
6581 CmdArgs.push_back(FlagsArgString);
6583 if (FRecordSwitches) {
6584 CmdArgs.push_back("-record-command-line");
6585 CmdArgs.push_back(FlagsArgString);
6589 // Host-side cuda compilation receives all device-side outputs in a single
6590 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
6591 if ((IsCuda || IsHIP) && CudaDeviceInput) {
6592 CmdArgs.push_back("-fcuda-include-gpubinary");
6593 CmdArgs.push_back(CudaDeviceInput->getFilename());
6594 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
6595 CmdArgs.push_back("-fgpu-rdc");
6599 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
6600 options::OPT_fno_cuda_short_ptr, false))
6601 CmdArgs.push_back("-fcuda-short-ptr");
6604 if (IsCuda || IsHIP) {
6605 // Determine the original source input.
6606 const Action *SourceAction = &JA;
6607 while (SourceAction->getKind() != Action::InputClass) {
6608 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6609 SourceAction = SourceAction->getInputs()[0];
6611 auto CUID = cast<InputAction>(SourceAction)->getId();
6613 CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
6617 CmdArgs.push_back("-fcuda-allow-variadic-functions");
6619 if (IsCudaDevice || IsHIPDevice) {
6620 StringRef InlineThresh =
6621 Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
6622 if (!InlineThresh.empty()) {
6623 std::string ArgStr =
6624 std::string("-inline-threshold=") + InlineThresh.str();
6625 CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
6629 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
6630 // to specify the result of the compile phase on the host, so the meaningful
6631 // device declarations can be identified. Also, -fopenmp-is-device is passed
6632 // along to tell the frontend that it is generating code for a device, so that
6633 // only the relevant declarations are emitted.
6634 if (IsOpenMPDevice) {
6635 CmdArgs.push_back("-fopenmp-is-device");
6636 if (OpenMPDeviceInput) {
6637 CmdArgs.push_back("-fopenmp-host-ir-file-path");
6638 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
6642 if (Triple.isAMDGPU()) {
6643 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
6645 if (Args.hasFlag(options::OPT_munsafe_fp_atomics,
6646 options::OPT_mno_unsafe_fp_atomics, /*Default=*/false))
6647 CmdArgs.push_back("-munsafe-fp-atomics");
6650 // For all the host OpenMP offloading compile jobs we need to pass the targets
6651 // information using -fopenmp-targets= option.
6652 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
6653 SmallString<128> TargetInfo("-fopenmp-targets=");
6655 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
6656 assert(Tgts && Tgts->getNumValues() &&
6657 "OpenMP offloading has to have targets specified.");
6658 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
6661 // We need to get the string from the triple because it may be not exactly
6662 // the same as the one we get directly from the arguments.
6663 llvm::Triple T(Tgts->getValue(i));
6664 TargetInfo += T.getTriple();
6666 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
6669 bool VirtualFunctionElimination =
6670 Args.hasFlag(options::OPT_fvirtual_function_elimination,
6671 options::OPT_fno_virtual_function_elimination, false);
6672 if (VirtualFunctionElimination) {
6673 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
6675 if (LTOMode != LTOK_Full)
6676 D.Diag(diag::err_drv_argument_only_allowed_with)
6677 << "-fvirtual-function-elimination"
6680 CmdArgs.push_back("-fvirtual-function-elimination");
6683 // VFE requires whole-program-vtables, and enables it by default.
6684 bool WholeProgramVTables = Args.hasFlag(
6685 options::OPT_fwhole_program_vtables,
6686 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
6687 if (VirtualFunctionElimination && !WholeProgramVTables) {
6688 D.Diag(diag::err_drv_argument_not_allowed_with)
6689 << "-fno-whole-program-vtables"
6690 << "-fvirtual-function-elimination";
6693 if (WholeProgramVTables) {
6694 // Propagate -fwhole-program-vtables if this is an LTO compile.
6696 CmdArgs.push_back("-fwhole-program-vtables");
6697 // Check if we passed LTO options but they were suppressed because this is a
6698 // device offloading action, or we passed device offload LTO options which
6699 // were suppressed because this is not the device offload action.
6700 // Otherwise, issue an error.
6701 else if (!D.isUsingLTO(!IsDeviceOffloadAction))
6702 D.Diag(diag::err_drv_argument_only_allowed_with)
6703 << "-fwhole-program-vtables"
6707 bool DefaultsSplitLTOUnit =
6708 (WholeProgramVTables || Sanitize.needsLTO()) &&
6709 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit());
6711 Args.hasFlag(options::OPT_fsplit_lto_unit,
6712 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
6713 if (Sanitize.needsLTO() && !SplitLTOUnit)
6714 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
6715 << "-fsanitize=cfi";
6717 CmdArgs.push_back("-fsplit-lto-unit");
6719 if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
6720 options::OPT_fno_global_isel)) {
6721 CmdArgs.push_back("-mllvm");
6722 if (A->getOption().matches(options::OPT_fglobal_isel)) {
6723 CmdArgs.push_back("-global-isel=1");
6725 // GISel is on by default on AArch64 -O0, so don't bother adding
6726 // the fallback remarks for it. Other combinations will add a warning of
6728 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
6729 bool IsOptLevelSupported = false;
6731 Arg *A = Args.getLastArg(options::OPT_O_Group);
6732 if (Triple.getArch() == llvm::Triple::aarch64) {
6733 if (!A || A->getOption().matches(options::OPT_O0))
6734 IsOptLevelSupported = true;
6736 if (!IsArchSupported || !IsOptLevelSupported) {
6737 CmdArgs.push_back("-mllvm");
6738 CmdArgs.push_back("-global-isel-abort=2");
6740 if (!IsArchSupported)
6741 D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName();
6743 D.Diag(diag::warn_drv_global_isel_incomplete_opt);
6746 CmdArgs.push_back("-global-isel=0");
6750 if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
6751 CmdArgs.push_back("-forder-file-instrumentation");
6752 // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
6753 // on, we need to pass these flags as linker flags and that will be handled
6754 // outside of the compiler.
6756 CmdArgs.push_back("-mllvm");
6757 CmdArgs.push_back("-enable-order-file-instrumentation");
6761 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
6762 options::OPT_fno_force_enable_int128)) {
6763 if (A->getOption().matches(options::OPT_fforce_enable_int128))
6764 CmdArgs.push_back("-fforce-enable-int128");
6767 if (Args.hasFlag(options::OPT_fkeep_static_consts,
6768 options::OPT_fno_keep_static_consts, false))
6769 CmdArgs.push_back("-fkeep-static-consts");
6771 if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
6772 options::OPT_fno_complete_member_pointers, false))
6773 CmdArgs.push_back("-fcomplete-member-pointers");
6775 if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
6776 options::OPT_fno_cxx_static_destructors, true))
6777 CmdArgs.push_back("-fno-c++-static-destructors");
6779 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
6781 if (Arg *A = Args.getLastArg(options::OPT_moutline_atomics,
6782 options::OPT_mno_outline_atomics)) {
6783 if (A->getOption().matches(options::OPT_moutline_atomics)) {
6784 // Option -moutline-atomics supported for AArch64 target only.
6785 if (!Triple.isAArch64()) {
6786 D.Diag(diag::warn_drv_moutline_atomics_unsupported_opt)
6787 << Triple.getArchName();
6789 CmdArgs.push_back("-target-feature");
6790 CmdArgs.push_back("+outline-atomics");
6793 CmdArgs.push_back("-target-feature");
6794 CmdArgs.push_back("-outline-atomics");
6796 } else if (Triple.isAArch64() &&
6797 getToolChain().IsAArch64OutlineAtomicsDefault(Args)) {
6798 CmdArgs.push_back("-target-feature");
6799 CmdArgs.push_back("+outline-atomics");
6802 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
6803 (TC.getTriple().isOSBinFormatELF() ||
6804 TC.getTriple().isOSBinFormatCOFF()) &&
6805 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
6806 !TC.getTriple().isOSNetBSD() &&
6807 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
6808 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
6809 CmdArgs.push_back("-faddrsig");
6811 if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
6812 (EH || UnwindTables || DebugInfoKind != codegenoptions::NoDebugInfo))
6813 CmdArgs.push_back("-D__GCC_HAVE_DWARF2_CFI_ASM=1");
6815 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
6816 std::string Str = A->getAsString(Args);
6817 if (!TC.getTriple().isOSBinFormatELF())
6818 D.Diag(diag::err_drv_unsupported_opt_for_target)
6819 << Str << TC.getTripleString();
6820 CmdArgs.push_back(Args.MakeArgString(Str));
6823 // Add the "-o out -x type src.c" flags last. This is done primarily to make
6824 // the -cc1 command easier to edit when reproducing compiler crashes.
6825 if (Output.getType() == types::TY_Dependencies) {
6826 // Handled with other dependency code.
6827 } else if (Output.isFilename()) {
6828 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
6829 Output.getType() == clang::driver::types::TY_IFS) {
6830 SmallString<128> OutputFilename(Output.getFilename());
6831 llvm::sys::path::replace_extension(OutputFilename, "ifs");
6832 CmdArgs.push_back("-o");
6833 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6835 CmdArgs.push_back("-o");
6836 CmdArgs.push_back(Output.getFilename());
6839 assert(Output.isNothing() && "Invalid output.");
6842 addDashXForInput(Args, Input, CmdArgs);
6844 ArrayRef<InputInfo> FrontendInputs = Input;
6845 if (IsHeaderModulePrecompile)
6846 FrontendInputs = ModuleHeaderInputs;
6847 else if (Input.isNothing())
6848 FrontendInputs = {};
6850 for (const InputInfo &Input : FrontendInputs) {
6851 if (Input.isFilename())
6852 CmdArgs.push_back(Input.getFilename());
6854 Input.getInputArg().renderAsInput(Args, CmdArgs);
6857 if (D.CC1Main && !D.CCGenDiagnostics) {
6858 // Invoke the CC1 directly in this process
6859 C.addCommand(std::make_unique<CC1Command>(JA, *this,
6860 ResponseFileSupport::AtFileUTF8(),
6861 Exec, CmdArgs, Inputs, Output));
6863 C.addCommand(std::make_unique<Command>(JA, *this,
6864 ResponseFileSupport::AtFileUTF8(),
6865 Exec, CmdArgs, Inputs, Output));
6868 // Make the compile command echo its inputs for /showFilenames.
6869 if (Output.getType() == types::TY_Object &&
6870 Args.hasFlag(options::OPT__SLASH_showFilenames,
6871 options::OPT__SLASH_showFilenames_, false)) {
6872 C.getJobs().getJobs().back()->PrintInputFilenames = true;
6875 if (Arg *A = Args.getLastArg(options::OPT_pg))
6876 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
6877 !Args.hasArg(options::OPT_mfentry))
6878 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
6879 << A->getAsString(Args);
6881 // Claim some arguments which clang supports automatically.
6883 // -fpch-preprocess is used with gcc to add a special marker in the output to
6884 // include the PCH file.
6885 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
6887 // Claim some arguments which clang doesn't support, but we don't
6888 // care to warn the user about.
6889 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
6890 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
6892 // Disable warnings for clang -E -emit-llvm foo.c
6893 Args.ClaimAllArgs(options::OPT_emit_llvm);
6896 Clang::Clang(const ToolChain &TC)
6897 // CAUTION! The first constructor argument ("clang") is not arbitrary,
6898 // as it is for other tools. Some operations on a Tool actually test
6899 // whether that tool is Clang based on the Tool's Name as a string.
6900 : Tool("clang", "clang frontend", TC) {}
6904 /// Add options related to the Objective-C runtime/ABI.
6906 /// Returns true if the runtime is non-fragile.
6907 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
6908 const InputInfoList &inputs,
6909 ArgStringList &cmdArgs,
6910 RewriteKind rewriteKind) const {
6911 // Look for the controlling runtime option.
6913 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
6914 options::OPT_fobjc_runtime_EQ);
6916 // Just forward -fobjc-runtime= to the frontend. This supercedes
6917 // options about fragility.
6919 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
6920 ObjCRuntime runtime;
6921 StringRef value = runtimeArg->getValue();
6922 if (runtime.tryParse(value)) {
6923 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
6926 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
6927 (runtime.getVersion() >= VersionTuple(2, 0)))
6928 if (!getToolChain().getTriple().isOSBinFormatELF() &&
6929 !getToolChain().getTriple().isOSBinFormatCOFF()) {
6930 getToolChain().getDriver().Diag(
6931 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
6932 << runtime.getVersion().getMajor();
6935 runtimeArg->render(args, cmdArgs);
6939 // Otherwise, we'll need the ABI "version". Version numbers are
6940 // slightly confusing for historical reasons:
6941 // 1 - Traditional "fragile" ABI
6942 // 2 - Non-fragile ABI, version 1
6943 // 3 - Non-fragile ABI, version 2
6944 unsigned objcABIVersion = 1;
6945 // If -fobjc-abi-version= is present, use that to set the version.
6946 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
6947 StringRef value = abiArg->getValue();
6950 else if (value == "2")
6952 else if (value == "3")
6955 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
6957 // Otherwise, determine if we are using the non-fragile ABI.
6958 bool nonFragileABIIsDefault =
6959 (rewriteKind == RK_NonFragile ||
6960 (rewriteKind == RK_None &&
6961 getToolChain().IsObjCNonFragileABIDefault()));
6962 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
6963 options::OPT_fno_objc_nonfragile_abi,
6964 nonFragileABIIsDefault)) {
6965 // Determine the non-fragile ABI version to use.
6966 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
6967 unsigned nonFragileABIVersion = 1;
6969 unsigned nonFragileABIVersion = 2;
6973 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
6974 StringRef value = abiArg->getValue();
6976 nonFragileABIVersion = 1;
6977 else if (value == "2")
6978 nonFragileABIVersion = 2;
6980 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
6984 objcABIVersion = 1 + nonFragileABIVersion;
6990 // We don't actually care about the ABI version other than whether
6991 // it's non-fragile.
6992 bool isNonFragile = objcABIVersion != 1;
6994 // If we have no runtime argument, ask the toolchain for its default runtime.
6995 // However, the rewriter only really supports the Mac runtime, so assume that.
6996 ObjCRuntime runtime;
6998 switch (rewriteKind) {
7000 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
7003 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
7006 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
7011 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
7012 // On Darwin, make this use the default behavior for the toolchain.
7013 if (getToolChain().getTriple().isOSDarwin()) {
7014 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
7016 // Otherwise, build for a generic macosx port.
7018 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
7023 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
7024 // Legacy behaviour is to target the gnustep runtime if we are in
7025 // non-fragile mode or the GCC runtime in fragile mode.
7027 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
7029 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
7032 if (llvm::any_of(inputs, [](const InputInfo &input) {
7033 return types::isObjC(input.getType());
7036 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
7040 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
7041 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
7049 bool Asynch = false;
7050 bool NoUnwindC = false;
7052 } // end anonymous namespace
7054 /// /EH controls whether to run destructor cleanups when exceptions are
7055 /// thrown. There are three modifiers:
7056 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
7057 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
7058 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
7059 /// - c: Assume that extern "C" functions are implicitly nounwind.
7060 /// The default is /EHs-c-, meaning cleanups are disabled.
7061 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
7064 std::vector<std::string> EHArgs =
7065 Args.getAllArgValues(options::OPT__SLASH_EH);
7066 for (auto EHVal : EHArgs) {
7067 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
7070 EH.Asynch = maybeConsumeDash(EHVal, I);
7075 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
7078 EH.Synch = maybeConsumeDash(EHVal, I);
7085 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
7089 // The /GX, /GX- flags are only processed if there are not /EH flags.
7090 // The default is that /GX is not specified.
7091 if (EHArgs.empty() &&
7092 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
7093 /*Default=*/false)) {
7095 EH.NoUnwindC = true;
7101 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
7102 ArgStringList &CmdArgs,
7103 codegenoptions::DebugInfoKind *DebugInfoKind,
7104 bool *EmitCodeView) const {
7105 unsigned RTOptionID = options::OPT__SLASH_MT;
7106 bool isNVPTX = getToolChain().getTriple().isNVPTX();
7108 if (Args.hasArg(options::OPT__SLASH_LDd))
7109 // The /LDd option implies /MTd. The dependent lib part can be overridden,
7110 // but defining _DEBUG is sticky.
7111 RTOptionID = options::OPT__SLASH_MTd;
7113 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
7114 RTOptionID = A->getOption().getID();
7116 StringRef FlagForCRT;
7117 switch (RTOptionID) {
7118 case options::OPT__SLASH_MD:
7119 if (Args.hasArg(options::OPT__SLASH_LDd))
7120 CmdArgs.push_back("-D_DEBUG");
7121 CmdArgs.push_back("-D_MT");
7122 CmdArgs.push_back("-D_DLL");
7123 FlagForCRT = "--dependent-lib=msvcrt";
7125 case options::OPT__SLASH_MDd:
7126 CmdArgs.push_back("-D_DEBUG");
7127 CmdArgs.push_back("-D_MT");
7128 CmdArgs.push_back("-D_DLL");
7129 FlagForCRT = "--dependent-lib=msvcrtd";
7131 case options::OPT__SLASH_MT:
7132 if (Args.hasArg(options::OPT__SLASH_LDd))
7133 CmdArgs.push_back("-D_DEBUG");
7134 CmdArgs.push_back("-D_MT");
7135 CmdArgs.push_back("-flto-visibility-public-std");
7136 FlagForCRT = "--dependent-lib=libcmt";
7138 case options::OPT__SLASH_MTd:
7139 CmdArgs.push_back("-D_DEBUG");
7140 CmdArgs.push_back("-D_MT");
7141 CmdArgs.push_back("-flto-visibility-public-std");
7142 FlagForCRT = "--dependent-lib=libcmtd";
7145 llvm_unreachable("Unexpected option ID.");
7148 if (Args.hasArg(options::OPT__SLASH_Zl)) {
7149 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
7151 CmdArgs.push_back(FlagForCRT.data());
7153 // This provides POSIX compatibility (maps 'open' to '_open'), which most
7154 // users want. The /Za flag to cl.exe turns this off, but it's not
7155 // implemented in clang.
7156 CmdArgs.push_back("--dependent-lib=oldnames");
7159 if (Arg *ShowIncludes =
7160 Args.getLastArg(options::OPT__SLASH_showIncludes,
7161 options::OPT__SLASH_showIncludes_user)) {
7162 CmdArgs.push_back("--show-includes");
7163 if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
7164 CmdArgs.push_back("-sys-header-deps");
7167 // This controls whether or not we emit RTTI data for polymorphic types.
7168 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
7170 CmdArgs.push_back("-fno-rtti-data");
7172 // This controls whether or not we emit stack-protector instrumentation.
7173 // In MSVC, Buffer Security Check (/GS) is on by default.
7174 if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
7175 /*Default=*/true)) {
7176 CmdArgs.push_back("-stack-protector");
7177 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
7180 // Emit CodeView if -Z7 or -gline-tables-only are present.
7181 if (Arg *DebugInfoArg = Args.getLastArg(options::OPT__SLASH_Z7,
7182 options::OPT_gline_tables_only)) {
7183 *EmitCodeView = true;
7184 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
7185 *DebugInfoKind = codegenoptions::DebugInfoConstructor;
7187 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
7189 *EmitCodeView = false;
7192 const Driver &D = getToolChain().getDriver();
7193 EHFlags EH = parseClangCLEHFlags(D, Args);
7194 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
7195 if (types::isCXX(InputType))
7196 CmdArgs.push_back("-fcxx-exceptions");
7197 CmdArgs.push_back("-fexceptions");
7199 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
7200 CmdArgs.push_back("-fexternc-nounwind");
7202 // /EP should expand to -E -P.
7203 if (Args.hasArg(options::OPT__SLASH_EP)) {
7204 CmdArgs.push_back("-E");
7205 CmdArgs.push_back("-P");
7208 unsigned VolatileOptionID;
7209 if (getToolChain().getTriple().isX86())
7210 VolatileOptionID = options::OPT__SLASH_volatile_ms;
7212 VolatileOptionID = options::OPT__SLASH_volatile_iso;
7214 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
7215 VolatileOptionID = A->getOption().getID();
7217 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
7218 CmdArgs.push_back("-fms-volatile");
7220 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
7221 options::OPT__SLASH_Zc_dllexportInlines,
7223 CmdArgs.push_back("-fno-dllexport-inlines");
7226 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
7227 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
7228 if (MostGeneralArg && BestCaseArg)
7229 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
7230 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
7232 if (MostGeneralArg) {
7233 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
7234 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
7235 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
7237 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
7238 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
7239 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
7240 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
7241 << FirstConflict->getAsString(Args)
7242 << SecondConflict->getAsString(Args);
7245 CmdArgs.push_back("-fms-memptr-rep=single");
7246 else if (MultipleArg)
7247 CmdArgs.push_back("-fms-memptr-rep=multiple");
7249 CmdArgs.push_back("-fms-memptr-rep=virtual");
7252 // Parse the default calling convention options.
7254 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
7255 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
7256 options::OPT__SLASH_Gregcall)) {
7257 unsigned DCCOptId = CCArg->getOption().getID();
7258 const char *DCCFlag = nullptr;
7259 bool ArchSupported = !isNVPTX;
7260 llvm::Triple::ArchType Arch = getToolChain().getArch();
7262 case options::OPT__SLASH_Gd:
7263 DCCFlag = "-fdefault-calling-conv=cdecl";
7265 case options::OPT__SLASH_Gr:
7266 ArchSupported = Arch == llvm::Triple::x86;
7267 DCCFlag = "-fdefault-calling-conv=fastcall";
7269 case options::OPT__SLASH_Gz:
7270 ArchSupported = Arch == llvm::Triple::x86;
7271 DCCFlag = "-fdefault-calling-conv=stdcall";
7273 case options::OPT__SLASH_Gv:
7274 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
7275 DCCFlag = "-fdefault-calling-conv=vectorcall";
7277 case options::OPT__SLASH_Gregcall:
7278 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
7279 DCCFlag = "-fdefault-calling-conv=regcall";
7283 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
7284 if (ArchSupported && DCCFlag)
7285 CmdArgs.push_back(DCCFlag);
7288 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
7290 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
7291 CmdArgs.push_back("-fdiagnostics-format");
7292 CmdArgs.push_back("msvc");
7295 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
7296 StringRef GuardArgs = A->getValue();
7297 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
7299 if (GuardArgs.equals_insensitive("cf")) {
7300 // Emit CFG instrumentation and the table of address-taken functions.
7301 CmdArgs.push_back("-cfguard");
7302 } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
7303 // Emit only the table of address-taken functions.
7304 CmdArgs.push_back("-cfguard-no-checks");
7305 } else if (GuardArgs.equals_insensitive("ehcont")) {
7306 // Emit EH continuation table.
7307 CmdArgs.push_back("-ehcontguard");
7308 } else if (GuardArgs.equals_insensitive("cf-") ||
7309 GuardArgs.equals_insensitive("ehcont-")) {
7310 // Do nothing, but we might want to emit a security warning in future.
7312 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
7317 const char *Clang::getBaseInputName(const ArgList &Args,
7318 const InputInfo &Input) {
7319 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
7322 const char *Clang::getBaseInputStem(const ArgList &Args,
7323 const InputInfoList &Inputs) {
7324 const char *Str = getBaseInputName(Args, Inputs[0]);
7326 if (const char *End = strrchr(Str, '.'))
7327 return Args.MakeArgString(std::string(Str, End));
7332 const char *Clang::getDependencyFileName(const ArgList &Args,
7333 const InputInfoList &Inputs) {
7334 // FIXME: Think about this more.
7336 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
7337 SmallString<128> OutputFilename(OutputOpt->getValue());
7338 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
7339 return Args.MakeArgString(OutputFilename);
7342 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
7347 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
7348 ArgStringList &CmdArgs) const {
7351 const llvm::Triple &Triple = getToolChain().getTriple();
7352 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
7354 CmdArgs.push_back("-target-abi");
7355 CmdArgs.push_back(ABIName.data());
7358 void ClangAs::AddX86TargetArgs(const ArgList &Args,
7359 ArgStringList &CmdArgs) const {
7360 addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
7363 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
7364 StringRef Value = A->getValue();
7365 if (Value == "intel" || Value == "att") {
7366 CmdArgs.push_back("-mllvm");
7367 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
7369 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
7370 << A->getOption().getName() << Value;
7375 void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
7376 ArgStringList &CmdArgs) const {
7377 const llvm::Triple &Triple = getToolChain().getTriple();
7378 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
7380 CmdArgs.push_back("-target-abi");
7381 CmdArgs.push_back(ABIName.data());
7384 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
7385 const InputInfo &Output, const InputInfoList &Inputs,
7386 const ArgList &Args,
7387 const char *LinkingOutput) const {
7388 ArgStringList CmdArgs;
7390 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
7391 const InputInfo &Input = Inputs[0];
7393 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
7394 const std::string &TripleStr = Triple.getTriple();
7395 const auto &D = getToolChain().getDriver();
7397 // Don't warn about "clang -w -c foo.s"
7398 Args.ClaimAllArgs(options::OPT_w);
7399 // and "clang -emit-llvm -c foo.s"
7400 Args.ClaimAllArgs(options::OPT_emit_llvm);
7402 claimNoWarnArgs(Args);
7404 // Invoke ourselves in -cc1as mode.
7406 // FIXME: Implement custom jobs for internal actions.
7407 CmdArgs.push_back("-cc1as");
7409 // Add the "effective" target triple.
7410 CmdArgs.push_back("-triple");
7411 CmdArgs.push_back(Args.MakeArgString(TripleStr));
7413 // Set the output mode, we currently only expect to be used as a real
7415 CmdArgs.push_back("-filetype");
7416 CmdArgs.push_back("obj");
7418 // Set the main file name, so that debug info works even with
7419 // -save-temps or preprocessed assembly.
7420 CmdArgs.push_back("-main-file-name");
7421 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
7423 // Add the target cpu
7424 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
7426 CmdArgs.push_back("-target-cpu");
7427 CmdArgs.push_back(Args.MakeArgString(CPU));
7430 // Add the target features
7431 getTargetFeatures(D, Triple, Args, CmdArgs, true);
7433 // Ignore explicit -force_cpusubtype_ALL option.
7434 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
7436 // Pass along any -I options so we get proper .include search paths.
7437 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
7439 // Determine the original source input.
7440 const Action *SourceAction = &JA;
7441 while (SourceAction->getKind() != Action::InputClass) {
7442 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7443 SourceAction = SourceAction->getInputs()[0];
7446 // Forward -g and handle debug info related flags, assuming we are dealing
7447 // with an actual assembly file.
7448 bool WantDebug = false;
7449 Args.ClaimAllArgs(options::OPT_g_Group);
7450 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
7451 WantDebug = !A->getOption().matches(options::OPT_g0) &&
7452 !A->getOption().matches(options::OPT_ggdb0);
7454 unsigned DwarfVersion = ParseDebugDefaultVersion(getToolChain(), Args);
7455 if (const Arg *GDwarfN = getDwarfNArg(Args))
7456 DwarfVersion = DwarfVersionNum(GDwarfN->getSpelling());
7458 if (DwarfVersion == 0)
7459 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
7461 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
7463 if (SourceAction->getType() == types::TY_Asm ||
7464 SourceAction->getType() == types::TY_PP_Asm) {
7465 // You might think that it would be ok to set DebugInfoKind outside of
7466 // the guard for source type, however there is a test which asserts
7467 // that some assembler invocation receives no -debug-info-kind,
7468 // and it's not clear whether that test is just overly restrictive.
7469 DebugInfoKind = (WantDebug ? codegenoptions::DebugInfoConstructor
7470 : codegenoptions::NoDebugInfo);
7471 // Add the -fdebug-compilation-dir flag if needed.
7472 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
7474 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
7476 // Set the AT_producer to the clang version when using the integrated
7477 // assembler on assembly source files.
7478 CmdArgs.push_back("-dwarf-debug-producer");
7479 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
7481 // And pass along -I options
7482 Args.AddAllArgs(CmdArgs, options::OPT_I);
7484 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
7485 llvm::DebuggerKind::Default);
7486 renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
7487 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
7490 // Handle -fPIC et al -- the relocation-model affects the assembler
7491 // for some targets.
7492 llvm::Reloc::Model RelocationModel;
7495 std::tie(RelocationModel, PICLevel, IsPIE) =
7496 ParsePICArgs(getToolChain(), Args);
7498 const char *RMName = RelocationModelName(RelocationModel);
7500 CmdArgs.push_back("-mrelocation-model");
7501 CmdArgs.push_back(RMName);
7504 // Optionally embed the -cc1as level arguments into the debug info, for build
7506 if (getToolChain().UseDwarfDebugFlags()) {
7507 ArgStringList OriginalArgs;
7508 for (const auto &Arg : Args)
7509 Arg->render(Args, OriginalArgs);
7511 SmallString<256> Flags;
7512 const char *Exec = getToolChain().getDriver().getClangProgramPath();
7513 EscapeSpacesAndBackslashes(Exec, Flags);
7514 for (const char *OriginalArg : OriginalArgs) {
7515 SmallString<128> EscapedArg;
7516 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
7518 Flags += EscapedArg;
7520 CmdArgs.push_back("-dwarf-debug-flags");
7521 CmdArgs.push_back(Args.MakeArgString(Flags));
7524 // FIXME: Add -static support, once we have it.
7526 // Add target specific flags.
7527 switch (getToolChain().getArch()) {
7531 case llvm::Triple::mips:
7532 case llvm::Triple::mipsel:
7533 case llvm::Triple::mips64:
7534 case llvm::Triple::mips64el:
7535 AddMIPSTargetArgs(Args, CmdArgs);
7538 case llvm::Triple::x86:
7539 case llvm::Triple::x86_64:
7540 AddX86TargetArgs(Args, CmdArgs);
7543 case llvm::Triple::arm:
7544 case llvm::Triple::armeb:
7545 case llvm::Triple::thumb:
7546 case llvm::Triple::thumbeb:
7547 // This isn't in AddARMTargetArgs because we want to do this for assembly
7549 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
7550 options::OPT_mno_default_build_attributes, true)) {
7551 CmdArgs.push_back("-mllvm");
7552 CmdArgs.push_back("-arm-add-build-attributes");
7556 case llvm::Triple::aarch64:
7557 case llvm::Triple::aarch64_32:
7558 case llvm::Triple::aarch64_be:
7559 if (Args.hasArg(options::OPT_mmark_bti_property)) {
7560 CmdArgs.push_back("-mllvm");
7561 CmdArgs.push_back("-aarch64-mark-bti-property");
7565 case llvm::Triple::riscv32:
7566 case llvm::Triple::riscv64:
7567 AddRISCVTargetArgs(Args, CmdArgs);
7571 // Consume all the warning flags. Usually this would be handled more
7572 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
7573 // doesn't handle that so rather than warning about unused flags that are
7574 // actually used, we'll lie by omission instead.
7575 // FIXME: Stop lying and consume only the appropriate driver flags
7576 Args.ClaimAllArgs(options::OPT_W_Group);
7578 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
7579 getToolChain().getDriver());
7581 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
7583 assert(Output.isFilename() && "Unexpected lipo output.");
7584 CmdArgs.push_back("-o");
7585 CmdArgs.push_back(Output.getFilename());
7587 const llvm::Triple &T = getToolChain().getTriple();
7589 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
7590 T.isOSBinFormatELF()) {
7591 CmdArgs.push_back("-split-dwarf-output");
7592 CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
7595 if (Triple.isAMDGPU())
7596 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
7598 assert(Input.isFilename() && "Invalid input.");
7599 CmdArgs.push_back(Input.getFilename());
7601 const char *Exec = getToolChain().getDriver().getClangProgramPath();
7602 if (D.CC1Main && !D.CCGenDiagnostics) {
7603 // Invoke cc1as directly in this process.
7604 C.addCommand(std::make_unique<CC1Command>(JA, *this,
7605 ResponseFileSupport::AtFileUTF8(),
7606 Exec, CmdArgs, Inputs, Output));
7608 C.addCommand(std::make_unique<Command>(JA, *this,
7609 ResponseFileSupport::AtFileUTF8(),
7610 Exec, CmdArgs, Inputs, Output));
7614 // Begin OffloadBundler
7616 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
7617 const InputInfo &Output,
7618 const InputInfoList &Inputs,
7619 const llvm::opt::ArgList &TCArgs,
7620 const char *LinkingOutput) const {
7621 // The version with only one output is expected to refer to a bundling job.
7622 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
7624 // The bundling command looks like this:
7625 // clang-offload-bundler -type=bc
7626 // -targets=host-triple,openmp-triple1,openmp-triple2
7627 // -outputs=input_file
7628 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
7630 ArgStringList CmdArgs;
7633 CmdArgs.push_back(TCArgs.MakeArgString(
7634 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
7636 assert(JA.getInputs().size() == Inputs.size() &&
7637 "Not have inputs for all dependence actions??");
7640 SmallString<128> Triples;
7641 Triples += "-targets=";
7642 for (unsigned I = 0; I < Inputs.size(); ++I) {
7646 // Find ToolChain for this input.
7647 Action::OffloadKind CurKind = Action::OFK_Host;
7648 const ToolChain *CurTC = &getToolChain();
7649 const Action *CurDep = JA.getInputs()[I];
7651 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
7653 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
7654 assert(CurTC == nullptr && "Expected one dependence!");
7655 CurKind = A->getOffloadingDeviceKind();
7659 Triples += Action::GetOffloadKindName(CurKind);
7661 std::string NormalizedTriple = CurTC->getTriple().normalize();
7662 Triples += NormalizedTriple;
7664 if (CurDep->getOffloadingArch() != nullptr) {
7665 // If OffloadArch is present it can only appear as the 6th hypen
7666 // sepearated field of Bundle Entry ID. So, pad required number of
7667 // hyphens in Triple.
7668 for (int i = 4 - StringRef(NormalizedTriple).count("-"); i > 0; i--)
7670 Triples += CurDep->getOffloadingArch();
7673 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
7675 // Get bundled file command.
7677 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
7679 // Get unbundled files command.
7680 SmallString<128> UB;
7682 for (unsigned I = 0; I < Inputs.size(); ++I) {
7686 // Find ToolChain for this input.
7687 const ToolChain *CurTC = &getToolChain();
7688 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
7690 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
7691 assert(CurTC == nullptr && "Expected one dependence!");
7694 UB += C.addTempFile(
7695 C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
7697 UB += CurTC->getInputFilename(Inputs[I]);
7700 CmdArgs.push_back(TCArgs.MakeArgString(UB));
7702 // All the inputs are encoded as commands.
7703 C.addCommand(std::make_unique<Command>(
7704 JA, *this, ResponseFileSupport::None(),
7705 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
7706 CmdArgs, None, Output));
7709 void OffloadBundler::ConstructJobMultipleOutputs(
7710 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
7711 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
7712 const char *LinkingOutput) const {
7713 // The version with multiple outputs is expected to refer to a unbundling job.
7714 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
7716 // The unbundling command looks like this:
7717 // clang-offload-bundler -type=bc
7718 // -targets=host-triple,openmp-triple1,openmp-triple2
7719 // -inputs=input_file
7720 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
7723 ArgStringList CmdArgs;
7725 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
7726 InputInfo Input = Inputs.front();
7729 CmdArgs.push_back(TCArgs.MakeArgString(
7730 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
7733 SmallString<128> Triples;
7734 Triples += "-targets=";
7735 auto DepInfo = UA.getDependentActionsInfo();
7736 for (unsigned I = 0; I < DepInfo.size(); ++I) {
7740 auto &Dep = DepInfo[I];
7741 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
7743 std::string NormalizedTriple =
7744 Dep.DependentToolChain->getTriple().normalize();
7745 Triples += NormalizedTriple;
7747 if (!Dep.DependentBoundArch.empty()) {
7748 // If OffloadArch is present it can only appear as the 6th hypen
7749 // sepearated field of Bundle Entry ID. So, pad required number of
7750 // hyphens in Triple.
7751 for (int i = 4 - StringRef(NormalizedTriple).count("-"); i > 0; i--)
7753 Triples += Dep.DependentBoundArch;
7757 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
7759 // Get bundled file command.
7761 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
7763 // Get unbundled files command.
7764 SmallString<128> UB;
7766 for (unsigned I = 0; I < Outputs.size(); ++I) {
7769 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
7771 CmdArgs.push_back(TCArgs.MakeArgString(UB));
7772 CmdArgs.push_back("-unbundle");
7773 CmdArgs.push_back("-allow-missing-bundles");
7775 // All the inputs are encoded as commands.
7776 C.addCommand(std::make_unique<Command>(
7777 JA, *this, ResponseFileSupport::None(),
7778 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
7779 CmdArgs, None, Outputs));
7782 void OffloadWrapper::ConstructJob(Compilation &C, const JobAction &JA,
7783 const InputInfo &Output,
7784 const InputInfoList &Inputs,
7785 const ArgList &Args,
7786 const char *LinkingOutput) const {
7787 ArgStringList CmdArgs;
7789 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
7791 // Add the "effective" target triple.
7792 CmdArgs.push_back("-target");
7793 CmdArgs.push_back(Args.MakeArgString(Triple.getTriple()));
7795 // Add the output file name.
7796 assert(Output.isFilename() && "Invalid output.");
7797 CmdArgs.push_back("-o");
7798 CmdArgs.push_back(Output.getFilename());
7801 for (const InputInfo &I : Inputs) {
7802 assert(I.isFilename() && "Invalid input.");
7803 CmdArgs.push_back(I.getFilename());
7806 C.addCommand(std::make_unique<Command>(
7807 JA, *this, ResponseFileSupport::None(),
7808 Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
7809 CmdArgs, Inputs, Output));