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 //===----------------------------------------------------------------------===//
10 #include "Arch/AArch64.h"
12 #include "Arch/Mips.h"
14 #include "Arch/RISCV.h"
15 #include "Arch/Sparc.h"
16 #include "Arch/SystemZ.h"
19 #include "CommonArgs.h"
22 #include "InputInfo.h"
24 #include "clang/Basic/CharInfo.h"
25 #include "clang/Basic/CodeGenOptions.h"
26 #include "clang/Basic/LangOptions.h"
27 #include "clang/Basic/ObjCRuntime.h"
28 #include "clang/Basic/Version.h"
29 #include "clang/Driver/Distro.h"
30 #include "clang/Driver/DriverDiagnostic.h"
31 #include "clang/Driver/Options.h"
32 #include "clang/Driver/SanitizerArgs.h"
33 #include "clang/Driver/XRayArgs.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Config/llvm-config.h"
36 #include "llvm/Option/ArgList.h"
37 #include "llvm/Support/CodeGen.h"
38 #include "llvm/Support/Compression.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/Process.h"
42 #include "llvm/Support/TargetParser.h"
43 #include "llvm/Support/YAMLParser.h"
46 #include <unistd.h> // For getuid().
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));
306 shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
307 const llvm::Triple &Triple) {
308 // We use the zero-cost exception tables for Objective-C if the non-fragile
309 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
311 if (runtime.isNonFragile())
314 if (!Triple.isMacOSX())
317 return (!Triple.isMacOSXVersionLT(10, 5) &&
318 (Triple.getArch() == llvm::Triple::x86_64 ||
319 Triple.getArch() == llvm::Triple::arm));
322 /// Adds exception related arguments to the driver command arguments. There's a
323 /// master flag, -fexceptions and also language specific flags to enable/disable
324 /// C++ and Objective-C exceptions. This makes it possible to for example
325 /// disable C++ exceptions but enable Objective-C exceptions.
326 static void addExceptionArgs(const ArgList &Args, types::ID InputType,
327 const ToolChain &TC, bool KernelOrKext,
328 const ObjCRuntime &objcRuntime,
329 ArgStringList &CmdArgs) {
330 const llvm::Triple &Triple = TC.getTriple();
333 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
334 // arguments now to avoid warnings about unused arguments.
335 Args.ClaimAllArgs(options::OPT_fexceptions);
336 Args.ClaimAllArgs(options::OPT_fno_exceptions);
337 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
338 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
339 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
340 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
344 // See if the user explicitly enabled exceptions.
345 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
348 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
349 // is not necessarily sensible, but follows GCC.
350 if (types::isObjC(InputType) &&
351 Args.hasFlag(options::OPT_fobjc_exceptions,
352 options::OPT_fno_objc_exceptions, true)) {
353 CmdArgs.push_back("-fobjc-exceptions");
355 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
358 if (types::isCXX(InputType)) {
359 // Disable C++ EH by default on XCore and PS4.
360 bool CXXExceptionsEnabled =
361 Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
362 Arg *ExceptionArg = Args.getLastArg(
363 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
364 options::OPT_fexceptions, options::OPT_fno_exceptions);
366 CXXExceptionsEnabled =
367 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
368 ExceptionArg->getOption().matches(options::OPT_fexceptions);
370 if (CXXExceptionsEnabled) {
371 CmdArgs.push_back("-fcxx-exceptions");
378 CmdArgs.push_back("-fexceptions");
381 static bool ShouldDisableAutolink(const ArgList &Args, const ToolChain &TC) {
383 if (TC.getTriple().isOSDarwin()) {
384 // The native darwin assembler doesn't support the linker_option directives,
385 // so we disable them if we think the .s file will be passed to it.
386 Default = TC.useIntegratedAs();
388 return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
392 static bool ShouldDisableDwarfDirectory(const ArgList &Args,
393 const ToolChain &TC) {
394 bool UseDwarfDirectory =
395 Args.hasFlag(options::OPT_fdwarf_directory_asm,
396 options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
397 return !UseDwarfDirectory;
400 // Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
401 // to the corresponding DebugInfoKind.
402 static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
403 assert(A.getOption().matches(options::OPT_gN_Group) &&
404 "Not a -g option that specifies a debug-info level");
405 if (A.getOption().matches(options::OPT_g0) ||
406 A.getOption().matches(options::OPT_ggdb0))
407 return codegenoptions::NoDebugInfo;
408 if (A.getOption().matches(options::OPT_gline_tables_only) ||
409 A.getOption().matches(options::OPT_ggdb1))
410 return codegenoptions::DebugLineTablesOnly;
411 if (A.getOption().matches(options::OPT_gline_directives_only))
412 return codegenoptions::DebugDirectivesOnly;
413 return codegenoptions::LimitedDebugInfo;
416 static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
417 switch (Triple.getArch()){
420 case llvm::Triple::arm:
421 case llvm::Triple::thumb:
422 // ARM Darwin targets require a frame pointer to be always present to aid
423 // offline debugging via backtraces.
424 return Triple.isOSDarwin();
428 static bool useFramePointerForTargetByDefault(const ArgList &Args,
429 const llvm::Triple &Triple) {
430 if (Args.hasArg(options::OPT_pg))
433 switch (Triple.getArch()) {
434 case llvm::Triple::xcore:
435 case llvm::Triple::wasm32:
436 case llvm::Triple::wasm64:
437 case llvm::Triple::msp430:
438 // XCore never wants frame pointers, regardless of OS.
439 // WebAssembly never wants frame pointers.
441 case llvm::Triple::ppc:
442 case llvm::Triple::ppc64:
443 case llvm::Triple::ppc64le:
444 case llvm::Triple::riscv32:
445 case llvm::Triple::riscv64:
446 return !areOptimizationsEnabled(Args);
451 if (Triple.isOSNetBSD()) {
452 return !areOptimizationsEnabled(Args);
455 if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
457 switch (Triple.getArch()) {
458 // Don't use a frame pointer on linux if optimizing for certain targets.
459 case llvm::Triple::mips64:
460 case llvm::Triple::mips64el:
461 case llvm::Triple::mips:
462 case llvm::Triple::mipsel:
463 case llvm::Triple::systemz:
464 case llvm::Triple::x86:
465 case llvm::Triple::x86_64:
466 return !areOptimizationsEnabled(Args);
472 if (Triple.isOSWindows()) {
473 switch (Triple.getArch()) {
474 case llvm::Triple::x86:
475 return !areOptimizationsEnabled(Args);
476 case llvm::Triple::x86_64:
477 return Triple.isOSBinFormatMachO();
478 case llvm::Triple::arm:
479 case llvm::Triple::thumb:
480 // Windows on ARM builds with FPO disabled to aid fast stack walking
483 // All other supported Windows ISAs use xdata unwind information, so frame
484 // pointers are not generally useful.
492 static CodeGenOptions::FramePointerKind
493 getFramePointerKind(const ArgList &Args, const llvm::Triple &Triple) {
496 // 00) leaf retained, non-leaf retained
497 // 01) leaf retained, non-leaf omitted (this is invalid)
498 // 10) leaf omitted, non-leaf retained
499 // (what -momit-leaf-frame-pointer was designed for)
500 // 11) leaf omitted, non-leaf omitted
502 // "omit" options taking precedence over "no-omit" options is the only way
503 // to make 3 valid states representable
504 Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
505 options::OPT_fno_omit_frame_pointer);
506 bool OmitFP = A && A->getOption().matches(options::OPT_fomit_frame_pointer);
508 A && A->getOption().matches(options::OPT_fno_omit_frame_pointer);
510 Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
511 options::OPT_mno_omit_leaf_frame_pointer, Triple.isPS4CPU());
512 if (NoOmitFP || mustUseNonLeafFramePointerForTarget(Triple) ||
513 (!OmitFP && useFramePointerForTargetByDefault(Args, Triple))) {
515 return CodeGenOptions::FramePointerKind::NonLeaf;
516 return CodeGenOptions::FramePointerKind::All;
518 return CodeGenOptions::FramePointerKind::None;
521 /// Add a CC1 option to specify the debug compilation directory.
522 static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs,
523 const llvm::vfs::FileSystem &VFS) {
524 if (Arg *A = Args.getLastArg(options::OPT_fdebug_compilation_dir)) {
525 CmdArgs.push_back("-fdebug-compilation-dir");
526 CmdArgs.push_back(A->getValue());
527 } else if (llvm::ErrorOr<std::string> CWD =
528 VFS.getCurrentWorkingDirectory()) {
529 CmdArgs.push_back("-fdebug-compilation-dir");
530 CmdArgs.push_back(Args.MakeArgString(*CWD));
534 /// Add a CC1 and CC1AS option to specify the debug file path prefix map.
535 static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
536 for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
537 StringRef Map = A->getValue();
538 if (Map.find('=') == StringRef::npos)
539 D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
541 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
546 /// Vectorize at all optimization levels greater than 1 except for -Oz.
547 /// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
549 static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
550 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
551 if (A->getOption().matches(options::OPT_O4) ||
552 A->getOption().matches(options::OPT_Ofast))
555 if (A->getOption().matches(options::OPT_O0))
558 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
561 StringRef S(A->getValue());
565 // Don't vectorize -Oz, unless it's the slp vectorizer.
569 unsigned OptLevel = 0;
570 if (S.getAsInteger(10, OptLevel))
579 /// Add -x lang to \p CmdArgs for \p Input.
580 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
581 ArgStringList &CmdArgs) {
582 // When using -verify-pch, we don't want to provide the type
583 // 'precompiled-header' if it was inferred from the file extension
584 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
587 CmdArgs.push_back("-x");
588 if (Args.hasArg(options::OPT_rewrite_objc))
589 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
591 // Map the driver type to the frontend type. This is mostly an identity
592 // mapping, except that the distinction between module interface units
593 // and other source files does not exist at the frontend layer.
594 const char *ClangType;
595 switch (Input.getType()) {
596 case types::TY_CXXModule:
599 case types::TY_PP_CXXModule:
600 ClangType = "c++-cpp-output";
603 ClangType = types::getTypeName(Input.getType());
606 CmdArgs.push_back(ClangType);
610 static void appendUserToPath(SmallVectorImpl<char> &Result) {
612 const char *Username = getenv("LOGNAME");
614 const char *Username = getenv("USERNAME");
617 // Validate that LoginName can be used in a path, and get its length.
619 for (const char *P = Username; *P; ++P, ++Len) {
620 if (!clang::isAlphanumeric(*P) && *P != '_') {
626 if (Username && Len > 0) {
627 Result.append(Username, Username + Len);
632 // Fallback to user id.
634 std::string UID = llvm::utostr(getuid());
636 // FIXME: Windows seems to have an 'SID' that might work.
637 std::string UID = "9999";
639 Result.append(UID.begin(), UID.end());
642 static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
643 const Driver &D, const InputInfo &Output,
645 ArgStringList &CmdArgs) {
647 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
648 options::OPT_fprofile_generate_EQ,
649 options::OPT_fno_profile_generate);
650 if (PGOGenerateArg &&
651 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
652 PGOGenerateArg = nullptr;
654 auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
655 options::OPT_fcs_profile_generate_EQ,
656 options::OPT_fno_profile_generate);
657 if (CSPGOGenerateArg &&
658 CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
659 CSPGOGenerateArg = nullptr;
661 auto *ProfileGenerateArg = Args.getLastArg(
662 options::OPT_fprofile_instr_generate,
663 options::OPT_fprofile_instr_generate_EQ,
664 options::OPT_fno_profile_instr_generate);
665 if (ProfileGenerateArg &&
666 ProfileGenerateArg->getOption().matches(
667 options::OPT_fno_profile_instr_generate))
668 ProfileGenerateArg = nullptr;
670 if (PGOGenerateArg && ProfileGenerateArg)
671 D.Diag(diag::err_drv_argument_not_allowed_with)
672 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
674 auto *ProfileUseArg = getLastProfileUseArg(Args);
676 if (PGOGenerateArg && ProfileUseArg)
677 D.Diag(diag::err_drv_argument_not_allowed_with)
678 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
680 if (ProfileGenerateArg && ProfileUseArg)
681 D.Diag(diag::err_drv_argument_not_allowed_with)
682 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
684 if (CSPGOGenerateArg && PGOGenerateArg)
685 D.Diag(diag::err_drv_argument_not_allowed_with)
686 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
688 if (ProfileGenerateArg) {
689 if (ProfileGenerateArg->getOption().matches(
690 options::OPT_fprofile_instr_generate_EQ))
691 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
692 ProfileGenerateArg->getValue()));
693 // The default is to use Clang Instrumentation.
694 CmdArgs.push_back("-fprofile-instrument=clang");
695 if (TC.getTriple().isWindowsMSVCEnvironment()) {
696 // Add dependent lib for clang_rt.profile
697 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
698 TC.getCompilerRT(Args, "profile")));
702 Arg *PGOGenArg = nullptr;
703 if (PGOGenerateArg) {
704 assert(!CSPGOGenerateArg);
705 PGOGenArg = PGOGenerateArg;
706 CmdArgs.push_back("-fprofile-instrument=llvm");
708 if (CSPGOGenerateArg) {
709 assert(!PGOGenerateArg);
710 PGOGenArg = CSPGOGenerateArg;
711 CmdArgs.push_back("-fprofile-instrument=csllvm");
714 if (TC.getTriple().isWindowsMSVCEnvironment()) {
715 CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
716 TC.getCompilerRT(Args, "profile")));
718 if (PGOGenArg->getOption().matches(
719 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
720 : options::OPT_fcs_profile_generate_EQ)) {
721 SmallString<128> Path(PGOGenArg->getValue());
722 llvm::sys::path::append(Path, "default_%m.profraw");
724 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
729 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
730 CmdArgs.push_back(Args.MakeArgString(
731 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
732 else if ((ProfileUseArg->getOption().matches(
733 options::OPT_fprofile_use_EQ) ||
734 ProfileUseArg->getOption().matches(
735 options::OPT_fprofile_instr_use))) {
736 SmallString<128> Path(
737 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
738 if (Path.empty() || llvm::sys::fs::is_directory(Path))
739 llvm::sys::path::append(Path, "default.profdata");
741 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
745 bool EmitCovNotes = Args.hasArg(options::OPT_ftest_coverage) ||
746 Args.hasArg(options::OPT_coverage);
747 bool EmitCovData = Args.hasFlag(options::OPT_fprofile_arcs,
748 options::OPT_fno_profile_arcs, false) ||
749 Args.hasArg(options::OPT_coverage);
751 CmdArgs.push_back("-femit-coverage-notes");
753 CmdArgs.push_back("-femit-coverage-data");
755 if (Args.hasFlag(options::OPT_fcoverage_mapping,
756 options::OPT_fno_coverage_mapping, false)) {
757 if (!ProfileGenerateArg)
758 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
759 << "-fcoverage-mapping"
760 << "-fprofile-instr-generate";
762 CmdArgs.push_back("-fcoverage-mapping");
765 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
766 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
767 if (!Args.hasArg(options::OPT_coverage))
768 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
769 << "-fprofile-exclude-files="
772 StringRef v = Arg->getValue();
774 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
777 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
778 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
779 if (!Args.hasArg(options::OPT_coverage))
780 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
781 << "-fprofile-filter-files="
784 StringRef v = Arg->getValue();
785 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
788 // Leave -fprofile-dir= an unused argument unless .gcda emission is
789 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
790 // the flag used. There is no -fno-profile-dir, so the user has no
791 // targeted way to suppress the warning.
792 Arg *FProfileDir = nullptr;
793 if (Args.hasArg(options::OPT_fprofile_arcs) ||
794 Args.hasArg(options::OPT_coverage))
795 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
797 // Put the .gcno and .gcda files (if needed) next to the object file or
798 // bitcode file in the case of LTO.
799 // FIXME: There should be a simpler way to find the object file for this
800 // input, and this code probably does the wrong thing for commands that
801 // compile and link all at once.
802 if ((Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) &&
803 (EmitCovNotes || EmitCovData) && Output.isFilename()) {
804 SmallString<128> OutputFilename;
805 if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
806 OutputFilename = FinalOutput->getValue();
808 OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
809 SmallString<128> CoverageFilename = OutputFilename;
810 if (llvm::sys::path::is_relative(CoverageFilename))
811 (void)D.getVFS().makeAbsolute(CoverageFilename);
812 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
814 CmdArgs.push_back("-coverage-notes-file");
815 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
819 CoverageFilename = FProfileDir->getValue();
820 llvm::sys::path::append(CoverageFilename, OutputFilename);
822 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
823 CmdArgs.push_back("-coverage-data-file");
824 CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
829 /// Check whether the given input tree contains any compilation actions.
830 static bool ContainsCompileAction(const Action *A) {
831 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
834 for (const auto &AI : A->inputs())
835 if (ContainsCompileAction(AI))
841 /// Check if -relax-all should be passed to the internal assembler.
842 /// This is done by default when compiling non-assembler source with -O0.
843 static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
844 bool RelaxDefault = true;
846 if (Arg *A = Args.getLastArg(options::OPT_O_Group))
847 RelaxDefault = A->getOption().matches(options::OPT_O0);
850 RelaxDefault = false;
851 for (const auto &Act : C.getActions()) {
852 if (ContainsCompileAction(Act)) {
859 return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
863 // Extract the integer N from a string spelled "-dwarf-N", returning 0
864 // on mismatch. The StringRef input (rather than an Arg) allows
865 // for use by the "-Xassembler" option parser.
866 static unsigned DwarfVersionNum(StringRef ArgValue) {
867 return llvm::StringSwitch<unsigned>(ArgValue)
868 .Case("-gdwarf-2", 2)
869 .Case("-gdwarf-3", 3)
870 .Case("-gdwarf-4", 4)
871 .Case("-gdwarf-5", 5)
875 static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
876 codegenoptions::DebugInfoKind DebugInfoKind,
877 unsigned DwarfVersion,
878 llvm::DebuggerKind DebuggerTuning) {
879 switch (DebugInfoKind) {
880 case codegenoptions::DebugDirectivesOnly:
881 CmdArgs.push_back("-debug-info-kind=line-directives-only");
883 case codegenoptions::DebugLineTablesOnly:
884 CmdArgs.push_back("-debug-info-kind=line-tables-only");
886 case codegenoptions::LimitedDebugInfo:
887 CmdArgs.push_back("-debug-info-kind=limited");
889 case codegenoptions::FullDebugInfo:
890 CmdArgs.push_back("-debug-info-kind=standalone");
895 if (DwarfVersion > 0)
897 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
898 switch (DebuggerTuning) {
899 case llvm::DebuggerKind::GDB:
900 CmdArgs.push_back("-debugger-tuning=gdb");
902 case llvm::DebuggerKind::LLDB:
903 CmdArgs.push_back("-debugger-tuning=lldb");
905 case llvm::DebuggerKind::SCE:
906 CmdArgs.push_back("-debugger-tuning=sce");
913 static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
914 const Driver &D, const ToolChain &TC) {
915 assert(A && "Expected non-nullptr argument.");
916 if (TC.supportsDebugInfoOption(A))
918 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
919 << A->getAsString(Args) << TC.getTripleString();
923 static void RenderDebugInfoCompressionArgs(const ArgList &Args,
924 ArgStringList &CmdArgs,
926 const ToolChain &TC) {
927 const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
930 if (checkDebugInfoOption(A, Args, D, TC)) {
931 if (A->getOption().getID() == options::OPT_gz) {
932 if (llvm::zlib::isAvailable())
933 CmdArgs.push_back("--compress-debug-sections");
935 D.Diag(diag::warn_debug_compression_unavailable);
939 StringRef Value = A->getValue();
940 if (Value == "none") {
941 CmdArgs.push_back("--compress-debug-sections=none");
942 } else if (Value == "zlib" || Value == "zlib-gnu") {
943 if (llvm::zlib::isAvailable()) {
945 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
947 D.Diag(diag::warn_debug_compression_unavailable);
950 D.Diag(diag::err_drv_unsupported_option_argument)
951 << A->getOption().getName() << Value;
956 static const char *RelocationModelName(llvm::Reloc::Model Model) {
958 case llvm::Reloc::Static:
960 case llvm::Reloc::PIC_:
962 case llvm::Reloc::DynamicNoPIC:
963 return "dynamic-no-pic";
964 case llvm::Reloc::ROPI:
966 case llvm::Reloc::RWPI:
968 case llvm::Reloc::ROPI_RWPI:
971 llvm_unreachable("Unknown Reloc::Model kind");
974 void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
975 const Driver &D, const ArgList &Args,
976 ArgStringList &CmdArgs,
977 const InputInfo &Output,
978 const InputInfoList &Inputs) const {
979 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
981 CheckPreprocessingOptions(D, Args);
983 Args.AddLastArg(CmdArgs, options::OPT_C);
984 Args.AddLastArg(CmdArgs, options::OPT_CC);
986 // Handle dependency file generation.
987 Arg *ArgM = Args.getLastArg(options::OPT_MM);
989 ArgM = Args.getLastArg(options::OPT_M);
990 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
992 ArgMD = Args.getLastArg(options::OPT_MD);
994 // -M and -MM imply -w.
996 CmdArgs.push_back("-w");
1001 // Determine the output location.
1002 const char *DepFile;
1003 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1004 DepFile = MF->getValue();
1005 C.addFailureResultFile(DepFile, &JA);
1006 } else if (Output.getType() == types::TY_Dependencies) {
1007 DepFile = Output.getFilename();
1008 } else if (!ArgMD) {
1011 DepFile = getDependencyFileName(Args, Inputs);
1012 C.addFailureResultFile(DepFile, &JA);
1014 CmdArgs.push_back("-dependency-file");
1015 CmdArgs.push_back(DepFile);
1017 bool HasTarget = false;
1018 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1021 if (A->getOption().matches(options::OPT_MT)) {
1022 A->render(Args, CmdArgs);
1024 CmdArgs.push_back("-MT");
1025 SmallString<128> Quoted;
1026 QuoteTarget(A->getValue(), Quoted);
1027 CmdArgs.push_back(Args.MakeArgString(Quoted));
1031 // Add a default target if one wasn't specified.
1033 const char *DepTarget;
1035 // If user provided -o, that is the dependency target, except
1036 // when we are only generating a dependency file.
1037 Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1038 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1039 DepTarget = OutputOpt->getValue();
1041 // Otherwise derive from the base input.
1043 // FIXME: This should use the computed output file location.
1044 SmallString<128> P(Inputs[0].getBaseInput());
1045 llvm::sys::path::replace_extension(P, "o");
1046 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1049 CmdArgs.push_back("-MT");
1050 SmallString<128> Quoted;
1051 QuoteTarget(DepTarget, Quoted);
1052 CmdArgs.push_back(Args.MakeArgString(Quoted));
1055 if (ArgM->getOption().matches(options::OPT_M) ||
1056 ArgM->getOption().matches(options::OPT_MD))
1057 CmdArgs.push_back("-sys-header-deps");
1058 if ((isa<PrecompileJobAction>(JA) &&
1059 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1060 Args.hasArg(options::OPT_fmodule_file_deps))
1061 CmdArgs.push_back("-module-file-deps");
1064 if (Args.hasArg(options::OPT_MG)) {
1065 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1066 ArgM->getOption().matches(options::OPT_MMD))
1067 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1068 CmdArgs.push_back("-MG");
1071 Args.AddLastArg(CmdArgs, options::OPT_MP);
1072 Args.AddLastArg(CmdArgs, options::OPT_MV);
1074 // Add offload include arguments specific for CUDA. This must happen before
1075 // we -I or -include anything else, because we must pick up the CUDA headers
1076 // from the particular CUDA installation, rather than from e.g.
1077 // /usr/local/include.
1078 if (JA.isOffloading(Action::OFK_Cuda))
1079 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1081 // If we are offloading to a target via OpenMP we need to include the
1082 // openmp_wrappers folder which contains alternative system headers.
1083 if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
1084 getToolChain().getTriple().isNVPTX()){
1085 if (!Args.hasArg(options::OPT_nobuiltininc)) {
1086 // Add openmp_wrappers/* to our system include path. This lets us wrap
1087 // standard library headers.
1088 SmallString<128> P(D.ResourceDir);
1089 llvm::sys::path::append(P, "include");
1090 llvm::sys::path::append(P, "openmp_wrappers");
1091 CmdArgs.push_back("-internal-isystem");
1092 CmdArgs.push_back(Args.MakeArgString(P));
1095 CmdArgs.push_back("-include");
1096 CmdArgs.push_back("__clang_openmp_math_declares.h");
1099 // Add -i* options, and automatically translate to
1100 // -include-pch/-include-pth for transparent PCH support. It's
1101 // wonky, but we include looking for .gch so we can support seamless
1102 // replacement into a build system already set up to be generating
1105 if (getToolChain().getDriver().IsCLMode()) {
1106 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1107 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1108 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1109 JA.getKind() <= Action::AssembleJobClass) {
1110 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1112 if (YcArg || YuArg) {
1113 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1114 if (!isa<PrecompileJobAction>(JA)) {
1115 CmdArgs.push_back("-include-pch");
1116 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1117 C, !ThroughHeader.empty()
1119 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1122 if (ThroughHeader.empty()) {
1123 CmdArgs.push_back(Args.MakeArgString(
1124 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1127 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1132 bool RenderedImplicitInclude = false;
1133 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1134 if (A->getOption().matches(options::OPT_include)) {
1135 // Handling of gcc-style gch precompiled headers.
1136 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1137 RenderedImplicitInclude = true;
1139 bool FoundPCH = false;
1140 SmallString<128> P(A->getValue());
1141 // We want the files to have a name like foo.h.pch. Add a dummy extension
1142 // so that replace_extension does the right thing.
1144 llvm::sys::path::replace_extension(P, "pch");
1145 if (llvm::sys::fs::exists(P))
1149 llvm::sys::path::replace_extension(P, "gch");
1150 if (llvm::sys::fs::exists(P)) {
1156 if (IsFirstImplicitInclude) {
1158 CmdArgs.push_back("-include-pch");
1159 CmdArgs.push_back(Args.MakeArgString(P));
1162 // Ignore the PCH if not first on command line and emit warning.
1163 D.Diag(diag::warn_drv_pch_not_first_include) << P
1164 << A->getAsString(Args);
1167 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1168 // Handling of paths which must come late. These entries are handled by
1169 // the toolchain itself after the resource dir is inserted in the right
1171 // Do not claim the argument so that the use of the argument does not
1172 // silently go unnoticed on toolchains which do not honour the option.
1174 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1175 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1179 // Not translated, render as usual.
1181 A->render(Args, CmdArgs);
1184 Args.AddAllArgs(CmdArgs,
1185 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1186 options::OPT_F, options::OPT_index_header_map});
1188 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1190 // FIXME: There is a very unfortunate problem here, some troubled
1191 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1192 // really support that we would have to parse and then translate
1193 // those options. :(
1194 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1195 options::OPT_Xpreprocessor);
1197 // -I- is a deprecated GCC feature, reject it.
1198 if (Arg *A = Args.getLastArg(options::OPT_I_))
1199 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1201 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1202 // -isysroot to the CC1 invocation.
1203 StringRef sysroot = C.getSysRoot();
1204 if (sysroot != "") {
1205 if (!Args.hasArg(options::OPT_isysroot)) {
1206 CmdArgs.push_back("-isysroot");
1207 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1211 // Parse additional include paths from environment variables.
1212 // FIXME: We should probably sink the logic for handling these from the
1213 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1214 // CPATH - included following the user specified includes (but prior to
1215 // builtin and standard includes).
1216 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1217 // C_INCLUDE_PATH - system includes enabled when compiling C.
1218 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1219 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1220 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1221 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1222 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1223 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1224 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1226 // While adding the include arguments, we also attempt to retrieve the
1227 // arguments of related offloading toolchains or arguments that are specific
1228 // of an offloading programming model.
1230 // Add C++ include arguments, if needed.
1231 if (types::isCXX(Inputs[0].getType())) {
1232 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1233 forAllAssociatedToolChains(
1234 C, JA, getToolChain(),
1235 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1236 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1237 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1241 // Add system include arguments for all targets but IAMCU.
1243 forAllAssociatedToolChains(C, JA, getToolChain(),
1244 [&Args, &CmdArgs](const ToolChain &TC) {
1245 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1248 // For IAMCU add special include arguments.
1249 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1253 // FIXME: Move to target hook.
1254 static bool isSignedCharDefault(const llvm::Triple &Triple) {
1255 switch (Triple.getArch()) {
1259 case llvm::Triple::aarch64:
1260 case llvm::Triple::aarch64_be:
1261 case llvm::Triple::arm:
1262 case llvm::Triple::armeb:
1263 case llvm::Triple::thumb:
1264 case llvm::Triple::thumbeb:
1265 if (Triple.isOSDarwin() || Triple.isOSWindows())
1269 case llvm::Triple::ppc:
1270 case llvm::Triple::ppc64:
1271 if (Triple.isOSDarwin())
1275 case llvm::Triple::hexagon:
1276 case llvm::Triple::ppc64le:
1277 case llvm::Triple::riscv32:
1278 case llvm::Triple::riscv64:
1279 case llvm::Triple::systemz:
1280 case llvm::Triple::xcore:
1285 static bool isNoCommonDefault(const llvm::Triple &Triple) {
1286 switch (Triple.getArch()) {
1288 if (Triple.isOSFuchsia())
1292 case llvm::Triple::xcore:
1293 case llvm::Triple::wasm32:
1294 case llvm::Triple::wasm64:
1300 void RenderARMABI(const llvm::Triple &Triple, const ArgList &Args,
1301 ArgStringList &CmdArgs) {
1302 // Select the ABI to use.
1303 // FIXME: Support -meabi.
1304 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1305 const char *ABIName = nullptr;
1306 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1307 ABIName = A->getValue();
1309 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
1310 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1313 CmdArgs.push_back("-target-abi");
1314 CmdArgs.push_back(ABIName);
1318 void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1319 ArgStringList &CmdArgs, bool KernelOrKext) const {
1320 RenderARMABI(Triple, Args, CmdArgs);
1322 // Determine floating point ABI from the options & target defaults.
1323 arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1324 if (ABI == arm::FloatABI::Soft) {
1325 // Floating point operations and argument passing are soft.
1326 // FIXME: This changes CPP defines, we need -target-soft-float.
1327 CmdArgs.push_back("-msoft-float");
1328 CmdArgs.push_back("-mfloat-abi");
1329 CmdArgs.push_back("soft");
1330 } else if (ABI == arm::FloatABI::SoftFP) {
1331 // Floating point operations are hard, but argument passing is soft.
1332 CmdArgs.push_back("-mfloat-abi");
1333 CmdArgs.push_back("soft");
1335 // Floating point operations and argument passing are hard.
1336 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1337 CmdArgs.push_back("-mfloat-abi");
1338 CmdArgs.push_back("hard");
1341 // Forward the -mglobal-merge option for explicit control over the pass.
1342 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1343 options::OPT_mno_global_merge)) {
1344 CmdArgs.push_back("-mllvm");
1345 if (A->getOption().matches(options::OPT_mno_global_merge))
1346 CmdArgs.push_back("-arm-global-merge=false");
1348 CmdArgs.push_back("-arm-global-merge=true");
1351 if (!Args.hasFlag(options::OPT_mimplicit_float,
1352 options::OPT_mno_implicit_float, true))
1353 CmdArgs.push_back("-no-implicit-float");
1355 if (Args.getLastArg(options::OPT_mcmse))
1356 CmdArgs.push_back("-mcmse");
1359 void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1360 const ArgList &Args, bool KernelOrKext,
1361 ArgStringList &CmdArgs) const {
1362 const ToolChain &TC = getToolChain();
1364 // Add the target features
1365 getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1367 // Add target specific flags.
1368 switch (TC.getArch()) {
1372 case llvm::Triple::arm:
1373 case llvm::Triple::armeb:
1374 case llvm::Triple::thumb:
1375 case llvm::Triple::thumbeb:
1376 // Use the effective triple, which takes into account the deployment target.
1377 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1378 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1381 case llvm::Triple::aarch64:
1382 case llvm::Triple::aarch64_be:
1383 AddAArch64TargetArgs(Args, CmdArgs);
1384 CmdArgs.push_back("-fallow-half-arguments-and-returns");
1387 case llvm::Triple::mips:
1388 case llvm::Triple::mipsel:
1389 case llvm::Triple::mips64:
1390 case llvm::Triple::mips64el:
1391 AddMIPSTargetArgs(Args, CmdArgs);
1394 case llvm::Triple::ppc:
1395 case llvm::Triple::ppc64:
1396 case llvm::Triple::ppc64le:
1397 AddPPCTargetArgs(Args, CmdArgs);
1400 case llvm::Triple::riscv32:
1401 case llvm::Triple::riscv64:
1402 AddRISCVTargetArgs(Args, CmdArgs);
1405 case llvm::Triple::sparc:
1406 case llvm::Triple::sparcel:
1407 case llvm::Triple::sparcv9:
1408 AddSparcTargetArgs(Args, CmdArgs);
1411 case llvm::Triple::systemz:
1412 AddSystemZTargetArgs(Args, CmdArgs);
1415 case llvm::Triple::x86:
1416 case llvm::Triple::x86_64:
1417 AddX86TargetArgs(Args, CmdArgs);
1420 case llvm::Triple::lanai:
1421 AddLanaiTargetArgs(Args, CmdArgs);
1424 case llvm::Triple::hexagon:
1425 AddHexagonTargetArgs(Args, CmdArgs);
1428 case llvm::Triple::wasm32:
1429 case llvm::Triple::wasm64:
1430 AddWebAssemblyTargetArgs(Args, CmdArgs);
1435 // Parse -mbranch-protection=<protection>[+<protection>]* where
1436 // <protection> ::= standard | none | [bti,pac-ret[+b-key,+leaf]*]
1437 // Returns a triple of (return address signing Scope, signing key, require
1439 static std::tuple<StringRef, StringRef, bool>
1440 ParseAArch64BranchProtection(const Driver &D, const ArgList &Args,
1442 StringRef Scope = "none";
1443 StringRef Key = "a_key";
1444 bool IndirectBranches = false;
1446 StringRef Value = A->getValue();
1447 // This maps onto -mbranch-protection=<scope>+<key>
1449 if (Value.equals("standard")) {
1452 IndirectBranches = true;
1454 } else if (!Value.equals("none")) {
1455 SmallVector<StringRef, 4> BranchProtection;
1456 StringRef(A->getValue()).split(BranchProtection, '+');
1458 auto Protection = BranchProtection.begin();
1459 while (Protection != BranchProtection.end()) {
1460 if (Protection->equals("bti"))
1461 IndirectBranches = true;
1462 else if (Protection->equals("pac-ret")) {
1464 while (++Protection != BranchProtection.end()) {
1465 // Inner loop as "leaf" and "b-key" options must only appear attached
1467 if (Protection->equals("leaf"))
1469 else if (Protection->equals("b-key"))
1476 D.Diag(diag::err_invalid_branch_protection)
1477 << *Protection << A->getAsString(Args);
1482 return std::make_tuple(Scope, Key, IndirectBranches);
1486 void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1487 ArgStringList &CmdArgs) {
1488 const char *ABIName = nullptr;
1489 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1490 ABIName = A->getValue();
1491 else if (Triple.isOSDarwin())
1492 ABIName = "darwinpcs";
1496 CmdArgs.push_back("-target-abi");
1497 CmdArgs.push_back(ABIName);
1501 void Clang::AddAArch64TargetArgs(const ArgList &Args,
1502 ArgStringList &CmdArgs) const {
1503 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1505 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1506 Args.hasArg(options::OPT_mkernel) ||
1507 Args.hasArg(options::OPT_fapple_kext))
1508 CmdArgs.push_back("-disable-red-zone");
1510 if (!Args.hasFlag(options::OPT_mimplicit_float,
1511 options::OPT_mno_implicit_float, true))
1512 CmdArgs.push_back("-no-implicit-float");
1514 RenderAArch64ABI(Triple, Args, CmdArgs);
1516 if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1517 options::OPT_mno_fix_cortex_a53_835769)) {
1518 CmdArgs.push_back("-mllvm");
1519 if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1520 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1522 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1523 } else if (Triple.isAndroid()) {
1524 // Enabled A53 errata (835769) workaround by default on android
1525 CmdArgs.push_back("-mllvm");
1526 CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1529 // Forward the -mglobal-merge option for explicit control over the pass.
1530 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1531 options::OPT_mno_global_merge)) {
1532 CmdArgs.push_back("-mllvm");
1533 if (A->getOption().matches(options::OPT_mno_global_merge))
1534 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1536 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1539 // Enable/disable return address signing and indirect branch targets.
1540 if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ,
1541 options::OPT_mbranch_protection_EQ)) {
1543 const Driver &D = getToolChain().getDriver();
1545 StringRef Scope, Key;
1546 bool IndirectBranches;
1548 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1549 Scope = A->getValue();
1550 if (!Scope.equals("none") && !Scope.equals("non-leaf") &&
1551 !Scope.equals("all"))
1552 D.Diag(diag::err_invalid_branch_protection)
1553 << Scope << A->getAsString(Args);
1555 IndirectBranches = false;
1557 std::tie(Scope, Key, IndirectBranches) =
1558 ParseAArch64BranchProtection(D, Args, A);
1561 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1563 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1564 if (IndirectBranches)
1565 CmdArgs.push_back("-mbranch-target-enforce");
1569 void Clang::AddMIPSTargetArgs(const ArgList &Args,
1570 ArgStringList &CmdArgs) const {
1571 const Driver &D = getToolChain().getDriver();
1574 const llvm::Triple &Triple = getToolChain().getTriple();
1575 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1577 CmdArgs.push_back("-target-abi");
1578 CmdArgs.push_back(ABIName.data());
1580 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1581 if (ABI == mips::FloatABI::Soft) {
1582 // Floating point operations and argument passing are soft.
1583 CmdArgs.push_back("-msoft-float");
1584 CmdArgs.push_back("-mfloat-abi");
1585 CmdArgs.push_back("soft");
1587 // Floating point operations and argument passing are hard.
1588 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1589 CmdArgs.push_back("-mfloat-abi");
1590 CmdArgs.push_back("hard");
1593 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1594 options::OPT_mno_ldc1_sdc1)) {
1595 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1596 CmdArgs.push_back("-mllvm");
1597 CmdArgs.push_back("-mno-ldc1-sdc1");
1601 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1602 options::OPT_mno_check_zero_division)) {
1603 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1604 CmdArgs.push_back("-mllvm");
1605 CmdArgs.push_back("-mno-check-zero-division");
1609 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1610 StringRef v = A->getValue();
1611 CmdArgs.push_back("-mllvm");
1612 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1616 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1618 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1620 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1621 // -mgpopt is the default for static, -fno-pic environments but these two
1622 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1623 // the only case where -mllvm -mgpopt is passed.
1624 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1625 // passed explicitly when compiling something with -mabicalls
1626 // (implictly) in affect. Currently the warning is in the backend.
1628 // When the ABI in use is N64, we also need to determine the PIC mode that
1629 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1631 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1633 llvm::Reloc::Model RelocationModel;
1636 std::tie(RelocationModel, PICLevel, IsPIE) =
1637 ParsePICArgs(getToolChain(), Args);
1639 NoABICalls = NoABICalls ||
1640 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1642 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1643 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1644 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1645 CmdArgs.push_back("-mllvm");
1646 CmdArgs.push_back("-mgpopt");
1648 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1649 options::OPT_mno_local_sdata);
1650 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1651 options::OPT_mno_extern_sdata);
1652 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1653 options::OPT_mno_embedded_data);
1655 CmdArgs.push_back("-mllvm");
1656 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1657 CmdArgs.push_back("-mlocal-sdata=1");
1659 CmdArgs.push_back("-mlocal-sdata=0");
1661 LocalSData->claim();
1665 CmdArgs.push_back("-mllvm");
1666 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1667 CmdArgs.push_back("-mextern-sdata=1");
1669 CmdArgs.push_back("-mextern-sdata=0");
1671 ExternSData->claim();
1675 CmdArgs.push_back("-mllvm");
1676 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1677 CmdArgs.push_back("-membedded-data=1");
1679 CmdArgs.push_back("-membedded-data=0");
1681 EmbeddedData->claim();
1684 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1685 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1690 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1691 StringRef Val = StringRef(A->getValue());
1692 if (mips::hasCompactBranches(CPUName)) {
1693 if (Val == "never" || Val == "always" || Val == "optimal") {
1694 CmdArgs.push_back("-mllvm");
1695 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1697 D.Diag(diag::err_drv_unsupported_option_argument)
1698 << A->getOption().getName() << Val;
1700 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1703 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1704 options::OPT_mno_relax_pic_calls)) {
1705 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1706 CmdArgs.push_back("-mllvm");
1707 CmdArgs.push_back("-mips-jalr-reloc=0");
1712 void Clang::AddPPCTargetArgs(const ArgList &Args,
1713 ArgStringList &CmdArgs) const {
1714 // Select the ABI to use.
1715 const char *ABIName = nullptr;
1716 if (getToolChain().getTriple().isOSLinux())
1717 switch (getToolChain().getArch()) {
1718 case llvm::Triple::ppc64: {
1719 // When targeting a processor that supports QPX, or if QPX is
1720 // specifically enabled, default to using the ABI that supports QPX (so
1721 // long as it is not specifically disabled).
1722 bool HasQPX = false;
1723 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1724 HasQPX = A->getValue() == StringRef("a2q");
1725 HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1727 ABIName = "elfv1-qpx";
1734 case llvm::Triple::ppc64le:
1741 bool IEEELongDouble = false;
1742 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1743 StringRef V = A->getValue();
1744 if (V == "ieeelongdouble")
1745 IEEELongDouble = true;
1746 else if (V == "ibmlongdouble")
1747 IEEELongDouble = false;
1748 else if (V != "altivec")
1749 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1750 // the option if given as we don't have backend support for any targets
1751 // that don't use the altivec abi.
1752 ABIName = A->getValue();
1755 CmdArgs.push_back("-mabi=ieeelongdouble");
1757 ppc::FloatABI FloatABI =
1758 ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1760 if (FloatABI == ppc::FloatABI::Soft) {
1761 // Floating point operations and argument passing are soft.
1762 CmdArgs.push_back("-msoft-float");
1763 CmdArgs.push_back("-mfloat-abi");
1764 CmdArgs.push_back("soft");
1766 // Floating point operations and argument passing are hard.
1767 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1768 CmdArgs.push_back("-mfloat-abi");
1769 CmdArgs.push_back("hard");
1773 CmdArgs.push_back("-target-abi");
1774 CmdArgs.push_back(ABIName);
1778 void Clang::AddRISCVTargetArgs(const ArgList &Args,
1779 ArgStringList &CmdArgs) const {
1780 const llvm::Triple &Triple = getToolChain().getTriple();
1781 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
1783 CmdArgs.push_back("-target-abi");
1784 CmdArgs.push_back(ABIName.data());
1787 void Clang::AddSparcTargetArgs(const ArgList &Args,
1788 ArgStringList &CmdArgs) const {
1789 sparc::FloatABI FloatABI =
1790 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1792 if (FloatABI == sparc::FloatABI::Soft) {
1793 // Floating point operations and argument passing are soft.
1794 CmdArgs.push_back("-msoft-float");
1795 CmdArgs.push_back("-mfloat-abi");
1796 CmdArgs.push_back("soft");
1798 // Floating point operations and argument passing are hard.
1799 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1800 CmdArgs.push_back("-mfloat-abi");
1801 CmdArgs.push_back("hard");
1805 void Clang::AddSystemZTargetArgs(const ArgList &Args,
1806 ArgStringList &CmdArgs) const {
1807 if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1808 CmdArgs.push_back("-mbackchain");
1811 void Clang::AddX86TargetArgs(const ArgList &Args,
1812 ArgStringList &CmdArgs) const {
1813 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1814 Args.hasArg(options::OPT_mkernel) ||
1815 Args.hasArg(options::OPT_fapple_kext))
1816 CmdArgs.push_back("-disable-red-zone");
1818 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
1819 options::OPT_mno_tls_direct_seg_refs, true))
1820 CmdArgs.push_back("-mno-tls-direct-seg-refs");
1822 // Default to avoid implicit floating-point for kernel/kext code, but allow
1823 // that to be overridden with -mno-soft-float.
1824 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1825 Args.hasArg(options::OPT_fapple_kext));
1826 if (Arg *A = Args.getLastArg(
1827 options::OPT_msoft_float, options::OPT_mno_soft_float,
1828 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1829 const Option &O = A->getOption();
1830 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1831 O.matches(options::OPT_msoft_float));
1833 if (NoImplicitFloat)
1834 CmdArgs.push_back("-no-implicit-float");
1836 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1837 StringRef Value = A->getValue();
1838 if (Value == "intel" || Value == "att") {
1839 CmdArgs.push_back("-mllvm");
1840 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1842 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1843 << A->getOption().getName() << Value;
1845 } else if (getToolChain().getDriver().IsCLMode()) {
1846 CmdArgs.push_back("-mllvm");
1847 CmdArgs.push_back("-x86-asm-syntax=intel");
1850 // Set flags to support MCU ABI.
1851 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1852 CmdArgs.push_back("-mfloat-abi");
1853 CmdArgs.push_back("soft");
1854 CmdArgs.push_back("-mstack-alignment=4");
1858 void Clang::AddHexagonTargetArgs(const ArgList &Args,
1859 ArgStringList &CmdArgs) const {
1860 CmdArgs.push_back("-mqdsp6-compat");
1861 CmdArgs.push_back("-Wreturn-type");
1863 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
1864 CmdArgs.push_back("-mllvm");
1865 CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1866 Twine(G.getValue())));
1869 if (!Args.hasArg(options::OPT_fno_short_enums))
1870 CmdArgs.push_back("-fshort-enums");
1871 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1872 CmdArgs.push_back("-mllvm");
1873 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1875 CmdArgs.push_back("-mllvm");
1876 CmdArgs.push_back("-machine-sink-split=0");
1879 void Clang::AddLanaiTargetArgs(const ArgList &Args,
1880 ArgStringList &CmdArgs) const {
1881 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1882 StringRef CPUName = A->getValue();
1884 CmdArgs.push_back("-target-cpu");
1885 CmdArgs.push_back(Args.MakeArgString(CPUName));
1887 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1888 StringRef Value = A->getValue();
1889 // Only support mregparm=4 to support old usage. Report error for all other
1892 if (Value.getAsInteger(10, Mregparm)) {
1893 if (Mregparm != 4) {
1894 getToolChain().getDriver().Diag(
1895 diag::err_drv_unsupported_option_argument)
1896 << A->getOption().getName() << Value;
1902 void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1903 ArgStringList &CmdArgs) const {
1904 // Default to "hidden" visibility.
1905 if (!Args.hasArg(options::OPT_fvisibility_EQ,
1906 options::OPT_fvisibility_ms_compat)) {
1907 CmdArgs.push_back("-fvisibility");
1908 CmdArgs.push_back("hidden");
1912 void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1913 StringRef Target, const InputInfo &Output,
1914 const InputInfo &Input, const ArgList &Args) const {
1915 // If this is a dry run, do not create the compilation database file.
1916 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1919 using llvm::yaml::escape;
1920 const Driver &D = getToolChain().getDriver();
1922 if (!CompilationDatabase) {
1924 auto File = std::make_unique<llvm::raw_fd_ostream>(Filename, EC,
1925 llvm::sys::fs::OF_Text);
1927 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1931 CompilationDatabase = std::move(File);
1933 auto &CDB = *CompilationDatabase;
1934 auto CWD = D.getVFS().getCurrentWorkingDirectory();
1937 CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
1938 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1939 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1940 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1941 SmallString<128> Buf;
1943 Buf += types::getTypeName(Input.getType());
1944 CDB << ", \"" << escape(Buf) << "\"";
1945 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1948 CDB << ", \"" << escape(Buf) << "\"";
1950 CDB << ", \"" << escape(Input.getFilename()) << "\"";
1951 for (auto &A: Args) {
1952 auto &O = A->getOption();
1953 // Skip language selection, which is positional.
1954 if (O.getID() == options::OPT_x)
1956 // Skip writing dependency output and the compilation database itself.
1957 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1959 if (O.getID() == options::OPT_gen_cdb_fragment_path)
1962 if (O.getKind() == Option::InputClass)
1964 // All other arguments are quoted and appended.
1966 A->render(Args, ASL);
1968 CDB << ", \"" << escape(it) << "\"";
1972 CDB << ", \"" << escape(Buf) << "\"]},\n";
1975 void Clang::DumpCompilationDatabaseFragmentToDir(
1976 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
1977 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
1978 // If this is a dry run, do not create the compilation database file.
1979 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1982 if (CompilationDatabase)
1983 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
1985 SmallString<256> Path = Dir;
1986 const auto &Driver = C.getDriver();
1987 Driver.getVFS().makeAbsolute(Path);
1988 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
1990 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
1994 llvm::sys::path::append(
1996 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
1998 SmallString<256> TempPath;
1999 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath);
2001 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2004 CompilationDatabase =
2005 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2006 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2009 static void CollectArgsForIntegratedAssembler(Compilation &C,
2010 const ArgList &Args,
2011 ArgStringList &CmdArgs,
2013 if (UseRelaxAll(C, Args))
2014 CmdArgs.push_back("-mrelax-all");
2016 // Only default to -mincremental-linker-compatible if we think we are
2017 // targeting the MSVC linker.
2018 bool DefaultIncrementalLinkerCompatible =
2019 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2020 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2021 options::OPT_mno_incremental_linker_compatible,
2022 DefaultIncrementalLinkerCompatible))
2023 CmdArgs.push_back("-mincremental-linker-compatible");
2025 switch (C.getDefaultToolChain().getArch()) {
2026 case llvm::Triple::arm:
2027 case llvm::Triple::armeb:
2028 case llvm::Triple::thumb:
2029 case llvm::Triple::thumbeb:
2030 if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
2031 StringRef Value = A->getValue();
2032 if (Value == "always" || Value == "never" || Value == "arm" ||
2034 CmdArgs.push_back("-mllvm");
2035 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2037 D.Diag(diag::err_drv_unsupported_option_argument)
2038 << A->getOption().getName() << Value;
2046 // If you add more args here, also add them to the block below that
2047 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2049 // When passing -I arguments to the assembler we sometimes need to
2050 // unconditionally take the next argument. For example, when parsing
2051 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2052 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2053 // arg after parsing the '-I' arg.
2054 bool TakeNextArg = false;
2056 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2057 bool UseNoExecStack = C.getDefaultToolChain().isNoExecStackDefault();
2058 const char *MipsTargetFeature = nullptr;
2060 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2063 for (StringRef Value : A->getValues()) {
2065 CmdArgs.push_back(Value.data());
2066 TakeNextArg = false;
2070 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2071 Value == "-mbig-obj")
2072 continue; // LLVM handles bigobj automatically
2074 switch (C.getDefaultToolChain().getArch()) {
2077 case llvm::Triple::thumb:
2078 case llvm::Triple::thumbeb:
2079 case llvm::Triple::arm:
2080 case llvm::Triple::armeb:
2081 if (Value == "-mthumb")
2082 // -mthumb has already been processed in ComputeLLVMTriple()
2083 // recognize but skip over here.
2086 case llvm::Triple::mips:
2087 case llvm::Triple::mipsel:
2088 case llvm::Triple::mips64:
2089 case llvm::Triple::mips64el:
2090 if (Value == "--trap") {
2091 CmdArgs.push_back("-target-feature");
2092 CmdArgs.push_back("+use-tcc-in-div");
2095 if (Value == "--break") {
2096 CmdArgs.push_back("-target-feature");
2097 CmdArgs.push_back("-use-tcc-in-div");
2100 if (Value.startswith("-msoft-float")) {
2101 CmdArgs.push_back("-target-feature");
2102 CmdArgs.push_back("+soft-float");
2105 if (Value.startswith("-mhard-float")) {
2106 CmdArgs.push_back("-target-feature");
2107 CmdArgs.push_back("-soft-float");
2111 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2112 .Case("-mips1", "+mips1")
2113 .Case("-mips2", "+mips2")
2114 .Case("-mips3", "+mips3")
2115 .Case("-mips4", "+mips4")
2116 .Case("-mips5", "+mips5")
2117 .Case("-mips32", "+mips32")
2118 .Case("-mips32r2", "+mips32r2")
2119 .Case("-mips32r3", "+mips32r3")
2120 .Case("-mips32r5", "+mips32r5")
2121 .Case("-mips32r6", "+mips32r6")
2122 .Case("-mips64", "+mips64")
2123 .Case("-mips64r2", "+mips64r2")
2124 .Case("-mips64r3", "+mips64r3")
2125 .Case("-mips64r5", "+mips64r5")
2126 .Case("-mips64r6", "+mips64r6")
2128 if (MipsTargetFeature)
2132 if (Value == "-force_cpusubtype_ALL") {
2133 // Do nothing, this is the default and we don't support anything else.
2134 } else if (Value == "-L") {
2135 CmdArgs.push_back("-msave-temp-labels");
2136 } else if (Value == "--fatal-warnings") {
2137 CmdArgs.push_back("-massembler-fatal-warnings");
2138 } else if (Value == "--no-warn" || Value == "-W") {
2139 CmdArgs.push_back("-massembler-no-warn");
2140 } else if (Value == "--noexecstack") {
2141 UseNoExecStack = true;
2142 } else if (Value.startswith("-compress-debug-sections") ||
2143 Value.startswith("--compress-debug-sections") ||
2144 Value == "-nocompress-debug-sections" ||
2145 Value == "--nocompress-debug-sections") {
2146 CmdArgs.push_back(Value.data());
2147 } else if (Value == "-mrelax-relocations=yes" ||
2148 Value == "--mrelax-relocations=yes") {
2149 UseRelaxRelocations = true;
2150 } else if (Value == "-mrelax-relocations=no" ||
2151 Value == "--mrelax-relocations=no") {
2152 UseRelaxRelocations = false;
2153 } else if (Value.startswith("-I")) {
2154 CmdArgs.push_back(Value.data());
2155 // We need to consume the next argument if the current arg is a plain
2156 // -I. The next arg will be the include directory.
2159 } else if (Value.startswith("-gdwarf-")) {
2160 // "-gdwarf-N" options are not cc1as options.
2161 unsigned DwarfVersion = DwarfVersionNum(Value);
2162 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2163 CmdArgs.push_back(Value.data());
2165 RenderDebugEnablingArgs(Args, CmdArgs,
2166 codegenoptions::LimitedDebugInfo,
2167 DwarfVersion, llvm::DebuggerKind::Default);
2169 } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2170 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2171 // Do nothing, we'll validate it later.
2172 } else if (Value == "-defsym") {
2173 if (A->getNumValues() != 2) {
2174 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2177 const char *S = A->getValue(1);
2178 auto Pair = StringRef(S).split('=');
2179 auto Sym = Pair.first;
2180 auto SVal = Pair.second;
2182 if (Sym.empty() || SVal.empty()) {
2183 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2187 if (SVal.getAsInteger(0, IVal)) {
2188 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2191 CmdArgs.push_back(Value.data());
2193 } else if (Value == "-fdebug-compilation-dir") {
2194 CmdArgs.push_back("-fdebug-compilation-dir");
2197 D.Diag(diag::err_drv_unsupported_option_argument)
2198 << A->getOption().getName() << Value;
2202 if (UseRelaxRelocations)
2203 CmdArgs.push_back("--mrelax-relocations");
2205 CmdArgs.push_back("-mnoexecstack");
2206 if (MipsTargetFeature != nullptr) {
2207 CmdArgs.push_back("-target-feature");
2208 CmdArgs.push_back(MipsTargetFeature);
2211 // forward -fembed-bitcode to assmebler
2212 if (C.getDriver().embedBitcodeEnabled() ||
2213 C.getDriver().embedBitcodeMarkerOnly())
2214 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2217 static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2218 bool OFastEnabled, const ArgList &Args,
2219 ArgStringList &CmdArgs) {
2220 // Handle various floating point optimization flags, mapping them to the
2221 // appropriate LLVM code generation flags. This is complicated by several
2222 // "umbrella" flags, so we do this by stepping through the flags incrementally
2223 // adjusting what we think is enabled/disabled, then at the end setting the
2224 // LLVM flags based on the final state.
2225 bool HonorINFs = true;
2226 bool HonorNaNs = true;
2227 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2228 bool MathErrno = TC.IsMathErrnoDefault();
2229 bool AssociativeMath = false;
2230 bool ReciprocalMath = false;
2231 bool SignedZeros = true;
2232 bool TrappingMath = true;
2233 StringRef DenormalFPMath = "";
2234 StringRef FPContract = "";
2236 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2237 CmdArgs.push_back("-mlimit-float-precision");
2238 CmdArgs.push_back(A->getValue());
2241 for (const Arg *A : Args) {
2242 switch (A->getOption().getID()) {
2243 // If this isn't an FP option skip the claim below
2246 // Options controlling individual features
2247 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2248 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2249 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2250 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2251 case options::OPT_fmath_errno: MathErrno = true; break;
2252 case options::OPT_fno_math_errno: MathErrno = false; break;
2253 case options::OPT_fassociative_math: AssociativeMath = true; break;
2254 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2255 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2256 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2257 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2258 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2259 case options::OPT_ftrapping_math: TrappingMath = true; break;
2260 case options::OPT_fno_trapping_math: TrappingMath = false; break;
2262 case options::OPT_fdenormal_fp_math_EQ:
2263 DenormalFPMath = A->getValue();
2266 // Validate and pass through -fp-contract option.
2267 case options::OPT_ffp_contract: {
2268 StringRef Val = A->getValue();
2269 if (Val == "fast" || Val == "on" || Val == "off")
2272 D.Diag(diag::err_drv_unsupported_option_argument)
2273 << A->getOption().getName() << Val;
2277 case options::OPT_ffinite_math_only:
2281 case options::OPT_fno_finite_math_only:
2286 case options::OPT_funsafe_math_optimizations:
2287 AssociativeMath = true;
2288 ReciprocalMath = true;
2289 SignedZeros = false;
2290 TrappingMath = false;
2292 case options::OPT_fno_unsafe_math_optimizations:
2293 AssociativeMath = false;
2294 ReciprocalMath = false;
2296 TrappingMath = true;
2297 // -fno_unsafe_math_optimizations restores default denormal handling
2298 DenormalFPMath = "";
2301 case options::OPT_Ofast:
2302 // If -Ofast is the optimization level, then -ffast-math should be enabled
2306 case options::OPT_ffast_math:
2310 AssociativeMath = true;
2311 ReciprocalMath = true;
2312 SignedZeros = false;
2313 TrappingMath = false;
2314 // If fast-math is set then set the fp-contract mode to fast.
2315 FPContract = "fast";
2317 case options::OPT_fno_fast_math:
2320 // Turning on -ffast-math (with either flag) removes the need for
2321 // MathErrno. However, turning *off* -ffast-math merely restores the
2322 // toolchain default (which may be false).
2323 MathErrno = TC.IsMathErrnoDefault();
2324 AssociativeMath = false;
2325 ReciprocalMath = false;
2327 TrappingMath = true;
2328 // -fno_fast_math restores default denormal and fpcontract handling
2329 DenormalFPMath = "";
2334 // If we handled this option claim it
2339 CmdArgs.push_back("-menable-no-infs");
2342 CmdArgs.push_back("-menable-no-nans");
2345 CmdArgs.push_back("-fmath-errno");
2347 if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2349 CmdArgs.push_back("-menable-unsafe-fp-math");
2352 CmdArgs.push_back("-fno-signed-zeros");
2354 if (AssociativeMath && !SignedZeros && !TrappingMath)
2355 CmdArgs.push_back("-mreassociate");
2358 CmdArgs.push_back("-freciprocal-math");
2361 CmdArgs.push_back("-fno-trapping-math");
2363 if (!DenormalFPMath.empty())
2365 Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2367 if (!FPContract.empty())
2368 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2370 ParseMRecip(D, Args, CmdArgs);
2372 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2373 // individual features enabled by -ffast-math instead of the option itself as
2374 // that's consistent with gcc's behaviour.
2375 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2376 ReciprocalMath && !SignedZeros && !TrappingMath)
2377 CmdArgs.push_back("-ffast-math");
2379 // Handle __FINITE_MATH_ONLY__ similarly.
2380 if (!HonorINFs && !HonorNaNs)
2381 CmdArgs.push_back("-ffinite-math-only");
2383 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2384 CmdArgs.push_back("-mfpmath");
2385 CmdArgs.push_back(A->getValue());
2388 // Disable a codegen optimization for floating-point casts.
2389 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2390 options::OPT_fstrict_float_cast_overflow, false))
2391 CmdArgs.push_back("-fno-strict-float-cast-overflow");
2394 static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2395 const llvm::Triple &Triple,
2396 const InputInfo &Input) {
2397 // Enable region store model by default.
2398 CmdArgs.push_back("-analyzer-store=region");
2400 // Treat blocks as analysis entry points.
2401 CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2403 // Add default argument set.
2404 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2405 CmdArgs.push_back("-analyzer-checker=core");
2406 CmdArgs.push_back("-analyzer-checker=apiModeling");
2408 if (!Triple.isWindowsMSVCEnvironment()) {
2409 CmdArgs.push_back("-analyzer-checker=unix");
2411 // Enable "unix" checkers that also work on Windows.
2412 CmdArgs.push_back("-analyzer-checker=unix.API");
2413 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2414 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2415 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2416 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2417 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2420 // Disable some unix checkers for PS4.
2421 if (Triple.isPS4CPU()) {
2422 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2423 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2426 if (Triple.isOSDarwin())
2427 CmdArgs.push_back("-analyzer-checker=osx");
2429 CmdArgs.push_back("-analyzer-checker=deadcode");
2431 if (types::isCXX(Input.getType()))
2432 CmdArgs.push_back("-analyzer-checker=cplusplus");
2434 if (!Triple.isPS4CPU()) {
2435 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2436 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2437 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2438 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2439 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2440 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2443 // Default nullability checks.
2444 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2445 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2448 // Set the output format. The default is plist, for (lame) historical reasons.
2449 CmdArgs.push_back("-analyzer-output");
2450 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2451 CmdArgs.push_back(A->getValue());
2453 CmdArgs.push_back("plist");
2455 // Disable the presentation of standard compiler warnings when using
2456 // --analyze. We only want to show static analyzer diagnostics or frontend
2458 CmdArgs.push_back("-w");
2460 // Add -Xanalyzer arguments when running as analyzer.
2461 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2464 static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
2465 ArgStringList &CmdArgs, bool KernelOrKext) {
2466 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2468 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2469 // doesn't even have a stack!
2470 if (EffectiveTriple.isNVPTX())
2473 // -stack-protector=0 is default.
2474 unsigned StackProtectorLevel = 0;
2475 unsigned DefaultStackProtectorLevel =
2476 TC.GetDefaultStackProtectorLevel(KernelOrKext);
2478 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2479 options::OPT_fstack_protector_all,
2480 options::OPT_fstack_protector_strong,
2481 options::OPT_fstack_protector)) {
2482 if (A->getOption().matches(options::OPT_fstack_protector))
2483 StackProtectorLevel =
2484 std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2485 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2486 StackProtectorLevel = LangOptions::SSPStrong;
2487 else if (A->getOption().matches(options::OPT_fstack_protector_all))
2488 StackProtectorLevel = LangOptions::SSPReq;
2490 StackProtectorLevel = DefaultStackProtectorLevel;
2493 if (StackProtectorLevel) {
2494 CmdArgs.push_back("-stack-protector");
2495 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2498 // --param ssp-buffer-size=
2499 for (const Arg *A : Args.filtered(options::OPT__param)) {
2500 StringRef Str(A->getValue());
2501 if (Str.startswith("ssp-buffer-size=")) {
2502 if (StackProtectorLevel) {
2503 CmdArgs.push_back("-stack-protector-buffer-size");
2504 // FIXME: Verify the argument is a valid integer.
2505 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2512 static void RenderTrivialAutoVarInitOptions(const Driver &D,
2513 const ToolChain &TC,
2514 const ArgList &Args,
2515 ArgStringList &CmdArgs) {
2516 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
2517 StringRef TrivialAutoVarInit = "";
2519 for (const Arg *A : Args) {
2520 switch (A->getOption().getID()) {
2523 case options::OPT_ftrivial_auto_var_init: {
2525 StringRef Val = A->getValue();
2526 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
2527 TrivialAutoVarInit = Val;
2529 D.Diag(diag::err_drv_unsupported_option_argument)
2530 << A->getOption().getName() << Val;
2536 if (TrivialAutoVarInit.empty())
2537 switch (DefaultTrivialAutoVarInit) {
2538 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
2540 case LangOptions::TrivialAutoVarInitKind::Pattern:
2541 TrivialAutoVarInit = "pattern";
2543 case LangOptions::TrivialAutoVarInitKind::Zero:
2544 TrivialAutoVarInit = "zero";
2548 if (!TrivialAutoVarInit.empty()) {
2549 if (TrivialAutoVarInit == "zero" && !Args.hasArg(options::OPT_enable_trivial_var_init_zero))
2550 D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled);
2552 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
2556 static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2557 const unsigned ForwardedArguments[] = {
2558 options::OPT_cl_opt_disable,
2559 options::OPT_cl_strict_aliasing,
2560 options::OPT_cl_single_precision_constant,
2561 options::OPT_cl_finite_math_only,
2562 options::OPT_cl_kernel_arg_info,
2563 options::OPT_cl_unsafe_math_optimizations,
2564 options::OPT_cl_fast_relaxed_math,
2565 options::OPT_cl_mad_enable,
2566 options::OPT_cl_no_signed_zeros,
2567 options::OPT_cl_denorms_are_zero,
2568 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
2569 options::OPT_cl_uniform_work_group_size
2572 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2573 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2574 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2577 for (const auto &Arg : ForwardedArguments)
2578 if (const auto *A = Args.getLastArg(Arg))
2579 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2582 static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
2583 ArgStringList &CmdArgs) {
2584 bool ARCMTEnabled = false;
2585 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2586 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2587 options::OPT_ccc_arcmt_modify,
2588 options::OPT_ccc_arcmt_migrate)) {
2589 ARCMTEnabled = true;
2590 switch (A->getOption().getID()) {
2591 default: llvm_unreachable("missed a case");
2592 case options::OPT_ccc_arcmt_check:
2593 CmdArgs.push_back("-arcmt-check");
2595 case options::OPT_ccc_arcmt_modify:
2596 CmdArgs.push_back("-arcmt-modify");
2598 case options::OPT_ccc_arcmt_migrate:
2599 CmdArgs.push_back("-arcmt-migrate");
2600 CmdArgs.push_back("-mt-migrate-directory");
2601 CmdArgs.push_back(A->getValue());
2603 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2604 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2609 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2610 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2611 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2614 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2616 D.Diag(diag::err_drv_argument_not_allowed_with)
2617 << A->getAsString(Args) << "-ccc-arcmt-migrate";
2619 CmdArgs.push_back("-mt-migrate-directory");
2620 CmdArgs.push_back(A->getValue());
2622 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2623 options::OPT_objcmt_migrate_subscripting,
2624 options::OPT_objcmt_migrate_property)) {
2625 // None specified, means enable them all.
2626 CmdArgs.push_back("-objcmt-migrate-literals");
2627 CmdArgs.push_back("-objcmt-migrate-subscripting");
2628 CmdArgs.push_back("-objcmt-migrate-property");
2630 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2631 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2632 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2635 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2636 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2637 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2638 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2639 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2640 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2641 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2642 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2643 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2644 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2645 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2646 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2647 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2648 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2649 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2650 Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2654 static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
2655 const ArgList &Args, ArgStringList &CmdArgs) {
2656 // -fbuiltin is default unless -mkernel is used.
2658 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2659 !Args.hasArg(options::OPT_mkernel));
2661 CmdArgs.push_back("-fno-builtin");
2663 // -ffreestanding implies -fno-builtin.
2664 if (Args.hasArg(options::OPT_ffreestanding))
2665 UseBuiltins = false;
2667 // Process the -fno-builtin-* options.
2668 for (const auto &Arg : Args) {
2669 const Option &O = Arg->getOption();
2670 if (!O.matches(options::OPT_fno_builtin_))
2675 // If -fno-builtin is specified, then there's no need to pass the option to
2680 StringRef FuncName = Arg->getValue();
2681 CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2684 // le32-specific flags:
2685 // -fno-math-builtin: clang should not convert math builtins to intrinsics
2687 if (TC.getArch() == llvm::Triple::le32)
2688 CmdArgs.push_back("-fno-math-builtin");
2691 void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2692 llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2693 llvm::sys::path::append(Result, "org.llvm.clang.");
2694 appendUserToPath(Result);
2695 llvm::sys::path::append(Result, "ModuleCache");
2698 static void RenderModulesOptions(Compilation &C, const Driver &D,
2699 const ArgList &Args, const InputInfo &Input,
2700 const InputInfo &Output,
2701 ArgStringList &CmdArgs, bool &HaveModules) {
2702 // -fmodules enables the use of precompiled modules (off by default).
2703 // Users can pass -fno-cxx-modules to turn off modules support for
2704 // C++/Objective-C++ programs.
2705 bool HaveClangModules = false;
2706 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2707 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2708 options::OPT_fno_cxx_modules, true);
2709 if (AllowedInCXX || !types::isCXX(Input.getType())) {
2710 CmdArgs.push_back("-fmodules");
2711 HaveClangModules = true;
2715 HaveModules |= HaveClangModules;
2716 if (Args.hasArg(options::OPT_fmodules_ts)) {
2717 CmdArgs.push_back("-fmodules-ts");
2721 // -fmodule-maps enables implicit reading of module map files. By default,
2722 // this is enabled if we are using Clang's flavor of precompiled modules.
2723 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2724 options::OPT_fno_implicit_module_maps, HaveClangModules))
2725 CmdArgs.push_back("-fimplicit-module-maps");
2727 // -fmodules-decluse checks that modules used are declared so (off by default)
2728 if (Args.hasFlag(options::OPT_fmodules_decluse,
2729 options::OPT_fno_modules_decluse, false))
2730 CmdArgs.push_back("-fmodules-decluse");
2732 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2733 // all #included headers are part of modules.
2734 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2735 options::OPT_fno_modules_strict_decluse, false))
2736 CmdArgs.push_back("-fmodules-strict-decluse");
2738 // -fno-implicit-modules turns off implicitly compiling modules on demand.
2739 bool ImplicitModules = false;
2740 if (!Args.hasFlag(options::OPT_fimplicit_modules,
2741 options::OPT_fno_implicit_modules, HaveClangModules)) {
2743 CmdArgs.push_back("-fno-implicit-modules");
2744 } else if (HaveModules) {
2745 ImplicitModules = true;
2746 // -fmodule-cache-path specifies where our implicitly-built module files
2747 // should be written.
2748 SmallString<128> Path;
2749 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2750 Path = A->getValue();
2752 if (C.isForDiagnostics()) {
2753 // When generating crash reports, we want to emit the modules along with
2754 // the reproduction sources, so we ignore any provided module path.
2755 Path = Output.getFilename();
2756 llvm::sys::path::replace_extension(Path, ".cache");
2757 llvm::sys::path::append(Path, "modules");
2758 } else if (Path.empty()) {
2759 // No module path was provided: use the default.
2760 Driver::getDefaultModuleCachePath(Path);
2763 const char Arg[] = "-fmodules-cache-path=";
2764 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2765 CmdArgs.push_back(Args.MakeArgString(Path));
2769 // -fprebuilt-module-path specifies where to load the prebuilt module files.
2770 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2771 CmdArgs.push_back(Args.MakeArgString(
2772 std::string("-fprebuilt-module-path=") + A->getValue()));
2775 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
2776 options::OPT_fno_modules_validate_input_files_content,
2778 CmdArgs.push_back("-fvalidate-ast-input-files-content");
2781 // -fmodule-name specifies the module that is currently being built (or
2782 // used for header checking by -fmodule-maps).
2783 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2785 // -fmodule-map-file can be used to specify files containing module
2787 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2789 // -fbuiltin-module-map can be used to load the clang
2790 // builtin headers modulemap file.
2791 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2792 SmallString<128> BuiltinModuleMap(D.ResourceDir);
2793 llvm::sys::path::append(BuiltinModuleMap, "include");
2794 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2795 if (llvm::sys::fs::exists(BuiltinModuleMap))
2797 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2800 // The -fmodule-file=<name>=<file> form specifies the mapping of module
2801 // names to precompiled module files (the module is loaded only if used).
2802 // The -fmodule-file=<file> form can be used to unconditionally load
2803 // precompiled module files (whether used or not).
2805 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2807 Args.ClaimAllArgs(options::OPT_fmodule_file);
2809 // When building modules and generating crashdumps, we need to dump a module
2810 // dependency VFS alongside the output.
2811 if (HaveClangModules && C.isForDiagnostics()) {
2812 SmallString<128> VFSDir(Output.getFilename());
2813 llvm::sys::path::replace_extension(VFSDir, ".cache");
2814 // Add the cache directory as a temp so the crash diagnostics pick it up.
2815 C.addTempFile(Args.MakeArgString(VFSDir));
2817 llvm::sys::path::append(VFSDir, "vfs");
2818 CmdArgs.push_back("-module-dependency-dir");
2819 CmdArgs.push_back(Args.MakeArgString(VFSDir));
2822 if (HaveClangModules)
2823 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2825 // Pass through all -fmodules-ignore-macro arguments.
2826 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2827 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2828 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2830 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2832 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2833 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2834 D.Diag(diag::err_drv_argument_not_allowed_with)
2835 << A->getAsString(Args) << "-fbuild-session-timestamp";
2837 llvm::sys::fs::file_status Status;
2838 if (llvm::sys::fs::status(A->getValue(), Status))
2839 D.Diag(diag::err_drv_no_such_file) << A->getValue();
2841 Args.MakeArgString("-fbuild-session-timestamp=" +
2842 Twine((uint64_t)Status.getLastModificationTime()
2847 if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2848 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2849 options::OPT_fbuild_session_file))
2850 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2852 Args.AddLastArg(CmdArgs,
2853 options::OPT_fmodules_validate_once_per_build_session);
2856 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2857 options::OPT_fno_modules_validate_system_headers,
2859 CmdArgs.push_back("-fmodules-validate-system-headers");
2861 Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2864 static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
2865 ArgStringList &CmdArgs) {
2866 // -fsigned-char is default.
2867 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2868 options::OPT_fno_signed_char,
2869 options::OPT_funsigned_char,
2870 options::OPT_fno_unsigned_char)) {
2871 if (A->getOption().matches(options::OPT_funsigned_char) ||
2872 A->getOption().matches(options::OPT_fno_signed_char)) {
2873 CmdArgs.push_back("-fno-signed-char");
2875 } else if (!isSignedCharDefault(T)) {
2876 CmdArgs.push_back("-fno-signed-char");
2879 // The default depends on the language standard.
2880 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
2882 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2883 options::OPT_fno_short_wchar)) {
2884 if (A->getOption().matches(options::OPT_fshort_wchar)) {
2885 CmdArgs.push_back("-fwchar-type=short");
2886 CmdArgs.push_back("-fno-signed-wchar");
2888 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
2889 CmdArgs.push_back("-fwchar-type=int");
2890 if (IsARM && !(T.isOSWindows() || T.isOSNetBSD() ||
2892 CmdArgs.push_back("-fno-signed-wchar");
2894 CmdArgs.push_back("-fsigned-wchar");
2899 static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
2900 const llvm::Triple &T, const ArgList &Args,
2901 ObjCRuntime &Runtime, bool InferCovariantReturns,
2902 const InputInfo &Input, ArgStringList &CmdArgs) {
2903 const llvm::Triple::ArchType Arch = TC.getArch();
2905 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2906 // is the default. Except for deployment target of 10.5, next runtime is
2907 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2908 if (Runtime.isNonFragile()) {
2909 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2910 options::OPT_fno_objc_legacy_dispatch,
2911 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2912 if (TC.UseObjCMixedDispatch())
2913 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2915 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2919 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2920 // to do Array/Dictionary subscripting by default.
2921 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
2922 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2923 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2925 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2926 // NOTE: This logic is duplicated in ToolChains.cpp.
2927 if (isObjCAutoRefCount(Args)) {
2930 CmdArgs.push_back("-fobjc-arc");
2932 // FIXME: It seems like this entire block, and several around it should be
2933 // wrapped in isObjC, but for now we just use it here as this is where it
2934 // was being used previously.
2935 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2936 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2937 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2939 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2942 // Allow the user to enable full exceptions code emission.
2943 // We default off for Objective-C, on for Objective-C++.
2944 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2945 options::OPT_fno_objc_arc_exceptions,
2946 /*Default=*/types::isCXX(Input.getType())))
2947 CmdArgs.push_back("-fobjc-arc-exceptions");
2950 // Silence warning for full exception code emission options when explicitly
2951 // set to use no ARC.
2952 if (Args.hasArg(options::OPT_fno_objc_arc)) {
2953 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2954 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2957 // Allow the user to control whether messages can be converted to runtime
2959 if (types::isObjC(Input.getType())) {
2960 auto *Arg = Args.getLastArg(
2961 options::OPT_fobjc_convert_messages_to_runtime_calls,
2962 options::OPT_fno_objc_convert_messages_to_runtime_calls);
2964 Arg->getOption().matches(
2965 options::OPT_fno_objc_convert_messages_to_runtime_calls))
2966 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
2969 // -fobjc-infer-related-result-type is the default, except in the Objective-C
2971 if (InferCovariantReturns)
2972 CmdArgs.push_back("-fno-objc-infer-related-result-type");
2974 // Pass down -fobjc-weak or -fno-objc-weak if present.
2975 if (types::isObjC(Input.getType())) {
2977 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
2980 } else if (!Runtime.allowsWeak()) {
2981 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
2982 D.Diag(diag::err_objc_weak_unsupported);
2984 WeakArg->render(Args, CmdArgs);
2989 static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
2990 ArgStringList &CmdArgs) {
2991 bool CaretDefault = true;
2992 bool ColumnDefault = true;
2994 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
2995 options::OPT__SLASH_diagnostics_column,
2996 options::OPT__SLASH_diagnostics_caret)) {
2997 switch (A->getOption().getID()) {
2998 case options::OPT__SLASH_diagnostics_caret:
2999 CaretDefault = true;
3000 ColumnDefault = true;
3002 case options::OPT__SLASH_diagnostics_column:
3003 CaretDefault = false;
3004 ColumnDefault = true;
3006 case options::OPT__SLASH_diagnostics_classic:
3007 CaretDefault = false;
3008 ColumnDefault = false;
3013 // -fcaret-diagnostics is default.
3014 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3015 options::OPT_fno_caret_diagnostics, CaretDefault))
3016 CmdArgs.push_back("-fno-caret-diagnostics");
3018 // -fdiagnostics-fixit-info is default, only pass non-default.
3019 if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
3020 options::OPT_fno_diagnostics_fixit_info))
3021 CmdArgs.push_back("-fno-diagnostics-fixit-info");
3023 // Enable -fdiagnostics-show-option by default.
3024 if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
3025 options::OPT_fno_diagnostics_show_option))
3026 CmdArgs.push_back("-fdiagnostics-show-option");
3029 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3030 CmdArgs.push_back("-fdiagnostics-show-category");
3031 CmdArgs.push_back(A->getValue());
3034 if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
3035 options::OPT_fno_diagnostics_show_hotness, false))
3036 CmdArgs.push_back("-fdiagnostics-show-hotness");
3039 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
3041 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
3042 CmdArgs.push_back(Args.MakeArgString(Opt));
3045 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3046 CmdArgs.push_back("-fdiagnostics-format");
3047 CmdArgs.push_back(A->getValue());
3050 if (const Arg *A = Args.getLastArg(
3051 options::OPT_fdiagnostics_show_note_include_stack,
3052 options::OPT_fno_diagnostics_show_note_include_stack)) {
3053 const Option &O = A->getOption();
3054 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
3055 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3057 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3060 // Color diagnostics are parsed by the driver directly from argv and later
3061 // re-parsed to construct this job; claim any possible color diagnostic here
3062 // to avoid warn_drv_unused_argument and diagnose bad
3063 // OPT_fdiagnostics_color_EQ values.
3064 for (const Arg *A : Args) {
3065 const Option &O = A->getOption();
3066 if (!O.matches(options::OPT_fcolor_diagnostics) &&
3067 !O.matches(options::OPT_fdiagnostics_color) &&
3068 !O.matches(options::OPT_fno_color_diagnostics) &&
3069 !O.matches(options::OPT_fno_diagnostics_color) &&
3070 !O.matches(options::OPT_fdiagnostics_color_EQ))
3073 if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
3074 StringRef Value(A->getValue());
3075 if (Value != "always" && Value != "never" && Value != "auto")
3076 D.Diag(diag::err_drv_clang_unsupported)
3077 << ("-fdiagnostics-color=" + Value).str();
3082 if (D.getDiags().getDiagnosticOptions().ShowColors)
3083 CmdArgs.push_back("-fcolor-diagnostics");
3085 if (Args.hasArg(options::OPT_fansi_escape_codes))
3086 CmdArgs.push_back("-fansi-escape-codes");
3088 if (!Args.hasFlag(options::OPT_fshow_source_location,
3089 options::OPT_fno_show_source_location))
3090 CmdArgs.push_back("-fno-show-source-location");
3092 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
3093 CmdArgs.push_back("-fdiagnostics-absolute-paths");
3095 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
3097 CmdArgs.push_back("-fno-show-column");
3099 if (!Args.hasFlag(options::OPT_fspell_checking,
3100 options::OPT_fno_spell_checking))
3101 CmdArgs.push_back("-fno-spell-checking");
3104 enum class DwarfFissionKind { None, Split, Single };
3106 static DwarfFissionKind getDebugFissionKind(const Driver &D,
3107 const ArgList &Args, Arg *&Arg) {
3109 Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ);
3111 return DwarfFissionKind::None;
3113 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
3114 return DwarfFissionKind::Split;
3116 StringRef Value = Arg->getValue();
3117 if (Value == "split")
3118 return DwarfFissionKind::Split;
3119 if (Value == "single")
3120 return DwarfFissionKind::Single;
3122 D.Diag(diag::err_drv_unsupported_option_argument)
3123 << Arg->getOption().getName() << Arg->getValue();
3124 return DwarfFissionKind::None;
3127 static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
3128 const llvm::Triple &T, const ArgList &Args,
3129 bool EmitCodeView, bool IsWindowsMSVC,
3130 ArgStringList &CmdArgs,
3131 codegenoptions::DebugInfoKind &DebugInfoKind,
3132 DwarfFissionKind &DwarfFission) {
3133 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
3134 options::OPT_fno_debug_info_for_profiling, false) &&
3135 checkDebugInfoOption(
3136 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
3137 CmdArgs.push_back("-fdebug-info-for-profiling");
3139 // The 'g' groups options involve a somewhat intricate sequence of decisions
3140 // about what to pass from the driver to the frontend, but by the time they
3141 // reach cc1 they've been factored into three well-defined orthogonal choices:
3142 // * what level of debug info to generate
3143 // * what dwarf version to write
3144 // * what debugger tuning to use
3145 // This avoids having to monkey around further in cc1 other than to disable
3146 // codeview if not running in a Windows environment. Perhaps even that
3147 // decision should be made in the driver as well though.
3148 unsigned DWARFVersion = 0;
3149 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
3151 bool SplitDWARFInlining =
3152 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
3153 options::OPT_fno_split_dwarf_inlining, true);
3155 Args.ClaimAllArgs(options::OPT_g_Group);
3158 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
3160 if (DwarfFission != DwarfFissionKind::None &&
3161 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
3162 DwarfFission = DwarfFissionKind::None;
3163 SplitDWARFInlining = false;
3167 Args.getLastArg(options::OPT_g_Group, options::OPT_gsplit_dwarf,
3168 options::OPT_gsplit_dwarf_EQ)) {
3169 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3171 // If the last option explicitly specified a debug-info level, use it.
3172 if (checkDebugInfoOption(A, Args, D, TC) &&
3173 A->getOption().matches(options::OPT_gN_Group)) {
3174 DebugInfoKind = DebugLevelToInfoKind(*A);
3175 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
3176 // complicated if you've disabled inline info in the skeleton CUs
3177 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
3178 // line-tables-only, so let those compose naturally in that case.
3179 if (DebugInfoKind == codegenoptions::NoDebugInfo ||
3180 DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
3181 (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
3182 SplitDWARFInlining))
3183 DwarfFission = DwarfFissionKind::None;
3187 // If a debugger tuning argument appeared, remember it.
3189 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
3190 if (checkDebugInfoOption(A, Args, D, TC)) {
3191 if (A->getOption().matches(options::OPT_glldb))
3192 DebuggerTuning = llvm::DebuggerKind::LLDB;
3193 else if (A->getOption().matches(options::OPT_gsce))
3194 DebuggerTuning = llvm::DebuggerKind::SCE;
3196 DebuggerTuning = llvm::DebuggerKind::GDB;
3200 // If a -gdwarf argument appeared, remember it.
3202 Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
3203 options::OPT_gdwarf_4, options::OPT_gdwarf_5))
3204 if (checkDebugInfoOption(A, Args, D, TC))
3205 DWARFVersion = DwarfVersionNum(A->getSpelling());
3207 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
3208 if (checkDebugInfoOption(A, Args, D, TC))
3209 EmitCodeView = true;
3212 // If the user asked for debug info but did not explicitly specify -gcodeview
3213 // or -gdwarf, ask the toolchain for the default format.
3214 if (!EmitCodeView && DWARFVersion == 0 &&
3215 DebugInfoKind != codegenoptions::NoDebugInfo) {
3216 switch (TC.getDefaultDebugFormat()) {
3217 case codegenoptions::DIF_CodeView:
3218 EmitCodeView = true;
3220 case codegenoptions::DIF_DWARF:
3221 DWARFVersion = TC.GetDefaultDwarfVersion();
3226 // -gline-directives-only supported only for the DWARF debug info.
3227 if (DWARFVersion == 0 && DebugInfoKind == codegenoptions::DebugDirectivesOnly)
3228 DebugInfoKind = codegenoptions::NoDebugInfo;
3230 // We ignore flag -gstrict-dwarf for now.
3231 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
3232 Args.ClaimAllArgs(options::OPT_g_flags_Group);
3234 // Column info is included by default for everything except SCE and
3235 // CodeView. Clang doesn't track end columns, just starting columns, which,
3236 // in theory, is fine for CodeView (and PDB). In practice, however, the
3237 // Microsoft debuggers don't handle missing end columns well, so it's better
3238 // not to include any column info.
3239 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
3240 (void)checkDebugInfoOption(A, Args, D, TC);
3241 if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
3242 /*Default=*/!EmitCodeView &&
3243 DebuggerTuning != llvm::DebuggerKind::SCE))
3244 CmdArgs.push_back("-dwarf-column-info");
3246 // FIXME: Move backend command line options to the module.
3247 // If -gline-tables-only or -gline-directives-only is the last option it wins.
3248 if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
3249 if (checkDebugInfoOption(A, Args, D, TC)) {
3250 if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
3251 DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
3252 DebugInfoKind = codegenoptions::LimitedDebugInfo;
3253 CmdArgs.push_back("-dwarf-ext-refs");
3254 CmdArgs.push_back("-fmodule-format=obj");
3258 if (T.isOSBinFormatELF() && !SplitDWARFInlining)
3259 CmdArgs.push_back("-fno-split-dwarf-inlining");
3261 // After we've dealt with all combinations of things that could
3262 // make DebugInfoKind be other than None or DebugLineTablesOnly,
3263 // figure out if we need to "upgrade" it to standalone debug info.
3264 // We parse these two '-f' options whether or not they will be used,
3265 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
3266 bool NeedFullDebug = Args.hasFlag(
3267 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
3268 DebuggerTuning == llvm::DebuggerKind::LLDB ||
3269 TC.GetDefaultStandaloneDebug());
3270 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3271 (void)checkDebugInfoOption(A, Args, D, TC);
3272 if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3273 DebugInfoKind = codegenoptions::FullDebugInfo;
3275 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
3277 // Source embedding is a vendor extension to DWARF v5. By now we have
3278 // checked if a DWARF version was stated explicitly, and have otherwise
3279 // fallen back to the target default, so if this is still not at least 5
3280 // we emit an error.
3281 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
3282 if (DWARFVersion < 5)
3283 D.Diag(diag::err_drv_argument_only_allowed_with)
3284 << A->getAsString(Args) << "-gdwarf-5";
3285 else if (checkDebugInfoOption(A, Args, D, TC))
3286 CmdArgs.push_back("-gembed-source");
3290 CmdArgs.push_back("-gcodeview");
3292 // Emit codeview type hashes if requested.
3293 if (Args.hasFlag(options::OPT_gcodeview_ghash,
3294 options::OPT_gno_codeview_ghash, false)) {
3295 CmdArgs.push_back("-gcodeview-ghash");
3299 // Adjust the debug info kind for the given toolchain.
3300 TC.adjustDebugInfoKind(DebugInfoKind, Args);
3302 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3305 // -fdebug-macro turns on macro debug info generation.
3306 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3308 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
3310 CmdArgs.push_back("-debug-info-macro");
3312 // -ggnu-pubnames turns on gnu style pubnames in the backend.
3313 const auto *PubnamesArg =
3314 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3315 options::OPT_gpubnames, options::OPT_gno_pubnames);
3316 if (DwarfFission != DwarfFissionKind::None ||
3317 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
3319 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
3320 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
3321 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
3322 options::OPT_gpubnames)
3324 : "-ggnu-pubnames");
3326 if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
3327 options::OPT_fno_debug_ranges_base_address, false)) {
3328 CmdArgs.push_back("-fdebug-ranges-base-address");
3331 // -gdwarf-aranges turns on the emission of the aranges section in the
3333 // Always enabled for SCE tuning.
3334 bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
3335 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
3336 NeedAranges = checkDebugInfoOption(A, Args, D, TC) || NeedAranges;
3338 CmdArgs.push_back("-mllvm");
3339 CmdArgs.push_back("-generate-arange-section");
3342 if (Args.hasFlag(options::OPT_fdebug_types_section,
3343 options::OPT_fno_debug_types_section, false)) {
3344 if (!T.isOSBinFormatELF()) {
3345 D.Diag(diag::err_drv_unsupported_opt_for_target)
3346 << Args.getLastArg(options::OPT_fdebug_types_section)
3349 } else if (checkDebugInfoOption(
3350 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
3352 CmdArgs.push_back("-mllvm");
3353 CmdArgs.push_back("-generate-type-units");
3357 // Decide how to render forward declarations of template instantiations.
3358 // SCE wants full descriptions, others just get them in the name.
3359 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3360 CmdArgs.push_back("-debug-forward-template-params");
3362 // Do we need to explicitly import anonymous namespaces into the parent
3364 if (DebuggerTuning == llvm::DebuggerKind::SCE)
3365 CmdArgs.push_back("-dwarf-explicit-import");
3367 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
3370 void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3371 const InputInfo &Output, const InputInfoList &Inputs,
3372 const ArgList &Args, const char *LinkingOutput) const {
3373 const auto &TC = getToolChain();
3374 const llvm::Triple &RawTriple = TC.getTriple();
3375 const llvm::Triple &Triple = TC.getEffectiveTriple();
3376 const std::string &TripleStr = Triple.getTriple();
3379 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3380 const Driver &D = TC.getDriver();
3381 ArgStringList CmdArgs;
3383 // Check number of inputs for sanity. We need at least one input.
3384 assert(Inputs.size() >= 1 && "Must have at least one input.");
3385 // CUDA/HIP compilation may have multiple inputs (source file + results of
3386 // device-side compilations). OpenMP device jobs also take the host IR as a
3387 // second input. Module precompilation accepts a list of header files to
3388 // include as part of the module. All other jobs are expected to have exactly
3390 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
3391 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
3392 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
3393 bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
3395 // A header module compilation doesn't have a main input file, so invent a
3396 // fake one as a placeholder.
3397 const char *ModuleName = [&]{
3398 auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
3399 return ModuleNameArg ? ModuleNameArg->getValue() : "";
3401 InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
3403 const InputInfo &Input =
3404 IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
3406 InputInfoList ModuleHeaderInputs;
3407 const InputInfo *CudaDeviceInput = nullptr;
3408 const InputInfo *OpenMPDeviceInput = nullptr;
3409 for (const InputInfo &I : Inputs) {
3411 // This is the primary input.
3412 } else if (IsHeaderModulePrecompile &&
3413 types::getPrecompiledType(I.getType()) == types::TY_PCH) {
3414 types::ID Expected = HeaderModuleInput.getType();
3415 if (I.getType() != Expected) {
3416 D.Diag(diag::err_drv_module_header_wrong_kind)
3417 << I.getFilename() << types::getTypeName(I.getType())
3418 << types::getTypeName(Expected);
3420 ModuleHeaderInputs.push_back(I);
3421 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
3422 CudaDeviceInput = &I;
3423 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
3424 OpenMPDeviceInput = &I;
3426 llvm_unreachable("unexpectedly given multiple inputs");
3430 const llvm::Triple *AuxTriple = IsCuda ? TC.getAuxTriple() : nullptr;
3431 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
3432 bool IsIAMCU = RawTriple.isOSIAMCU();
3434 // Adjust IsWindowsXYZ for CUDA/HIP compilations. Even when compiling in
3435 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3436 // Windows), we need to pass Windows-specific flags to cc1.
3437 if (IsCuda || IsHIP)
3438 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3440 // C++ is not supported for IAMCU.
3441 if (IsIAMCU && types::isCXX(Input.getType()))
3442 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3444 // Invoke ourselves in -cc1 mode.
3446 // FIXME: Implement custom jobs for internal actions.
3447 CmdArgs.push_back("-cc1");
3449 // Add the "effective" target triple.
3450 CmdArgs.push_back("-triple");
3451 CmdArgs.push_back(Args.MakeArgString(TripleStr));
3453 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3454 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3455 Args.ClaimAllArgs(options::OPT_MJ);
3456 } else if (const Arg *GenCDBFragment =
3457 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
3458 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
3459 TripleStr, Output, Input, Args);
3460 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
3463 if (IsCuda || IsHIP) {
3464 // We have to pass the triple of the host if compiling for a CUDA/HIP device
3466 std::string NormalizedTriple;
3467 if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3468 JA.isDeviceOffloading(Action::OFK_HIP))
3469 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3473 // Host-side compilation.
3475 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3476 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3480 // We need to figure out which CUDA version we're compiling for, as that
3481 // determines how we load and launch GPU kernels.
3482 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
3483 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
3484 assert(CTC && "Expected valid CUDA Toolchain.");
3485 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
3486 CmdArgs.push_back(Args.MakeArgString(
3487 Twine("-target-sdk-version=") +
3488 CudaVersionToString(CTC->CudaInstallation.version())));
3491 CmdArgs.push_back("-aux-triple");
3492 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3495 if (IsOpenMPDevice) {
3496 // We have to pass the triple of the host if compiling for an OpenMP device.
3497 std::string NormalizedTriple =
3498 C.getSingleOffloadToolChain<Action::OFK_Host>()
3501 CmdArgs.push_back("-aux-triple");
3502 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3505 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3506 Triple.getArch() == llvm::Triple::thumb)) {
3507 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3509 Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3511 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3515 // Push all default warning arguments that are specific to
3516 // the given target. These come before user provided warning options
3518 TC.addClangWarningOptions(CmdArgs);
3520 // Select the appropriate action.
3521 RewriteKind rewriteKind = RK_None;
3523 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
3524 // it claims when not running an assembler. Otherwise, clang would emit
3525 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
3526 // flags while debugging something. That'd be somewhat inconvenient, and it's
3527 // also inconsistent with most other flags -- we don't warn on
3528 // -ffunction-sections not being used in -E mode either for example, even
3529 // though it's not really used either.
3530 if (!isa<AssembleJobAction>(JA)) {
3531 // The args claimed here should match the args used in
3532 // CollectArgsForIntegratedAssembler().
3533 if (TC.useIntegratedAs()) {
3534 Args.ClaimAllArgs(options::OPT_mrelax_all);
3535 Args.ClaimAllArgs(options::OPT_mno_relax_all);
3536 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
3537 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
3538 switch (C.getDefaultToolChain().getArch()) {
3539 case llvm::Triple::arm:
3540 case llvm::Triple::armeb:
3541 case llvm::Triple::thumb:
3542 case llvm::Triple::thumbeb:
3543 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
3549 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
3550 Args.ClaimAllArgs(options::OPT_Xassembler);
3553 if (isa<AnalyzeJobAction>(JA)) {
3554 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3555 CmdArgs.push_back("-analyze");
3556 } else if (isa<MigrateJobAction>(JA)) {
3557 CmdArgs.push_back("-migrate");
3558 } else if (isa<PreprocessJobAction>(JA)) {
3559 if (Output.getType() == types::TY_Dependencies)
3560 CmdArgs.push_back("-Eonly");
3562 CmdArgs.push_back("-E");
3563 if (Args.hasArg(options::OPT_rewrite_objc) &&
3564 !Args.hasArg(options::OPT_g_Group))
3565 CmdArgs.push_back("-P");
3567 } else if (isa<AssembleJobAction>(JA)) {
3568 CmdArgs.push_back("-emit-obj");
3570 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3572 // Also ignore explicit -force_cpusubtype_ALL option.
3573 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3574 } else if (isa<PrecompileJobAction>(JA)) {
3575 if (JA.getType() == types::TY_Nothing)
3576 CmdArgs.push_back("-fsyntax-only");
3577 else if (JA.getType() == types::TY_ModuleFile)
3578 CmdArgs.push_back(IsHeaderModulePrecompile
3579 ? "-emit-header-module"
3580 : "-emit-module-interface");
3582 CmdArgs.push_back("-emit-pch");
3583 } else if (isa<VerifyPCHJobAction>(JA)) {
3584 CmdArgs.push_back("-verify-pch");
3586 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3587 "Invalid action for clang tool.");
3588 if (JA.getType() == types::TY_Nothing) {
3589 CmdArgs.push_back("-fsyntax-only");
3590 } else if (JA.getType() == types::TY_LLVM_IR ||
3591 JA.getType() == types::TY_LTO_IR) {
3592 CmdArgs.push_back("-emit-llvm");
3593 } else if (JA.getType() == types::TY_LLVM_BC ||
3594 JA.getType() == types::TY_LTO_BC) {
3595 CmdArgs.push_back("-emit-llvm-bc");
3596 } else if (JA.getType() == types::TY_IFS ||
3597 JA.getType() == types::TY_IFS_CPP) {
3599 Args.hasArg(options::OPT_interface_stub_version_EQ)
3600 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
3601 : "experimental-ifs-v1";
3602 CmdArgs.push_back("-emit-interface-stubs");
3604 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
3605 } else if (JA.getType() == types::TY_PP_Asm) {
3606 CmdArgs.push_back("-S");
3607 } else if (JA.getType() == types::TY_AST) {
3608 CmdArgs.push_back("-emit-pch");
3609 } else if (JA.getType() == types::TY_ModuleFile) {
3610 CmdArgs.push_back("-module-file-info");
3611 } else if (JA.getType() == types::TY_RewrittenObjC) {
3612 CmdArgs.push_back("-rewrite-objc");
3613 rewriteKind = RK_NonFragile;
3614 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3615 CmdArgs.push_back("-rewrite-objc");
3616 rewriteKind = RK_Fragile;
3618 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3621 // Preserve use-list order by default when emitting bitcode, so that
3622 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3623 // same result as running passes here. For LTO, we don't need to preserve
3624 // the use-list order, since serialization to bitcode is part of the flow.
3625 if (JA.getType() == types::TY_LLVM_BC)
3626 CmdArgs.push_back("-emit-llvm-uselists");
3628 // Device-side jobs do not support LTO.
3629 bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3630 JA.isDeviceOffloading(Action::OFK_Host));
3632 if (D.isUsingLTO() && !isDeviceOffloadAction) {
3633 Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3634 CmdArgs.push_back("-flto-unit");
3638 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3639 if (!types::isLLVMIR(Input.getType()))
3640 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
3641 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3644 if (Args.getLastArg(options::OPT_save_temps_EQ))
3645 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3647 // Embed-bitcode option.
3648 // Only white-listed flags below are allowed to be embedded.
3649 if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3650 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3651 // Add flags implied by -fembed-bitcode.
3652 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3653 // Disable all llvm IR level optimizations.
3654 CmdArgs.push_back("-disable-llvm-passes");
3656 // Render target options such as -fuse-init-array on modern ELF platforms.
3657 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
3659 // reject options that shouldn't be supported in bitcode
3660 // also reject kernel/kext
3661 static const constexpr unsigned kBitcodeOptionBlacklist[] = {
3662 options::OPT_mkernel,
3663 options::OPT_fapple_kext,
3664 options::OPT_ffunction_sections,
3665 options::OPT_fno_function_sections,
3666 options::OPT_fdata_sections,
3667 options::OPT_fno_data_sections,
3668 options::OPT_funique_section_names,
3669 options::OPT_fno_unique_section_names,
3670 options::OPT_mrestrict_it,
3671 options::OPT_mno_restrict_it,
3672 options::OPT_mstackrealign,
3673 options::OPT_mno_stackrealign,
3674 options::OPT_mstack_alignment,
3675 options::OPT_mcmodel_EQ,
3676 options::OPT_mlong_calls,
3677 options::OPT_mno_long_calls,
3678 options::OPT_ggnu_pubnames,
3679 options::OPT_gdwarf_aranges,
3680 options::OPT_fdebug_types_section,
3681 options::OPT_fno_debug_types_section,
3682 options::OPT_fdwarf_directory_asm,
3683 options::OPT_fno_dwarf_directory_asm,
3684 options::OPT_mrelax_all,
3685 options::OPT_mno_relax_all,
3686 options::OPT_ftrap_function_EQ,
3687 options::OPT_ffixed_r9,
3688 options::OPT_mfix_cortex_a53_835769,
3689 options::OPT_mno_fix_cortex_a53_835769,
3690 options::OPT_ffixed_x18,
3691 options::OPT_mglobal_merge,
3692 options::OPT_mno_global_merge,
3693 options::OPT_mred_zone,
3694 options::OPT_mno_red_zone,
3695 options::OPT_Wa_COMMA,
3696 options::OPT_Xassembler,
3699 for (const auto &A : Args)
3700 if (llvm::find(kBitcodeOptionBlacklist, A->getOption().getID()) !=
3701 std::end(kBitcodeOptionBlacklist))
3702 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
3704 // Render the CodeGen options that need to be passed.
3705 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3706 options::OPT_fno_optimize_sibling_calls))
3707 CmdArgs.push_back("-mdisable-tail-calls");
3709 RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
3712 // Render ABI arguments
3713 switch (TC.getArch()) {
3715 case llvm::Triple::arm:
3716 case llvm::Triple::armeb:
3717 case llvm::Triple::thumbeb:
3718 RenderARMABI(Triple, Args, CmdArgs);
3720 case llvm::Triple::aarch64:
3721 case llvm::Triple::aarch64_be:
3722 RenderAArch64ABI(Triple, Args, CmdArgs);
3726 // Optimization level for CodeGen.
3727 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3728 if (A->getOption().matches(options::OPT_O4)) {
3729 CmdArgs.push_back("-O3");
3730 D.Diag(diag::warn_O4_is_O3);
3732 A->render(Args, CmdArgs);
3736 // Input/Output file.
3737 if (Output.getType() == types::TY_Dependencies) {
3738 // Handled with other dependency code.
3739 } else if (Output.isFilename()) {
3740 CmdArgs.push_back("-o");
3741 CmdArgs.push_back(Output.getFilename());
3743 assert(Output.isNothing() && "Input output.");
3746 for (const auto &II : Inputs) {
3747 addDashXForInput(Args, II, CmdArgs);
3748 if (II.isFilename())
3749 CmdArgs.push_back(II.getFilename());
3751 II.getInputArg().renderAsInput(Args, CmdArgs);
3754 C.addCommand(std::make_unique<Command>(JA, *this, D.getClangProgramPath(),
3759 if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3760 CmdArgs.push_back("-fembed-bitcode=marker");
3762 // We normally speed up the clang process a bit by skipping destructors at
3763 // exit, but when we're generating diagnostics we can rely on some of the
3765 if (!C.isForDiagnostics())
3766 CmdArgs.push_back("-disable-free");
3769 const bool IsAssertBuild = false;
3771 const bool IsAssertBuild = true;
3774 // Disable the verification pass in -asserts builds.
3776 CmdArgs.push_back("-disable-llvm-verifier");
3778 // Discard value names in assert builds unless otherwise specified.
3779 if (Args.hasFlag(options::OPT_fdiscard_value_names,
3780 options::OPT_fno_discard_value_names, !IsAssertBuild))
3781 CmdArgs.push_back("-discard-value-names");
3783 // Set the main file name, so that debug info works even with
3785 CmdArgs.push_back("-main-file-name");
3786 CmdArgs.push_back(getBaseInputName(Args, Input));
3788 // Some flags which affect the language (via preprocessor
3790 if (Args.hasArg(options::OPT_static))
3791 CmdArgs.push_back("-static-define");
3793 if (Args.hasArg(options::OPT_municode))
3794 CmdArgs.push_back("-DUNICODE");
3796 if (isa<AnalyzeJobAction>(JA))
3797 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
3799 if (isa<AnalyzeJobAction>(JA) ||
3800 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
3801 CmdArgs.push_back("-setup-static-analyzer");
3803 // Enable compatilibily mode to avoid analyzer-config related errors.
3804 // Since we can't access frontend flags through hasArg, let's manually iterate
3806 bool FoundAnalyzerConfig = false;
3807 for (auto Arg : Args.filtered(options::OPT_Xclang))
3808 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3809 FoundAnalyzerConfig = true;
3812 if (!FoundAnalyzerConfig)
3813 for (auto Arg : Args.filtered(options::OPT_Xanalyzer))
3814 if (StringRef(Arg->getValue()) == "-analyzer-config") {
3815 FoundAnalyzerConfig = true;
3818 if (FoundAnalyzerConfig)
3819 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
3821 CheckCodeGenerationOptions(D, Args);
3823 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
3824 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3825 if (FunctionAlignment) {
3826 CmdArgs.push_back("-function-alignment");
3827 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3830 llvm::Reloc::Model RelocationModel;
3833 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
3835 const char *RMName = RelocationModelName(RelocationModel);
3837 if ((RelocationModel == llvm::Reloc::ROPI ||
3838 RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3839 types::isCXX(Input.getType()) &&
3840 !Args.hasArg(options::OPT_fallow_unsupported))
3841 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3844 CmdArgs.push_back("-mrelocation-model");
3845 CmdArgs.push_back(RMName);
3848 CmdArgs.push_back("-pic-level");
3849 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3851 CmdArgs.push_back("-pic-is-pie");
3854 if (RelocationModel == llvm::Reloc::ROPI ||
3855 RelocationModel == llvm::Reloc::ROPI_RWPI)
3856 CmdArgs.push_back("-fropi");
3857 if (RelocationModel == llvm::Reloc::RWPI ||
3858 RelocationModel == llvm::Reloc::ROPI_RWPI)
3859 CmdArgs.push_back("-frwpi");
3861 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3862 CmdArgs.push_back("-meabi");
3863 CmdArgs.push_back(A->getValue());
3866 CmdArgs.push_back("-mthread-model");
3867 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
3868 if (!TC.isThreadModelSupported(A->getValue()))
3869 D.Diag(diag::err_drv_invalid_thread_model_for_target)
3870 << A->getValue() << A->getAsString(Args);
3871 CmdArgs.push_back(A->getValue());
3874 CmdArgs.push_back(Args.MakeArgString(TC.getThreadModel()));
3876 Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3878 if (Args.hasFlag(options::OPT_fmerge_all_constants,
3879 options::OPT_fno_merge_all_constants, false))
3880 CmdArgs.push_back("-fmerge-all-constants");
3882 if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
3883 options::OPT_fdelete_null_pointer_checks, false))
3884 CmdArgs.push_back("-fno-delete-null-pointer-checks");
3886 // LLVM Code Generator Options.
3888 if (Args.hasArg(options::OPT_frewrite_map_file) ||
3889 Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3890 for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3891 options::OPT_frewrite_map_file_EQ)) {
3892 StringRef Map = A->getValue();
3893 if (!llvm::sys::fs::exists(Map)) {
3894 D.Diag(diag::err_drv_no_such_file) << Map;
3896 CmdArgs.push_back("-frewrite-map-file");
3897 CmdArgs.push_back(A->getValue());
3903 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3904 StringRef v = A->getValue();
3905 CmdArgs.push_back("-mllvm");
3906 CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3910 if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3912 CmdArgs.push_back("-fno-jump-tables");
3914 if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3915 options::OPT_fno_profile_sample_accurate, false))
3916 CmdArgs.push_back("-fprofile-sample-accurate");
3918 if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3919 options::OPT_fno_preserve_as_comments, true))
3920 CmdArgs.push_back("-fno-preserve-as-comments");
3922 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3923 CmdArgs.push_back("-mregparm");
3924 CmdArgs.push_back(A->getValue());
3927 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3928 options::OPT_freg_struct_return)) {
3929 if (TC.getArch() != llvm::Triple::x86) {
3930 D.Diag(diag::err_drv_unsupported_opt_for_target)
3931 << A->getSpelling() << RawTriple.str();
3932 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3933 CmdArgs.push_back("-fpcc-struct-return");
3935 assert(A->getOption().matches(options::OPT_freg_struct_return));
3936 CmdArgs.push_back("-freg-struct-return");
3940 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3941 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3943 CodeGenOptions::FramePointerKind FPKeepKind =
3944 getFramePointerKind(Args, RawTriple);
3945 const char *FPKeepKindStr = nullptr;
3946 switch (FPKeepKind) {
3947 case CodeGenOptions::FramePointerKind::None:
3948 FPKeepKindStr = "-mframe-pointer=none";
3950 case CodeGenOptions::FramePointerKind::NonLeaf:
3951 FPKeepKindStr = "-mframe-pointer=non-leaf";
3953 case CodeGenOptions::FramePointerKind::All:
3954 FPKeepKindStr = "-mframe-pointer=all";
3957 assert(FPKeepKindStr && "unknown FramePointerKind");
3958 CmdArgs.push_back(FPKeepKindStr);
3960 if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3961 options::OPT_fno_zero_initialized_in_bss))
3962 CmdArgs.push_back("-mno-zero-initialized-in-bss");
3964 bool OFastEnabled = isOptimizationLevelFast(Args);
3965 // If -Ofast is the optimization level, then -fstrict-aliasing should be
3966 // enabled. This alias option is being used to simplify the hasFlag logic.
3967 OptSpecifier StrictAliasingAliasOption =
3968 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3969 // We turn strict aliasing off by default if we're in CL mode, since MSVC
3970 // doesn't do any TBAA.
3971 bool TBAAOnByDefault = !D.IsCLMode();
3972 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3973 options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3974 CmdArgs.push_back("-relaxed-aliasing");
3975 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3976 options::OPT_fno_struct_path_tbaa))
3977 CmdArgs.push_back("-no-struct-path-tbaa");
3978 if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3980 CmdArgs.push_back("-fstrict-enums");
3981 if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3983 CmdArgs.push_back("-fno-strict-return");
3984 if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3985 options::OPT_fno_allow_editor_placeholders, false))
3986 CmdArgs.push_back("-fallow-editor-placeholders");
3987 if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3988 options::OPT_fno_strict_vtable_pointers,
3990 CmdArgs.push_back("-fstrict-vtable-pointers");
3991 if (Args.hasFlag(options::OPT_fforce_emit_vtables,
3992 options::OPT_fno_force_emit_vtables,
3994 CmdArgs.push_back("-fforce-emit-vtables");
3995 if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3996 options::OPT_fno_optimize_sibling_calls))
3997 CmdArgs.push_back("-mdisable-tail-calls");
3998 if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
3999 options::OPT_fescaping_block_tail_calls, false))
4000 CmdArgs.push_back("-fno-escaping-block-tail-calls");
4002 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
4003 options::OPT_fno_fine_grained_bitfield_accesses);
4005 // Handle segmented stacks.
4006 if (Args.hasArg(options::OPT_fsplit_stack))
4007 CmdArgs.push_back("-split-stacks");
4009 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs);
4011 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
4012 if (TC.getArch() == llvm::Triple::x86 ||
4013 TC.getArch() == llvm::Triple::x86_64)
4014 A->render(Args, CmdArgs);
4015 else if ((TC.getArch() == llvm::Triple::ppc || TC.getTriple().isPPC64()) &&
4016 (A->getOption().getID() != options::OPT_mlong_double_80))
4017 A->render(Args, CmdArgs);
4019 D.Diag(diag::err_drv_unsupported_opt_for_target)
4020 << A->getAsString(Args) << TripleStr;
4023 // Decide whether to use verbose asm. Verbose assembly is the default on
4024 // toolchains which have the integrated assembler on by default.
4025 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
4026 if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
4027 IsIntegratedAssemblerDefault))
4028 CmdArgs.push_back("-masm-verbose");
4030 if (!TC.useIntegratedAs())
4031 CmdArgs.push_back("-no-integrated-as");
4033 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
4034 CmdArgs.push_back("-mdebug-pass");
4035 CmdArgs.push_back("Structure");
4037 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
4038 CmdArgs.push_back("-mdebug-pass");
4039 CmdArgs.push_back("Arguments");
4042 // Enable -mconstructor-aliases except on darwin, where we have to work around
4043 // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
4044 // aliases aren't supported.
4045 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
4046 CmdArgs.push_back("-mconstructor-aliases");
4048 // Darwin's kernel doesn't support guard variables; just die if we
4050 if (KernelOrKext && RawTriple.isOSDarwin())
4051 CmdArgs.push_back("-fforbid-guard-variables");
4053 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
4055 CmdArgs.push_back("-mms-bitfields");
4058 if (Args.hasFlag(options::OPT_mpie_copy_relocations,
4059 options::OPT_mno_pie_copy_relocations,
4061 CmdArgs.push_back("-mpie-copy-relocations");
4064 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
4065 CmdArgs.push_back("-fno-plt");
4068 // -fhosted is default.
4069 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
4070 // use Freestanding.
4072 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4075 CmdArgs.push_back("-ffreestanding");
4077 // This is a coarse approximation of what llvm-gcc actually does, both
4078 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4079 // complicated ways.
4080 bool AsynchronousUnwindTables =
4081 Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4082 options::OPT_fno_asynchronous_unwind_tables,
4083 (TC.IsUnwindTablesDefault(Args) ||
4084 TC.getSanitizerArgs().needsUnwindTables()) &&
4086 if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4087 AsynchronousUnwindTables))
4088 CmdArgs.push_back("-munwind-tables");
4090 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
4092 // FIXME: Handle -mtune=.
4093 (void)Args.hasArg(options::OPT_mtune_EQ);
4095 if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4096 CmdArgs.push_back("-mcode-model");
4097 CmdArgs.push_back(A->getValue());
4100 // Add the target cpu
4101 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4103 CmdArgs.push_back("-target-cpu");
4104 CmdArgs.push_back(Args.MakeArgString(CPU));
4107 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
4109 // These two are potentially updated by AddClangCLArgs.
4110 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4111 bool EmitCodeView = false;
4113 // Add clang-cl arguments.
4114 types::ID InputType = Input.getType();
4116 AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4118 DwarfFissionKind DwarfFission;
4119 RenderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, IsWindowsMSVC,
4120 CmdArgs, DebugInfoKind, DwarfFission);
4122 // Add the split debug info name to the command lines here so we
4123 // can propagate it to the backend.
4124 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
4125 TC.getTriple().isOSBinFormatELF() &&
4126 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4127 isa<BackendJobAction>(JA));
4129 const char *SplitDWARFOut = SplitDebugName(Args, Input, Output);
4130 CmdArgs.push_back("-split-dwarf-file");
4131 CmdArgs.push_back(SplitDWARFOut);
4132 if (DwarfFission == DwarfFissionKind::Split) {
4133 CmdArgs.push_back("-split-dwarf-output");
4134 CmdArgs.push_back(SplitDWARFOut);
4138 // Pass the linker version in use.
4139 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4140 CmdArgs.push_back("-target-linker-version");
4141 CmdArgs.push_back(A->getValue());
4144 // Explicitly error on some things we know we don't support and can't just
4146 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4148 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
4149 TC.getArch() == llvm::Triple::x86) {
4150 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4151 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4152 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4153 << Unsupported->getOption().getName();
4155 // The faltivec option has been superseded by the maltivec option.
4156 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
4157 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4158 << Unsupported->getOption().getName()
4159 << "please use -maltivec and include altivec.h explicitly";
4160 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
4161 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4162 << Unsupported->getOption().getName() << "please use -mno-altivec";
4165 Args.AddAllArgs(CmdArgs, options::OPT_v);
4166 Args.AddLastArg(CmdArgs, options::OPT_H);
4167 if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4168 CmdArgs.push_back("-header-include-file");
4169 CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4172 Args.AddLastArg(CmdArgs, options::OPT_P);
4173 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4175 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4176 CmdArgs.push_back("-diagnostic-log-file");
4177 CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4181 bool UseSeparateSections = isUseSeparateSections(Triple);
4183 if (Args.hasFlag(options::OPT_ffunction_sections,
4184 options::OPT_fno_function_sections, UseSeparateSections)) {
4185 CmdArgs.push_back("-ffunction-sections");
4188 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4189 UseSeparateSections)) {
4190 CmdArgs.push_back("-fdata-sections");
4193 if (!Args.hasFlag(options::OPT_funique_section_names,
4194 options::OPT_fno_unique_section_names, true))
4195 CmdArgs.push_back("-fno-unique-section-names");
4197 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
4198 options::OPT_finstrument_functions_after_inlining,
4199 options::OPT_finstrument_function_entry_bare);
4201 // NVPTX doesn't support PGO or coverage. There's no runtime support for
4202 // sampling, overhead of call arc collection is way too high and there's no
4203 // way to collect the output.
4204 if (!Triple.isNVPTX())
4205 addPGOAndCoverageFlags(TC, C, D, Output, Args, CmdArgs);
4207 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
4209 // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
4210 if (RawTriple.isPS4CPU() &&
4211 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
4212 PS4cpu::addProfileRTArgs(TC, Args, CmdArgs);
4213 PS4cpu::addSanitizerArgs(TC, CmdArgs);
4216 // Pass options for controlling the default header search paths.
4217 if (Args.hasArg(options::OPT_nostdinc)) {
4218 CmdArgs.push_back("-nostdsysteminc");
4219 CmdArgs.push_back("-nobuiltininc");
4221 if (Args.hasArg(options::OPT_nostdlibinc))
4222 CmdArgs.push_back("-nostdsysteminc");
4223 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4224 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4227 // Pass the path to compiler resource files.
4228 CmdArgs.push_back("-resource-dir");
4229 CmdArgs.push_back(D.ResourceDir.c_str());
4231 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4233 RenderARCMigrateToolOptions(D, Args, CmdArgs);
4235 // Add preprocessing options like -I, -D, etc. if we are using the
4238 // FIXME: Support -fpreprocessed
4239 if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4240 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
4242 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4243 // that "The compiler can only warn and ignore the option if not recognized".
4244 // When building with ccache, it will pass -D options to clang even on
4245 // preprocessed inputs and configure concludes that -fPIC is not supported.
4246 Args.ClaimAllArgs(options::OPT_D);
4248 // Manually translate -O4 to -O3; let clang reject others.
4249 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4250 if (A->getOption().matches(options::OPT_O4)) {
4251 CmdArgs.push_back("-O3");
4252 D.Diag(diag::warn_O4_is_O3);
4254 A->render(Args, CmdArgs);
4258 // Warn about ignored options to clang.
4260 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4261 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4266 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
4267 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
4271 claimNoWarnArgs(Args);
4273 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4275 Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4276 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4277 CmdArgs.push_back("-pedantic");
4278 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4279 Args.AddLastArg(CmdArgs, options::OPT_w);
4281 // Fixed point flags
4282 if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
4284 Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
4286 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4287 // (-ansi is equivalent to -std=c89 or -std=c++98).
4289 // If a std is supplied, only add -trigraphs if it follows the
4291 bool ImplyVCPPCXXVer = false;
4292 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
4294 if (Std->getOption().matches(options::OPT_ansi))
4295 if (types::isCXX(InputType))
4296 CmdArgs.push_back("-std=c++98");
4298 CmdArgs.push_back("-std=c89");
4300 Std->render(Args, CmdArgs);
4302 // If -f(no-)trigraphs appears after the language standard flag, honor it.
4303 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4304 options::OPT_ftrigraphs,
4305 options::OPT_fno_trigraphs))
4307 A->render(Args, CmdArgs);
4309 // Honor -std-default.
4311 // FIXME: Clang doesn't correctly handle -std= when the input language
4312 // doesn't match. For the time being just ignore this for C++ inputs;
4313 // eventually we want to do all the standard defaulting here instead of
4314 // splitting it between the driver and clang -cc1.
4315 if (!types::isCXX(InputType))
4316 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4318 else if (IsWindowsMSVC)
4319 ImplyVCPPCXXVer = true;
4321 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4322 options::OPT_fno_trigraphs);
4325 // GCC's behavior for -Wwrite-strings is a bit strange:
4326 // * In C, this "warning flag" changes the types of string literals from
4327 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4328 // for the discarded qualifier.
4329 // * In C++, this is just a normal warning flag.
4331 // Implementing this warning correctly in C is hard, so we follow GCC's
4332 // behavior for now. FIXME: Directly diagnose uses of a string literal as
4333 // a non-const char* in C, rather than using this crude hack.
4334 if (!types::isCXX(InputType)) {
4335 // FIXME: This should behave just like a warning flag, and thus should also
4336 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4338 Args.getLastArg(options::OPT_Wwrite_strings,
4339 options::OPT_Wno_write_strings, options::OPT_w);
4341 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4342 CmdArgs.push_back("-fconst-strings");
4345 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4346 // during C++ compilation, which it is by default. GCC keeps this define even
4347 // in the presence of '-w', match this behavior bug-for-bug.
4348 if (types::isCXX(InputType) &&
4349 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4351 CmdArgs.push_back("-fdeprecated-macro");
4354 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4355 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4356 if (Asm->getOption().matches(options::OPT_fasm))
4357 CmdArgs.push_back("-fgnu-keywords");
4359 CmdArgs.push_back("-fno-gnu-keywords");
4362 if (ShouldDisableDwarfDirectory(Args, TC))
4363 CmdArgs.push_back("-fno-dwarf-directory-asm");
4365 if (ShouldDisableAutolink(Args, TC))
4366 CmdArgs.push_back("-fno-autolink");
4368 // Add in -fdebug-compilation-dir if necessary.
4369 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
4371 addDebugPrefixMapArg(D, Args, CmdArgs);
4373 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4374 options::OPT_ftemplate_depth_EQ)) {
4375 CmdArgs.push_back("-ftemplate-depth");
4376 CmdArgs.push_back(A->getValue());
4379 if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4380 CmdArgs.push_back("-foperator-arrow-depth");
4381 CmdArgs.push_back(A->getValue());
4384 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4385 CmdArgs.push_back("-fconstexpr-depth");
4386 CmdArgs.push_back(A->getValue());
4389 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4390 CmdArgs.push_back("-fconstexpr-steps");
4391 CmdArgs.push_back(A->getValue());
4394 if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
4395 CmdArgs.push_back("-fexperimental-new-constant-interpreter");
4397 if (Args.hasArg(options::OPT_fforce_experimental_new_constant_interpreter))
4398 CmdArgs.push_back("-fforce-experimental-new-constant-interpreter");
4400 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4401 CmdArgs.push_back("-fbracket-depth");
4402 CmdArgs.push_back(A->getValue());
4405 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4406 options::OPT_Wlarge_by_value_copy_def)) {
4407 if (A->getNumValues()) {
4408 StringRef bytes = A->getValue();
4409 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4411 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4414 if (Args.hasArg(options::OPT_relocatable_pch))
4415 CmdArgs.push_back("-relocatable-pch");
4417 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
4418 static const char *kCFABIs[] = {
4419 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
4422 if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs))
4423 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
4425 A->render(Args, CmdArgs);
4428 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4429 CmdArgs.push_back("-fconstant-string-class");
4430 CmdArgs.push_back(A->getValue());
4433 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4434 CmdArgs.push_back("-ftabstop");
4435 CmdArgs.push_back(A->getValue());
4438 if (Args.hasFlag(options::OPT_fstack_size_section,
4439 options::OPT_fno_stack_size_section, RawTriple.isPS4()))
4440 CmdArgs.push_back("-fstack-size-section");
4442 CmdArgs.push_back("-ferror-limit");
4443 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4444 CmdArgs.push_back(A->getValue());
4446 CmdArgs.push_back("19");
4448 if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4449 CmdArgs.push_back("-fmacro-backtrace-limit");
4450 CmdArgs.push_back(A->getValue());
4453 if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4454 CmdArgs.push_back("-ftemplate-backtrace-limit");
4455 CmdArgs.push_back(A->getValue());
4458 if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4459 CmdArgs.push_back("-fconstexpr-backtrace-limit");
4460 CmdArgs.push_back(A->getValue());
4463 if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4464 CmdArgs.push_back("-fspell-checking-limit");
4465 CmdArgs.push_back(A->getValue());
4468 // Pass -fmessage-length=.
4469 CmdArgs.push_back("-fmessage-length");
4470 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4471 CmdArgs.push_back(A->getValue());
4473 // If -fmessage-length=N was not specified, determine whether this is a
4474 // terminal and, if so, implicitly define -fmessage-length appropriately.
4475 unsigned N = llvm::sys::Process::StandardErrColumns();
4476 CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4479 // -fvisibility= and -fvisibility-ms-compat are of a piece.
4480 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4481 options::OPT_fvisibility_ms_compat)) {
4482 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4483 CmdArgs.push_back("-fvisibility");
4484 CmdArgs.push_back(A->getValue());
4486 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4487 CmdArgs.push_back("-fvisibility");
4488 CmdArgs.push_back("hidden");
4489 CmdArgs.push_back("-ftype-visibility");
4490 CmdArgs.push_back("default");
4494 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4495 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
4497 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4499 // Forward -f (flag) options which we can pass directly.
4500 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4501 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
4502 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
4503 Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
4504 Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
4505 options::OPT_fno_emulated_tls);
4506 Args.AddLastArg(CmdArgs, options::OPT_fkeep_static_consts);
4508 // AltiVec-like language extensions aren't relevant for assembling.
4509 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
4510 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
4512 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4513 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4515 // Forward flags for OpenMP. We don't do this if the current action is an
4516 // device offloading action other than OpenMP.
4517 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4518 options::OPT_fno_openmp, false) &&
4519 (JA.isDeviceOffloading(Action::OFK_None) ||
4520 JA.isDeviceOffloading(Action::OFK_OpenMP))) {
4521 switch (D.getOpenMPRuntime(Args)) {
4522 case Driver::OMPRT_OMP:
4523 case Driver::OMPRT_IOMP5:
4524 // Clang can generate useful OpenMP code for these two runtime libraries.
4525 CmdArgs.push_back("-fopenmp");
4527 // If no option regarding the use of TLS in OpenMP codegeneration is
4528 // given, decide a default based on the target. Otherwise rely on the
4529 // options and pass the right information to the frontend.
4530 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4531 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4532 CmdArgs.push_back("-fnoopenmp-use-tls");
4533 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4534 options::OPT_fno_openmp_simd);
4535 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
4536 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
4537 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
4538 Args.AddAllArgs(CmdArgs,
4539 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
4540 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
4541 options::OPT_fno_openmp_optimistic_collapse,
4543 CmdArgs.push_back("-fopenmp-optimistic-collapse");
4545 // When in OpenMP offloading mode with NVPTX target, forward
4547 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
4548 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
4549 CmdArgs.push_back("-fopenmp-cuda-mode");
4551 // When in OpenMP offloading mode with NVPTX target, check if full runtime
4553 if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime,
4554 options::OPT_fno_openmp_cuda_force_full_runtime,
4556 CmdArgs.push_back("-fopenmp-cuda-force-full-runtime");
4559 // By default, if Clang doesn't know how to generate useful OpenMP code
4560 // for a specific runtime library, we just don't pass the '-fopenmp' flag
4561 // down to the actual compilation.
4562 // FIXME: It would be better to have a mode which *only* omits IR
4563 // generation based on the OpenMP support so that we get consistent
4564 // semantic analysis, etc.
4568 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4569 options::OPT_fno_openmp_simd);
4570 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
4573 const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
4574 Sanitize.addArgs(TC, Args, CmdArgs, InputType);
4576 const XRayArgs &XRay = TC.getXRayArgs();
4577 XRay.addArgs(TC, Args, CmdArgs, InputType);
4579 if (TC.SupportsProfiling())
4580 Args.AddLastArg(CmdArgs, options::OPT_pg);
4582 if (TC.SupportsProfiling())
4583 Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4585 if (Args.getLastArg(options::OPT_fapple_kext) ||
4586 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4587 CmdArgs.push_back("-fapple-kext");
4589 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
4590 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4591 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4592 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4593 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4594 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace);
4595 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
4596 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4597 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
4599 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4600 CmdArgs.push_back("-ftrapv-handler");
4601 CmdArgs.push_back(A->getValue());
4604 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4606 // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4607 // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4608 if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4609 if (A->getOption().matches(options::OPT_fwrapv))
4610 CmdArgs.push_back("-fwrapv");
4611 } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4612 options::OPT_fno_strict_overflow)) {
4613 if (A->getOption().matches(options::OPT_fno_strict_overflow))
4614 CmdArgs.push_back("-fwrapv");
4617 if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4618 options::OPT_fno_reroll_loops))
4619 if (A->getOption().matches(options::OPT_freroll_loops))
4620 CmdArgs.push_back("-freroll-loops");
4622 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4623 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4624 options::OPT_fno_unroll_loops);
4626 Args.AddLastArg(CmdArgs, options::OPT_pthread);
4628 if (Args.hasFlag(options::OPT_mspeculative_load_hardening, options::OPT_mno_speculative_load_hardening,
4630 CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
4632 RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext);
4633 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
4635 // Translate -mstackrealign
4636 if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4638 CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4640 if (Args.hasArg(options::OPT_mstack_alignment)) {
4641 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4642 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4645 if (Args.hasArg(options::OPT_mstack_probe_size)) {
4646 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4649 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4651 CmdArgs.push_back("-mstack-probe-size=0");
4654 if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4655 options::OPT_mno_stack_arg_probe, true))
4656 CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4658 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4659 options::OPT_mno_restrict_it)) {
4660 if (A->getOption().matches(options::OPT_mrestrict_it)) {
4661 CmdArgs.push_back("-mllvm");
4662 CmdArgs.push_back("-arm-restrict-it");
4664 CmdArgs.push_back("-mllvm");
4665 CmdArgs.push_back("-arm-no-restrict-it");
4667 } else if (Triple.isOSWindows() &&
4668 (Triple.getArch() == llvm::Triple::arm ||
4669 Triple.getArch() == llvm::Triple::thumb)) {
4670 // Windows on ARM expects restricted IT blocks
4671 CmdArgs.push_back("-mllvm");
4672 CmdArgs.push_back("-arm-restrict-it");
4675 // Forward -cl options to -cc1
4676 RenderOpenCLOptions(Args, CmdArgs);
4678 if (Args.hasFlag(options::OPT_fhip_new_launch_api,
4679 options::OPT_fno_hip_new_launch_api, false))
4680 CmdArgs.push_back("-fhip-new-launch-api");
4682 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4684 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4687 // Forward -f options with positive and negative forms; we translate
4689 if (Arg *A = getLastProfileSampleUseArg(Args)) {
4690 auto *PGOArg = Args.getLastArg(
4691 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
4692 options::OPT_fcs_profile_generate, options::OPT_fcs_profile_generate_EQ,
4693 options::OPT_fprofile_use, options::OPT_fprofile_use_EQ);
4695 D.Diag(diag::err_drv_argument_not_allowed_with)
4696 << "SampleUse with PGO options";
4698 StringRef fname = A->getValue();
4699 if (!llvm::sys::fs::exists(fname))
4700 D.Diag(diag::err_drv_no_such_file) << fname;
4702 A->render(Args, CmdArgs);
4704 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
4706 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
4708 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4709 options::OPT_fno_assume_sane_operator_new))
4710 CmdArgs.push_back("-fno-assume-sane-operator-new");
4712 // -fblocks=0 is default.
4713 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4714 TC.IsBlocksDefault()) ||
4715 (Args.hasArg(options::OPT_fgnu_runtime) &&
4716 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4717 !Args.hasArg(options::OPT_fno_blocks))) {
4718 CmdArgs.push_back("-fblocks");
4720 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
4721 CmdArgs.push_back("-fblocks-runtime-optional");
4724 // -fencode-extended-block-signature=1 is default.
4725 if (TC.IsEncodeExtendedBlockSignatureDefault())
4726 CmdArgs.push_back("-fencode-extended-block-signature");
4728 if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4730 types::isCXX(InputType)) {
4731 CmdArgs.push_back("-fcoroutines-ts");
4734 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4735 options::OPT_fno_double_square_bracket_attributes);
4737 // -faccess-control is default.
4738 if (Args.hasFlag(options::OPT_fno_access_control,
4739 options::OPT_faccess_control, false))
4740 CmdArgs.push_back("-fno-access-control");
4742 // -felide-constructors is the default.
4743 if (Args.hasFlag(options::OPT_fno_elide_constructors,
4744 options::OPT_felide_constructors, false))
4745 CmdArgs.push_back("-fno-elide-constructors");
4747 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
4749 if (KernelOrKext || (types::isCXX(InputType) &&
4750 (RTTIMode == ToolChain::RM_Disabled)))
4751 CmdArgs.push_back("-fno-rtti");
4753 // -fshort-enums=0 is default for all architectures except Hexagon.
4754 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4755 TC.getArch() == llvm::Triple::hexagon))
4756 CmdArgs.push_back("-fshort-enums");
4758 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
4760 // -fuse-cxa-atexit is default.
4762 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
4763 !RawTriple.isOSWindows() &&
4764 TC.getArch() != llvm::Triple::xcore &&
4765 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4766 RawTriple.hasEnvironment())) ||
4768 CmdArgs.push_back("-fno-use-cxa-atexit");
4770 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4771 options::OPT_fno_register_global_dtors_with_atexit,
4772 RawTriple.isOSDarwin() && !KernelOrKext))
4773 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4775 // -fms-extensions=0 is default.
4776 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4778 CmdArgs.push_back("-fms-extensions");
4780 // -fno-use-line-directives is default.
4781 if (Args.hasFlag(options::OPT_fuse_line_directives,
4782 options::OPT_fno_use_line_directives, false))
4783 CmdArgs.push_back("-fuse-line-directives");
4785 // -fms-compatibility=0 is default.
4786 bool IsMSVCCompat = Args.hasFlag(
4787 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
4788 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
4789 options::OPT_fno_ms_extensions, true)));
4791 CmdArgs.push_back("-fms-compatibility");
4793 // Handle -fgcc-version, if present.
4794 VersionTuple GNUCVer;
4795 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
4796 // Check that the version has 1 to 3 components and the minor and patch
4797 // versions fit in two decimal digits.
4798 StringRef Val = A->getValue();
4799 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
4800 bool Invalid = GNUCVer.tryParse(Val);
4801 unsigned Minor = GNUCVer.getMinor().getValueOr(0);
4802 unsigned Patch = GNUCVer.getSubminor().getValueOr(0);
4803 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
4804 D.Diag(diag::err_drv_invalid_value)
4805 << A->getAsString(Args) << A->getValue();
4807 } else if (!IsMSVCCompat) {
4808 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
4809 GNUCVer = VersionTuple(4, 2, 1);
4811 if (!GNUCVer.empty()) {
4813 Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
4816 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
4819 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4821 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4822 if (ImplyVCPPCXXVer) {
4823 StringRef LanguageStandard;
4824 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
4826 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4827 .Case("c++14", "-std=c++14")
4828 .Case("c++17", "-std=c++17")
4829 .Case("c++latest", "-std=c++2a")
4831 if (LanguageStandard.empty())
4832 D.Diag(clang::diag::warn_drv_unused_argument)
4833 << StdArg->getAsString(Args);
4836 if (LanguageStandard.empty()) {
4837 if (IsMSVC2015Compatible)
4838 LanguageStandard = "-std=c++14";
4840 LanguageStandard = "-std=c++11";
4843 CmdArgs.push_back(LanguageStandard.data());
4846 // -fno-borland-extensions is default.
4847 if (Args.hasFlag(options::OPT_fborland_extensions,
4848 options::OPT_fno_borland_extensions, false))
4849 CmdArgs.push_back("-fborland-extensions");
4851 // -fno-declspec is default, except for PS4.
4852 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
4854 CmdArgs.push_back("-fdeclspec");
4855 else if (Args.hasArg(options::OPT_fno_declspec))
4856 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4858 // -fthreadsafe-static is default, except for MSVC compatibility versions less
4860 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4861 options::OPT_fno_threadsafe_statics,
4862 !IsWindowsMSVC || IsMSVC2015Compatible))
4863 CmdArgs.push_back("-fno-threadsafe-statics");
4865 // -fno-delayed-template-parsing is default, except when targeting MSVC.
4866 // Many old Windows SDK versions require this to parse.
4867 // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4868 // compiler. We should be able to disable this by default at some point.
4869 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4870 options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4871 CmdArgs.push_back("-fdelayed-template-parsing");
4873 // -fgnu-keywords default varies depending on language; only pass if
4875 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
4876 options::OPT_fno_gnu_keywords);
4878 if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4880 CmdArgs.push_back("-fgnu89-inline");
4882 if (Args.hasArg(options::OPT_fno_inline))
4883 CmdArgs.push_back("-fno-inline");
4885 Args.AddLastArg(CmdArgs, options::OPT_finline_functions,
4886 options::OPT_finline_hint_functions,
4887 options::OPT_fno_inline_functions);
4889 // FIXME: Find a better way to determine whether the language has modules
4890 // support by default, or just assume that all languages do.
4892 Std && (Std->containsValue("c++2a") || Std->containsValue("c++latest"));
4893 RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
4895 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
4896 options::OPT_fno_pch_validate_input_files_content, false))
4897 CmdArgs.push_back("-fvalidate-ast-input-files-content");
4899 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4900 options::OPT_fno_experimental_new_pass_manager);
4902 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4903 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
4906 if (Args.hasFlag(options::OPT_fapplication_extension,
4907 options::OPT_fno_application_extension, false))
4908 CmdArgs.push_back("-fapplication-extension");
4910 // Handle GCC-style exception args.
4911 if (!C.getDriver().IsCLMode())
4912 addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
4914 // Handle exception personalities
4915 Arg *A = Args.getLastArg(
4916 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
4917 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
4919 const Option &Opt = A->getOption();
4920 if (Opt.matches(options::OPT_fsjlj_exceptions))
4921 CmdArgs.push_back("-fsjlj-exceptions");
4922 if (Opt.matches(options::OPT_fseh_exceptions))
4923 CmdArgs.push_back("-fseh-exceptions");
4924 if (Opt.matches(options::OPT_fdwarf_exceptions))
4925 CmdArgs.push_back("-fdwarf-exceptions");
4926 if (Opt.matches(options::OPT_fwasm_exceptions))
4927 CmdArgs.push_back("-fwasm-exceptions");
4929 switch (TC.GetExceptionModel(Args)) {
4932 case llvm::ExceptionHandling::DwarfCFI:
4933 CmdArgs.push_back("-fdwarf-exceptions");
4935 case llvm::ExceptionHandling::SjLj:
4936 CmdArgs.push_back("-fsjlj-exceptions");
4938 case llvm::ExceptionHandling::WinEH:
4939 CmdArgs.push_back("-fseh-exceptions");
4944 // C++ "sane" operator new.
4945 if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4946 options::OPT_fno_assume_sane_operator_new))
4947 CmdArgs.push_back("-fno-assume-sane-operator-new");
4949 // -frelaxed-template-template-args is off by default, as it is a severe
4950 // breaking change until a corresponding change to template partial ordering
4952 if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4953 options::OPT_fno_relaxed_template_template_args, false))
4954 CmdArgs.push_back("-frelaxed-template-template-args");
4956 // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4958 if (Args.hasFlag(options::OPT_fsized_deallocation,
4959 options::OPT_fno_sized_deallocation, false))
4960 CmdArgs.push_back("-fsized-deallocation");
4962 // -faligned-allocation is on by default in C++17 onwards and otherwise off
4964 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4965 options::OPT_fno_aligned_allocation,
4966 options::OPT_faligned_new_EQ)) {
4967 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4968 CmdArgs.push_back("-fno-aligned-allocation");
4970 CmdArgs.push_back("-faligned-allocation");
4973 // The default new alignment can be specified using a dedicated option or via
4974 // a GCC-compatible option that also turns on aligned allocation.
4975 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4976 options::OPT_faligned_new_EQ))
4978 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4980 // -fconstant-cfstrings is default, and may be subject to argument translation
4982 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4983 options::OPT_fno_constant_cfstrings) ||
4984 !Args.hasFlag(options::OPT_mconstant_cfstrings,
4985 options::OPT_mno_constant_cfstrings))
4986 CmdArgs.push_back("-fno-constant-cfstrings");
4988 // -fno-pascal-strings is default, only pass non-default.
4989 if (Args.hasFlag(options::OPT_fpascal_strings,
4990 options::OPT_fno_pascal_strings, false))
4991 CmdArgs.push_back("-fpascal-strings");
4993 // Honor -fpack-struct= and -fpack-struct, if given. Note that
4994 // -fno-pack-struct doesn't apply to -fpack-struct=.
4995 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4996 std::string PackStructStr = "-fpack-struct=";
4997 PackStructStr += A->getValue();
4998 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4999 } else if (Args.hasFlag(options::OPT_fpack_struct,
5000 options::OPT_fno_pack_struct, false)) {
5001 CmdArgs.push_back("-fpack-struct=1");
5004 // Handle -fmax-type-align=N and -fno-type-align
5005 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
5006 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
5007 if (!SkipMaxTypeAlign) {
5008 std::string MaxTypeAlignStr = "-fmax-type-align=";
5009 MaxTypeAlignStr += A->getValue();
5010 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5012 } else if (RawTriple.isOSDarwin()) {
5013 if (!SkipMaxTypeAlign) {
5014 std::string MaxTypeAlignStr = "-fmax-type-align=16";
5015 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
5019 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
5020 CmdArgs.push_back("-Qn");
5022 // -fcommon is the default unless compiling kernel code or the target says so
5023 bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
5024 if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
5026 CmdArgs.push_back("-fno-common");
5028 // -fsigned-bitfields is default, and clang doesn't yet support
5029 // -funsigned-bitfields.
5030 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
5031 options::OPT_funsigned_bitfields))
5032 D.Diag(diag::warn_drv_clang_unsupported)
5033 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
5035 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
5036 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
5037 D.Diag(diag::err_drv_clang_unsupported)
5038 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
5040 // -finput_charset=UTF-8 is default. Reject others
5041 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
5042 StringRef value = inputCharset->getValue();
5043 if (!value.equals_lower("utf-8"))
5044 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
5048 // -fexec_charset=UTF-8 is default. Reject others
5049 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
5050 StringRef value = execCharset->getValue();
5051 if (!value.equals_lower("utf-8"))
5052 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
5056 RenderDiagnosticsOptions(D, Args, CmdArgs);
5058 // -fno-asm-blocks is default.
5059 if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
5061 CmdArgs.push_back("-fasm-blocks");
5063 // -fgnu-inline-asm is default.
5064 if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
5065 options::OPT_fno_gnu_inline_asm, true))
5066 CmdArgs.push_back("-fno-gnu-inline-asm");
5068 // Enable vectorization per default according to the optimization level
5069 // selected. For optimization levels that want vectorization we use the alias
5070 // option to simplify the hasFlag logic.
5071 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
5072 OptSpecifier VectorizeAliasOption =
5073 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
5074 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
5075 options::OPT_fno_vectorize, EnableVec))
5076 CmdArgs.push_back("-vectorize-loops");
5078 // -fslp-vectorize is enabled based on the optimization level selected.
5079 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5080 OptSpecifier SLPVectAliasOption =
5081 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5082 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5083 options::OPT_fno_slp_vectorize, EnableSLPVec))
5084 CmdArgs.push_back("-vectorize-slp");
5086 ParseMPreferVectorWidth(D, Args, CmdArgs);
5088 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
5089 Args.AddLastArg(CmdArgs,
5090 options::OPT_fsanitize_undefined_strip_path_components_EQ);
5092 // -fdollars-in-identifiers default varies depending on platform and
5093 // language; only pass if specified.
5094 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5095 options::OPT_fno_dollars_in_identifiers)) {
5096 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5097 CmdArgs.push_back("-fdollars-in-identifiers");
5099 CmdArgs.push_back("-fno-dollars-in-identifiers");
5102 // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5103 // practical purposes.
5104 if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5105 options::OPT_fno_unit_at_a_time)) {
5106 if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5107 D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5110 if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5111 options::OPT_fno_apple_pragma_pack, false))
5112 CmdArgs.push_back("-fapple-pragma-pack");
5114 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
5115 if (Args.hasFlag(options::OPT_fsave_optimization_record,
5116 options::OPT_foptimization_record_file_EQ,
5117 options::OPT_fno_save_optimization_record, false) ||
5118 Args.hasFlag(options::OPT_fsave_optimization_record_EQ,
5119 options::OPT_fno_save_optimization_record, false) ||
5120 Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
5121 options::OPT_fno_save_optimization_record, false)) {
5122 CmdArgs.push_back("-opt-record-file");
5124 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
5126 CmdArgs.push_back(A->getValue());
5130 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
5131 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
5132 F = FinalOutput->getValue();
5136 // Use the input filename.
5137 F = llvm::sys::path::stem(Input.getBaseInput());
5139 // If we're compiling for an offload architecture (i.e. a CUDA device),
5140 // we need to make the file name for the device compilation different
5141 // from the host compilation.
5142 if (!JA.isDeviceOffloading(Action::OFK_None) &&
5143 !JA.isDeviceOffloading(Action::OFK_Host)) {
5144 llvm::sys::path::replace_extension(F, "");
5145 F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
5146 Triple.normalize());
5148 F += JA.getOffloadingArch();
5152 std::string Extension = "opt.";
5154 Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
5155 Extension += A->getValue();
5157 Extension += "yaml";
5159 llvm::sys::path::replace_extension(F, Extension);
5160 CmdArgs.push_back(Args.MakeArgString(F));
5164 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
5165 CmdArgs.push_back("-opt-record-passes");
5166 CmdArgs.push_back(A->getValue());
5170 Args.getLastArg(options::OPT_fsave_optimization_record_EQ)) {
5171 CmdArgs.push_back("-opt-record-format");
5172 CmdArgs.push_back(A->getValue());
5176 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
5177 options::OPT_fno_rewrite_imports, false);
5179 CmdArgs.push_back("-frewrite-imports");
5181 // Enable rewrite includes if the user's asked for it or if we're generating
5183 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5184 // nice to enable this when doing a crashdump for modules as well.
5185 if (Args.hasFlag(options::OPT_frewrite_includes,
5186 options::OPT_fno_rewrite_includes, false) ||
5187 (C.isForDiagnostics() && !HaveModules))
5188 CmdArgs.push_back("-frewrite-includes");
5190 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5191 if (Arg *A = Args.getLastArg(options::OPT_traditional,
5192 options::OPT_traditional_cpp)) {
5193 if (isa<PreprocessJobAction>(JA))
5194 CmdArgs.push_back("-traditional-cpp");
5196 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5199 Args.AddLastArg(CmdArgs, options::OPT_dM);
5200 Args.AddLastArg(CmdArgs, options::OPT_dD);
5202 // Handle serialized diagnostics.
5203 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5204 CmdArgs.push_back("-serialize-diagnostic-file");
5205 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5208 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5209 CmdArgs.push_back("-fretain-comments-from-system-headers");
5211 // Forward -fcomment-block-commands to -cc1.
5212 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5213 // Forward -fparse-all-comments to -cc1.
5214 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5216 // Turn -fplugin=name.so into -load name.so
5217 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5218 CmdArgs.push_back("-load");
5219 CmdArgs.push_back(A->getValue());
5223 // Forward -fpass-plugin=name.so to -cc1.
5224 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
5226 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
5230 // Setup statistics file output.
5231 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
5232 if (!StatsFile.empty())
5233 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
5235 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5237 // -finclude-default-header flag is for preprocessor,
5238 // do not pass it to other cc1 commands when save-temps is enabled
5239 if (C.getDriver().isSaveTempsEnabled() &&
5240 !isa<PreprocessJobAction>(JA)) {
5241 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
5243 if (StringRef(Arg->getValue()) != "-finclude-default-header")
5244 CmdArgs.push_back(Arg->getValue());
5248 Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5250 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5253 // We translate this by hand to the -cc1 argument, since nightly test uses
5254 // it and developers have been trained to spell it with -mllvm. Both
5255 // spellings are now deprecated and should be removed.
5256 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5257 CmdArgs.push_back("-disable-llvm-optzns");
5259 A->render(Args, CmdArgs);
5263 // With -save-temps, we want to save the unoptimized bitcode output from the
5264 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5266 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5267 // has slightly different breakdown between stages.
5268 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5269 // pristine IR generated by the frontend. Ideally, a new compile action should
5270 // be added so both IR can be captured.
5271 if (C.getDriver().isSaveTempsEnabled() &&
5272 !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
5273 isa<CompileJobAction>(JA))
5274 CmdArgs.push_back("-disable-llvm-passes");
5276 Args.AddAllArgs(CmdArgs, options::OPT_undef);
5278 const char *Exec = D.getClangProgramPath();
5280 // Optionally embed the -cc1 level arguments into the debug info or a
5281 // section, for build analysis.
5282 // Also record command line arguments into the debug info if
5283 // -grecord-gcc-switches options is set on.
5284 // By default, -gno-record-gcc-switches is set on and no recording.
5285 auto GRecordSwitches =
5286 Args.hasFlag(options::OPT_grecord_command_line,
5287 options::OPT_gno_record_command_line, false);
5288 auto FRecordSwitches =
5289 Args.hasFlag(options::OPT_frecord_command_line,
5290 options::OPT_fno_record_command_line, false);
5291 if (FRecordSwitches && !Triple.isOSBinFormatELF())
5292 D.Diag(diag::err_drv_unsupported_opt_for_target)
5293 << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
5295 if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
5296 ArgStringList OriginalArgs;
5297 for (const auto &Arg : Args)
5298 Arg->render(Args, OriginalArgs);
5300 SmallString<256> Flags;
5302 for (const char *OriginalArg : OriginalArgs) {
5303 SmallString<128> EscapedArg;
5304 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5306 Flags += EscapedArg;
5308 auto FlagsArgString = Args.MakeArgString(Flags);
5309 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
5310 CmdArgs.push_back("-dwarf-debug-flags");
5311 CmdArgs.push_back(FlagsArgString);
5313 if (FRecordSwitches) {
5314 CmdArgs.push_back("-record-command-line");
5315 CmdArgs.push_back(FlagsArgString);
5319 // Host-side cuda compilation receives all device-side outputs in a single
5320 // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
5321 if ((IsCuda || IsHIP) && CudaDeviceInput) {
5322 CmdArgs.push_back("-fcuda-include-gpubinary");
5323 CmdArgs.push_back(CudaDeviceInput->getFilename());
5324 if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
5325 CmdArgs.push_back("-fgpu-rdc");
5329 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
5330 options::OPT_fno_cuda_short_ptr, false))
5331 CmdArgs.push_back("-fcuda-short-ptr");
5334 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
5335 // to specify the result of the compile phase on the host, so the meaningful
5336 // device declarations can be identified. Also, -fopenmp-is-device is passed
5337 // along to tell the frontend that it is generating code for a device, so that
5338 // only the relevant declarations are emitted.
5339 if (IsOpenMPDevice) {
5340 CmdArgs.push_back("-fopenmp-is-device");
5341 if (OpenMPDeviceInput) {
5342 CmdArgs.push_back("-fopenmp-host-ir-file-path");
5343 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
5347 // For all the host OpenMP offloading compile jobs we need to pass the targets
5348 // information using -fopenmp-targets= option.
5349 if (JA.isHostOffloading(Action::OFK_OpenMP)) {
5350 SmallString<128> TargetInfo("-fopenmp-targets=");
5352 Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
5353 assert(Tgts && Tgts->getNumValues() &&
5354 "OpenMP offloading has to have targets specified.");
5355 for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
5358 // We need to get the string from the triple because it may be not exactly
5359 // the same as the one we get directly from the arguments.
5360 llvm::Triple T(Tgts->getValue(i));
5361 TargetInfo += T.getTriple();
5363 CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
5366 bool VirtualFunctionElimination =
5367 Args.hasFlag(options::OPT_fvirtual_function_elimination,
5368 options::OPT_fno_virtual_function_elimination, false);
5369 if (VirtualFunctionElimination) {
5370 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
5372 if (D.getLTOMode() != LTOK_Full)
5373 D.Diag(diag::err_drv_argument_only_allowed_with)
5374 << "-fvirtual-function-elimination"
5377 CmdArgs.push_back("-fvirtual-function-elimination");
5380 // VFE requires whole-program-vtables, and enables it by default.
5381 bool WholeProgramVTables = Args.hasFlag(
5382 options::OPT_fwhole_program_vtables,
5383 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
5384 if (VirtualFunctionElimination && !WholeProgramVTables) {
5385 D.Diag(diag::err_drv_argument_not_allowed_with)
5386 << "-fno-whole-program-vtables"
5387 << "-fvirtual-function-elimination";
5390 if (WholeProgramVTables) {
5391 if (!D.isUsingLTO())
5392 D.Diag(diag::err_drv_argument_only_allowed_with)
5393 << "-fwhole-program-vtables"
5395 CmdArgs.push_back("-fwhole-program-vtables");
5398 bool DefaultsSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
5400 Args.hasFlag(options::OPT_fsplit_lto_unit,
5401 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
5402 if (Sanitize.needsLTO() && !SplitLTOUnit)
5403 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
5404 << "-fsanitize=cfi";
5406 CmdArgs.push_back("-fsplit-lto-unit");
5408 if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
5409 options::OPT_fno_experimental_isel)) {
5410 CmdArgs.push_back("-mllvm");
5411 if (A->getOption().matches(options::OPT_fexperimental_isel)) {
5412 CmdArgs.push_back("-global-isel=1");
5414 // GISel is on by default on AArch64 -O0, so don't bother adding
5415 // the fallback remarks for it. Other combinations will add a warning of
5417 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
5418 bool IsOptLevelSupported = false;
5420 Arg *A = Args.getLastArg(options::OPT_O_Group);
5421 if (Triple.getArch() == llvm::Triple::aarch64) {
5422 if (!A || A->getOption().matches(options::OPT_O0))
5423 IsOptLevelSupported = true;
5425 if (!IsArchSupported || !IsOptLevelSupported) {
5426 CmdArgs.push_back("-mllvm");
5427 CmdArgs.push_back("-global-isel-abort=2");
5429 if (!IsArchSupported)
5430 D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
5432 D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
5435 CmdArgs.push_back("-global-isel=0");
5439 if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
5440 CmdArgs.push_back("-forder-file-instrumentation");
5441 // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
5442 // on, we need to pass these flags as linker flags and that will be handled
5443 // outside of the compiler.
5444 if (!D.isUsingLTO()) {
5445 CmdArgs.push_back("-mllvm");
5446 CmdArgs.push_back("-enable-order-file-instrumentation");
5450 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
5451 options::OPT_fno_force_enable_int128)) {
5452 if (A->getOption().matches(options::OPT_fforce_enable_int128))
5453 CmdArgs.push_back("-fforce-enable-int128");
5456 if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
5457 options::OPT_fno_complete_member_pointers, false))
5458 CmdArgs.push_back("-fcomplete-member-pointers");
5460 if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
5461 options::OPT_fno_cxx_static_destructors, true))
5462 CmdArgs.push_back("-fno-c++-static-destructors");
5464 if (Arg *A = Args.getLastArg(options::OPT_moutline,
5465 options::OPT_mno_outline)) {
5466 if (A->getOption().matches(options::OPT_moutline)) {
5467 // We only support -moutline in AArch64 right now. If we're not compiling
5468 // for AArch64, emit a warning and ignore the flag. Otherwise, add the
5469 // proper mllvm flags.
5470 if (Triple.getArch() != llvm::Triple::aarch64) {
5471 D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
5473 CmdArgs.push_back("-mllvm");
5474 CmdArgs.push_back("-enable-machine-outliner");
5477 // Disable all outlining behaviour.
5478 CmdArgs.push_back("-mllvm");
5479 CmdArgs.push_back("-enable-machine-outliner=never");
5483 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
5484 (TC.getTriple().isOSBinFormatELF() ||
5485 TC.getTriple().isOSBinFormatCOFF()) &&
5486 !TC.getTriple().isPS4() &&
5487 !TC.getTriple().isOSNetBSD() &&
5488 !Distro(D.getVFS()).IsGentoo() &&
5489 !TC.getTriple().isAndroid() &&
5490 TC.useIntegratedAs()))
5491 CmdArgs.push_back("-faddrsig");
5493 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
5494 std::string Str = A->getAsString(Args);
5495 if (!TC.getTriple().isOSBinFormatELF())
5496 D.Diag(diag::err_drv_unsupported_opt_for_target)
5497 << Str << TC.getTripleString();
5498 CmdArgs.push_back(Args.MakeArgString(Str));
5501 // Add the "-o out -x type src.c" flags last. This is done primarily to make
5502 // the -cc1 command easier to edit when reproducing compiler crashes.
5503 if (Output.getType() == types::TY_Dependencies) {
5504 // Handled with other dependency code.
5505 } else if (Output.isFilename()) {
5506 CmdArgs.push_back("-o");
5507 CmdArgs.push_back(Output.getFilename());
5509 assert(Output.isNothing() && "Invalid output.");
5512 addDashXForInput(Args, Input, CmdArgs);
5514 ArrayRef<InputInfo> FrontendInputs = Input;
5515 if (IsHeaderModulePrecompile)
5516 FrontendInputs = ModuleHeaderInputs;
5517 else if (Input.isNothing())
5518 FrontendInputs = {};
5520 for (const InputInfo &Input : FrontendInputs) {
5521 if (Input.isFilename())
5522 CmdArgs.push_back(Input.getFilename());
5524 Input.getInputArg().renderAsInput(Args, CmdArgs);
5527 // Finally add the compile command to the compilation.
5528 if (Args.hasArg(options::OPT__SLASH_fallback) &&
5529 Output.getType() == types::TY_Object &&
5530 (InputType == types::TY_C || InputType == types::TY_CXX)) {
5532 getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5533 C.addCommand(std::make_unique<FallbackCommand>(
5534 JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5535 } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
5536 isa<PrecompileJobAction>(JA)) {
5537 // In /fallback builds, run the main compilation even if the pch generation
5538 // fails, so that the main compilation's fallback to cl.exe runs.
5539 C.addCommand(std::make_unique<ForceSuccessCommand>(JA, *this, Exec,
5542 C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5545 // Make the compile command echo its inputs for /showFilenames.
5546 if (Output.getType() == types::TY_Object &&
5547 Args.hasFlag(options::OPT__SLASH_showFilenames,
5548 options::OPT__SLASH_showFilenames_, false)) {
5549 C.getJobs().getJobs().back()->setPrintInputFilenames(true);
5552 if (Arg *A = Args.getLastArg(options::OPT_pg))
5553 if (FPKeepKind == CodeGenOptions::FramePointerKind::None)
5554 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5555 << A->getAsString(Args);
5557 // Claim some arguments which clang supports automatically.
5559 // -fpch-preprocess is used with gcc to add a special marker in the output to
5560 // include the PCH file.
5561 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5563 // Claim some arguments which clang doesn't support, but we don't
5564 // care to warn the user about.
5565 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5566 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5568 // Disable warnings for clang -E -emit-llvm foo.c
5569 Args.ClaimAllArgs(options::OPT_emit_llvm);
5572 Clang::Clang(const ToolChain &TC)
5573 // CAUTION! The first constructor argument ("clang") is not arbitrary,
5574 // as it is for other tools. Some operations on a Tool actually test
5575 // whether that tool is Clang based on the Tool's Name as a string.
5576 : Tool("clang", "clang frontend", TC, RF_Full) {}
5580 /// Add options related to the Objective-C runtime/ABI.
5582 /// Returns true if the runtime is non-fragile.
5583 ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5584 ArgStringList &cmdArgs,
5585 RewriteKind rewriteKind) const {
5586 // Look for the controlling runtime option.
5588 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5589 options::OPT_fobjc_runtime_EQ);
5591 // Just forward -fobjc-runtime= to the frontend. This supercedes
5592 // options about fragility.
5594 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5595 ObjCRuntime runtime;
5596 StringRef value = runtimeArg->getValue();
5597 if (runtime.tryParse(value)) {
5598 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5601 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
5602 (runtime.getVersion() >= VersionTuple(2, 0)))
5603 if (!getToolChain().getTriple().isOSBinFormatELF() &&
5604 !getToolChain().getTriple().isOSBinFormatCOFF()) {
5605 getToolChain().getDriver().Diag(
5606 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
5607 << runtime.getVersion().getMajor();
5610 runtimeArg->render(args, cmdArgs);
5614 // Otherwise, we'll need the ABI "version". Version numbers are
5615 // slightly confusing for historical reasons:
5616 // 1 - Traditional "fragile" ABI
5617 // 2 - Non-fragile ABI, version 1
5618 // 3 - Non-fragile ABI, version 2
5619 unsigned objcABIVersion = 1;
5620 // If -fobjc-abi-version= is present, use that to set the version.
5621 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5622 StringRef value = abiArg->getValue();
5625 else if (value == "2")
5627 else if (value == "3")
5630 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5632 // Otherwise, determine if we are using the non-fragile ABI.
5633 bool nonFragileABIIsDefault =
5634 (rewriteKind == RK_NonFragile ||
5635 (rewriteKind == RK_None &&
5636 getToolChain().IsObjCNonFragileABIDefault()));
5637 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5638 options::OPT_fno_objc_nonfragile_abi,
5639 nonFragileABIIsDefault)) {
5640 // Determine the non-fragile ABI version to use.
5641 #ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5642 unsigned nonFragileABIVersion = 1;
5644 unsigned nonFragileABIVersion = 2;
5648 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5649 StringRef value = abiArg->getValue();
5651 nonFragileABIVersion = 1;
5652 else if (value == "2")
5653 nonFragileABIVersion = 2;
5655 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5659 objcABIVersion = 1 + nonFragileABIVersion;
5665 // We don't actually care about the ABI version other than whether
5666 // it's non-fragile.
5667 bool isNonFragile = objcABIVersion != 1;
5669 // If we have no runtime argument, ask the toolchain for its default runtime.
5670 // However, the rewriter only really supports the Mac runtime, so assume that.
5671 ObjCRuntime runtime;
5673 switch (rewriteKind) {
5675 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5678 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5681 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5686 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5687 // On Darwin, make this use the default behavior for the toolchain.
5688 if (getToolChain().getTriple().isOSDarwin()) {
5689 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5691 // Otherwise, build for a generic macosx port.
5693 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5698 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5699 // Legacy behaviour is to target the gnustep runtime if we are in
5700 // non-fragile mode or the GCC runtime in fragile mode.
5702 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
5704 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5708 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5712 static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5713 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5721 bool Asynch = false;
5722 bool NoUnwindC = false;
5724 } // end anonymous namespace
5726 /// /EH controls whether to run destructor cleanups when exceptions are
5727 /// thrown. There are three modifiers:
5728 /// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5729 /// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5730 /// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5731 /// - c: Assume that extern "C" functions are implicitly nounwind.
5732 /// The default is /EHs-c-, meaning cleanups are disabled.
5733 static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args) {
5736 std::vector<std::string> EHArgs =
5737 Args.getAllArgValues(options::OPT__SLASH_EH);
5738 for (auto EHVal : EHArgs) {
5739 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5742 EH.Asynch = maybeConsumeDash(EHVal, I);
5747 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5750 EH.Synch = maybeConsumeDash(EHVal, I);
5757 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5761 // The /GX, /GX- flags are only processed if there are not /EH flags.
5762 // The default is that /GX is not specified.
5763 if (EHArgs.empty() &&
5764 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
5765 /*Default=*/false)) {
5767 EH.NoUnwindC = true;
5773 void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5774 ArgStringList &CmdArgs,
5775 codegenoptions::DebugInfoKind *DebugInfoKind,
5776 bool *EmitCodeView) const {
5777 unsigned RTOptionID = options::OPT__SLASH_MT;
5779 if (Args.hasArg(options::OPT__SLASH_LDd))
5780 // The /LDd option implies /MTd. The dependent lib part can be overridden,
5781 // but defining _DEBUG is sticky.
5782 RTOptionID = options::OPT__SLASH_MTd;
5784 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5785 RTOptionID = A->getOption().getID();
5787 StringRef FlagForCRT;
5788 switch (RTOptionID) {
5789 case options::OPT__SLASH_MD:
5790 if (Args.hasArg(options::OPT__SLASH_LDd))
5791 CmdArgs.push_back("-D_DEBUG");
5792 CmdArgs.push_back("-D_MT");
5793 CmdArgs.push_back("-D_DLL");
5794 FlagForCRT = "--dependent-lib=msvcrt";
5796 case options::OPT__SLASH_MDd:
5797 CmdArgs.push_back("-D_DEBUG");
5798 CmdArgs.push_back("-D_MT");
5799 CmdArgs.push_back("-D_DLL");
5800 FlagForCRT = "--dependent-lib=msvcrtd";
5802 case options::OPT__SLASH_MT:
5803 if (Args.hasArg(options::OPT__SLASH_LDd))
5804 CmdArgs.push_back("-D_DEBUG");
5805 CmdArgs.push_back("-D_MT");
5806 CmdArgs.push_back("-flto-visibility-public-std");
5807 FlagForCRT = "--dependent-lib=libcmt";
5809 case options::OPT__SLASH_MTd:
5810 CmdArgs.push_back("-D_DEBUG");
5811 CmdArgs.push_back("-D_MT");
5812 CmdArgs.push_back("-flto-visibility-public-std");
5813 FlagForCRT = "--dependent-lib=libcmtd";
5816 llvm_unreachable("Unexpected option ID.");
5819 if (Args.hasArg(options::OPT__SLASH_Zl)) {
5820 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5822 CmdArgs.push_back(FlagForCRT.data());
5824 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5825 // users want. The /Za flag to cl.exe turns this off, but it's not
5826 // implemented in clang.
5827 CmdArgs.push_back("--dependent-lib=oldnames");
5830 Args.AddLastArg(CmdArgs, options::OPT_show_includes);
5832 // This controls whether or not we emit RTTI data for polymorphic types.
5833 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5835 CmdArgs.push_back("-fno-rtti-data");
5837 // This controls whether or not we emit stack-protector instrumentation.
5838 // In MSVC, Buffer Security Check (/GS) is on by default.
5839 if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
5840 /*Default=*/true)) {
5841 CmdArgs.push_back("-stack-protector");
5842 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5845 // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5846 if (Arg *DebugInfoArg =
5847 Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5848 options::OPT_gline_tables_only)) {
5849 *EmitCodeView = true;
5850 if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5851 *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5853 *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
5855 *EmitCodeView = false;
5858 const Driver &D = getToolChain().getDriver();
5859 EHFlags EH = parseClangCLEHFlags(D, Args);
5860 if (EH.Synch || EH.Asynch) {
5861 if (types::isCXX(InputType))
5862 CmdArgs.push_back("-fcxx-exceptions");
5863 CmdArgs.push_back("-fexceptions");
5865 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5866 CmdArgs.push_back("-fexternc-nounwind");
5868 // /EP should expand to -E -P.
5869 if (Args.hasArg(options::OPT__SLASH_EP)) {
5870 CmdArgs.push_back("-E");
5871 CmdArgs.push_back("-P");
5874 unsigned VolatileOptionID;
5875 if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5876 getToolChain().getArch() == llvm::Triple::x86)
5877 VolatileOptionID = options::OPT__SLASH_volatile_ms;
5879 VolatileOptionID = options::OPT__SLASH_volatile_iso;
5881 if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5882 VolatileOptionID = A->getOption().getID();
5884 if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5885 CmdArgs.push_back("-fms-volatile");
5887 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
5888 options::OPT__SLASH_Zc_dllexportInlines,
5890 if (Args.hasArg(options::OPT__SLASH_fallback)) {
5891 D.Diag(clang::diag::err_drv_dllexport_inlines_and_fallback);
5893 CmdArgs.push_back("-fno-dllexport-inlines");
5897 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5898 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5899 if (MostGeneralArg && BestCaseArg)
5900 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5901 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5903 if (MostGeneralArg) {
5904 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5905 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5906 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5908 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5909 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5910 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5911 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5912 << FirstConflict->getAsString(Args)
5913 << SecondConflict->getAsString(Args);
5916 CmdArgs.push_back("-fms-memptr-rep=single");
5917 else if (MultipleArg)
5918 CmdArgs.push_back("-fms-memptr-rep=multiple");
5920 CmdArgs.push_back("-fms-memptr-rep=virtual");
5923 // Parse the default calling convention options.
5925 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
5926 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5927 options::OPT__SLASH_Gregcall)) {
5928 unsigned DCCOptId = CCArg->getOption().getID();
5929 const char *DCCFlag = nullptr;
5930 bool ArchSupported = true;
5931 llvm::Triple::ArchType Arch = getToolChain().getArch();
5933 case options::OPT__SLASH_Gd:
5934 DCCFlag = "-fdefault-calling-conv=cdecl";
5936 case options::OPT__SLASH_Gr:
5937 ArchSupported = Arch == llvm::Triple::x86;
5938 DCCFlag = "-fdefault-calling-conv=fastcall";
5940 case options::OPT__SLASH_Gz:
5941 ArchSupported = Arch == llvm::Triple::x86;
5942 DCCFlag = "-fdefault-calling-conv=stdcall";
5944 case options::OPT__SLASH_Gv:
5945 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5946 DCCFlag = "-fdefault-calling-conv=vectorcall";
5948 case options::OPT__SLASH_Gregcall:
5949 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5950 DCCFlag = "-fdefault-calling-conv=regcall";
5954 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5955 if (ArchSupported && DCCFlag)
5956 CmdArgs.push_back(DCCFlag);
5959 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
5961 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5962 CmdArgs.push_back("-fdiagnostics-format");
5963 if (Args.hasArg(options::OPT__SLASH_fallback))
5964 CmdArgs.push_back("msvc-fallback");
5966 CmdArgs.push_back("msvc");
5969 if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
5970 SmallVector<StringRef, 1> SplitArgs;
5971 StringRef(A->getValue()).split(SplitArgs, ",");
5972 bool Instrument = false;
5973 bool NoChecks = false;
5974 for (StringRef Arg : SplitArgs) {
5975 if (Arg.equals_lower("cf"))
5977 else if (Arg.equals_lower("cf-"))
5979 else if (Arg.equals_lower("nochecks"))
5981 else if (Arg.equals_lower("nochecks-"))
5984 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << Arg;
5986 // Currently there's no support emitting CFG instrumentation; the flag only
5987 // emits the table of address-taken functions.
5988 if (Instrument || NoChecks)
5989 CmdArgs.push_back("-cfguard");
5993 visualstudio::Compiler *Clang::getCLFallback() const {
5995 CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5996 return CLFallback.get();
6000 const char *Clang::getBaseInputName(const ArgList &Args,
6001 const InputInfo &Input) {
6002 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
6005 const char *Clang::getBaseInputStem(const ArgList &Args,
6006 const InputInfoList &Inputs) {
6007 const char *Str = getBaseInputName(Args, Inputs[0]);
6009 if (const char *End = strrchr(Str, '.'))
6010 return Args.MakeArgString(std::string(Str, End));
6015 const char *Clang::getDependencyFileName(const ArgList &Args,
6016 const InputInfoList &Inputs) {
6017 // FIXME: Think about this more.
6019 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6020 SmallString<128> OutputFilename(OutputOpt->getValue());
6021 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
6022 return Args.MakeArgString(OutputFilename);
6025 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
6030 void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
6031 ArgStringList &CmdArgs) const {
6034 const llvm::Triple &Triple = getToolChain().getTriple();
6035 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
6037 CmdArgs.push_back("-target-abi");
6038 CmdArgs.push_back(ABIName.data());
6041 void ClangAs::AddX86TargetArgs(const ArgList &Args,
6042 ArgStringList &CmdArgs) const {
6043 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
6044 StringRef Value = A->getValue();
6045 if (Value == "intel" || Value == "att") {
6046 CmdArgs.push_back("-mllvm");
6047 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
6049 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
6050 << A->getOption().getName() << Value;
6055 void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
6056 ArgStringList &CmdArgs) const {
6057 const llvm::Triple &Triple = getToolChain().getTriple();
6058 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
6060 CmdArgs.push_back("-target-abi");
6061 CmdArgs.push_back(ABIName.data());
6064 void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
6065 const InputInfo &Output, const InputInfoList &Inputs,
6066 const ArgList &Args,
6067 const char *LinkingOutput) const {
6068 ArgStringList CmdArgs;
6070 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
6071 const InputInfo &Input = Inputs[0];
6073 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
6074 const std::string &TripleStr = Triple.getTriple();
6075 const auto &D = getToolChain().getDriver();
6077 // Don't warn about "clang -w -c foo.s"
6078 Args.ClaimAllArgs(options::OPT_w);
6079 // and "clang -emit-llvm -c foo.s"
6080 Args.ClaimAllArgs(options::OPT_emit_llvm);
6082 claimNoWarnArgs(Args);
6084 // Invoke ourselves in -cc1as mode.
6086 // FIXME: Implement custom jobs for internal actions.
6087 CmdArgs.push_back("-cc1as");
6089 // Add the "effective" target triple.
6090 CmdArgs.push_back("-triple");
6091 CmdArgs.push_back(Args.MakeArgString(TripleStr));
6093 // Set the output mode, we currently only expect to be used as a real
6095 CmdArgs.push_back("-filetype");
6096 CmdArgs.push_back("obj");
6098 // Set the main file name, so that debug info works even with
6099 // -save-temps or preprocessed assembly.
6100 CmdArgs.push_back("-main-file-name");
6101 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
6103 // Add the target cpu
6104 std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
6106 CmdArgs.push_back("-target-cpu");
6107 CmdArgs.push_back(Args.MakeArgString(CPU));
6110 // Add the target features
6111 getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
6113 // Ignore explicit -force_cpusubtype_ALL option.
6114 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
6116 // Pass along any -I options so we get proper .include search paths.
6117 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
6119 // Determine the original source input.
6120 const Action *SourceAction = &JA;
6121 while (SourceAction->getKind() != Action::InputClass) {
6122 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6123 SourceAction = SourceAction->getInputs()[0];
6126 // Forward -g and handle debug info related flags, assuming we are dealing
6127 // with an actual assembly file.
6128 bool WantDebug = false;
6129 unsigned DwarfVersion = 0;
6130 Args.ClaimAllArgs(options::OPT_g_Group);
6131 if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
6132 WantDebug = !A->getOption().matches(options::OPT_g0) &&
6133 !A->getOption().matches(options::OPT_ggdb0);
6135 DwarfVersion = DwarfVersionNum(A->getSpelling());
6137 if (DwarfVersion == 0)
6138 DwarfVersion = getToolChain().GetDefaultDwarfVersion();
6140 codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
6142 if (SourceAction->getType() == types::TY_Asm ||
6143 SourceAction->getType() == types::TY_PP_Asm) {
6144 // You might think that it would be ok to set DebugInfoKind outside of
6145 // the guard for source type, however there is a test which asserts
6146 // that some assembler invocation receives no -debug-info-kind,
6147 // and it's not clear whether that test is just overly restrictive.
6148 DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
6149 : codegenoptions::NoDebugInfo);
6150 // Add the -fdebug-compilation-dir flag if needed.
6151 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
6153 addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
6155 // Set the AT_producer to the clang version when using the integrated
6156 // assembler on assembly source files.
6157 CmdArgs.push_back("-dwarf-debug-producer");
6158 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6160 // And pass along -I options
6161 Args.AddAllArgs(CmdArgs, options::OPT_I);
6163 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
6164 llvm::DebuggerKind::Default);
6165 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
6168 // Handle -fPIC et al -- the relocation-model affects the assembler
6169 // for some targets.
6170 llvm::Reloc::Model RelocationModel;
6173 std::tie(RelocationModel, PICLevel, IsPIE) =
6174 ParsePICArgs(getToolChain(), Args);
6176 const char *RMName = RelocationModelName(RelocationModel);
6178 CmdArgs.push_back("-mrelocation-model");
6179 CmdArgs.push_back(RMName);
6182 // Optionally embed the -cc1as level arguments into the debug info, for build
6184 if (getToolChain().UseDwarfDebugFlags()) {
6185 ArgStringList OriginalArgs;
6186 for (const auto &Arg : Args)
6187 Arg->render(Args, OriginalArgs);
6189 SmallString<256> Flags;
6190 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6192 for (const char *OriginalArg : OriginalArgs) {
6193 SmallString<128> EscapedArg;
6194 EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6196 Flags += EscapedArg;
6198 CmdArgs.push_back("-dwarf-debug-flags");
6199 CmdArgs.push_back(Args.MakeArgString(Flags));
6202 // FIXME: Add -static support, once we have it.
6204 // Add target specific flags.
6205 switch (getToolChain().getArch()) {
6209 case llvm::Triple::mips:
6210 case llvm::Triple::mipsel:
6211 case llvm::Triple::mips64:
6212 case llvm::Triple::mips64el:
6213 AddMIPSTargetArgs(Args, CmdArgs);
6216 case llvm::Triple::x86:
6217 case llvm::Triple::x86_64:
6218 AddX86TargetArgs(Args, CmdArgs);
6221 case llvm::Triple::arm:
6222 case llvm::Triple::armeb:
6223 case llvm::Triple::thumb:
6224 case llvm::Triple::thumbeb:
6225 // This isn't in AddARMTargetArgs because we want to do this for assembly
6227 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
6228 options::OPT_mno_default_build_attributes, true)) {
6229 CmdArgs.push_back("-mllvm");
6230 CmdArgs.push_back("-arm-add-build-attributes");
6234 case llvm::Triple::riscv32:
6235 case llvm::Triple::riscv64:
6236 AddRISCVTargetArgs(Args, CmdArgs);
6240 // Consume all the warning flags. Usually this would be handled more
6241 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6242 // doesn't handle that so rather than warning about unused flags that are
6243 // actually used, we'll lie by omission instead.
6244 // FIXME: Stop lying and consume only the appropriate driver flags
6245 Args.ClaimAllArgs(options::OPT_W_Group);
6247 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6248 getToolChain().getDriver());
6250 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6252 assert(Output.isFilename() && "Unexpected lipo output.");
6253 CmdArgs.push_back("-o");
6254 CmdArgs.push_back(Output.getFilename());
6256 const llvm::Triple &T = getToolChain().getTriple();
6258 if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
6259 T.isOSBinFormatELF()) {
6260 CmdArgs.push_back("-split-dwarf-output");
6261 CmdArgs.push_back(SplitDebugName(Args, Input, Output));
6264 assert(Input.isFilename() && "Invalid input.");
6265 CmdArgs.push_back(Input.getFilename());
6267 const char *Exec = getToolChain().getDriver().getClangProgramPath();
6268 C.addCommand(std::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6271 // Begin OffloadBundler
6273 void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
6274 const InputInfo &Output,
6275 const InputInfoList &Inputs,
6276 const llvm::opt::ArgList &TCArgs,
6277 const char *LinkingOutput) const {
6278 // The version with only one output is expected to refer to a bundling job.
6279 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
6281 // The bundling command looks like this:
6282 // clang-offload-bundler -type=bc
6283 // -targets=host-triple,openmp-triple1,openmp-triple2
6284 // -outputs=input_file
6285 // -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6287 ArgStringList CmdArgs;
6290 CmdArgs.push_back(TCArgs.MakeArgString(
6291 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
6293 assert(JA.getInputs().size() == Inputs.size() &&
6294 "Not have inputs for all dependence actions??");
6297 SmallString<128> Triples;
6298 Triples += "-targets=";
6299 for (unsigned I = 0; I < Inputs.size(); ++I) {
6303 // Find ToolChain for this input.
6304 Action::OffloadKind CurKind = Action::OFK_Host;
6305 const ToolChain *CurTC = &getToolChain();
6306 const Action *CurDep = JA.getInputs()[I];
6308 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
6310 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
6311 assert(CurTC == nullptr && "Expected one dependence!");
6312 CurKind = A->getOffloadingDeviceKind();
6316 Triples += Action::GetOffloadKindName(CurKind);
6318 Triples += CurTC->getTriple().normalize();
6319 if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
6321 Triples += CurDep->getOffloadingArch();
6324 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6326 // Get bundled file command.
6328 TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
6330 // Get unbundled files command.
6331 SmallString<128> UB;
6333 for (unsigned I = 0; I < Inputs.size(); ++I) {
6337 // Find ToolChain for this input.
6338 const ToolChain *CurTC = &getToolChain();
6339 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
6341 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
6342 assert(CurTC == nullptr && "Expected one dependence!");
6346 UB += CurTC->getInputFilename(Inputs[I]);
6348 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6350 // All the inputs are encoded as commands.
6351 C.addCommand(std::make_unique<Command>(
6353 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6357 void OffloadBundler::ConstructJobMultipleOutputs(
6358 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
6359 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
6360 const char *LinkingOutput) const {
6361 // The version with multiple outputs is expected to refer to a unbundling job.
6362 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
6364 // The unbundling command looks like this:
6365 // clang-offload-bundler -type=bc
6366 // -targets=host-triple,openmp-triple1,openmp-triple2
6367 // -inputs=input_file
6368 // -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6371 ArgStringList CmdArgs;
6373 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
6374 InputInfo Input = Inputs.front();
6377 CmdArgs.push_back(TCArgs.MakeArgString(
6378 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
6381 SmallString<128> Triples;
6382 Triples += "-targets=";
6383 auto DepInfo = UA.getDependentActionsInfo();
6384 for (unsigned I = 0; I < DepInfo.size(); ++I) {
6388 auto &Dep = DepInfo[I];
6389 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
6391 Triples += Dep.DependentToolChain->getTriple().normalize();
6392 if (Dep.DependentOffloadKind == Action::OFK_HIP &&
6393 !Dep.DependentBoundArch.empty()) {
6395 Triples += Dep.DependentBoundArch;
6399 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6401 // Get bundled file command.
6403 TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
6405 // Get unbundled files command.
6406 SmallString<128> UB;
6408 for (unsigned I = 0; I < Outputs.size(); ++I) {
6411 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
6413 CmdArgs.push_back(TCArgs.MakeArgString(UB));
6414 CmdArgs.push_back("-unbundle");
6416 // All the inputs are encoded as commands.
6417 C.addCommand(std::make_unique<Command>(
6419 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6423 void OffloadWrapper::ConstructJob(Compilation &C, const JobAction &JA,
6424 const InputInfo &Output,
6425 const InputInfoList &Inputs,
6426 const ArgList &Args,
6427 const char *LinkingOutput) const {
6428 ArgStringList CmdArgs;
6430 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
6432 // Add the "effective" target triple.
6433 CmdArgs.push_back("-target");
6434 CmdArgs.push_back(Args.MakeArgString(Triple.getTriple()));
6436 // Add the output file name.
6437 assert(Output.isFilename() && "Invalid output.");
6438 CmdArgs.push_back("-o");
6439 CmdArgs.push_back(Output.getFilename());
6442 for (const InputInfo &I : Inputs) {
6443 assert(I.isFilename() && "Invalid input.");
6444 CmdArgs.push_back(I.getFilename());
6447 C.addCommand(std::make_unique<Command>(
6449 Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),