clang 20.0.0git
Clang.cpp
Go to the documentation of this file.
1//===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "Clang.h"
10#include "AMDGPU.h"
11#include "Arch/AArch64.h"
12#include "Arch/ARM.h"
13#include "Arch/CSKY.h"
14#include "Arch/LoongArch.h"
15#include "Arch/M68k.h"
16#include "Arch/Mips.h"
17#include "Arch/PPC.h"
18#include "Arch/RISCV.h"
19#include "Arch/Sparc.h"
20#include "Arch/SystemZ.h"
21#include "Arch/VE.h"
22#include "Arch/X86.h"
23#include "CommonArgs.h"
24#include "Hexagon.h"
25#include "MSP430.h"
26#include "PS4CPU.h"
27#include "SYCL.h"
35#include "clang/Basic/Version.h"
36#include "clang/Config/config.h"
37#include "clang/Driver/Action.h"
38#include "clang/Driver/Distro.h"
43#include "clang/Driver/Types.h"
45#include "llvm/ADT/ScopeExit.h"
46#include "llvm/ADT/SmallSet.h"
47#include "llvm/ADT/StringExtras.h"
48#include "llvm/BinaryFormat/Magic.h"
49#include "llvm/Config/llvm-config.h"
50#include "llvm/Frontend/Debug/Options.h"
51#include "llvm/Object/ObjectFile.h"
52#include "llvm/Option/ArgList.h"
53#include "llvm/Support/CodeGen.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/Support/Compression.h"
56#include "llvm/Support/Error.h"
57#include "llvm/Support/FileSystem.h"
58#include "llvm/Support/Path.h"
59#include "llvm/Support/Process.h"
60#include "llvm/Support/YAMLParser.h"
61#include "llvm/TargetParser/AArch64TargetParser.h"
62#include "llvm/TargetParser/ARMTargetParserCommon.h"
63#include "llvm/TargetParser/Host.h"
64#include "llvm/TargetParser/LoongArchTargetParser.h"
65#include "llvm/TargetParser/PPCTargetParser.h"
66#include "llvm/TargetParser/RISCVISAInfo.h"
67#include "llvm/TargetParser/RISCVTargetParser.h"
68#include <cctype>
69
70using namespace clang::driver;
71using namespace clang::driver::tools;
72using namespace clang;
73using namespace llvm::opt;
74
75static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
76 if (Arg *A = Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC,
77 options::OPT_fminimize_whitespace,
78 options::OPT_fno_minimize_whitespace,
79 options::OPT_fkeep_system_includes,
80 options::OPT_fno_keep_system_includes)) {
81 if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
82 !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
83 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
84 << A->getBaseArg().getAsString(Args)
85 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
86 }
87 }
88}
89
90static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
91 // In gcc, only ARM checks this, but it seems reasonable to check universally.
92 if (Args.hasArg(options::OPT_static))
93 if (const Arg *A =
94 Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
95 D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
96 << "-static";
97}
98
99/// Apply \a Work on the current tool chain \a RegularToolChain and any other
100/// offloading tool chain that is associated with the current action \a JA.
101static void
103 const ToolChain &RegularToolChain,
104 llvm::function_ref<void(const ToolChain &)> Work) {
105 // Apply Work on the current/regular tool chain.
106 Work(RegularToolChain);
107
108 // Apply Work on all the offloading tool chains associated with the current
109 // action.
111 Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
113 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
115 Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
117 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
118
120 auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
121 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
122 Work(*II->second);
124 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
125
127 auto TCs = C.getOffloadToolChains<Action::OFK_SYCL>();
128 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
129 Work(*II->second);
131 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
132
133 //
134 // TODO: Add support for other offloading programming models here.
135 //
136}
137
138/// This is a helper function for validating the optional refinement step
139/// parameter in reciprocal argument strings. Return false if there is an error
140/// parsing the refinement step. Otherwise, return true and set the Position
141/// of the refinement step in the input string.
142static bool getRefinementStep(StringRef In, const Driver &D,
143 const Arg &A, size_t &Position) {
144 const char RefinementStepToken = ':';
145 Position = In.find(RefinementStepToken);
146 if (Position != StringRef::npos) {
147 StringRef Option = A.getOption().getName();
148 StringRef RefStep = In.substr(Position + 1);
149 // Allow exactly one numeric character for the additional refinement
150 // step parameter. This is reasonable for all currently-supported
151 // operations and architectures because we would expect that a larger value
152 // of refinement steps would cause the estimate "optimization" to
153 // under-perform the native operation. Also, if the estimate does not
154 // converge quickly, it probably will not ever converge, so further
155 // refinement steps will not produce a better answer.
156 if (RefStep.size() != 1) {
157 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
158 return false;
159 }
160 char RefStepChar = RefStep[0];
161 if (RefStepChar < '0' || RefStepChar > '9') {
162 D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
163 return false;
164 }
165 }
166 return true;
167}
168
169/// The -mrecip flag requires processing of many optional parameters.
170static void ParseMRecip(const Driver &D, const ArgList &Args,
171 ArgStringList &OutStrings) {
172 StringRef DisabledPrefixIn = "!";
173 StringRef DisabledPrefixOut = "!";
174 StringRef EnabledPrefixOut = "";
175 StringRef Out = "-mrecip=";
176
177 Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
178 if (!A)
179 return;
180
181 unsigned NumOptions = A->getNumValues();
182 if (NumOptions == 0) {
183 // No option is the same as "all".
184 OutStrings.push_back(Args.MakeArgString(Out + "all"));
185 return;
186 }
187
188 // Pass through "all", "none", or "default" with an optional refinement step.
189 if (NumOptions == 1) {
190 StringRef Val = A->getValue(0);
191 size_t RefStepLoc;
192 if (!getRefinementStep(Val, D, *A, RefStepLoc))
193 return;
194 StringRef ValBase = Val.slice(0, RefStepLoc);
195 if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
196 OutStrings.push_back(Args.MakeArgString(Out + Val));
197 return;
198 }
199 }
200
201 // Each reciprocal type may be enabled or disabled individually.
202 // Check each input value for validity, concatenate them all back together,
203 // and pass through.
204
205 llvm::StringMap<bool> OptionStrings;
206 OptionStrings.insert(std::make_pair("divd", false));
207 OptionStrings.insert(std::make_pair("divf", false));
208 OptionStrings.insert(std::make_pair("divh", false));
209 OptionStrings.insert(std::make_pair("vec-divd", false));
210 OptionStrings.insert(std::make_pair("vec-divf", false));
211 OptionStrings.insert(std::make_pair("vec-divh", false));
212 OptionStrings.insert(std::make_pair("sqrtd", false));
213 OptionStrings.insert(std::make_pair("sqrtf", false));
214 OptionStrings.insert(std::make_pair("sqrth", false));
215 OptionStrings.insert(std::make_pair("vec-sqrtd", false));
216 OptionStrings.insert(std::make_pair("vec-sqrtf", false));
217 OptionStrings.insert(std::make_pair("vec-sqrth", false));
218
219 for (unsigned i = 0; i != NumOptions; ++i) {
220 StringRef Val = A->getValue(i);
221
222 bool IsDisabled = Val.starts_with(DisabledPrefixIn);
223 // Ignore the disablement token for string matching.
224 if (IsDisabled)
225 Val = Val.substr(1);
226
227 size_t RefStep;
228 if (!getRefinementStep(Val, D, *A, RefStep))
229 return;
230
231 StringRef ValBase = Val.slice(0, RefStep);
232 llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
233 if (OptionIter == OptionStrings.end()) {
234 // Try again specifying float suffix.
235 OptionIter = OptionStrings.find(ValBase.str() + 'f');
236 if (OptionIter == OptionStrings.end()) {
237 // The input name did not match any known option string.
238 D.Diag(diag::err_drv_unknown_argument) << Val;
239 return;
240 }
241 // The option was specified without a half or float or double suffix.
242 // Make sure that the double or half entry was not already specified.
243 // The float entry will be checked below.
244 if (OptionStrings[ValBase.str() + 'd'] ||
245 OptionStrings[ValBase.str() + 'h']) {
246 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
247 return;
248 }
249 }
250
251 if (OptionIter->second == true) {
252 // Duplicate option specified.
253 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
254 return;
255 }
256
257 // Mark the matched option as found. Do not allow duplicate specifiers.
258 OptionIter->second = true;
259
260 // If the precision was not specified, also mark the double and half entry
261 // as found.
262 if (ValBase.back() != 'f' && ValBase.back() != 'd' && ValBase.back() != 'h') {
263 OptionStrings[ValBase.str() + 'd'] = true;
264 OptionStrings[ValBase.str() + 'h'] = true;
265 }
266
267 // Build the output string.
268 StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
269 Out = Args.MakeArgString(Out + Prefix + Val);
270 if (i != NumOptions - 1)
271 Out = Args.MakeArgString(Out + ",");
272 }
273
274 OutStrings.push_back(Args.MakeArgString(Out));
275}
276
277/// The -mprefer-vector-width option accepts either a positive integer
278/// or the string "none".
279static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
280 ArgStringList &CmdArgs) {
281 Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
282 if (!A)
283 return;
284
285 StringRef Value = A->getValue();
286 if (Value == "none") {
287 CmdArgs.push_back("-mprefer-vector-width=none");
288 } else {
289 unsigned Width;
290 if (Value.getAsInteger(10, Width)) {
291 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
292 return;
293 }
294 CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
295 }
296}
297
298static bool
300 const llvm::Triple &Triple) {
301 // We use the zero-cost exception tables for Objective-C if the non-fragile
302 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
303 // later.
304 if (runtime.isNonFragile())
305 return true;
306
307 if (!Triple.isMacOSX())
308 return false;
309
310 return (!Triple.isMacOSXVersionLT(10, 5) &&
311 (Triple.getArch() == llvm::Triple::x86_64 ||
312 Triple.getArch() == llvm::Triple::arm));
313}
314
315/// Adds exception related arguments to the driver command arguments. There's a
316/// main flag, -fexceptions and also language specific flags to enable/disable
317/// C++ and Objective-C exceptions. This makes it possible to for example
318/// disable C++ exceptions but enable Objective-C exceptions.
319static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
320 const ToolChain &TC, bool KernelOrKext,
321 const ObjCRuntime &objcRuntime,
322 ArgStringList &CmdArgs) {
323 const llvm::Triple &Triple = TC.getTriple();
324
325 if (KernelOrKext) {
326 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
327 // arguments now to avoid warnings about unused arguments.
328 Args.ClaimAllArgs(options::OPT_fexceptions);
329 Args.ClaimAllArgs(options::OPT_fno_exceptions);
330 Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
331 Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
332 Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
333 Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
334 Args.ClaimAllArgs(options::OPT_fasync_exceptions);
335 Args.ClaimAllArgs(options::OPT_fno_async_exceptions);
336 return false;
337 }
338
339 // See if the user explicitly enabled exceptions.
340 bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
341 false);
342
343 // Async exceptions are Windows MSVC only.
344 if (Triple.isWindowsMSVCEnvironment()) {
345 bool EHa = Args.hasFlag(options::OPT_fasync_exceptions,
346 options::OPT_fno_async_exceptions, false);
347 if (EHa) {
348 CmdArgs.push_back("-fasync-exceptions");
349 EH = true;
350 }
351 }
352
353 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
354 // is not necessarily sensible, but follows GCC.
355 if (types::isObjC(InputType) &&
356 Args.hasFlag(options::OPT_fobjc_exceptions,
357 options::OPT_fno_objc_exceptions, true)) {
358 CmdArgs.push_back("-fobjc-exceptions");
359
360 EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
361 }
362
363 if (types::isCXX(InputType)) {
364 // Disable C++ EH by default on XCore and PS4/PS5.
365 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
366 !Triple.isPS() && !Triple.isDriverKit();
367 Arg *ExceptionArg = Args.getLastArg(
368 options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
369 options::OPT_fexceptions, options::OPT_fno_exceptions);
370 if (ExceptionArg)
371 CXXExceptionsEnabled =
372 ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
373 ExceptionArg->getOption().matches(options::OPT_fexceptions);
374
375 if (CXXExceptionsEnabled) {
376 CmdArgs.push_back("-fcxx-exceptions");
377
378 EH = true;
379 }
380 }
381
382 // OPT_fignore_exceptions means exception could still be thrown,
383 // but no clean up or catch would happen in current module.
384 // So we do not set EH to false.
385 Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
386
387 Args.addOptInFlag(CmdArgs, options::OPT_fassume_nothrow_exception_dtor,
388 options::OPT_fno_assume_nothrow_exception_dtor);
389
390 if (EH)
391 CmdArgs.push_back("-fexceptions");
392 return EH;
393}
394
395static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
396 const JobAction &JA) {
397 bool Default = true;
398 if (TC.getTriple().isOSDarwin()) {
399 // The native darwin assembler doesn't support the linker_option directives,
400 // so we disable them if we think the .s file will be passed to it.
402 }
403 // The linker_option directives are intended for host compilation.
406 Default = false;
407 return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
408 Default);
409}
410
411/// Add a CC1 option to specify the debug compilation directory.
412static const char *addDebugCompDirArg(const ArgList &Args,
413 ArgStringList &CmdArgs,
414 const llvm::vfs::FileSystem &VFS) {
415 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
416 options::OPT_fdebug_compilation_dir_EQ)) {
417 if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
418 CmdArgs.push_back(Args.MakeArgString(Twine("-fdebug-compilation-dir=") +
419 A->getValue()));
420 else
421 A->render(Args, CmdArgs);
422 } else if (llvm::ErrorOr<std::string> CWD =
423 VFS.getCurrentWorkingDirectory()) {
424 CmdArgs.push_back(Args.MakeArgString("-fdebug-compilation-dir=" + *CWD));
425 }
426 StringRef Path(CmdArgs.back());
427 return Path.substr(Path.find('=') + 1).data();
428}
429
430static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
431 const char *DebugCompilationDir,
432 const char *OutputFileName) {
433 // No need to generate a value for -object-file-name if it was provided.
434 for (auto *Arg : Args.filtered(options::OPT_Xclang))
435 if (StringRef(Arg->getValue()).starts_with("-object-file-name"))
436 return;
437
438 if (Args.hasArg(options::OPT_object_file_name_EQ))
439 return;
440
441 SmallString<128> ObjFileNameForDebug(OutputFileName);
442 if (ObjFileNameForDebug != "-" &&
443 !llvm::sys::path::is_absolute(ObjFileNameForDebug) &&
444 (!DebugCompilationDir ||
445 llvm::sys::path::is_absolute(DebugCompilationDir))) {
446 // Make the path absolute in the debug infos like MSVC does.
447 llvm::sys::fs::make_absolute(ObjFileNameForDebug);
448 }
449 // If the object file name is a relative path, then always use Windows
450 // backslash style as -object-file-name is used for embedding object file path
451 // in codeview and it can only be generated when targeting on Windows.
452 // Otherwise, just use native absolute path.
453 llvm::sys::path::Style Style =
454 llvm::sys::path::is_absolute(ObjFileNameForDebug)
455 ? llvm::sys::path::Style::native
456 : llvm::sys::path::Style::windows_backslash;
457 llvm::sys::path::remove_dots(ObjFileNameForDebug, /*remove_dot_dot=*/true,
458 Style);
459 CmdArgs.push_back(
460 Args.MakeArgString(Twine("-object-file-name=") + ObjFileNameForDebug));
461}
462
463/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
464static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
465 const ArgList &Args, ArgStringList &CmdArgs) {
466 auto AddOneArg = [&](StringRef Map, StringRef Name) {
467 if (!Map.contains('='))
468 D.Diag(diag::err_drv_invalid_argument_to_option) << Map << Name;
469 else
470 CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
471 };
472
473 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
474 options::OPT_fdebug_prefix_map_EQ)) {
475 AddOneArg(A->getValue(), A->getOption().getName());
476 A->claim();
477 }
478 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
479 if (GlobalRemapEntry.empty())
480 return;
481 AddOneArg(GlobalRemapEntry, "environment");
482}
483
484/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
485static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
486 ArgStringList &CmdArgs) {
487 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
488 options::OPT_fmacro_prefix_map_EQ)) {
489 StringRef Map = A->getValue();
490 if (!Map.contains('='))
491 D.Diag(diag::err_drv_invalid_argument_to_option)
492 << Map << A->getOption().getName();
493 else
494 CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
495 A->claim();
496 }
497}
498
499/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
500static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
501 ArgStringList &CmdArgs) {
502 for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
503 options::OPT_fcoverage_prefix_map_EQ)) {
504 StringRef Map = A->getValue();
505 if (!Map.contains('='))
506 D.Diag(diag::err_drv_invalid_argument_to_option)
507 << Map << A->getOption().getName();
508 else
509 CmdArgs.push_back(Args.MakeArgString("-fcoverage-prefix-map=" + Map));
510 A->claim();
511 }
512}
513
514/// Vectorize at all optimization levels greater than 1 except for -Oz.
515/// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
516/// enabled.
517static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
518 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
519 if (A->getOption().matches(options::OPT_O4) ||
520 A->getOption().matches(options::OPT_Ofast))
521 return true;
522
523 if (A->getOption().matches(options::OPT_O0))
524 return false;
525
526 assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
527
528 // Vectorize -Os.
529 StringRef S(A->getValue());
530 if (S == "s")
531 return true;
532
533 // Don't vectorize -Oz, unless it's the slp vectorizer.
534 if (S == "z")
535 return isSlpVec;
536
537 unsigned OptLevel = 0;
538 if (S.getAsInteger(10, OptLevel))
539 return false;
540
541 return OptLevel > 1;
542 }
543
544 return false;
545}
546
547/// Add -x lang to \p CmdArgs for \p Input.
548static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
549 ArgStringList &CmdArgs) {
550 // When using -verify-pch, we don't want to provide the type
551 // 'precompiled-header' if it was inferred from the file extension
552 if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
553 return;
554
555 CmdArgs.push_back("-x");
556 if (Args.hasArg(options::OPT_rewrite_objc))
557 CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
558 else {
559 // Map the driver type to the frontend type. This is mostly an identity
560 // mapping, except that the distinction between module interface units
561 // and other source files does not exist at the frontend layer.
562 const char *ClangType;
563 switch (Input.getType()) {
564 case types::TY_CXXModule:
565 ClangType = "c++";
566 break;
567 case types::TY_PP_CXXModule:
568 ClangType = "c++-cpp-output";
569 break;
570 default:
571 ClangType = types::getTypeName(Input.getType());
572 break;
573 }
574 CmdArgs.push_back(ClangType);
575 }
576}
577
579 const JobAction &JA, const InputInfo &Output,
580 const ArgList &Args, SanitizerArgs &SanArgs,
581 ArgStringList &CmdArgs) {
582 const Driver &D = TC.getDriver();
583 auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
584 options::OPT_fprofile_generate_EQ,
585 options::OPT_fno_profile_generate);
586 if (PGOGenerateArg &&
587 PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
588 PGOGenerateArg = nullptr;
589
590 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
591
592 auto *ProfileGenerateArg = Args.getLastArg(
593 options::OPT_fprofile_instr_generate,
594 options::OPT_fprofile_instr_generate_EQ,
595 options::OPT_fno_profile_instr_generate);
596 if (ProfileGenerateArg &&
597 ProfileGenerateArg->getOption().matches(
598 options::OPT_fno_profile_instr_generate))
599 ProfileGenerateArg = nullptr;
600
601 if (PGOGenerateArg && ProfileGenerateArg)
602 D.Diag(diag::err_drv_argument_not_allowed_with)
603 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
604
605 auto *ProfileUseArg = getLastProfileUseArg(Args);
606
607 if (PGOGenerateArg && ProfileUseArg)
608 D.Diag(diag::err_drv_argument_not_allowed_with)
609 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
610
611 if (ProfileGenerateArg && ProfileUseArg)
612 D.Diag(diag::err_drv_argument_not_allowed_with)
613 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
614
615 if (CSPGOGenerateArg && PGOGenerateArg) {
616 D.Diag(diag::err_drv_argument_not_allowed_with)
617 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
618 PGOGenerateArg = nullptr;
619 }
620
621 if (TC.getTriple().isOSAIX()) {
622 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
623 D.Diag(diag::err_drv_unsupported_opt_for_target)
624 << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
625 }
626
627 if (ProfileGenerateArg) {
628 if (ProfileGenerateArg->getOption().matches(
629 options::OPT_fprofile_instr_generate_EQ))
630 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
631 ProfileGenerateArg->getValue()));
632 // The default is to use Clang Instrumentation.
633 CmdArgs.push_back("-fprofile-instrument=clang");
634 if (TC.getTriple().isWindowsMSVCEnvironment() &&
635 Args.hasFlag(options::OPT_frtlib_defaultlib,
636 options::OPT_fno_rtlib_defaultlib, true)) {
637 // Add dependent lib for clang_rt.profile
638 CmdArgs.push_back(Args.MakeArgString(
639 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
640 }
641 }
642
643 if (auto *ColdFuncCoverageArg = Args.getLastArg(
644 options::OPT_fprofile_generate_cold_function_coverage,
645 options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
647 ColdFuncCoverageArg->getOption().matches(
648 options::OPT_fprofile_generate_cold_function_coverage_EQ)
649 ? ColdFuncCoverageArg->getValue()
650 : "");
651 llvm::sys::path::append(Path, "default_%m.profraw");
652 // FIXME: Idealy the file path should be passed through
653 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
654 // shared with other profile use path(see PGOOptions), we need to refactor
655 // PGOOptions to make it work.
656 CmdArgs.push_back("-mllvm");
657 CmdArgs.push_back(Args.MakeArgString(
658 Twine("--instrument-cold-function-only-path=") + Path));
659 CmdArgs.push_back("-mllvm");
660 CmdArgs.push_back("--pgo-instrument-cold-function-only");
661 CmdArgs.push_back("-mllvm");
662 CmdArgs.push_back("--pgo-function-entry-coverage");
663 }
664
665 Arg *PGOGenArg = nullptr;
666 if (PGOGenerateArg) {
667 assert(!CSPGOGenerateArg);
668 PGOGenArg = PGOGenerateArg;
669 CmdArgs.push_back("-fprofile-instrument=llvm");
670 }
671 if (CSPGOGenerateArg) {
672 assert(!PGOGenerateArg);
673 PGOGenArg = CSPGOGenerateArg;
674 CmdArgs.push_back("-fprofile-instrument=csllvm");
675 }
676 if (PGOGenArg) {
677 if (TC.getTriple().isWindowsMSVCEnvironment() &&
678 Args.hasFlag(options::OPT_frtlib_defaultlib,
679 options::OPT_fno_rtlib_defaultlib, true)) {
680 // Add dependent lib for clang_rt.profile
681 CmdArgs.push_back(Args.MakeArgString(
682 "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
683 }
684 if (PGOGenArg->getOption().matches(
685 PGOGenerateArg ? options::OPT_fprofile_generate_EQ
686 : options::OPT_fcs_profile_generate_EQ)) {
687 SmallString<128> Path(PGOGenArg->getValue());
688 llvm::sys::path::append(Path, "default_%m.profraw");
689 CmdArgs.push_back(
690 Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
691 }
692 }
693
694 if (ProfileUseArg) {
695 if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
696 CmdArgs.push_back(Args.MakeArgString(
697 Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
698 else if ((ProfileUseArg->getOption().matches(
699 options::OPT_fprofile_use_EQ) ||
700 ProfileUseArg->getOption().matches(
701 options::OPT_fprofile_instr_use))) {
703 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
704 if (Path.empty() || llvm::sys::fs::is_directory(Path))
705 llvm::sys::path::append(Path, "default.profdata");
706 CmdArgs.push_back(
707 Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
708 }
709 }
710
711 bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
712 options::OPT_fno_test_coverage, false) ||
713 Args.hasArg(options::OPT_coverage);
714 bool EmitCovData = TC.needsGCovInstrumentation(Args);
715
716 if (Args.hasFlag(options::OPT_fcoverage_mapping,
717 options::OPT_fno_coverage_mapping, false)) {
718 if (!ProfileGenerateArg)
719 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
720 << "-fcoverage-mapping"
721 << "-fprofile-instr-generate";
722
723 CmdArgs.push_back("-fcoverage-mapping");
724 }
725
726 if (Args.hasFlag(options::OPT_fmcdc_coverage, options::OPT_fno_mcdc_coverage,
727 false)) {
728 if (!Args.hasFlag(options::OPT_fcoverage_mapping,
729 options::OPT_fno_coverage_mapping, false))
730 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
731 << "-fcoverage-mcdc"
732 << "-fcoverage-mapping";
733
734 CmdArgs.push_back("-fcoverage-mcdc");
735 }
736
737 if (Arg *A = Args.getLastArg(options::OPT_ffile_compilation_dir_EQ,
738 options::OPT_fcoverage_compilation_dir_EQ)) {
739 if (A->getOption().matches(options::OPT_ffile_compilation_dir_EQ))
740 CmdArgs.push_back(Args.MakeArgString(
741 Twine("-fcoverage-compilation-dir=") + A->getValue()));
742 else
743 A->render(Args, CmdArgs);
744 } else if (llvm::ErrorOr<std::string> CWD =
745 D.getVFS().getCurrentWorkingDirectory()) {
746 CmdArgs.push_back(Args.MakeArgString("-fcoverage-compilation-dir=" + *CWD));
747 }
748
749 if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
750 auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
751 if (!Args.hasArg(options::OPT_coverage))
752 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
753 << "-fprofile-exclude-files="
754 << "--coverage";
755
756 StringRef v = Arg->getValue();
757 CmdArgs.push_back(
758 Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
759 }
760
761 if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
762 auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
763 if (!Args.hasArg(options::OPT_coverage))
764 D.Diag(clang::diag::err_drv_argument_only_allowed_with)
765 << "-fprofile-filter-files="
766 << "--coverage";
767
768 StringRef v = Arg->getValue();
769 CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
770 }
771
772 if (const auto *A = Args.getLastArg(options::OPT_fprofile_update_EQ)) {
773 StringRef Val = A->getValue();
774 if (Val == "atomic" || Val == "prefer-atomic")
775 CmdArgs.push_back("-fprofile-update=atomic");
776 else if (Val != "single")
777 D.Diag(diag::err_drv_unsupported_option_argument)
778 << A->getSpelling() << Val;
779 }
780
781 int FunctionGroups = 1;
782 int SelectedFunctionGroup = 0;
783 if (const auto *A = Args.getLastArg(options::OPT_fprofile_function_groups)) {
784 StringRef Val = A->getValue();
785 if (Val.getAsInteger(0, FunctionGroups) || FunctionGroups < 1)
786 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
787 }
788 if (const auto *A =
789 Args.getLastArg(options::OPT_fprofile_selected_function_group)) {
790 StringRef Val = A->getValue();
791 if (Val.getAsInteger(0, SelectedFunctionGroup) ||
792 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
793 D.Diag(diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
794 }
795 if (FunctionGroups != 1)
796 CmdArgs.push_back(Args.MakeArgString("-fprofile-function-groups=" +
797 Twine(FunctionGroups)));
798 if (SelectedFunctionGroup != 0)
799 CmdArgs.push_back(Args.MakeArgString("-fprofile-selected-function-group=" +
800 Twine(SelectedFunctionGroup)));
801
802 // Leave -fprofile-dir= an unused argument unless .gcda emission is
803 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
804 // the flag used. There is no -fno-profile-dir, so the user has no
805 // targeted way to suppress the warning.
806 Arg *FProfileDir = nullptr;
807 if (Args.hasArg(options::OPT_fprofile_arcs) ||
808 Args.hasArg(options::OPT_coverage))
809 FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
810
811 // Put the .gcno and .gcda files (if needed) next to the primary output file,
812 // or fall back to a file in the current directory for `clang -c --coverage
813 // d/a.c` in the absence of -o.
814 if (EmitCovNotes || EmitCovData) {
815 SmallString<128> CoverageFilename;
816 if (Arg *DumpDir = Args.getLastArgNoClaim(options::OPT_dumpdir)) {
817 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
818 // path separator.
819 CoverageFilename = DumpDir->getValue();
820 CoverageFilename += llvm::sys::path::filename(Output.getBaseInput());
821 } else if (Arg *FinalOutput =
822 C.getArgs().getLastArg(options::OPT__SLASH_Fo)) {
823 CoverageFilename = FinalOutput->getValue();
824 } else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) {
825 CoverageFilename = FinalOutput->getValue();
826 } else {
827 CoverageFilename = llvm::sys::path::filename(Output.getBaseInput());
828 }
829 if (llvm::sys::path::is_relative(CoverageFilename))
830 (void)D.getVFS().makeAbsolute(CoverageFilename);
831 llvm::sys::path::replace_extension(CoverageFilename, "gcno");
832 if (EmitCovNotes) {
833 CmdArgs.push_back(
834 Args.MakeArgString("-coverage-notes-file=" + CoverageFilename));
835 }
836
837 if (EmitCovData) {
838 if (FProfileDir) {
839 SmallString<128> Gcno = std::move(CoverageFilename);
840 CoverageFilename = FProfileDir->getValue();
841 llvm::sys::path::append(CoverageFilename, Gcno);
842 }
843 llvm::sys::path::replace_extension(CoverageFilename, "gcda");
844 CmdArgs.push_back(
845 Args.MakeArgString("-coverage-data-file=" + CoverageFilename));
846 }
847 }
848}
849
850static void
851RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
852 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
853 unsigned DwarfVersion,
854 llvm::DebuggerKind DebuggerTuning) {
855 addDebugInfoKind(CmdArgs, DebugInfoKind);
856 if (DwarfVersion > 0)
857 CmdArgs.push_back(
858 Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
859 switch (DebuggerTuning) {
860 case llvm::DebuggerKind::GDB:
861 CmdArgs.push_back("-debugger-tuning=gdb");
862 break;
863 case llvm::DebuggerKind::LLDB:
864 CmdArgs.push_back("-debugger-tuning=lldb");
865 break;
866 case llvm::DebuggerKind::SCE:
867 CmdArgs.push_back("-debugger-tuning=sce");
868 break;
869 case llvm::DebuggerKind::DBX:
870 CmdArgs.push_back("-debugger-tuning=dbx");
871 break;
872 default:
873 break;
874 }
875}
876
877static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
878 const Driver &D, const ToolChain &TC) {
879 assert(A && "Expected non-nullptr argument.");
880 if (TC.supportsDebugInfoOption(A))
881 return true;
882 D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
883 << A->getAsString(Args) << TC.getTripleString();
884 return false;
885}
886
887static void RenderDebugInfoCompressionArgs(const ArgList &Args,
888 ArgStringList &CmdArgs,
889 const Driver &D,
890 const ToolChain &TC) {
891 const Arg *A = Args.getLastArg(options::OPT_gz_EQ);
892 if (!A)
893 return;
894 if (checkDebugInfoOption(A, Args, D, TC)) {
895 StringRef Value = A->getValue();
896 if (Value == "none") {
897 CmdArgs.push_back("--compress-debug-sections=none");
898 } else if (Value == "zlib") {
899 if (llvm::compression::zlib::isAvailable()) {
900 CmdArgs.push_back(
901 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
902 } else {
903 D.Diag(diag::warn_debug_compression_unavailable) << "zlib";
904 }
905 } else if (Value == "zstd") {
906 if (llvm::compression::zstd::isAvailable()) {
907 CmdArgs.push_back(
908 Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
909 } else {
910 D.Diag(diag::warn_debug_compression_unavailable) << "zstd";
911 }
912 } else {
913 D.Diag(diag::err_drv_unsupported_option_argument)
914 << A->getSpelling() << Value;
915 }
916 }
917}
918
920 const ArgList &Args,
921 ArgStringList &CmdArgs,
922 bool IsCC1As = false) {
923 // If no version was requested by the user, use the default value from the
924 // back end. This is consistent with the value returned from
925 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
926 // requiring the corresponding llvm to have the AMDGPU target enabled,
927 // provided the user (e.g. front end tests) can use the default.
929 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
930 CmdArgs.insert(CmdArgs.begin() + 1,
931 Args.MakeArgString(Twine("--amdhsa-code-object-version=") +
932 Twine(CodeObjVer)));
933 CmdArgs.insert(CmdArgs.begin() + 1, "-mllvm");
934 // -cc1as does not accept -mcode-object-version option.
935 if (!IsCC1As)
936 CmdArgs.insert(CmdArgs.begin() + 1,
937 Args.MakeArgString(Twine("-mcode-object-version=") +
938 Twine(CodeObjVer)));
939 }
940}
941
942static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
943 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
944 D.getVFS().getBufferForFile(Path);
945 if (!MemBuf)
946 return false;
947 llvm::file_magic Magic = llvm::identify_magic((*MemBuf)->getBuffer());
948 if (Magic == llvm::file_magic::unknown)
949 return false;
950 // Return true for both raw Clang AST files and object files which may
951 // contain a __clangast section.
952 if (Magic == llvm::file_magic::clang_ast)
953 return true;
955 llvm::object::ObjectFile::createObjectFile(**MemBuf, Magic);
956 return !Obj.takeError();
957}
958
959static bool gchProbe(const Driver &D, StringRef Path) {
960 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
961 if (!Status)
962 return false;
963
964 if (Status->isDirectory()) {
965 std::error_code EC;
966 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Path, EC), DE;
967 !EC && DI != DE; DI = DI.increment(EC)) {
968 if (maybeHasClangPchSignature(D, DI->path()))
969 return true;
970 }
971 D.Diag(diag::warn_drv_pch_ignoring_gch_dir) << Path;
972 return false;
973 }
974
976 return true;
977 D.Diag(diag::warn_drv_pch_ignoring_gch_file) << Path;
978 return false;
979}
980
981void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
982 const Driver &D, const ArgList &Args,
983 ArgStringList &CmdArgs,
984 const InputInfo &Output,
985 const InputInfoList &Inputs) const {
986 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
987
989
990 Args.AddLastArg(CmdArgs, options::OPT_C);
991 Args.AddLastArg(CmdArgs, options::OPT_CC);
992
993 // Handle dependency file generation.
994 Arg *ArgM = Args.getLastArg(options::OPT_MM);
995 if (!ArgM)
996 ArgM = Args.getLastArg(options::OPT_M);
997 Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
998 if (!ArgMD)
999 ArgMD = Args.getLastArg(options::OPT_MD);
1000
1001 // -M and -MM imply -w.
1002 if (ArgM)
1003 CmdArgs.push_back("-w");
1004 else
1005 ArgM = ArgMD;
1006
1007 if (ArgM) {
1008 // Determine the output location.
1009 const char *DepFile;
1010 if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1011 DepFile = MF->getValue();
1012 C.addFailureResultFile(DepFile, &JA);
1013 } else if (Output.getType() == types::TY_Dependencies) {
1014 DepFile = Output.getFilename();
1015 } else if (!ArgMD) {
1016 DepFile = "-";
1017 } else {
1018 DepFile = getDependencyFileName(Args, Inputs);
1019 C.addFailureResultFile(DepFile, &JA);
1020 }
1021 CmdArgs.push_back("-dependency-file");
1022 CmdArgs.push_back(DepFile);
1023
1024 bool HasTarget = false;
1025 for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1026 HasTarget = true;
1027 A->claim();
1028 if (A->getOption().matches(options::OPT_MT)) {
1029 A->render(Args, CmdArgs);
1030 } else {
1031 CmdArgs.push_back("-MT");
1033 quoteMakeTarget(A->getValue(), Quoted);
1034 CmdArgs.push_back(Args.MakeArgString(Quoted));
1035 }
1036 }
1037
1038 // Add a default target if one wasn't specified.
1039 if (!HasTarget) {
1040 const char *DepTarget;
1041
1042 // If user provided -o, that is the dependency target, except
1043 // when we are only generating a dependency file.
1044 Arg *OutputOpt = Args.getLastArg(options::OPT_o, options::OPT__SLASH_Fo);
1045 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1046 DepTarget = OutputOpt->getValue();
1047 } else {
1048 // Otherwise derive from the base input.
1049 //
1050 // FIXME: This should use the computed output file location.
1051 SmallString<128> P(Inputs[0].getBaseInput());
1052 llvm::sys::path::replace_extension(P, "o");
1053 DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1054 }
1055
1056 CmdArgs.push_back("-MT");
1058 quoteMakeTarget(DepTarget, Quoted);
1059 CmdArgs.push_back(Args.MakeArgString(Quoted));
1060 }
1061
1062 if (ArgM->getOption().matches(options::OPT_M) ||
1063 ArgM->getOption().matches(options::OPT_MD))
1064 CmdArgs.push_back("-sys-header-deps");
1065 if ((isa<PrecompileJobAction>(JA) &&
1066 !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1067 Args.hasArg(options::OPT_fmodule_file_deps))
1068 CmdArgs.push_back("-module-file-deps");
1069 }
1070
1071 if (Args.hasArg(options::OPT_MG)) {
1072 if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1073 ArgM->getOption().matches(options::OPT_MMD))
1074 D.Diag(diag::err_drv_mg_requires_m_or_mm);
1075 CmdArgs.push_back("-MG");
1076 }
1077
1078 Args.AddLastArg(CmdArgs, options::OPT_MP);
1079 Args.AddLastArg(CmdArgs, options::OPT_MV);
1080
1081 // Add offload include arguments specific for CUDA/HIP/SYCL. This must happen
1082 // before we -I or -include anything else, because we must pick up the
1083 // CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL installation,
1084 // rather than from e.g. /usr/local/include.
1086 getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1088 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
1090 getToolChain().addSYCLIncludeArgs(Args, CmdArgs);
1091
1092 // If we are offloading to a target via OpenMP we need to include the
1093 // openmp_wrappers folder which contains alternative system headers.
1095 !Args.hasArg(options::OPT_nostdinc) &&
1096 !Args.hasArg(options::OPT_nogpuinc) &&
1097 (getToolChain().getTriple().isNVPTX() ||
1098 getToolChain().getTriple().isAMDGCN())) {
1099 if (!Args.hasArg(options::OPT_nobuiltininc)) {
1100 // Add openmp_wrappers/* to our system include path. This lets us wrap
1101 // standard library headers.
1102 SmallString<128> P(D.ResourceDir);
1103 llvm::sys::path::append(P, "include");
1104 llvm::sys::path::append(P, "openmp_wrappers");
1105 CmdArgs.push_back("-internal-isystem");
1106 CmdArgs.push_back(Args.MakeArgString(P));
1107 }
1108
1109 CmdArgs.push_back("-include");
1110 CmdArgs.push_back("__clang_openmp_device_functions.h");
1111 }
1112
1113 if (Args.hasArg(options::OPT_foffload_via_llvm)) {
1114 // Add llvm_wrappers/* to our system include path. This lets us wrap
1115 // standard library headers and other headers.
1116 SmallString<128> P(D.ResourceDir);
1117 llvm::sys::path::append(P, "include", "llvm_offload_wrappers");
1118 CmdArgs.append({"-internal-isystem", Args.MakeArgString(P), "-include"});
1120 CmdArgs.push_back("__llvm_offload_device.h");
1121 else
1122 CmdArgs.push_back("__llvm_offload_host.h");
1123 }
1124
1125 // Add -i* options, and automatically translate to
1126 // -include-pch/-include-pth for transparent PCH support. It's
1127 // wonky, but we include looking for .gch so we can support seamless
1128 // replacement into a build system already set up to be generating
1129 // .gch files.
1130
1131 if (getToolChain().getDriver().IsCLMode()) {
1132 const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1133 const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1134 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1136 CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1137 // -fpch-instantiate-templates is the default when creating
1138 // precomp using /Yc
1139 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
1140 options::OPT_fno_pch_instantiate_templates, true))
1141 CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1142 }
1143 if (YcArg || YuArg) {
1144 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1145 if (!isa<PrecompileJobAction>(JA)) {
1146 CmdArgs.push_back("-include-pch");
1147 CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1148 C, !ThroughHeader.empty()
1149 ? ThroughHeader
1150 : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1151 }
1152
1153 if (ThroughHeader.empty()) {
1154 CmdArgs.push_back(Args.MakeArgString(
1155 Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1156 } else {
1157 CmdArgs.push_back(
1158 Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1159 }
1160 }
1161 }
1162
1163 bool RenderedImplicitInclude = false;
1164 for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1165 if (A->getOption().matches(options::OPT_include) &&
1166 D.getProbePrecompiled()) {
1167 // Handling of gcc-style gch precompiled headers.
1168 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1169 RenderedImplicitInclude = true;
1170
1171 bool FoundPCH = false;
1172 SmallString<128> P(A->getValue());
1173 // We want the files to have a name like foo.h.pch. Add a dummy extension
1174 // so that replace_extension does the right thing.
1175 P += ".dummy";
1176 llvm::sys::path::replace_extension(P, "pch");
1177 if (D.getVFS().exists(P))
1178 FoundPCH = true;
1179
1180 if (!FoundPCH) {
1181 // For GCC compat, probe for a file or directory ending in .gch instead.
1182 llvm::sys::path::replace_extension(P, "gch");
1183 FoundPCH = gchProbe(D, P.str());
1184 }
1185
1186 if (FoundPCH) {
1187 if (IsFirstImplicitInclude) {
1188 A->claim();
1189 CmdArgs.push_back("-include-pch");
1190 CmdArgs.push_back(Args.MakeArgString(P));
1191 continue;
1192 } else {
1193 // Ignore the PCH if not first on command line and emit warning.
1194 D.Diag(diag::warn_drv_pch_not_first_include) << P
1195 << A->getAsString(Args);
1196 }
1197 }
1198 } else if (A->getOption().matches(options::OPT_isystem_after)) {
1199 // Handling of paths which must come late. These entries are handled by
1200 // the toolchain itself after the resource dir is inserted in the right
1201 // search order.
1202 // Do not claim the argument so that the use of the argument does not
1203 // silently go unnoticed on toolchains which do not honour the option.
1204 continue;
1205 } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1206 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1207 continue;
1208 } else if (A->getOption().matches(options::OPT_ibuiltininc)) {
1209 // This is used only by the driver. No need to pass to cc1.
1210 continue;
1211 }
1212
1213 // Not translated, render as usual.
1214 A->claim();
1215 A->render(Args, CmdArgs);
1216 }
1217
1218 Args.addAllArgs(CmdArgs,
1219 {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1220 options::OPT_F, options::OPT_embed_dir_EQ});
1221
1222 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1223
1224 // FIXME: There is a very unfortunate problem here, some troubled
1225 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1226 // really support that we would have to parse and then translate
1227 // those options. :(
1228 Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1229 options::OPT_Xpreprocessor);
1230
1231 // -I- is a deprecated GCC feature, reject it.
1232 if (Arg *A = Args.getLastArg(options::OPT_I_))
1233 D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1234
1235 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1236 // -isysroot to the CC1 invocation.
1237 StringRef sysroot = C.getSysRoot();
1238 if (sysroot != "") {
1239 if (!Args.hasArg(options::OPT_isysroot)) {
1240 CmdArgs.push_back("-isysroot");
1241 CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1242 }
1243 }
1244
1245 // Parse additional include paths from environment variables.
1246 // FIXME: We should probably sink the logic for handling these from the
1247 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1248 // CPATH - included following the user specified includes (but prior to
1249 // builtin and standard includes).
1250 addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1251 // C_INCLUDE_PATH - system includes enabled when compiling C.
1252 addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1253 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1254 addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1255 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1256 addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1257 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1258 addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1259
1260 // While adding the include arguments, we also attempt to retrieve the
1261 // arguments of related offloading toolchains or arguments that are specific
1262 // of an offloading programming model.
1263
1264 // Add C++ include arguments, if needed.
1265 if (types::isCXX(Inputs[0].getType())) {
1266 bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1268 C, JA, getToolChain(),
1269 [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1270 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1271 : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1272 });
1273 }
1274
1275 // If we are compiling for a GPU target we want to override the system headers
1276 // with ones created by the 'libc' project if present.
1277 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1278 // OffloadKind as an argument.
1279 if (!Args.hasArg(options::OPT_nostdinc) &&
1280 !Args.hasArg(options::OPT_nogpuinc) &&
1281 !Args.hasArg(options::OPT_nobuiltininc)) {
1282 // Without an offloading language we will include these headers directly.
1283 // Offloading languages will instead only use the declarations stored in
1284 // the resource directory at clang/lib/Headers/llvm_libc_wrappers.
1285 if ((getToolChain().getTriple().isNVPTX() ||
1286 getToolChain().getTriple().isAMDGCN()) &&
1287 C.getActiveOffloadKinds() == Action::OFK_None) {
1288 SmallString<128> P(llvm::sys::path::parent_path(D.Dir));
1289 llvm::sys::path::append(P, "include");
1290 llvm::sys::path::append(P, getToolChain().getTripleString());
1291 CmdArgs.push_back("-internal-isystem");
1292 CmdArgs.push_back(Args.MakeArgString(P));
1293 } else if (C.getActiveOffloadKinds() == Action::OFK_OpenMP) {
1294 // TODO: CUDA / HIP include their own headers for some common functions
1295 // implemented here. We'll need to clean those up so they do not conflict.
1296 SmallString<128> P(D.ResourceDir);
1297 llvm::sys::path::append(P, "include");
1298 llvm::sys::path::append(P, "llvm_libc_wrappers");
1299 CmdArgs.push_back("-internal-isystem");
1300 CmdArgs.push_back(Args.MakeArgString(P));
1301 }
1302 }
1303
1304 // Add system include arguments for all targets but IAMCU.
1305 if (!IsIAMCU)
1307 [&Args, &CmdArgs](const ToolChain &TC) {
1308 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1309 });
1310 else {
1311 // For IAMCU add special include arguments.
1312 getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1313 }
1314
1315 addMacroPrefixMapArg(D, Args, CmdArgs);
1316 addCoveragePrefixMapArg(D, Args, CmdArgs);
1317
1318 Args.AddLastArg(CmdArgs, options::OPT_ffile_reproducible,
1319 options::OPT_fno_file_reproducible);
1320
1321 if (const char *Epoch = std::getenv("SOURCE_DATE_EPOCH")) {
1322 CmdArgs.push_back("-source-date-epoch");
1323 CmdArgs.push_back(Args.MakeArgString(Epoch));
1324 }
1325
1326 Args.addOptInFlag(CmdArgs, options::OPT_fdefine_target_os_macros,
1327 options::OPT_fno_define_target_os_macros);
1328}
1329
1330// FIXME: Move to target hook.
1331static bool isSignedCharDefault(const llvm::Triple &Triple) {
1332 switch (Triple.getArch()) {
1333 default:
1334 return true;
1335
1336 case llvm::Triple::aarch64:
1337 case llvm::Triple::aarch64_32:
1338 case llvm::Triple::aarch64_be:
1339 case llvm::Triple::arm:
1340 case llvm::Triple::armeb:
1341 case llvm::Triple::thumb:
1342 case llvm::Triple::thumbeb:
1343 if (Triple.isOSDarwin() || Triple.isOSWindows())
1344 return true;
1345 return false;
1346
1347 case llvm::Triple::ppc:
1348 case llvm::Triple::ppc64:
1349 if (Triple.isOSDarwin())
1350 return true;
1351 return false;
1352
1353 case llvm::Triple::hexagon:
1354 case llvm::Triple::msp430:
1355 case llvm::Triple::ppcle:
1356 case llvm::Triple::ppc64le:
1357 case llvm::Triple::riscv32:
1358 case llvm::Triple::riscv64:
1359 case llvm::Triple::systemz:
1360 case llvm::Triple::xcore:
1361 case llvm::Triple::xtensa:
1362 return false;
1363 }
1364}
1365
1366static bool hasMultipleInvocations(const llvm::Triple &Triple,
1367 const ArgList &Args) {
1368 // Supported only on Darwin where we invoke the compiler multiple times
1369 // followed by an invocation to lipo.
1370 if (!Triple.isOSDarwin())
1371 return false;
1372 // If more than one "-arch <arch>" is specified, we're targeting multiple
1373 // architectures resulting in a fat binary.
1374 return Args.getAllArgValues(options::OPT_arch).size() > 1;
1375}
1376
1377static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1378 const llvm::Triple &Triple) {
1379 // When enabling remarks, we need to error if:
1380 // * The remark file is specified but we're targeting multiple architectures,
1381 // which means more than one remark file is being generated.
1383 bool hasExplicitOutputFile =
1384 Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1385 if (hasMultipleInvocations && hasExplicitOutputFile) {
1386 D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1387 << "-foptimization-record-file";
1388 return false;
1389 }
1390 return true;
1391}
1392
1393static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1394 const llvm::Triple &Triple,
1395 const InputInfo &Input,
1396 const InputInfo &Output, const JobAction &JA) {
1397 StringRef Format = "yaml";
1398 if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1399 Format = A->getValue();
1400
1401 CmdArgs.push_back("-opt-record-file");
1402
1403 const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1404 if (A) {
1405 CmdArgs.push_back(A->getValue());
1406 } else {
1407 bool hasMultipleArchs =
1408 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1409 Args.getAllArgValues(options::OPT_arch).size() > 1;
1410
1412
1413 if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
1414 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1415 F = FinalOutput->getValue();
1416 } else {
1417 if (Format != "yaml" && // For YAML, keep the original behavior.
1418 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1419 Output.isFilename())
1420 F = Output.getFilename();
1421 }
1422
1423 if (F.empty()) {
1424 // Use the input filename.
1425 F = llvm::sys::path::stem(Input.getBaseInput());
1426
1427 // If we're compiling for an offload architecture (i.e. a CUDA device),
1428 // we need to make the file name for the device compilation different
1429 // from the host compilation.
1432 llvm::sys::path::replace_extension(F, "");
1434 Triple.normalize());
1435 F += "-";
1436 F += JA.getOffloadingArch();
1437 }
1438 }
1439
1440 // If we're having more than one "-arch", we should name the files
1441 // differently so that every cc1 invocation writes to a different file.
1442 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1443 // name from the triple.
1444 if (hasMultipleArchs) {
1445 // First, remember the extension.
1446 SmallString<64> OldExtension = llvm::sys::path::extension(F);
1447 // then, remove it.
1448 llvm::sys::path::replace_extension(F, "");
1449 // attach -<arch> to it.
1450 F += "-";
1451 F += Triple.getArchName();
1452 // put back the extension.
1453 llvm::sys::path::replace_extension(F, OldExtension);
1454 }
1455
1456 SmallString<32> Extension;
1457 Extension += "opt.";
1458 Extension += Format;
1459
1460 llvm::sys::path::replace_extension(F, Extension);
1461 CmdArgs.push_back(Args.MakeArgString(F));
1462 }
1463
1464 if (const Arg *A =
1465 Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1466 CmdArgs.push_back("-opt-record-passes");
1467 CmdArgs.push_back(A->getValue());
1468 }
1469
1470 if (!Format.empty()) {
1471 CmdArgs.push_back("-opt-record-format");
1472 CmdArgs.push_back(Format.data());
1473 }
1474}
1475
1476void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1477 if (!Args.hasFlag(options::OPT_faapcs_bitfield_width,
1478 options::OPT_fno_aapcs_bitfield_width, true))
1479 CmdArgs.push_back("-fno-aapcs-bitfield-width");
1480
1481 if (Args.getLastArg(options::OPT_ForceAAPCSBitfieldLoad))
1482 CmdArgs.push_back("-faapcs-bitfield-load");
1483}
1484
1485namespace {
1486void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1487 const ArgList &Args, ArgStringList &CmdArgs) {
1488 // Select the ABI to use.
1489 // FIXME: Support -meabi.
1490 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1491 const char *ABIName = nullptr;
1492 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1493 ABIName = A->getValue();
1494 } else {
1495 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
1496 ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1497 }
1498
1499 CmdArgs.push_back("-target-abi");
1500 CmdArgs.push_back(ABIName);
1501}
1502
1503void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1504 auto StrictAlignIter =
1505 llvm::find_if(llvm::reverse(CmdArgs), [](StringRef Arg) {
1506 return Arg == "+strict-align" || Arg == "-strict-align";
1507 });
1508 if (StrictAlignIter != CmdArgs.rend() &&
1509 StringRef(*StrictAlignIter) == "+strict-align")
1510 CmdArgs.push_back("-Wunaligned-access");
1511}
1512}
1513
1514// Each combination of options here forms a signing schema, and in most cases
1515// each signing schema is its own incompatible ABI. The default values of the
1516// options represent the default signing schema.
1517static void handlePAuthABI(const ArgList &DriverArgs, ArgStringList &CC1Args) {
1518 if (!DriverArgs.hasArg(options::OPT_fptrauth_intrinsics,
1519 options::OPT_fno_ptrauth_intrinsics))
1520 CC1Args.push_back("-fptrauth-intrinsics");
1521
1522 if (!DriverArgs.hasArg(options::OPT_fptrauth_calls,
1523 options::OPT_fno_ptrauth_calls))
1524 CC1Args.push_back("-fptrauth-calls");
1525
1526 if (!DriverArgs.hasArg(options::OPT_fptrauth_returns,
1527 options::OPT_fno_ptrauth_returns))
1528 CC1Args.push_back("-fptrauth-returns");
1529
1530 if (!DriverArgs.hasArg(options::OPT_fptrauth_auth_traps,
1531 options::OPT_fno_ptrauth_auth_traps))
1532 CC1Args.push_back("-fptrauth-auth-traps");
1533
1534 if (!DriverArgs.hasArg(
1535 options::OPT_fptrauth_vtable_pointer_address_discrimination,
1536 options::OPT_fno_ptrauth_vtable_pointer_address_discrimination))
1537 CC1Args.push_back("-fptrauth-vtable-pointer-address-discrimination");
1538
1539 if (!DriverArgs.hasArg(
1540 options::OPT_fptrauth_vtable_pointer_type_discrimination,
1541 options::OPT_fno_ptrauth_vtable_pointer_type_discrimination))
1542 CC1Args.push_back("-fptrauth-vtable-pointer-type-discrimination");
1543
1544 if (!DriverArgs.hasArg(options::OPT_fptrauth_indirect_gotos,
1545 options::OPT_fno_ptrauth_indirect_gotos))
1546 CC1Args.push_back("-fptrauth-indirect-gotos");
1547
1548 if (!DriverArgs.hasArg(options::OPT_fptrauth_init_fini,
1549 options::OPT_fno_ptrauth_init_fini))
1550 CC1Args.push_back("-fptrauth-init-fini");
1551}
1552
1553static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1554 ArgStringList &CmdArgs, bool isAArch64) {
1555 const Arg *A = isAArch64
1556 ? Args.getLastArg(options::OPT_msign_return_address_EQ,
1557 options::OPT_mbranch_protection_EQ)
1558 : Args.getLastArg(options::OPT_mbranch_protection_EQ);
1559 if (!A)
1560 return;
1561
1562 const Driver &D = TC.getDriver();
1563 const llvm::Triple &Triple = TC.getEffectiveTriple();
1564 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1565 D.Diag(diag::warn_incompatible_branch_protection_option)
1566 << Triple.getArchName();
1567
1568 StringRef Scope, Key;
1569 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1570
1571 if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1572 Scope = A->getValue();
1573 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1574 D.Diag(diag::err_drv_unsupported_option_argument)
1575 << A->getSpelling() << Scope;
1576 Key = "a_key";
1577 IndirectBranches = false;
1578 BranchProtectionPAuthLR = false;
1579 GuardedControlStack = false;
1580 } else {
1581 StringRef DiagMsg;
1582 llvm::ARM::ParsedBranchProtection PBP;
1583 bool EnablePAuthLR = false;
1584
1585 // To know if we need to enable PAuth-LR As part of the standard branch
1586 // protection option, it needs to be determined if the feature has been
1587 // activated in the `march` argument. This information is stored within the
1588 // CmdArgs variable and can be found using a search.
1589 if (isAArch64) {
1590 auto isPAuthLR = [](const char *member) {
1591 llvm::AArch64::ExtensionInfo pauthlr_extension =
1592 llvm::AArch64::getExtensionByID(llvm::AArch64::AEK_PAUTHLR);
1593 return pauthlr_extension.PosTargetFeature == member;
1594 };
1595
1596 if (std::any_of(CmdArgs.begin(), CmdArgs.end(), isPAuthLR))
1597 EnablePAuthLR = true;
1598 }
1599 if (!llvm::ARM::parseBranchProtection(A->getValue(), PBP, DiagMsg,
1600 EnablePAuthLR))
1601 D.Diag(diag::err_drv_unsupported_option_argument)
1602 << A->getSpelling() << DiagMsg;
1603 if (!isAArch64 && PBP.Key == "b_key")
1604 D.Diag(diag::warn_unsupported_branch_protection)
1605 << "b-key" << A->getAsString(Args);
1606 Scope = PBP.Scope;
1607 Key = PBP.Key;
1608 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1609 IndirectBranches = PBP.BranchTargetEnforcement;
1610 GuardedControlStack = PBP.GuardedControlStack;
1611 }
1612
1613 CmdArgs.push_back(
1614 Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1615 if (Scope != "none") {
1616 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1617 D.Diag(diag::err_drv_unsupported_opt_for_target)
1618 << A->getAsString(Args) << Triple.getTriple();
1619 CmdArgs.push_back(
1620 Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1621 }
1622 if (BranchProtectionPAuthLR) {
1623 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1624 D.Diag(diag::err_drv_unsupported_opt_for_target)
1625 << A->getAsString(Args) << Triple.getTriple();
1626 CmdArgs.push_back(
1627 Args.MakeArgString(Twine("-mbranch-protection-pauth-lr")));
1628 }
1629 if (IndirectBranches)
1630 CmdArgs.push_back("-mbranch-target-enforce");
1631 // GCS is currently untested with PAuthABI, but enabling this could be allowed
1632 // in future after testing with a suitable system.
1633 if (GuardedControlStack) {
1634 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1635 D.Diag(diag::err_drv_unsupported_opt_for_target)
1636 << A->getAsString(Args) << Triple.getTriple();
1637 CmdArgs.push_back("-mguarded-control-stack");
1638 }
1639}
1640
1641void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1642 ArgStringList &CmdArgs, bool KernelOrKext) const {
1643 RenderARMABI(getToolChain().getDriver(), Triple, Args, CmdArgs);
1644
1645 // Determine floating point ABI from the options & target defaults.
1647 if (ABI == arm::FloatABI::Soft) {
1648 // Floating point operations and argument passing are soft.
1649 // FIXME: This changes CPP defines, we need -target-soft-float.
1650 CmdArgs.push_back("-msoft-float");
1651 CmdArgs.push_back("-mfloat-abi");
1652 CmdArgs.push_back("soft");
1653 } else if (ABI == arm::FloatABI::SoftFP) {
1654 // Floating point operations are hard, but argument passing is soft.
1655 CmdArgs.push_back("-mfloat-abi");
1656 CmdArgs.push_back("soft");
1657 } else {
1658 // Floating point operations and argument passing are hard.
1659 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1660 CmdArgs.push_back("-mfloat-abi");
1661 CmdArgs.push_back("hard");
1662 }
1663
1664 // Forward the -mglobal-merge option for explicit control over the pass.
1665 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1666 options::OPT_mno_global_merge)) {
1667 CmdArgs.push_back("-mllvm");
1668 if (A->getOption().matches(options::OPT_mno_global_merge))
1669 CmdArgs.push_back("-arm-global-merge=false");
1670 else
1671 CmdArgs.push_back("-arm-global-merge=true");
1672 }
1673
1674 if (!Args.hasFlag(options::OPT_mimplicit_float,
1675 options::OPT_mno_implicit_float, true))
1676 CmdArgs.push_back("-no-implicit-float");
1677
1678 if (Args.getLastArg(options::OPT_mcmse))
1679 CmdArgs.push_back("-mcmse");
1680
1681 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1682
1683 // Enable/disable return address signing and indirect branch targets.
1684 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, false /*isAArch64*/);
1685
1686 AddUnalignedAccessWarning(CmdArgs);
1687}
1688
1689void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1690 const ArgList &Args, bool KernelOrKext,
1691 ArgStringList &CmdArgs) const {
1692 const ToolChain &TC = getToolChain();
1693
1694 // Add the target features
1695 getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1696
1697 // Add target specific flags.
1698 switch (TC.getArch()) {
1699 default:
1700 break;
1701
1702 case llvm::Triple::arm:
1703 case llvm::Triple::armeb:
1704 case llvm::Triple::thumb:
1705 case llvm::Triple::thumbeb:
1706 // Use the effective triple, which takes into account the deployment target.
1707 AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1708 break;
1709
1710 case llvm::Triple::aarch64:
1711 case llvm::Triple::aarch64_32:
1712 case llvm::Triple::aarch64_be:
1713 AddAArch64TargetArgs(Args, CmdArgs);
1714 break;
1715
1716 case llvm::Triple::loongarch32:
1717 case llvm::Triple::loongarch64:
1718 AddLoongArchTargetArgs(Args, CmdArgs);
1719 break;
1720
1721 case llvm::Triple::mips:
1722 case llvm::Triple::mipsel:
1723 case llvm::Triple::mips64:
1724 case llvm::Triple::mips64el:
1725 AddMIPSTargetArgs(Args, CmdArgs);
1726 break;
1727
1728 case llvm::Triple::ppc:
1729 case llvm::Triple::ppcle:
1730 case llvm::Triple::ppc64:
1731 case llvm::Triple::ppc64le:
1732 AddPPCTargetArgs(Args, CmdArgs);
1733 break;
1734
1735 case llvm::Triple::riscv32:
1736 case llvm::Triple::riscv64:
1737 AddRISCVTargetArgs(Args, CmdArgs);
1738 break;
1739
1740 case llvm::Triple::sparc:
1741 case llvm::Triple::sparcel:
1742 case llvm::Triple::sparcv9:
1743 AddSparcTargetArgs(Args, CmdArgs);
1744 break;
1745
1746 case llvm::Triple::systemz:
1747 AddSystemZTargetArgs(Args, CmdArgs);
1748 break;
1749
1750 case llvm::Triple::x86:
1751 case llvm::Triple::x86_64:
1752 AddX86TargetArgs(Args, CmdArgs);
1753 break;
1754
1755 case llvm::Triple::lanai:
1756 AddLanaiTargetArgs(Args, CmdArgs);
1757 break;
1758
1759 case llvm::Triple::hexagon:
1760 AddHexagonTargetArgs(Args, CmdArgs);
1761 break;
1762
1763 case llvm::Triple::wasm32:
1764 case llvm::Triple::wasm64:
1765 AddWebAssemblyTargetArgs(Args, CmdArgs);
1766 break;
1767
1768 case llvm::Triple::ve:
1769 AddVETargetArgs(Args, CmdArgs);
1770 break;
1771 }
1772}
1773
1774namespace {
1775void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1776 ArgStringList &CmdArgs) {
1777 const char *ABIName = nullptr;
1778 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1779 ABIName = A->getValue();
1780 else if (Triple.isOSDarwin())
1781 ABIName = "darwinpcs";
1782 else if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1783 ABIName = "pauthtest";
1784 else
1785 ABIName = "aapcs";
1786
1787 CmdArgs.push_back("-target-abi");
1788 CmdArgs.push_back(ABIName);
1789}
1790}
1791
1792void Clang::AddAArch64TargetArgs(const ArgList &Args,
1793 ArgStringList &CmdArgs) const {
1794 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1795
1796 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1797 Args.hasArg(options::OPT_mkernel) ||
1798 Args.hasArg(options::OPT_fapple_kext))
1799 CmdArgs.push_back("-disable-red-zone");
1800
1801 if (!Args.hasFlag(options::OPT_mimplicit_float,
1802 options::OPT_mno_implicit_float, true))
1803 CmdArgs.push_back("-no-implicit-float");
1804
1805 RenderAArch64ABI(Triple, Args, CmdArgs);
1806
1807 // Forward the -mglobal-merge option for explicit control over the pass.
1808 if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1809 options::OPT_mno_global_merge)) {
1810 CmdArgs.push_back("-mllvm");
1811 if (A->getOption().matches(options::OPT_mno_global_merge))
1812 CmdArgs.push_back("-aarch64-enable-global-merge=false");
1813 else
1814 CmdArgs.push_back("-aarch64-enable-global-merge=true");
1815 }
1816
1817 // Enable/disable return address signing and indirect branch targets.
1818 CollectARMPACBTIOptions(getToolChain(), Args, CmdArgs, true /*isAArch64*/);
1819
1820 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1821 handlePAuthABI(Args, CmdArgs);
1822
1823 // Handle -msve_vector_bits=<bits>
1824 if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
1825 StringRef Val = A->getValue();
1826 const Driver &D = getToolChain().getDriver();
1827 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1828 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1829 Val == "1024+" || Val == "2048+") {
1830 unsigned Bits = 0;
1831 if (!Val.consume_back("+")) {
1832 bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1833 assert(!Invalid && "Failed to parse value");
1834 CmdArgs.push_back(
1835 Args.MakeArgString("-mvscale-max=" + llvm::Twine(Bits / 128)));
1836 }
1837
1838 bool Invalid = Val.getAsInteger(10, Bits); (void)Invalid;
1839 assert(!Invalid && "Failed to parse value");
1840 CmdArgs.push_back(
1841 Args.MakeArgString("-mvscale-min=" + llvm::Twine(Bits / 128)));
1842 // Silently drop requests for vector-length agnostic code as it's implied.
1843 } else if (Val != "scalable")
1844 // Handle the unsupported values passed to msve-vector-bits.
1845 D.Diag(diag::err_drv_unsupported_option_argument)
1846 << A->getSpelling() << Val;
1847 }
1848
1849 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1850
1851 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
1852 CmdArgs.push_back("-tune-cpu");
1853 if (strcmp(A->getValue(), "native") == 0)
1854 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
1855 else
1856 CmdArgs.push_back(A->getValue());
1857 }
1858
1859 AddUnalignedAccessWarning(CmdArgs);
1860
1861 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_intrinsics,
1862 options::OPT_fno_ptrauth_intrinsics);
1863 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_calls,
1864 options::OPT_fno_ptrauth_calls);
1865 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_returns,
1866 options::OPT_fno_ptrauth_returns);
1867 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_auth_traps,
1868 options::OPT_fno_ptrauth_auth_traps);
1869 Args.addOptInFlag(
1870 CmdArgs, options::OPT_fptrauth_vtable_pointer_address_discrimination,
1871 options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1872 Args.addOptInFlag(
1873 CmdArgs, options::OPT_fptrauth_vtable_pointer_type_discrimination,
1874 options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1875 Args.addOptInFlag(
1876 CmdArgs, options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1877 options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1878 Args.addOptInFlag(
1879 CmdArgs, options::OPT_fptrauth_function_pointer_type_discrimination,
1880 options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1881
1882 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_indirect_gotos,
1883 options::OPT_fno_ptrauth_indirect_gotos);
1884 Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_init_fini,
1885 options::OPT_fno_ptrauth_init_fini);
1886 Args.addOptInFlag(CmdArgs,
1887 options::OPT_fptrauth_init_fini_address_discrimination,
1888 options::OPT_fno_ptrauth_init_fini_address_discrimination);
1889 Args.addOptInFlag(CmdArgs, options::OPT_faarch64_jump_table_hardening,
1890 options::OPT_fno_aarch64_jump_table_hardening);
1891}
1892
1893void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1894 ArgStringList &CmdArgs) const {
1895 const llvm::Triple &Triple = getToolChain().getTriple();
1896
1897 CmdArgs.push_back("-target-abi");
1898 CmdArgs.push_back(
1899 loongarch::getLoongArchABI(getToolChain().getDriver(), Args, Triple)
1900 .data());
1901
1902 // Handle -mtune.
1903 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
1904 std::string TuneCPU = A->getValue();
1905 TuneCPU = loongarch::postProcessTargetCPUString(TuneCPU, Triple);
1906 CmdArgs.push_back("-tune-cpu");
1907 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
1908 }
1909
1910 if (Arg *A = Args.getLastArg(options::OPT_mannotate_tablejump,
1911 options::OPT_mno_annotate_tablejump)) {
1912 if (A->getOption().matches(options::OPT_mannotate_tablejump)) {
1913 CmdArgs.push_back("-mllvm");
1914 CmdArgs.push_back("-loongarch-annotate-tablejump");
1915 }
1916 }
1917}
1918
1919void Clang::AddMIPSTargetArgs(const ArgList &Args,
1920 ArgStringList &CmdArgs) const {
1921 const Driver &D = getToolChain().getDriver();
1922 StringRef CPUName;
1923 StringRef ABIName;
1924 const llvm::Triple &Triple = getToolChain().getTriple();
1925 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1926
1927 CmdArgs.push_back("-target-abi");
1928 CmdArgs.push_back(ABIName.data());
1929
1930 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1931 if (ABI == mips::FloatABI::Soft) {
1932 // Floating point operations and argument passing are soft.
1933 CmdArgs.push_back("-msoft-float");
1934 CmdArgs.push_back("-mfloat-abi");
1935 CmdArgs.push_back("soft");
1936 } else {
1937 // Floating point operations and argument passing are hard.
1938 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1939 CmdArgs.push_back("-mfloat-abi");
1940 CmdArgs.push_back("hard");
1941 }
1942
1943 if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1944 options::OPT_mno_ldc1_sdc1)) {
1945 if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1946 CmdArgs.push_back("-mllvm");
1947 CmdArgs.push_back("-mno-ldc1-sdc1");
1948 }
1949 }
1950
1951 if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1952 options::OPT_mno_check_zero_division)) {
1953 if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1954 CmdArgs.push_back("-mllvm");
1955 CmdArgs.push_back("-mno-check-zero-division");
1956 }
1957 }
1958
1959 if (Args.getLastArg(options::OPT_mfix4300)) {
1960 CmdArgs.push_back("-mllvm");
1961 CmdArgs.push_back("-mfix4300");
1962 }
1963
1964 if (Arg *A = Args.getLastArg(options::OPT_G)) {
1965 StringRef v = A->getValue();
1966 CmdArgs.push_back("-mllvm");
1967 CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1968 A->claim();
1969 }
1970
1971 Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1972 Arg *ABICalls =
1973 Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1974
1975 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1976 // -mgpopt is the default for static, -fno-pic environments but these two
1977 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1978 // the only case where -mllvm -mgpopt is passed.
1979 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1980 // passed explicitly when compiling something with -mabicalls
1981 // (implictly) in affect. Currently the warning is in the backend.
1982 //
1983 // When the ABI in use is N64, we also need to determine the PIC mode that
1984 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1985 bool NoABICalls =
1986 ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1987
1988 llvm::Reloc::Model RelocationModel;
1989 unsigned PICLevel;
1990 bool IsPIE;
1991 std::tie(RelocationModel, PICLevel, IsPIE) =
1992 ParsePICArgs(getToolChain(), Args);
1993
1994 NoABICalls = NoABICalls ||
1995 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1996
1997 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1998 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1999 if (NoABICalls && (!GPOpt || WantGPOpt)) {
2000 CmdArgs.push_back("-mllvm");
2001 CmdArgs.push_back("-mgpopt");
2002
2003 Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
2004 options::OPT_mno_local_sdata);
2005 Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
2006 options::OPT_mno_extern_sdata);
2007 Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
2008 options::OPT_mno_embedded_data);
2009 if (LocalSData) {
2010 CmdArgs.push_back("-mllvm");
2011 if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
2012 CmdArgs.push_back("-mlocal-sdata=1");
2013 } else {
2014 CmdArgs.push_back("-mlocal-sdata=0");
2015 }
2016 LocalSData->claim();
2017 }
2018
2019 if (ExternSData) {
2020 CmdArgs.push_back("-mllvm");
2021 if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
2022 CmdArgs.push_back("-mextern-sdata=1");
2023 } else {
2024 CmdArgs.push_back("-mextern-sdata=0");
2025 }
2026 ExternSData->claim();
2027 }
2028
2029 if (EmbeddedData) {
2030 CmdArgs.push_back("-mllvm");
2031 if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
2032 CmdArgs.push_back("-membedded-data=1");
2033 } else {
2034 CmdArgs.push_back("-membedded-data=0");
2035 }
2036 EmbeddedData->claim();
2037 }
2038
2039 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
2040 D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
2041
2042 if (GPOpt)
2043 GPOpt->claim();
2044
2045 if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
2046 StringRef Val = StringRef(A->getValue());
2047 if (mips::hasCompactBranches(CPUName)) {
2048 if (Val == "never" || Val == "always" || Val == "optimal") {
2049 CmdArgs.push_back("-mllvm");
2050 CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
2051 } else
2052 D.Diag(diag::err_drv_unsupported_option_argument)
2053 << A->getSpelling() << Val;
2054 } else
2055 D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
2056 }
2057
2058 if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
2059 options::OPT_mno_relax_pic_calls)) {
2060 if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
2061 CmdArgs.push_back("-mllvm");
2062 CmdArgs.push_back("-mips-jalr-reloc=0");
2063 }
2064 }
2065}
2066
2067void Clang::AddPPCTargetArgs(const ArgList &Args,
2068 ArgStringList &CmdArgs) const {
2069 const Driver &D = getToolChain().getDriver();
2070 const llvm::Triple &T = getToolChain().getTriple();
2071 if (Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2072 CmdArgs.push_back("-tune-cpu");
2073 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, A->getValue());
2074 CmdArgs.push_back(Args.MakeArgString(CPU.str()));
2075 }
2076
2077 // Select the ABI to use.
2078 const char *ABIName = nullptr;
2079 if (T.isOSBinFormatELF()) {
2080 switch (getToolChain().getArch()) {
2081 case llvm::Triple::ppc64: {
2082 if (T.isPPC64ELFv2ABI())
2083 ABIName = "elfv2";
2084 else
2085 ABIName = "elfv1";
2086 break;
2087 }
2088 case llvm::Triple::ppc64le:
2089 ABIName = "elfv2";
2090 break;
2091 default:
2092 break;
2093 }
2094 }
2095
2096 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
2097 bool VecExtabi = false;
2098 for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
2099 StringRef V = A->getValue();
2100 if (V == "ieeelongdouble") {
2101 IEEELongDouble = true;
2102 A->claim();
2103 } else if (V == "ibmlongdouble") {
2104 IEEELongDouble = false;
2105 A->claim();
2106 } else if (V == "vec-default") {
2107 VecExtabi = false;
2108 A->claim();
2109 } else if (V == "vec-extabi") {
2110 VecExtabi = true;
2111 A->claim();
2112 } else if (V == "elfv1") {
2113 ABIName = "elfv1";
2114 A->claim();
2115 } else if (V == "elfv2") {
2116 ABIName = "elfv2";
2117 A->claim();
2118 } else if (V != "altivec")
2119 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
2120 // the option if given as we don't have backend support for any targets
2121 // that don't use the altivec abi.
2122 ABIName = A->getValue();
2123 }
2124 if (IEEELongDouble)
2125 CmdArgs.push_back("-mabi=ieeelongdouble");
2126 if (VecExtabi) {
2127 if (!T.isOSAIX())
2128 D.Diag(diag::err_drv_unsupported_opt_for_target)
2129 << "-mabi=vec-extabi" << T.str();
2130 CmdArgs.push_back("-mabi=vec-extabi");
2131 }
2132
2133 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true))
2134 CmdArgs.push_back("-disable-red-zone");
2135
2137 if (FloatABI == ppc::FloatABI::Soft) {
2138 // Floating point operations and argument passing are soft.
2139 CmdArgs.push_back("-msoft-float");
2140 CmdArgs.push_back("-mfloat-abi");
2141 CmdArgs.push_back("soft");
2142 } else {
2143 // Floating point operations and argument passing are hard.
2144 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2145 CmdArgs.push_back("-mfloat-abi");
2146 CmdArgs.push_back("hard");
2147 }
2148
2149 if (ABIName) {
2150 CmdArgs.push_back("-target-abi");
2151 CmdArgs.push_back(ABIName);
2152 }
2153}
2154
2155void Clang::AddRISCVTargetArgs(const ArgList &Args,
2156 ArgStringList &CmdArgs) const {
2157 const llvm::Triple &Triple = getToolChain().getTriple();
2158 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2159
2160 CmdArgs.push_back("-target-abi");
2161 CmdArgs.push_back(ABIName.data());
2162
2163 if (Arg *A = Args.getLastArg(options::OPT_G)) {
2164 CmdArgs.push_back("-msmall-data-limit");
2165 CmdArgs.push_back(A->getValue());
2166 }
2167
2168 if (!Args.hasFlag(options::OPT_mimplicit_float,
2169 options::OPT_mno_implicit_float, true))
2170 CmdArgs.push_back("-no-implicit-float");
2171
2172 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2173 CmdArgs.push_back("-tune-cpu");
2174 if (strcmp(A->getValue(), "native") == 0)
2175 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2176 else
2177 CmdArgs.push_back(A->getValue());
2178 }
2179
2180 // Handle -mrvv-vector-bits=<bits>
2181 if (Arg *A = Args.getLastArg(options::OPT_mrvv_vector_bits_EQ)) {
2182 StringRef Val = A->getValue();
2183 const Driver &D = getToolChain().getDriver();
2184
2185 // Get minimum VLen from march.
2186 unsigned MinVLen = 0;
2187 std::string Arch = riscv::getRISCVArch(Args, Triple);
2188 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2189 Arch, /*EnableExperimentalExtensions*/ true);
2190 // Ignore parsing error.
2191 if (!errorToBool(ISAInfo.takeError()))
2192 MinVLen = (*ISAInfo)->getMinVLen();
2193
2194 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2195 // as integer as long as we have a MinVLen.
2196 unsigned Bits = 0;
2197 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2198 Bits = MinVLen;
2199 } else if (!Val.getAsInteger(10, Bits)) {
2200 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2201 // at least MinVLen.
2202 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2203 Bits > 65536 || !llvm::isPowerOf2_32(Bits))
2204 Bits = 0;
2205 }
2206
2207 // If we got a valid value try to use it.
2208 if (Bits != 0) {
2209 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2210 CmdArgs.push_back(
2211 Args.MakeArgString("-mvscale-max=" + llvm::Twine(VScaleMin)));
2212 CmdArgs.push_back(
2213 Args.MakeArgString("-mvscale-min=" + llvm::Twine(VScaleMin)));
2214 } else if (Val != "scalable") {
2215 // Handle the unsupported values passed to mrvv-vector-bits.
2216 D.Diag(diag::err_drv_unsupported_option_argument)
2217 << A->getSpelling() << Val;
2218 }
2219 }
2220}
2221
2222void Clang::AddSparcTargetArgs(const ArgList &Args,
2223 ArgStringList &CmdArgs) const {
2225 sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
2226
2227 if (FloatABI == sparc::FloatABI::Soft) {
2228 // Floating point operations and argument passing are soft.
2229 CmdArgs.push_back("-msoft-float");
2230 CmdArgs.push_back("-mfloat-abi");
2231 CmdArgs.push_back("soft");
2232 } else {
2233 // Floating point operations and argument passing are hard.
2234 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2235 CmdArgs.push_back("-mfloat-abi");
2236 CmdArgs.push_back("hard");
2237 }
2238
2239 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2240 StringRef Name = A->getValue();
2241 std::string TuneCPU;
2242 if (Name == "native")
2243 TuneCPU = std::string(llvm::sys::getHostCPUName());
2244 else
2245 TuneCPU = std::string(Name);
2246
2247 CmdArgs.push_back("-tune-cpu");
2248 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2249 }
2250}
2251
2252void Clang::AddSystemZTargetArgs(const ArgList &Args,
2253 ArgStringList &CmdArgs) const {
2254 if (const Arg *A = Args.getLastArg(options::OPT_mtune_EQ)) {
2255 CmdArgs.push_back("-tune-cpu");
2256 if (strcmp(A->getValue(), "native") == 0)
2257 CmdArgs.push_back(Args.MakeArgString(llvm::sys::getHostCPUName()));
2258 else
2259 CmdArgs.push_back(A->getValue());
2260 }
2261
2262 bool HasBackchain =
2263 Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false);
2264 bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2265 options::OPT_mno_packed_stack, false);
2267 systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2268 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2269 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2270 const Driver &D = getToolChain().getDriver();
2271 D.Diag(diag::err_drv_unsupported_opt)
2272 << "-mpacked-stack -mbackchain -mhard-float";
2273 }
2274 if (HasBackchain)
2275 CmdArgs.push_back("-mbackchain");
2276 if (HasPackedStack)
2277 CmdArgs.push_back("-mpacked-stack");
2278 if (HasSoftFloat) {
2279 // Floating point operations and argument passing are soft.
2280 CmdArgs.push_back("-msoft-float");
2281 CmdArgs.push_back("-mfloat-abi");
2282 CmdArgs.push_back("soft");
2283 }
2284}
2285
2286void Clang::AddX86TargetArgs(const ArgList &Args,
2287 ArgStringList &CmdArgs) const {
2288 const Driver &D = getToolChain().getDriver();
2289 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2290
2291 if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2292 Args.hasArg(options::OPT_mkernel) ||
2293 Args.hasArg(options::OPT_fapple_kext))
2294 CmdArgs.push_back("-disable-red-zone");
2295
2296 if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2297 options::OPT_mno_tls_direct_seg_refs, true))
2298 CmdArgs.push_back("-mno-tls-direct-seg-refs");
2299
2300 // Default to avoid implicit floating-point for kernel/kext code, but allow
2301 // that to be overridden with -mno-soft-float.
2302 bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2303 Args.hasArg(options::OPT_fapple_kext));
2304 if (Arg *A = Args.getLastArg(
2305 options::OPT_msoft_float, options::OPT_mno_soft_float,
2306 options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2307 const Option &O = A->getOption();
2308 NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2309 O.matches(options::OPT_msoft_float));
2310 }
2311 if (NoImplicitFloat)
2312 CmdArgs.push_back("-no-implicit-float");
2313
2314 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2315 StringRef Value = A->getValue();
2316 if (Value == "intel" || Value == "att") {
2317 CmdArgs.push_back("-mllvm");
2318 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2319 CmdArgs.push_back(Args.MakeArgString("-inline-asm=" + Value));
2320 } else {
2321 D.Diag(diag::err_drv_unsupported_option_argument)
2322 << A->getSpelling() << Value;
2323 }
2324 } else if (D.IsCLMode()) {
2325 CmdArgs.push_back("-mllvm");
2326 CmdArgs.push_back("-x86-asm-syntax=intel");
2327 }
2328
2329 if (Arg *A = Args.getLastArg(options::OPT_mskip_rax_setup,
2330 options::OPT_mno_skip_rax_setup))
2331 if (A->getOption().matches(options::OPT_mskip_rax_setup))
2332 CmdArgs.push_back(Args.MakeArgString("-mskip-rax-setup"));
2333
2334 // Set flags to support MCU ABI.
2335 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2336 CmdArgs.push_back("-mfloat-abi");
2337 CmdArgs.push_back("soft");
2338 CmdArgs.push_back("-mstack-alignment=4");
2339 }
2340
2341 // Handle -mtune.
2342
2343 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2344 std::string TuneCPU;
2345 if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
2346 !getToolChain().getTriple().isPS())
2347 TuneCPU = "generic";
2348
2349 // Override based on -mtune.
2350 if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2351 StringRef Name = A->getValue();
2352
2353 if (Name == "native") {
2354 Name = llvm::sys::getHostCPUName();
2355 if (!Name.empty())
2356 TuneCPU = std::string(Name);
2357 } else
2358 TuneCPU = std::string(Name);
2359 }
2360
2361 if (!TuneCPU.empty()) {
2362 CmdArgs.push_back("-tune-cpu");
2363 CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2364 }
2365}
2366
2367void Clang::AddHexagonTargetArgs(const ArgList &Args,
2368 ArgStringList &CmdArgs) const {
2369 CmdArgs.push_back("-mqdsp6-compat");
2370 CmdArgs.push_back("-Wreturn-type");
2371
2373 CmdArgs.push_back("-mllvm");
2374 CmdArgs.push_back(
2375 Args.MakeArgString("-hexagon-small-data-threshold=" + Twine(*G)));
2376 }
2377
2378 if (!Args.hasArg(options::OPT_fno_short_enums))
2379 CmdArgs.push_back("-fshort-enums");
2380 if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2381 CmdArgs.push_back("-mllvm");
2382 CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2383 }
2384 CmdArgs.push_back("-mllvm");
2385 CmdArgs.push_back("-machine-sink-split=0");
2386}
2387
2388void Clang::AddLanaiTargetArgs(const ArgList &Args,
2389 ArgStringList &CmdArgs) const {
2390 if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2391 StringRef CPUName = A->getValue();
2392
2393 CmdArgs.push_back("-target-cpu");
2394 CmdArgs.push_back(Args.MakeArgString(CPUName));
2395 }
2396 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2397 StringRef Value = A->getValue();
2398 // Only support mregparm=4 to support old usage. Report error for all other
2399 // cases.
2400 int Mregparm;
2401 if (Value.getAsInteger(10, Mregparm)) {
2402 if (Mregparm != 4) {
2404 diag::err_drv_unsupported_option_argument)
2405 << A->getSpelling() << Value;
2406 }
2407 }
2408 }
2409}
2410
2411void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2412 ArgStringList &CmdArgs) const {
2413 // Default to "hidden" visibility.
2414 if (!Args.hasArg(options::OPT_fvisibility_EQ,
2415 options::OPT_fvisibility_ms_compat))
2416 CmdArgs.push_back("-fvisibility=hidden");
2417}
2418
2419void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2420 // Floating point operations and argument passing are hard.
2421 CmdArgs.push_back("-mfloat-abi");
2422 CmdArgs.push_back("hard");
2423}
2424
2425void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2426 StringRef Target, const InputInfo &Output,
2427 const InputInfo &Input, const ArgList &Args) const {
2428 // If this is a dry run, do not create the compilation database file.
2429 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2430 return;
2431
2432 using llvm::yaml::escape;
2433 const Driver &D = getToolChain().getDriver();
2434
2435 if (!CompilationDatabase) {
2436 std::error_code EC;
2437 auto File = std::make_unique<llvm::raw_fd_ostream>(
2438 Filename, EC,
2439 llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2440 if (EC) {
2441 D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2442 << EC.message();
2443 return;
2444 }
2445 CompilationDatabase = std::move(File);
2446 }
2447 auto &CDB = *CompilationDatabase;
2448 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2449 if (!CWD)
2450 CWD = ".";
2451 CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2452 CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2453 if (Output.isFilename())
2454 CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2455 CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2456 SmallString<128> Buf;
2457 Buf = "-x";
2458 Buf += types::getTypeName(Input.getType());
2459 CDB << ", \"" << escape(Buf) << "\"";
2460 if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
2461 Buf = "--sysroot=";
2462 Buf += D.SysRoot;
2463 CDB << ", \"" << escape(Buf) << "\"";
2464 }
2465 CDB << ", \"" << escape(Input.getFilename()) << "\"";
2466 if (Output.isFilename())
2467 CDB << ", \"-o\", \"" << escape(Output.getFilename()) << "\"";
2468 for (auto &A: Args) {
2469 auto &O = A->getOption();
2470 // Skip language selection, which is positional.
2471 if (O.getID() == options::OPT_x)
2472 continue;
2473 // Skip writing dependency output and the compilation database itself.
2474 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2475 continue;
2476 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2477 continue;
2478 // Skip inputs.
2479 if (O.getKind() == Option::InputClass)
2480 continue;
2481 // Skip output.
2482 if (O.getID() == options::OPT_o)
2483 continue;
2484 // All other arguments are quoted and appended.
2485 ArgStringList ASL;
2486 A->render(Args, ASL);
2487 for (auto &it: ASL)
2488 CDB << ", \"" << escape(it) << "\"";
2489 }
2490 Buf = "--target=";
2491 Buf += Target;
2492 CDB << ", \"" << escape(Buf) << "\"]},\n";
2493}
2494
2495void Clang::DumpCompilationDatabaseFragmentToDir(
2496 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2497 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2498 // If this is a dry run, do not create the compilation database file.
2499 if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2500 return;
2501
2502 if (CompilationDatabase)
2503 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2504
2505 SmallString<256> Path = Dir;
2506 const auto &Driver = C.getDriver();
2507 Driver.getVFS().makeAbsolute(Path);
2508 auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2509 if (Err) {
2510 Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2511 return;
2512 }
2513
2514 llvm::sys::path::append(
2515 Path,
2516 Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2517 int FD;
2518 SmallString<256> TempPath;
2519 Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath,
2520 llvm::sys::fs::OF_Text);
2521 if (Err) {
2522 Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2523 return;
2524 }
2525 CompilationDatabase =
2526 std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2527 DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2528}
2529
2530static bool CheckARMImplicitITArg(StringRef Value) {
2531 return Value == "always" || Value == "never" || Value == "arm" ||
2532 Value == "thumb";
2533}
2534
2535static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2536 StringRef Value) {
2537 CmdArgs.push_back("-mllvm");
2538 CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2539}
2540
2542 const ArgList &Args,
2543 ArgStringList &CmdArgs,
2544 const Driver &D) {
2545 // Default to -mno-relax-all.
2546 //
2547 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2548 // cannot be done by assembler branch relaxation as it needs a free temporary
2549 // register. Because of this, branch relaxation is handled by a MachineIR pass
2550 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2551 // MachineIR branch relaxation inaccurate and it will miss cases where an
2552 // indirect branch is necessary.
2553 Args.addOptInFlag(CmdArgs, options::OPT_mrelax_all,
2554 options::OPT_mno_relax_all);
2555
2556 // Only default to -mincremental-linker-compatible if we think we are
2557 // targeting the MSVC linker.
2558 bool DefaultIncrementalLinkerCompatible =
2559 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2560 if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2561 options::OPT_mno_incremental_linker_compatible,
2562 DefaultIncrementalLinkerCompatible))
2563 CmdArgs.push_back("-mincremental-linker-compatible");
2564
2565 Args.AddLastArg(CmdArgs, options::OPT_femit_dwarf_unwind_EQ);
2566
2567 Args.addOptInFlag(CmdArgs, options::OPT_femit_compact_unwind_non_canonical,
2568 options::OPT_fno_emit_compact_unwind_non_canonical);
2569
2570 // If you add more args here, also add them to the block below that
2571 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2572
2573 // When passing -I arguments to the assembler we sometimes need to
2574 // unconditionally take the next argument. For example, when parsing
2575 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2576 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2577 // arg after parsing the '-I' arg.
2578 bool TakeNextArg = false;
2579
2580 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2581 bool IsELF = Triple.isOSBinFormatELF();
2582 bool Crel = false, ExperimentalCrel = false;
2583 bool ImplicitMapSyms = false;
2584 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2585 bool UseNoExecStack = false;
2586 bool Msa = false;
2587 const char *MipsTargetFeature = nullptr;
2588 StringRef ImplicitIt;
2589 for (const Arg *A :
2590 Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler,
2591 options::OPT_mimplicit_it_EQ)) {
2592 A->claim();
2593
2594 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2595 switch (C.getDefaultToolChain().getArch()) {
2596 case llvm::Triple::arm:
2597 case llvm::Triple::armeb:
2598 case llvm::Triple::thumb:
2599 case llvm::Triple::thumbeb:
2600 // Only store the value; the last value set takes effect.
2601 ImplicitIt = A->getValue();
2602 if (!CheckARMImplicitITArg(ImplicitIt))
2603 D.Diag(diag::err_drv_unsupported_option_argument)
2604 << A->getSpelling() << ImplicitIt;
2605 continue;
2606 default:
2607 break;
2608 }
2609 }
2610
2611 for (StringRef Value : A->getValues()) {
2612 if (TakeNextArg) {
2613 CmdArgs.push_back(Value.data());
2614 TakeNextArg = false;
2615 continue;
2616 }
2617
2618 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2619 Value == "-mbig-obj")
2620 continue; // LLVM handles bigobj automatically
2621
2622 auto Equal = Value.split('=');
2623 auto checkArg = [&](bool ValidTarget,
2624 std::initializer_list<const char *> Set) {
2625 if (!ValidTarget) {
2626 D.Diag(diag::err_drv_unsupported_opt_for_target)
2627 << (Twine("-Wa,") + Equal.first + "=").str()
2628 << Triple.getTriple();
2629 } else if (!llvm::is_contained(Set, Equal.second)) {
2630 D.Diag(diag::err_drv_unsupported_option_argument)
2631 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2632 }
2633 };
2634 switch (C.getDefaultToolChain().getArch()) {
2635 default:
2636 break;
2637 case llvm::Triple::x86:
2638 case llvm::Triple::x86_64:
2639 if (Equal.first == "-mrelax-relocations" ||
2640 Equal.first == "--mrelax-relocations") {
2641 UseRelaxRelocations = Equal.second == "yes";
2642 checkArg(IsELF, {"yes", "no"});
2643 continue;
2644 }
2645 if (Value == "-msse2avx") {
2646 CmdArgs.push_back("-msse2avx");
2647 continue;
2648 }
2649 break;
2650 case llvm::Triple::wasm32:
2651 case llvm::Triple::wasm64:
2652 if (Value == "--no-type-check") {
2653 CmdArgs.push_back("-mno-type-check");
2654 continue;
2655 }
2656 break;
2657 case llvm::Triple::thumb:
2658 case llvm::Triple::thumbeb:
2659 case llvm::Triple::arm:
2660 case llvm::Triple::armeb:
2661 if (Equal.first == "-mimplicit-it") {
2662 // Only store the value; the last value set takes effect.
2663 ImplicitIt = Equal.second;
2664 checkArg(true, {"always", "never", "arm", "thumb"});
2665 continue;
2666 }
2667 if (Value == "-mthumb")
2668 // -mthumb has already been processed in ComputeLLVMTriple()
2669 // recognize but skip over here.
2670 continue;
2671 break;
2672 case llvm::Triple::aarch64:
2673 case llvm::Triple::aarch64_be:
2674 case llvm::Triple::aarch64_32:
2675 if (Equal.first == "-mmapsyms") {
2676 ImplicitMapSyms = Equal.second == "implicit";
2677 checkArg(IsELF, {"default", "implicit"});
2678 continue;
2679 }
2680 break;
2681 case llvm::Triple::mips:
2682 case llvm::Triple::mipsel:
2683 case llvm::Triple::mips64:
2684 case llvm::Triple::mips64el:
2685 if (Value == "--trap") {
2686 CmdArgs.push_back("-target-feature");
2687 CmdArgs.push_back("+use-tcc-in-div");
2688 continue;
2689 }
2690 if (Value == "--break") {
2691 CmdArgs.push_back("-target-feature");
2692 CmdArgs.push_back("-use-tcc-in-div");
2693 continue;
2694 }
2695 if (Value.starts_with("-msoft-float")) {
2696 CmdArgs.push_back("-target-feature");
2697 CmdArgs.push_back("+soft-float");
2698 continue;
2699 }
2700 if (Value.starts_with("-mhard-float")) {
2701 CmdArgs.push_back("-target-feature");
2702 CmdArgs.push_back("-soft-float");
2703 continue;
2704 }
2705 if (Value == "-mmsa") {
2706 Msa = true;
2707 continue;
2708 }
2709 if (Value == "-mno-msa") {
2710 Msa = false;
2711 continue;
2712 }
2713 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2714 .Case("-mips1", "+mips1")
2715 .Case("-mips2", "+mips2")
2716 .Case("-mips3", "+mips3")
2717 .Case("-mips4", "+mips4")
2718 .Case("-mips5", "+mips5")
2719 .Case("-mips32", "+mips32")
2720 .Case("-mips32r2", "+mips32r2")
2721 .Case("-mips32r3", "+mips32r3")
2722 .Case("-mips32r5", "+mips32r5")
2723 .Case("-mips32r6", "+mips32r6")
2724 .Case("-mips64", "+mips64")
2725 .Case("-mips64r2", "+mips64r2")
2726 .Case("-mips64r3", "+mips64r3")
2727 .Case("-mips64r5", "+mips64r5")
2728 .Case("-mips64r6", "+mips64r6")
2729 .Default(nullptr);
2730 if (MipsTargetFeature)
2731 continue;
2732 break;
2733 }
2734
2735 if (Value == "-force_cpusubtype_ALL") {
2736 // Do nothing, this is the default and we don't support anything else.
2737 } else if (Value == "-L") {
2738 CmdArgs.push_back("-msave-temp-labels");
2739 } else if (Value == "--fatal-warnings") {
2740 CmdArgs.push_back("-massembler-fatal-warnings");
2741 } else if (Value == "--no-warn" || Value == "-W") {
2742 CmdArgs.push_back("-massembler-no-warn");
2743 } else if (Value == "--noexecstack") {
2744 UseNoExecStack = true;
2745 } else if (Value.starts_with("-compress-debug-sections") ||
2746 Value.starts_with("--compress-debug-sections") ||
2747 Value == "-nocompress-debug-sections" ||
2748 Value == "--nocompress-debug-sections") {
2749 CmdArgs.push_back(Value.data());
2750 } else if (Value == "--crel") {
2751 Crel = true;
2752 } else if (Value == "--no-crel") {
2753 Crel = false;
2754 } else if (Value == "--allow-experimental-crel") {
2755 ExperimentalCrel = true;
2756 } else if (Value.starts_with("-I")) {
2757 CmdArgs.push_back(Value.data());
2758 // We need to consume the next argument if the current arg is a plain
2759 // -I. The next arg will be the include directory.
2760 if (Value == "-I")
2761 TakeNextArg = true;
2762 } else if (Value.starts_with("-gdwarf-")) {
2763 // "-gdwarf-N" options are not cc1as options.
2764 unsigned DwarfVersion = DwarfVersionNum(Value);
2765 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2766 CmdArgs.push_back(Value.data());
2767 } else {
2768 RenderDebugEnablingArgs(Args, CmdArgs,
2769 llvm::codegenoptions::DebugInfoConstructor,
2770 DwarfVersion, llvm::DebuggerKind::Default);
2771 }
2772 } else if (Value.starts_with("-mcpu") || Value.starts_with("-mfpu") ||
2773 Value.starts_with("-mhwdiv") || Value.starts_with("-march")) {
2774 // Do nothing, we'll validate it later.
2775 } else if (Value == "-defsym" || Value == "--defsym") {
2776 if (A->getNumValues() != 2) {
2777 D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2778 break;
2779 }
2780 const char *S = A->getValue(1);
2781 auto Pair = StringRef(S).split('=');
2782 auto Sym = Pair.first;
2783 auto SVal = Pair.second;
2784
2785 if (Sym.empty() || SVal.empty()) {
2786 D.Diag(diag::err_drv_defsym_invalid_format) << S;
2787 break;
2788 }
2789 int64_t IVal;
2790 if (SVal.getAsInteger(0, IVal)) {
2791 D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2792 break;
2793 }
2794 CmdArgs.push_back("--defsym");
2795 TakeNextArg = true;
2796 } else if (Value == "-fdebug-compilation-dir") {
2797 CmdArgs.push_back("-fdebug-compilation-dir");
2798 TakeNextArg = true;
2799 } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2800 // The flag is a -Wa / -Xassembler argument and Options doesn't
2801 // parse the argument, so this isn't automatically aliased to
2802 // -fdebug-compilation-dir (without '=') here.
2803 CmdArgs.push_back("-fdebug-compilation-dir");
2804 CmdArgs.push_back(Value.data());
2805 } else if (Value == "--version") {
2806 D.PrintVersion(C, llvm::outs());
2807 } else {
2808 D.Diag(diag::err_drv_unsupported_option_argument)
2809 << A->getSpelling() << Value;
2810 }
2811 }
2812 }
2813 if (ImplicitIt.size())
2814 AddARMImplicitITArgs(Args, CmdArgs, ImplicitIt);
2815 if (Crel) {
2816 if (!ExperimentalCrel)
2817 D.Diag(diag::err_drv_experimental_crel);
2818 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2819 CmdArgs.push_back("--crel");
2820 } else {
2821 D.Diag(diag::err_drv_unsupported_opt_for_target)
2822 << "-Wa,--crel" << D.getTargetTriple();
2823 }
2824 }
2825 if (ImplicitMapSyms)
2826 CmdArgs.push_back("-mmapsyms=implicit");
2827 if (Msa)
2828 CmdArgs.push_back("-mmsa");
2829 if (!UseRelaxRelocations)
2830 CmdArgs.push_back("-mrelax-relocations=no");
2831 if (UseNoExecStack)
2832 CmdArgs.push_back("-mnoexecstack");
2833 if (MipsTargetFeature != nullptr) {
2834 CmdArgs.push_back("-target-feature");
2835 CmdArgs.push_back(MipsTargetFeature);
2836 }
2837
2838 // forward -fembed-bitcode to assmebler
2839 if (C.getDriver().embedBitcodeEnabled() ||
2840 C.getDriver().embedBitcodeMarkerOnly())
2841 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2842
2843 if (const char *AsSecureLogFile = getenv("AS_SECURE_LOG_FILE")) {
2844 CmdArgs.push_back("-as-secure-log-file");
2845 CmdArgs.push_back(Args.MakeArgString(AsSecureLogFile));
2846 }
2847}
2848
2850 switch (Range) {
2852 return "full";
2853 break;
2855 return "basic";
2856 break;
2858 return "improved";
2859 break;
2861 return "promoted";
2862 break;
2863 default:
2864 return "";
2865 }
2866}
2867
2870 ? ""
2871 : "-fcomplex-arithmetic=" + ComplexRangeKindToStr(Range);
2872}
2873
2874static void EmitComplexRangeDiag(const Driver &D, std::string str1,
2875 std::string str2) {
2876 if (str1 != str2 && !str2.empty() && !str1.empty()) {
2877 D.Diag(clang::diag::warn_drv_overriding_option) << str1 << str2;
2878 }
2879}
2880
2881static std::string
2883 std::string ComplexRangeStr = ComplexRangeKindToStr(Range);
2884 if (!ComplexRangeStr.empty())
2885 return "-complex-range=" + ComplexRangeStr;
2886 return ComplexRangeStr;
2887}
2888
2889static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2890 bool OFastEnabled, const ArgList &Args,
2891 ArgStringList &CmdArgs,
2892 const JobAction &JA) {
2893 // List of veclibs which when used with -fveclib imply -fno-math-errno.
2894 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2895 llvm::StringLiteral("SLEEF")};
2896 bool NoMathErrnoWasImpliedByVecLib = false;
2897 const Arg *VecLibArg = nullptr;
2898 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
2899 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
2900
2901 // Handle various floating point optimization flags, mapping them to the
2902 // appropriate LLVM code generation flags. This is complicated by several
2903 // "umbrella" flags, so we do this by stepping through the flags incrementally
2904 // adjusting what we think is enabled/disabled, then at the end setting the
2905 // LLVM flags based on the final state.
2906 bool HonorINFs = true;
2907 bool HonorNaNs = true;
2908 bool ApproxFunc = false;
2909 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2910 bool MathErrno = TC.IsMathErrnoDefault();
2911 bool AssociativeMath = false;
2912 bool ReciprocalMath = false;
2913 bool SignedZeros = true;
2914 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2915 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2916 // overriden by ffp-exception-behavior?
2917 bool RoundingFPMath = false;
2918 // -ffp-model values: strict, fast, precise
2919 StringRef FPModel = "";
2920 // -ffp-exception-behavior options: strict, maytrap, ignore
2921 StringRef FPExceptionBehavior = "";
2922 // -ffp-eval-method options: double, extended, source
2923 StringRef FPEvalMethod = "";
2924 llvm::DenormalMode DenormalFPMath =
2925 TC.getDefaultDenormalModeForType(Args, JA);
2926 llvm::DenormalMode DenormalFP32Math =
2927 TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2928
2929 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2930 // If one wasn't given by the user, don't pass it here.
2931 StringRef FPContract;
2932 StringRef LastSeenFfpContractOption;
2933 StringRef LastFpContractOverrideOption;
2934 bool SeenUnsafeMathModeOption = false;
2937 FPContract = "on";
2938 bool StrictFPModel = false;
2939 StringRef Float16ExcessPrecision = "";
2940 StringRef BFloat16ExcessPrecision = "";
2942 std::string ComplexRangeStr = "";
2943 std::string GccRangeComplexOption = "";
2944
2945 auto setComplexRange = [&](LangOptions::ComplexRangeKind NewRange) {
2946 // Warn if user expects to perform full implementation of complex
2947 // multiplication or division in the presence of nnan or ninf flags.
2948 if (Range != NewRange)
2950 !GccRangeComplexOption.empty()
2951 ? GccRangeComplexOption
2953 ComplexArithmeticStr(NewRange));
2954 Range = NewRange;
2955 };
2956
2957 // Lambda to set fast-math options. This is also used by -ffp-model=fast
2958 auto applyFastMath = [&](bool Aggressive) {
2959 if (Aggressive) {
2960 HonorINFs = false;
2961 HonorNaNs = false;
2963 } else {
2964 HonorINFs = true;
2965 HonorNaNs = true;
2967 }
2968 MathErrno = false;
2969 AssociativeMath = true;
2970 ReciprocalMath = true;
2971 ApproxFunc = true;
2972 SignedZeros = false;
2973 TrappingMath = false;
2974 RoundingFPMath = false;
2975 FPExceptionBehavior = "";
2976 FPContract = "fast";
2977 SeenUnsafeMathModeOption = true;
2978 };
2979
2980 // Lambda to consolidate common handling for fp-contract
2981 auto restoreFPContractState = [&]() {
2982 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2983 // For other targets, if the state has been changed by one of the
2984 // unsafe-math umbrella options a subsequent -fno-fast-math or
2985 // -fno-unsafe-math-optimizations option reverts to the last value seen for
2986 // the -ffp-contract option or "on" if we have not seen the -ffp-contract
2987 // option. If we have not seen an unsafe-math option or -ffp-contract,
2988 // we leave the FPContract state unchanged.
2991 if (LastSeenFfpContractOption != "")
2992 FPContract = LastSeenFfpContractOption;
2993 else if (SeenUnsafeMathModeOption)
2994 FPContract = "on";
2995 }
2996 // In this case, we're reverting to the last explicit fp-contract option
2997 // or the platform default
2998 LastFpContractOverrideOption = "";
2999 };
3000
3001 if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
3002 CmdArgs.push_back("-mlimit-float-precision");
3003 CmdArgs.push_back(A->getValue());
3004 }
3005
3006 for (const Arg *A : Args) {
3007 auto CheckMathErrnoForVecLib =
3008 llvm::make_scope_exit([&, MathErrnoBeforeArg = MathErrno] {
3009 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
3010 ArgThatEnabledMathErrnoAfterVecLib = A;
3011 });
3012
3013 switch (A->getOption().getID()) {
3014 // If this isn't an FP option skip the claim below
3015 default: continue;
3016
3017 case options::OPT_fcx_limited_range:
3018 if (GccRangeComplexOption.empty()) {
3021 "-fcx-limited-range");
3022 } else {
3023 if (GccRangeComplexOption != "-fno-cx-limited-range")
3024 EmitComplexRangeDiag(D, GccRangeComplexOption, "-fcx-limited-range");
3025 }
3026 GccRangeComplexOption = "-fcx-limited-range";
3028 break;
3029 case options::OPT_fno_cx_limited_range:
3030 if (GccRangeComplexOption.empty()) {
3032 "-fno-cx-limited-range");
3033 } else {
3034 if (GccRangeComplexOption != "-fcx-limited-range" &&
3035 GccRangeComplexOption != "-fno-cx-fortran-rules")
3036 EmitComplexRangeDiag(D, GccRangeComplexOption,
3037 "-fno-cx-limited-range");
3038 }
3039 GccRangeComplexOption = "-fno-cx-limited-range";
3041 break;
3042 case options::OPT_fcx_fortran_rules:
3043 if (GccRangeComplexOption.empty())
3045 "-fcx-fortran-rules");
3046 else
3047 EmitComplexRangeDiag(D, GccRangeComplexOption, "-fcx-fortran-rules");
3048 GccRangeComplexOption = "-fcx-fortran-rules";
3050 break;
3051 case options::OPT_fno_cx_fortran_rules:
3052 if (GccRangeComplexOption.empty()) {
3054 "-fno-cx-fortran-rules");
3055 } else {
3056 if (GccRangeComplexOption != "-fno-cx-limited-range")
3057 EmitComplexRangeDiag(D, GccRangeComplexOption,
3058 "-fno-cx-fortran-rules");
3059 }
3060 GccRangeComplexOption = "-fno-cx-fortran-rules";
3062 break;
3063 case options::OPT_fcomplex_arithmetic_EQ: {
3065 StringRef Val = A->getValue();
3066 if (Val == "full")
3068 else if (Val == "improved")
3070 else if (Val == "promoted")
3072 else if (Val == "basic")
3074 else {
3075 D.Diag(diag::err_drv_unsupported_option_argument)
3076 << A->getSpelling() << Val;
3077 break;
3078 }
3079 if (!GccRangeComplexOption.empty()) {
3080 if (GccRangeComplexOption != "-fcx-limited-range") {
3081 if (GccRangeComplexOption != "-fcx-fortran-rules") {
3083 EmitComplexRangeDiag(D, GccRangeComplexOption,
3084 ComplexArithmeticStr(RangeVal));
3085 } else {
3086 EmitComplexRangeDiag(D, GccRangeComplexOption,
3087 ComplexArithmeticStr(RangeVal));
3088 }
3089 } else {
3091 EmitComplexRangeDiag(D, GccRangeComplexOption,
3092 ComplexArithmeticStr(RangeVal));
3093 }
3094 }
3095 Range = RangeVal;
3096 break;
3097 }
3098 case options::OPT_ffp_model_EQ: {
3099 // If -ffp-model= is seen, reset to fno-fast-math
3100 HonorINFs = true;
3101 HonorNaNs = true;
3102 ApproxFunc = false;
3103 // Turning *off* -ffast-math restores the toolchain default.
3104 MathErrno = TC.IsMathErrnoDefault();
3105 AssociativeMath = false;
3106 ReciprocalMath = false;
3107 SignedZeros = true;
3108
3109 StringRef Val = A->getValue();
3110 if (OFastEnabled && Val != "aggressive") {
3111 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
3112 D.Diag(clang::diag::warn_drv_overriding_option)
3113 << Args.MakeArgString("-ffp-model=" + Val) << "-Ofast";
3114 break;
3115 }
3116 StrictFPModel = false;
3117 if (!FPModel.empty() && FPModel != Val)
3118 D.Diag(clang::diag::warn_drv_overriding_option)
3119 << Args.MakeArgString("-ffp-model=" + FPModel)
3120 << Args.MakeArgString("-ffp-model=" + Val);
3121 if (Val == "fast") {
3122 FPModel = Val;
3123 applyFastMath(false);
3124 // applyFastMath sets fp-contract="fast"
3125 LastFpContractOverrideOption = "-ffp-model=fast";
3126 } else if (Val == "aggressive") {
3127 FPModel = Val;
3128 applyFastMath(true);
3129 // applyFastMath sets fp-contract="fast"
3130 LastFpContractOverrideOption = "-ffp-model=aggressive";
3131 } else if (Val == "precise") {
3132 FPModel = Val;
3133 FPContract = "on";
3134 LastFpContractOverrideOption = "-ffp-model=precise";
3136 } else if (Val == "strict") {
3137 StrictFPModel = true;
3138 FPExceptionBehavior = "strict";
3139 FPModel = Val;
3140 FPContract = "off";
3141 LastFpContractOverrideOption = "-ffp-model=strict";
3142 TrappingMath = true;
3143 RoundingFPMath = true;
3145 } else
3146 D.Diag(diag::err_drv_unsupported_option_argument)
3147 << A->getSpelling() << Val;
3148 break;
3149 }
3150
3151 // Options controlling individual features
3152 case options::OPT_fhonor_infinities: HonorINFs = true; break;
3153 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
3154 case options::OPT_fhonor_nans: HonorNaNs = true; break;
3155 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
3156 case options::OPT_fapprox_func: ApproxFunc = true; break;
3157 case options::OPT_fno_approx_func: ApproxFunc = false; break;
3158 case options::OPT_fmath_errno: MathErrno = true; break;
3159 case options::OPT_fno_math_errno: MathErrno = false; break;
3160 case options::OPT_fassociative_math: AssociativeMath = true; break;
3161 case options::OPT_fno_associative_math: AssociativeMath = false; break;
3162 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
3163 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
3164 case options::OPT_fsigned_zeros: SignedZeros = true; break;
3165 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
3166 case options::OPT_ftrapping_math:
3167 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3168 FPExceptionBehavior != "strict")
3169 // Warn that previous value of option is overridden.
3170 D.Diag(clang::diag::warn_drv_overriding_option)
3171 << Args.MakeArgString("-ffp-exception-behavior=" +
3172 FPExceptionBehavior)
3173 << "-ftrapping-math";
3174 TrappingMath = true;
3175 TrappingMathPresent = true;
3176 FPExceptionBehavior = "strict";
3177 break;
3178 case options::OPT_fveclib:
3179 VecLibArg = A;
3180 NoMathErrnoWasImpliedByVecLib =
3181 llvm::is_contained(VecLibImpliesNoMathErrno, A->getValue());
3182 if (NoMathErrnoWasImpliedByVecLib)
3183 MathErrno = false;
3184 break;
3185 case options::OPT_fno_trapping_math:
3186 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3187 FPExceptionBehavior != "ignore")
3188 // Warn that previous value of option is overridden.
3189 D.Diag(clang::diag::warn_drv_overriding_option)
3190 << Args.MakeArgString("-ffp-exception-behavior=" +
3191 FPExceptionBehavior)
3192 << "-fno-trapping-math";
3193 TrappingMath = false;
3194 TrappingMathPresent = true;
3195 FPExceptionBehavior = "ignore";
3196 break;
3197
3198 case options::OPT_frounding_math:
3199 RoundingFPMath = true;
3200 break;
3201
3202 case options::OPT_fno_rounding_math:
3203 RoundingFPMath = false;
3204 break;
3205
3206 case options::OPT_fdenormal_fp_math_EQ:
3207 DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
3208 DenormalFP32Math = DenormalFPMath;
3209 if (!DenormalFPMath.isValid()) {
3210 D.Diag(diag::err_drv_invalid_value)
3211 << A->getAsString(Args) << A->getValue();
3212 }
3213 break;
3214
3215 case options::OPT_fdenormal_fp_math_f32_EQ:
3216 DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
3217 if (!DenormalFP32Math.isValid()) {
3218 D.Diag(diag::err_drv_invalid_value)
3219 << A->getAsString(Args) << A->getValue();
3220 }
3221 break;
3222
3223 // Validate and pass through -ffp-contract option.
3224 case options::OPT_ffp_contract: {
3225 StringRef Val = A->getValue();
3226 if (Val == "fast" || Val == "on" || Val == "off" ||
3227 Val == "fast-honor-pragmas") {
3228 if (Val != FPContract && LastFpContractOverrideOption != "") {
3229 D.Diag(clang::diag::warn_drv_overriding_option)
3230 << LastFpContractOverrideOption
3231 << Args.MakeArgString("-ffp-contract=" + Val);
3232 }
3233
3234 FPContract = Val;
3235 LastSeenFfpContractOption = Val;
3236 LastFpContractOverrideOption = "";
3237 } else
3238 D.Diag(diag::err_drv_unsupported_option_argument)
3239 << A->getSpelling() << Val;
3240 break;
3241 }
3242
3243 // Validate and pass through -ffp-exception-behavior option.
3244 case options::OPT_ffp_exception_behavior_EQ: {
3245 StringRef Val = A->getValue();
3246 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3247 FPExceptionBehavior != Val)
3248 // Warn that previous value of option is overridden.
3249 D.Diag(clang::diag::warn_drv_overriding_option)
3250 << Args.MakeArgString("-ffp-exception-behavior=" +
3251 FPExceptionBehavior)
3252 << Args.MakeArgString("-ffp-exception-behavior=" + Val);
3253 TrappingMath = TrappingMathPresent = false;
3254 if (Val == "ignore" || Val == "maytrap")
3255 FPExceptionBehavior = Val;
3256 else if (Val == "strict") {
3257 FPExceptionBehavior = Val;
3258 TrappingMath = TrappingMathPresent = true;
3259 } else
3260 D.Diag(diag::err_drv_unsupported_option_argument)
3261 << A->getSpelling() << Val;
3262 break;
3263 }
3264
3265 // Validate and pass through -ffp-eval-method option.
3266 case options::OPT_ffp_eval_method_EQ: {
3267 StringRef Val = A->getValue();
3268 if (Val == "double" || Val == "extended" || Val == "source")
3269 FPEvalMethod = Val;
3270 else
3271 D.Diag(diag::err_drv_unsupported_option_argument)
3272 << A->getSpelling() << Val;
3273 break;
3274 }
3275
3276 case options::OPT_fexcess_precision_EQ: {
3277 StringRef Val = A->getValue();
3278 const llvm::Triple::ArchType Arch = TC.getArch();
3279 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3280 if (Val == "standard" || Val == "fast")
3281 Float16ExcessPrecision = Val;
3282 // To make it GCC compatible, allow the value of "16" which
3283 // means disable excess precision, the same meaning than clang's
3284 // equivalent value "none".
3285 else if (Val == "16")
3286 Float16ExcessPrecision = "none";
3287 else
3288 D.Diag(diag::err_drv_unsupported_option_argument)
3289 << A->getSpelling() << Val;
3290 } else {
3291 if (!(Val == "standard" || Val == "fast"))
3292 D.Diag(diag::err_drv_unsupported_option_argument)
3293 << A->getSpelling() << Val;
3294 }
3295 BFloat16ExcessPrecision = Float16ExcessPrecision;
3296 break;
3297 }
3298 case options::OPT_ffinite_math_only:
3299 HonorINFs = false;
3300 HonorNaNs = false;
3301 break;
3302 case options::OPT_fno_finite_math_only:
3303 HonorINFs = true;
3304 HonorNaNs = true;
3305 break;
3306
3307 case options::OPT_funsafe_math_optimizations:
3308 AssociativeMath = true;
3309 ReciprocalMath = true;
3310 SignedZeros = false;
3311 ApproxFunc = true;
3312 TrappingMath = false;
3313 FPExceptionBehavior = "";
3314 FPContract = "fast";
3315 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3316 SeenUnsafeMathModeOption = true;
3317 break;
3318 case options::OPT_fno_unsafe_math_optimizations:
3319 AssociativeMath = false;
3320 ReciprocalMath = false;
3321 SignedZeros = true;
3322 ApproxFunc = false;
3323 restoreFPContractState();
3324 break;
3325
3326 case options::OPT_Ofast:
3327 // If -Ofast is the optimization level, then -ffast-math should be enabled
3328 if (!OFastEnabled)
3329 continue;
3330 [[fallthrough]];
3331 case options::OPT_ffast_math:
3332 applyFastMath(true);
3333 if (A->getOption().getID() == options::OPT_Ofast)
3334 LastFpContractOverrideOption = "-Ofast";
3335 else
3336 LastFpContractOverrideOption = "-ffast-math";
3337 break;
3338 case options::OPT_fno_fast_math:
3339 HonorINFs = true;
3340 HonorNaNs = true;
3341 // Turning on -ffast-math (with either flag) removes the need for
3342 // MathErrno. However, turning *off* -ffast-math merely restores the
3343 // toolchain default (which may be false).
3344 MathErrno = TC.IsMathErrnoDefault();
3345 AssociativeMath = false;
3346 ReciprocalMath = false;
3347 ApproxFunc = false;
3348 SignedZeros = true;
3349 restoreFPContractState();
3350 LastFpContractOverrideOption = "";
3351 break;
3352 } // End switch (A->getOption().getID())
3353
3354 // The StrictFPModel local variable is needed to report warnings
3355 // in the way we intend. If -ffp-model=strict has been used, we
3356 // want to report a warning for the next option encountered that
3357 // takes us out of the settings described by fp-model=strict, but
3358 // we don't want to continue issuing warnings for other conflicting
3359 // options after that.
3360 if (StrictFPModel) {
3361 // If -ffp-model=strict has been specified on command line but
3362 // subsequent options conflict then emit warning diagnostic.
3363 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3364 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3365 FPContract == "off")
3366 // OK: Current Arg doesn't conflict with -ffp-model=strict
3367 ;
3368 else {
3369 StrictFPModel = false;
3370 FPModel = "";
3371 // The warning for -ffp-contract would have been reported by the
3372 // OPT_ffp_contract_EQ handler above. A special check here is needed
3373 // to avoid duplicating the warning.
3374 auto RHS = (A->getNumValues() == 0)
3375 ? A->getSpelling()
3376 : Args.MakeArgString(A->getSpelling() + A->getValue());
3377 if (A->getSpelling() != "-ffp-contract=") {
3378 if (RHS != "-ffp-model=strict")
3379 D.Diag(clang::diag::warn_drv_overriding_option)
3380 << "-ffp-model=strict" << RHS;
3381 }
3382 }
3383 }
3384
3385 // If we handled this option claim it
3386 A->claim();
3387 }
3388
3389 if (!HonorINFs)
3390 CmdArgs.push_back("-menable-no-infs");
3391
3392 if (!HonorNaNs)
3393 CmdArgs.push_back("-menable-no-nans");
3394
3395 if (ApproxFunc)
3396 CmdArgs.push_back("-fapprox-func");
3397
3398 if (MathErrno) {
3399 CmdArgs.push_back("-fmath-errno");
3400 if (NoMathErrnoWasImpliedByVecLib)
3401 D.Diag(clang::diag::warn_drv_math_errno_enabled_after_veclib)
3402 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3403 << VecLibArg->getAsString(Args);
3404 }
3405
3406 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3407 !TrappingMath)
3408 CmdArgs.push_back("-funsafe-math-optimizations");
3409
3410 if (!SignedZeros)
3411 CmdArgs.push_back("-fno-signed-zeros");
3412
3413 if (AssociativeMath && !SignedZeros && !TrappingMath)
3414 CmdArgs.push_back("-mreassociate");
3415
3416 if (ReciprocalMath)
3417 CmdArgs.push_back("-freciprocal-math");
3418
3419 if (TrappingMath) {
3420 // FP Exception Behavior is also set to strict
3421 assert(FPExceptionBehavior == "strict");
3422 }
3423
3424 // The default is IEEE.
3425 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3426 llvm::SmallString<64> DenormFlag;
3427 llvm::raw_svector_ostream ArgStr(DenormFlag);
3428 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3429 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3430 }
3431
3432 // Add f32 specific denormal mode flag if it's different.
3433 if (DenormalFP32Math != DenormalFPMath) {
3434 llvm::SmallString<64> DenormFlag;
3435 llvm::raw_svector_ostream ArgStr(DenormFlag);
3436 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3437 CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
3438 }
3439
3440 if (!FPContract.empty())
3441 CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
3442
3443 if (RoundingFPMath)
3444 CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
3445 else
3446 CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
3447
3448 if (!FPExceptionBehavior.empty())
3449 CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
3450 FPExceptionBehavior));
3451
3452 if (!FPEvalMethod.empty())
3453 CmdArgs.push_back(Args.MakeArgString("-ffp-eval-method=" + FPEvalMethod));
3454
3455 if (!Float16ExcessPrecision.empty())
3456 CmdArgs.push_back(Args.MakeArgString("-ffloat16-excess-precision=" +
3457 Float16ExcessPrecision));
3458 if (!BFloat16ExcessPrecision.empty())
3459 CmdArgs.push_back(Args.MakeArgString("-fbfloat16-excess-precision=" +
3460 BFloat16ExcessPrecision));
3461
3462 ParseMRecip(D, Args, CmdArgs);
3463
3464 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3465 // individual features enabled by -ffast-math instead of the option itself as
3466 // that's consistent with gcc's behaviour.
3467 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3468 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3469 CmdArgs.push_back("-ffast-math");
3470
3471 // Handle __FINITE_MATH_ONLY__ similarly.
3472 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3473 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3474 // -menable-no-nans are set by the user.
3475 bool shouldAddFiniteMathOnly = false;
3476 if (!HonorINFs && !HonorNaNs) {
3477 shouldAddFiniteMathOnly = true;
3478 } else {
3479 bool InfValues = true;
3480 bool NanValues = true;
3481 for (const auto *Arg : Args.filtered(options::OPT_Xclang)) {
3482 StringRef ArgValue = Arg->getValue();
3483 if (ArgValue == "-menable-no-nans")
3484 NanValues = false;
3485 else if (ArgValue == "-menable-no-infs")
3486 InfValues = false;
3487 }
3488 if (!NanValues && !InfValues)
3489 shouldAddFiniteMathOnly = true;
3490 }
3491 if (shouldAddFiniteMathOnly) {
3492 CmdArgs.push_back("-ffinite-math-only");
3493 }
3494 if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
3495 CmdArgs.push_back("-mfpmath");
3496 CmdArgs.push_back(A->getValue());
3497 }
3498
3499 // Disable a codegen optimization for floating-point casts.
3500 if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
3501 options::OPT_fstrict_float_cast_overflow, false))
3502 CmdArgs.push_back("-fno-strict-float-cast-overflow");
3503
3505 ComplexRangeStr = RenderComplexRangeOption(Range);
3506 if (!ComplexRangeStr.empty()) {
3507 CmdArgs.push_back(Args.MakeArgString(ComplexRangeStr));
3508 if (Args.hasArg(options::OPT_fcomplex_arithmetic_EQ))
3509 CmdArgs.push_back(Args.MakeArgString("-fcomplex-arithmetic=" +
3511 }
3512 if (Args.hasArg(options::OPT_fcx_limited_range))
3513 CmdArgs.push_back("-fcx-limited-range");
3514 if (Args.hasArg(options::OPT_fcx_fortran_rules))
3515 CmdArgs.push_back("-fcx-fortran-rules");
3516 if (Args.hasArg(options::OPT_fno_cx_limited_range))
3517 CmdArgs.push_back("-fno-cx-limited-range");
3518 if (Args.hasArg(options::OPT_fno_cx_fortran_rules))
3519 CmdArgs.push_back("-fno-cx-fortran-rules");
3520}
3521
3522static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3523 const llvm::Triple &Triple,
3524 const InputInfo &Input) {
3525 // Add default argument set.
3526 if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
3527 CmdArgs.push_back("-analyzer-checker=core");
3528 CmdArgs.push_back("-analyzer-checker=apiModeling");
3529
3530 if (!Triple.isWindowsMSVCEnvironment()) {
3531 CmdArgs.push_back("-analyzer-checker=unix");
3532 } else {
3533 // Enable "unix" checkers that also work on Windows.
3534 CmdArgs.push_back("-analyzer-checker=unix.API");
3535 CmdArgs.push_back("-analyzer-checker=unix.Malloc");
3536 CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
3537 CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
3538 CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
3539 CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
3540 }
3541
3542 // Disable some unix checkers for PS4/PS5.
3543 if (Triple.isPS()) {
3544 CmdArgs.push_back("-analyzer-disable-checker=unix.API");
3545 CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
3546 }
3547
3548 if (Triple.isOSDarwin()) {
3549 CmdArgs.push_back("-analyzer-checker=osx");
3550 CmdArgs.push_back(
3551 "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3552 }
3553 else if (Triple.isOSFuchsia())
3554 CmdArgs.push_back("-analyzer-checker=fuchsia");
3555
3556 CmdArgs.push_back("-analyzer-checker=deadcode");
3557
3558 if (types::isCXX(Input.getType()))
3559 CmdArgs.push_back("-analyzer-checker=cplusplus");
3560
3561 if (!Triple.isPS()) {
3562 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
3563 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
3564 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
3565 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
3566 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
3567 CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
3568 }
3569
3570 // Default nullability checks.
3571 CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
3572 CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
3573 }
3574
3575 // Set the output format. The default is plist, for (lame) historical reasons.
3576 CmdArgs.push_back("-analyzer-output");
3577 if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
3578 CmdArgs.push_back(A->getValue());
3579 else
3580 CmdArgs.push_back("plist");
3581
3582 // Disable the presentation of standard compiler warnings when using
3583 // --analyze. We only want to show static analyzer diagnostics or frontend
3584 // errors.
3585 CmdArgs.push_back("-w");
3586
3587 // Add -Xanalyzer arguments when running as analyzer.
3588 Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
3589}
3590
3591static bool isValidSymbolName(StringRef S) {
3592 if (S.empty())
3593 return false;
3594
3595 if (std::isdigit(S[0]))
3596 return false;
3597
3598 return llvm::all_of(S, [](char C) { return std::isalnum(C) || C == '_'; });
3599}
3600
3601static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3602 const ArgList &Args, ArgStringList &CmdArgs,
3603 bool KernelOrKext) {
3604 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3605
3606 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3607 // doesn't even have a stack!
3608 if (EffectiveTriple.isNVPTX())
3609 return;
3610
3611 // -stack-protector=0 is default.
3613 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3614 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3615
3616 if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
3617 options::OPT_fstack_protector_all,
3618 options::OPT_fstack_protector_strong,
3619 options::OPT_fstack_protector)) {
3620 if (A->getOption().matches(options::OPT_fstack_protector))
3621 StackProtectorLevel =
3622 std::max<>(LangOptions::SSPOn, DefaultStackProtectorLevel);
3623 else if (A->getOption().matches(options::OPT_fstack_protector_strong))
3624 StackProtectorLevel = LangOptions::SSPStrong;
3625 else if (A->getOption().matches(options::OPT_fstack_protector_all))
3626 StackProtectorLevel = LangOptions::SSPReq;
3627
3628 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3629 D.Diag(diag::warn_drv_unsupported_option_for_target)
3630 << A->getSpelling() << EffectiveTriple.getTriple();
3631 StackProtectorLevel = DefaultStackProtectorLevel;
3632 }
3633 } else {
3634 StackProtectorLevel = DefaultStackProtectorLevel;
3635 }
3636
3637 if (StackProtectorLevel) {
3638 CmdArgs.push_back("-stack-protector");
3639 CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
3640 }
3641
3642 // --param ssp-buffer-size=
3643 for (const Arg *A : Args.filtered(options::OPT__param)) {
3644 StringRef Str(A->getValue());
3645 if (Str.starts_with("ssp-buffer-size=")) {
3646 if (StackProtectorLevel) {
3647 CmdArgs.push_back("-stack-protector-buffer-size");
3648 // FIXME: Verify the argument is a valid integer.
3649 CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
3650 }
3651 A->claim();
3652 }
3653 }
3654
3655 const std::string &TripleStr = EffectiveTriple.getTriple();
3656 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_EQ)) {
3657 StringRef Value = A->getValue();
3658 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3659 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3660 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3661 D.Diag(diag::err_drv_unsupported_opt_for_target)
3662 << A->getAsString(Args) << TripleStr;
3663 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3664 EffectiveTriple.isThumb()) &&
3665 Value != "tls" && Value != "global") {
3666 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3667 << A->getOption().getName() << Value << "tls global";
3668 return;
3669 }
3670 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3671 Value == "tls") {
3672 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3673 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3674 << A->getAsString(Args);
3675 return;
3676 }
3677 // Check whether the target subarch supports the hardware TLS register
3678 if (!arm::isHardTPSupported(EffectiveTriple)) {
3679 D.Diag(diag::err_target_unsupported_tp_hard)
3680 << EffectiveTriple.getArchName();
3681 return;
3682 }
3683 // Check whether the user asked for something other than -mtp=cp15
3684 if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
3685 StringRef Value = A->getValue();
3686 if (Value != "cp15") {
3687 D.Diag(diag::err_drv_argument_not_allowed_with)
3688 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3689 return;
3690 }
3691 }
3692 CmdArgs.push_back("-target-feature");
3693 CmdArgs.push_back("+read-tp-tpidruro");
3694 }
3695 if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3696 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3697 << A->getOption().getName() << Value << "sysreg global";
3698 return;
3699 }
3700 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3701 if (Value != "tls" && Value != "global") {
3702 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3703 << A->getOption().getName() << Value << "tls global";
3704 return;
3705 }
3706 if (Value == "tls") {
3707 if (!Args.hasArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3708 D.Diag(diag::err_drv_ssp_missing_offset_argument)
3709 << A->getAsString(Args);
3710 return;
3711 }
3712 }
3713 }
3714 A->render(Args, CmdArgs);
3715 }
3716
3717 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_offset_EQ)) {
3718 StringRef Value = A->getValue();
3719 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3720 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3721 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3722 D.Diag(diag::err_drv_unsupported_opt_for_target)
3723 << A->getAsString(Args) << TripleStr;
3724 int Offset;
3725 if (Value.getAsInteger(10, Offset)) {
3726 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3727 return;
3728 }
3729 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3730 (Offset < 0 || Offset > 0xfffff)) {
3731 D.Diag(diag::err_drv_invalid_int_value)
3732 << A->getOption().getName() << Value;
3733 return;
3734 }
3735 A->render(Args, CmdArgs);
3736 }
3737
3738 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_reg_EQ)) {
3739 StringRef Value = A->getValue();
3740 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3741 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3742 D.Diag(diag::err_drv_unsupported_opt_for_target)
3743 << A->getAsString(Args) << TripleStr;
3744 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3745 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3746 << A->getOption().getName() << Value << "fs gs";
3747 return;
3748 }
3749 if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3750 D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3751 return;
3752 }
3753 if (EffectiveTriple.isRISCV() && Value != "tp") {
3754 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3755 << A->getOption().getName() << Value << "tp";
3756 return;
3757 }
3758 if (EffectiveTriple.isPPC64() && Value != "r13") {
3759 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3760 << A->getOption().getName() << Value << "r13";
3761 return;
3762 }
3763 if (EffectiveTriple.isPPC32() && Value != "r2") {
3764 D.Diag(diag::err_drv_invalid_value_with_suggestion)
3765 << A->getOption().getName() << Value << "r2";
3766 return;
3767 }
3768 A->render(Args, CmdArgs);
3769 }
3770
3771 if (Arg *A = Args.getLastArg(options::OPT_mstack_protector_guard_symbol_EQ)) {
3772 StringRef Value = A->getValue();
3773 if (!isValidSymbolName(Value)) {
3774 D.Diag(diag::err_drv_argument_only_allowed_with)
3775 << A->getOption().getName() << "legal symbol name";
3776 return;
3777 }
3778 A->render(Args, CmdArgs);
3779 }
3780}
3781
3782static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3783 ArgStringList &CmdArgs) {
3784 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3785
3786 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3787 !EffectiveTriple.isOSFuchsia())
3788 return;
3789
3790 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3791 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3792 !EffectiveTriple.isRISCV())
3793 return;
3794
3795 Args.addOptInFlag(CmdArgs, options::OPT_fstack_clash_protection,
3796 options::OPT_fno_stack_clash_protection);
3797}
3798
3800 const ToolChain &TC,
3801 const ArgList &Args,
3802 ArgStringList &CmdArgs) {
3803 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3804 StringRef TrivialAutoVarInit = "";
3805
3806 for (const Arg *A : Args) {
3807 switch (A->getOption().getID()) {
3808 default:
3809 continue;
3810 case options::OPT_ftrivial_auto_var_init: {
3811 A->claim();
3812 StringRef Val = A->getValue();
3813 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3814 TrivialAutoVarInit = Val;
3815 else
3816 D.Diag(diag::err_drv_unsupported_option_argument)
3817 << A->getSpelling() << Val;
3818 break;
3819 }
3820 }
3821 }
3822
3823 if (TrivialAutoVarInit.empty())
3824 switch (DefaultTrivialAutoVarInit) {
3826 break;
3828 TrivialAutoVarInit = "pattern";
3829 break;
3831 TrivialAutoVarInit = "zero";
3832 break;
3833 }
3834
3835 if (!TrivialAutoVarInit.empty()) {
3836 CmdArgs.push_back(
3837 Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3838 }
3839
3840 if (Arg *A =
3841 Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3842 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3843 StringRef(
3844 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3845 "uninitialized")
3846 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3847 A->claim();
3848 StringRef Val = A->getValue();
3849 if (std::stoi(Val.str()) <= 0)
3850 D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3851 CmdArgs.push_back(
3852 Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3853 }
3854
3855 if (Arg *A = Args.getLastArg(options::OPT_ftrivial_auto_var_init_max_size)) {
3856 if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3857 StringRef(
3858 Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3859 "uninitialized")
3860 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3861 A->claim();
3862 StringRef Val = A->getValue();
3863 if (std::stoi(Val.str()) <= 0)
3864 D.Diag(diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3865 CmdArgs.push_back(
3866 Args.MakeArgString("-ftrivial-auto-var-init-max-size=" + Val));
3867 }
3868}
3869
3870static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3871 types::ID InputType) {
3872 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3873 // for denormal flushing handling based on the target.
3874 const unsigned ForwardedArguments[] = {
3875 options::OPT_cl_opt_disable,
3876 options::OPT_cl_strict_aliasing,
3877 options::OPT_cl_single_precision_constant,
3878 options::OPT_cl_finite_math_only,
3879 options::OPT_cl_kernel_arg_info,
3880 options::OPT_cl_unsafe_math_optimizations,
3881 options::OPT_cl_fast_relaxed_math,
3882 options::OPT_cl_mad_enable,
3883 options::OPT_cl_no_signed_zeros,
3884 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3885 options::OPT_cl_uniform_work_group_size
3886 };
3887
3888 if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3889 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3890 CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3891 } else if (Arg *A = Args.getLastArg(options::OPT_cl_ext_EQ)) {
3892 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3893 CmdArgs.push_back(Args.MakeArgString(CLExtStr));
3894 }
3895
3896 if (Args.hasArg(options::OPT_cl_finite_math_only)) {
3897 CmdArgs.push_back("-menable-no-infs");
3898 CmdArgs.push_back("-menable-no-nans");
3899 }
3900
3901 for (const auto &Arg : ForwardedArguments)
3902 if (const auto *A = Args.getLastArg(Arg))
3903 CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3904
3905 // Only add the default headers if we are compiling OpenCL sources.
3906 if ((types::isOpenCL(InputType) ||
3907 (Args.hasArg(options::OPT_cl_std_EQ) && types::isSrcFile(InputType))) &&
3908 !Args.hasArg(options::OPT_cl_no_stdinc)) {
3909 CmdArgs.push_back("-finclude-default-header");
3910 CmdArgs.push_back("-fdeclare-opencl-builtins");
3911 }
3912}
3913
3914static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3915 types::ID InputType) {
3916 const unsigned ForwardedArguments[] = {options::OPT_dxil_validator_version,
3917 options::OPT_D,
3918 options::OPT_I,
3919 options::OPT_O,
3920 options::OPT_emit_llvm,
3921 options::OPT_emit_obj,
3922 options::OPT_disable_llvm_passes,
3923 options::OPT_fnative_half_type,
3924 options::OPT_hlsl_entrypoint};
3925 if (!types::isHLSL(InputType))
3926 return;
3927 for (const auto &Arg : ForwardedArguments)
3928 if (const auto *A = Args.getLastArg(Arg))
3929 A->renderAsInput(Args, CmdArgs);
3930 // Add the default headers if dxc_no_stdinc is not set.
3931 if (!Args.hasArg(options::OPT_dxc_no_stdinc) &&
3932 !Args.hasArg(options::OPT_nostdinc))
3933 CmdArgs.push_back("-finclude-default-header");
3934}
3935
3936static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
3937 ArgStringList &CmdArgs, types::ID InputType) {
3938 if (!Args.hasArg(options::OPT_fopenacc))
3939 return;
3940
3941 CmdArgs.push_back("-fopenacc");
3942
3943 if (Arg *A = Args.getLastArg(options::OPT_openacc_macro_override)) {
3944 StringRef Value = A->getValue();
3945 int Version;
3946 if (!Value.getAsInteger(10, Version))
3947 A->renderAsInput(Args, CmdArgs);
3948 else
3949 D.Diag(diag::err_drv_clang_unsupported) << Value;
3950 }
3951}
3952
3953static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
3954 ArgStringList &CmdArgs) {
3955 bool ARCMTEnabled = false;
3956 if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3957 if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3958 options::OPT_ccc_arcmt_modify,
3959 options::OPT_ccc_arcmt_migrate)) {
3960 ARCMTEnabled = true;
3961 switch (A->getOption().getID()) {
3962 default: llvm_unreachable("missed a case");
3963 case options::OPT_ccc_arcmt_check:
3964 CmdArgs.push_back("-arcmt-action=check");
3965 break;
3966 case options::OPT_ccc_arcmt_modify:
3967 CmdArgs.push_back("-arcmt-action=modify");
3968 break;
3969 case options::OPT_ccc_arcmt_migrate:
3970 CmdArgs.push_back("-arcmt-action=migrate");
3971 CmdArgs.push_back("-mt-migrate-directory");
3972 CmdArgs.push_back(A->getValue());
3973
3974 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3975 Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3976 break;
3977 }
3978 }
3979 } else {
3980 Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3981 Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3982 Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3983 }
3984
3985 if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3986 if (ARCMTEnabled)
3987 D.Diag(diag::err_drv_argument_not_allowed_with)
3988 << A->getAsString(Args) << "-ccc-arcmt-migrate";
3989
3990 CmdArgs.push_back("-mt-migrate-directory");
3991 CmdArgs.push_back(A->getValue());
3992
3993 if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3994 options::OPT_objcmt_migrate_subscripting,
3995 options::OPT_objcmt_migrate_property)) {
3996 // None specified, means enable them all.
3997 CmdArgs.push_back("-objcmt-migrate-literals");
3998 CmdArgs.push_back("-objcmt-migrate-subscripting");
3999 CmdArgs.push_back("-objcmt-migrate-property");
4000 } else {
4001 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4002 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4003 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4004 }
4005 } else {
4006 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
4007 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
4008 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
4009 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
4010 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
4011 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
4012 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
4013 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
4014 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
4015 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
4016 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
4017 Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
4018 Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
4019 Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
4020 Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
4021 Args.AddLastArg(CmdArgs, options::OPT_objcmt_allowlist_dir_path);
4022 }
4023}
4024
4025static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
4026 const ArgList &Args, ArgStringList &CmdArgs) {
4027 // -fbuiltin is default unless -mkernel is used.
4028 bool UseBuiltins =
4029 Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
4030 !Args.hasArg(options::OPT_mkernel));
4031 if (!UseBuiltins)
4032 CmdArgs.push_back("-fno-builtin");
4033
4034 // -ffreestanding implies -fno-builtin.
4035 if (Args.hasArg(options::OPT_ffreestanding))
4036 UseBuiltins = false;
4037
4038 // Process the -fno-builtin-* options.
4039 for (const Arg *A : Args.filtered(options::OPT_fno_builtin_)) {
4040 A->claim();
4041
4042 // If -fno-builtin is specified, then there's no need to pass the option to
4043 // the frontend.
4044 if (UseBuiltins)
4045 A->render(Args, CmdArgs);
4046 }
4047}
4048
4050 if (const char *Str = std::getenv("CLANG_MODULE_CACHE_PATH")) {
4051 Twine Path{Str};
4052 Path.toVector(Result);
4053 return Path.getSingleStringRef() != "";
4054 }
4055 if (llvm::sys::path::cache_directory(Result)) {
4056 llvm::sys::path::append(Result, "clang");
4057 llvm::sys::path::append(Result, "ModuleCache");
4058 return true;
4059 }
4060 return false;
4061}
4062
4065 const char *BaseInput) {
4066 if (Arg *ModuleOutputEQ = Args.getLastArg(options::OPT_fmodule_output_EQ))
4067 return StringRef(ModuleOutputEQ->getValue());
4068
4069 SmallString<256> OutputPath;
4070 if (Arg *FinalOutput = Args.getLastArg(options::OPT_o);
4071 FinalOutput && Args.hasArg(options::OPT_c))
4072 OutputPath = FinalOutput->getValue();
4073 else
4074 OutputPath = BaseInput;
4075
4076 const char *Extension = types::getTypeTempSuffix(types::TY_ModuleFile);
4077 llvm::sys::path::replace_extension(OutputPath, Extension);
4078 return OutputPath;
4079}
4080
4082 const ArgList &Args, const InputInfo &Input,
4083 const InputInfo &Output, bool HaveStd20,
4084 ArgStringList &CmdArgs) {
4085 bool IsCXX = types::isCXX(Input.getType());
4086 bool HaveStdCXXModules = IsCXX && HaveStd20;
4087 bool HaveModules = HaveStdCXXModules;
4088
4089 // -fmodules enables the use of precompiled modules (off by default).
4090 // Users can pass -fno-cxx-modules to turn off modules support for
4091 // C++/Objective-C++ programs.
4092 bool HaveClangModules = false;
4093 if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
4094 bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
4095 options::OPT_fno_cxx_modules, true);
4096 if (AllowedInCXX || !IsCXX) {
4097 CmdArgs.push_back("-fmodules");
4098 HaveClangModules = true;
4099 }
4100 }
4101
4102 HaveModules |= HaveClangModules;
4103
4104 // -fmodule-maps enables implicit reading of module map files. By default,
4105 // this is enabled if we are using Clang's flavor of precompiled modules.
4106 if (Args.hasFlag(options::OPT_fimplicit_module_maps,
4107 options::OPT_fno_implicit_module_maps, HaveClangModules))
4108 CmdArgs.push_back("-fimplicit-module-maps");
4109
4110 // -fmodules-decluse checks that modules used are declared so (off by default)
4111 Args.addOptInFlag(CmdArgs, options::OPT_fmodules_decluse,
4112 options::OPT_fno_modules_decluse);
4113
4114 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
4115 // all #included headers are part of modules.
4116 if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
4117 options::OPT_fno_modules_strict_decluse, false))
4118 CmdArgs.push_back("-fmodules-strict-decluse");
4119
4120 Args.addOptOutFlag(CmdArgs, options::OPT_fmodulemap_allow_subdirectory_search,
4121 options::OPT_fno_modulemap_allow_subdirectory_search);
4122
4123 // -fno-implicit-modules turns off implicitly compiling modules on demand.
4124 bool ImplicitModules = false;
4125 if (!Args.hasFlag(options::OPT_fimplicit_modules,
4126 options::OPT_fno_implicit_modules, HaveClangModules)) {
4127 if (HaveModules)
4128 CmdArgs.push_back("-fno-implicit-modules");
4129 } else if (HaveModules) {
4130 ImplicitModules = true;
4131 // -fmodule-cache-path specifies where our implicitly-built module files
4132 // should be written.
4134 if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
4135 Path = A->getValue();
4136
4137 bool HasPath = true;
4138 if (C.isForDiagnostics()) {
4139 // When generating crash reports, we want to emit the modules along with
4140 // the reproduction sources, so we ignore any provided module path.
4141 Path = Output.getFilename();
4142 llvm::sys::path::replace_extension(Path, ".cache");
4143 llvm::sys::path::append(Path, "modules");
4144 } else if (Path.empty()) {
4145 // No module path was provided: use the default.
4147 }
4148
4149 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
4150 // That being said, that failure is unlikely and not caching is harmless.
4151 if (HasPath) {
4152 const char Arg[] = "-fmodules-cache-path=";
4153 Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
4154 CmdArgs.push_back(Args.MakeArgString(Path));
4155 }
4156 }
4157
4158 if (HaveModules) {
4159 if (Args.hasFlag(options::OPT_fprebuilt_implicit_modules,
4160 options::OPT_fno_prebuilt_implicit_modules, false))
4161 CmdArgs.push_back("-fprebuilt-implicit-modules");
4162 if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
4163 options::OPT_fno_modules_validate_input_files_content,
4164 false))
4165 CmdArgs.push_back("-fvalidate-ast-input-files-content");
4166 }
4167
4168 // -fmodule-name specifies the module that is currently being built (or
4169 // used for header checking by -fmodule-maps).
4170 Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
4171
4172 // -fmodule-map-file can be used to specify files containing module
4173 // definitions.
4174 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
4175
4176 // -fbuiltin-module-map can be used to load the clang
4177 // builtin headers modulemap file.
4178 if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
4179 SmallString<128> BuiltinModuleMap(D.ResourceDir);
4180 llvm::sys::path::append(BuiltinModuleMap, "include");
4181 llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
4182 if (llvm::sys::fs::exists(BuiltinModuleMap))
4183 CmdArgs.push_back(
4184 Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
4185 }
4186
4187 // The -fmodule-file=<name>=<file> form specifies the mapping of module
4188 // names to precompiled module files (the module is loaded only if used).
4189 // The -fmodule-file=<file> form can be used to unconditionally load
4190 // precompiled module files (whether used or not).
4191 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
4192 Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
4193
4194 // -fprebuilt-module-path specifies where to load the prebuilt module files.
4195 for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
4196 CmdArgs.push_back(Args.MakeArgString(
4197 std::string("-fprebuilt-module-path=") + A->getValue()));
4198 A->claim();
4199 }
4200 } else
4201 Args.ClaimAllArgs(options::OPT_fmodule_file);
4202
4203 // When building modules and generating crashdumps, we need to dump a module
4204 // dependency VFS alongside the output.
4205 if (HaveClangModules && C.isForDiagnostics()) {
4206 SmallString<128> VFSDir(Output.getFilename());
4207 llvm::sys::path::replace_extension(VFSDir, ".cache");
4208 // Add the cache directory as a temp so the crash diagnostics pick it up.
4209 C.addTempFile(Args.MakeArgString(VFSDir));
4210
4211 llvm::sys::path::append(VFSDir, "vfs");
4212 CmdArgs.push_back("-module-dependency-dir");
4213 CmdArgs.push_back(Args.MakeArgString(VFSDir));
4214 }
4215
4216 if (HaveClangModules)
4217 Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
4218
4219 // Pass through all -fmodules-ignore-macro arguments.
4220 Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
4221 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
4222 Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
4223
4224 if (HaveClangModules) {
4225 Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
4226
4227 if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
4228 if (Args.hasArg(options::OPT_fbuild_session_timestamp))
4229 D.Diag(diag::err_drv_argument_not_allowed_with)
4230 << A->getAsString(Args) << "-fbuild-session-timestamp";
4231
4232 llvm::sys::fs::file_status Status;
4233 if (llvm::sys::fs::status(A->getValue(), Status))
4234 D.Diag(diag::err_drv_no_such_file) << A->getValue();
4235 CmdArgs.push_back(Args.MakeArgString(
4236 "-fbuild-session-timestamp=" +
4237 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4238 Status.getLastModificationTime().time_since_epoch())
4239 .count())));
4240 }
4241
4242 if (Args.getLastArg(
4243 options::OPT_fmodules_validate_once_per_build_session)) {
4244 if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
4245 options::OPT_fbuild_session_file))
4246 D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
4247
4248 Args.AddLastArg(CmdArgs,
4249 options::OPT_fmodules_validate_once_per_build_session);
4250 }
4251
4252 if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
4253 options::OPT_fno_modules_validate_system_headers,
4254 ImplicitModules))
4255 CmdArgs.push_back("-fmodules-validate-system-headers");
4256
4257 Args.AddLastArg(CmdArgs,
4258 options::OPT_fmodules_disable_diagnostic_validation);
4259 } else {
4260 Args.ClaimAllArgs(options::OPT_fbuild_session_timestamp);
4261 Args.ClaimAllArgs(options::OPT_fbuild_session_file);
4262 Args.ClaimAllArgs(options::OPT_fmodules_validate_once_per_build_session);
4263 Args.ClaimAllArgs(options::OPT_fmodules_validate_system_headers);
4264 Args.ClaimAllArgs(options::OPT_fno_modules_validate_system_headers);
4265 Args.ClaimAllArgs(options::OPT_fmodules_disable_diagnostic_validation);
4266 }
4267
4268 // FIXME: We provisionally don't check ODR violations for decls in the global
4269 // module fragment.
4270 CmdArgs.push_back("-fskip-odr-check-in-gmf");
4271
4272 if (Args.hasArg(options::OPT_modules_reduced_bmi) &&
4273 (Input.getType() == driver::types::TY_CXXModule ||
4274 Input.getType() == driver::types::TY_PP_CXXModule)) {
4275 CmdArgs.push_back("-fmodules-reduced-bmi");
4276
4277 if (Args.hasArg(options::OPT_fmodule_output_EQ))
4278 Args.AddLastArg(CmdArgs, options::OPT_fmodule_output_EQ);
4279 else
4280 CmdArgs.push_back(Args.MakeArgString(
4281 "-fmodule-output=" +
4283 }
4284
4285 // Noop if we see '-fmodules-reduced-bmi' with other translation
4286 // units than module units. This is more user friendly to allow end uers to
4287 // enable this feature without asking for help from build systems.
4288 Args.ClaimAllArgs(options::OPT_modules_reduced_bmi);
4289
4290 // We need to include the case the input file is a module file here.
4291 // Since the default compilation model for C++ module interface unit will
4292 // create temporary module file and compile the temporary module file
4293 // to get the object file. Then the `-fmodule-output` flag will be
4294 // brought to the second compilation process. So we have to claim it for
4295 // the case too.
4296 if (Input.getType() == driver::types::TY_CXXModule ||
4297 Input.getType() == driver::types::TY_PP_CXXModule ||
4298 Input.getType() == driver::types::TY_ModuleFile) {
4299 Args.ClaimAllArgs(options::OPT_fmodule_output);
4300 Args.ClaimAllArgs(options::OPT_fmodule_output_EQ);
4301 }
4302
4303 if (Args.hasArg(options::OPT_fmodules_embed_all_files))
4304 CmdArgs.push_back("-fmodules-embed-all-files");
4305
4306 return HaveModules;
4307}
4308
4309static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4310 ArgStringList &CmdArgs) {
4311 // -fsigned-char is default.
4312 if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
4313 options::OPT_fno_signed_char,
4314 options::OPT_funsigned_char,
4315 options::OPT_fno_unsigned_char)) {
4316 if (A->getOption().matches(options::OPT_funsigned_char) ||
4317 A->getOption().matches(options::OPT_fno_signed_char)) {
4318 CmdArgs.push_back("-fno-signed-char");
4319 }
4320 } else if (!isSignedCharDefault(T)) {
4321 CmdArgs.push_back("-fno-signed-char");
4322 }
4323
4324 // The default depends on the language standard.
4325 Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
4326
4327 if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
4328 options::OPT_fno_short_wchar)) {
4329 if (A->getOption().matches(options::OPT_fshort_wchar)) {
4330 CmdArgs.push_back("-fwchar-type=short");
4331 CmdArgs.push_back("-fno-signed-wchar");
4332 } else {
4333 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4334 CmdArgs.push_back("-fwchar-type=int");
4335 if (T.isOSzOS() ||
4336 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4337 CmdArgs.push_back("-fno-signed-wchar");
4338 else
4339 CmdArgs.push_back("-fsigned-wchar");
4340 }
4341 } else if (T.isOSzOS())
4342 CmdArgs.push_back("-fno-signed-wchar");
4343}
4344
4345static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4346 const llvm::Triple &T, const ArgList &Args,
4347 ObjCRuntime &Runtime, bool InferCovariantReturns,
4348 const InputInfo &Input, ArgStringList &CmdArgs) {
4349 const llvm::Triple::ArchType Arch = TC.getArch();
4350
4351 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4352 // is the default. Except for deployment target of 10.5, next runtime is
4353 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4354 if (Runtime.isNonFragile()) {
4355 if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
4356 options::OPT_fno_objc_legacy_dispatch,
4357 Runtime.isLegacyDispatchDefaultForArch(Arch))) {
4358 if (TC.UseObjCMixedDispatch())
4359 CmdArgs.push_back("-fobjc-dispatch-method=mixed");
4360 else
4361 CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
4362 }
4363 }
4364
4365 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4366 // to do Array/Dictionary subscripting by default.
4367 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4368 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4369 CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
4370
4371 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4372 // NOTE: This logic is duplicated in ToolChains.cpp.
4373 if (isObjCAutoRefCount(Args)) {
4374 TC.CheckObjCARC();
4375
4376 CmdArgs.push_back("-fobjc-arc");
4377
4378 // FIXME: It seems like this entire block, and several around it should be
4379 // wrapped in isObjC, but for now we just use it here as this is where it
4380 // was being used previously.
4381 if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
4383 CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
4384 else
4385 CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
4386 }
4387
4388 // Allow the user to enable full exceptions code emission.
4389 // We default off for Objective-C, on for Objective-C++.
4390 if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
4391 options::OPT_fno_objc_arc_exceptions,
4392 /*Default=*/types::isCXX(Input.getType())))
4393 CmdArgs.push_back("-fobjc-arc-exceptions");
4394 }
4395
4396 // Silence warning for full exception code emission options when explicitly
4397 // set to use no ARC.
4398 if (Args.hasArg(options::OPT_fno_objc_arc)) {
4399 Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
4400 Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
4401 }
4402
4403 // Allow the user to control whether messages can be converted to runtime
4404 // functions.
4405 if (types::isObjC(Input.getType())) {
4406 auto *Arg = Args.getLastArg(
4407 options::OPT_fobjc_convert_messages_to_runtime_calls,
4408 options::OPT_fno_objc_convert_messages_to_runtime_calls);
4409 if (Arg &&
4410 Arg->getOption().matches(
4411 options::OPT_fno_objc_convert_messages_to_runtime_calls))
4412 CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
4413 }
4414
4415 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4416 // rewriter.
4417 if (InferCovariantReturns)
4418 CmdArgs.push_back("-fno-objc-infer-related-result-type");
4419
4420 // Pass down -fobjc-weak or -fno-objc-weak if present.
4421 if (types::isObjC(Input.getType())) {
4422 auto WeakArg =
4423 Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
4424 if (!WeakArg) {
4425 // nothing to do
4426 } else if (!Runtime.allowsWeak()) {
4427 if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
4428 D.Diag(diag::err_objc_weak_unsupported);
4429 } else {
4430 WeakArg->render(Args, CmdArgs);
4431 }
4432 }
4433
4434 if (Args.hasArg(options::OPT_fobjc_disable_direct_methods_for_testing))
4435 CmdArgs.push_back("-fobjc-disable-direct-methods-for-testing");
4436}
4437
4438static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4439 ArgStringList &CmdArgs) {
4440 bool CaretDefault = true;
4441 bool ColumnDefault = true;
4442
4443 if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
4444 options::OPT__SLASH_diagnostics_column,
4445 options::OPT__SLASH_diagnostics_caret)) {
4446 switch (A->getOption().getID()) {
4447 case options::OPT__SLASH_diagnostics_caret:
4448 CaretDefault = true;
4449 ColumnDefault = true;
4450 break;
4451 case options::OPT__SLASH_diagnostics_column:
4452 CaretDefault = false;
4453 ColumnDefault = true;
4454 break;
4455 case options::OPT__SLASH_diagnostics_classic:
4456 CaretDefault = false;
4457 ColumnDefault = false;
4458 break;
4459 }
4460 }
4461
4462 // -fcaret-diagnostics is default.
4463 if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
4464 options::OPT_fno_caret_diagnostics, CaretDefault))
4465 CmdArgs.push_back("-fno-caret-diagnostics");
4466
4467 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_fixit_info,
4468 options::OPT_fno_diagnostics_fixit_info);
4469 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_option,
4470 options::OPT_fno_diagnostics_show_option);
4471
4472 if (const Arg *A =
4473 Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
4474 CmdArgs.push_back("-fdiagnostics-show-category");
4475 CmdArgs.push_back(A->getValue());
4476 }
4477
4478 Args.addOptInFlag(CmdArgs, options::OPT_fdiagnostics_show_hotness,
4479 options::OPT_fno_diagnostics_show_hotness);
4480
4481 if (const Arg *A =
4482 Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4483 std::string Opt =
4484 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4485 CmdArgs.push_back(Args.MakeArgString(Opt));
4486 }
4487
4488 if (const Arg *A =
4489 Args.getLastArg(options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4490 std::string Opt =
4491 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4492 CmdArgs.push_back(Args.MakeArgString(Opt));
4493 }
4494
4495 if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
4496 CmdArgs.push_back("-fdiagnostics-format");
4497 CmdArgs.push_back(A->getValue());
4498 if (StringRef(A->getValue()) == "sarif" ||
4499 StringRef(A->getValue()) == "SARIF")
4500 D.Diag(diag::warn_drv_sarif_format_unstable);
4501 }
4502
4503 if (const Arg *A = Args.getLastArg(
4504 options::OPT_fdiagnostics_show_note_include_stack,
4505 options::OPT_fno_diagnostics_show_note_include_stack)) {
4506 const Option &O = A->getOption();
4507 if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
4508 CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
4509 else
4510 CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
4511 }
4512
4513 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4514
4515 if (Args.hasArg(options::OPT_fansi_escape_codes))
4516 CmdArgs.push_back("-fansi-escape-codes");
4517
4518 Args.addOptOutFlag(CmdArgs, options::OPT_fshow_source_location,
4519 options::OPT_fno_show_source_location);
4520
4521 Args.addOptOutFlag(CmdArgs, options::OPT_fdiagnostics_show_line_numbers,
4522 options::OPT_fno_diagnostics_show_line_numbers);
4523
4524 if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
4525 CmdArgs.push_back("-fdiagnostics-absolute-paths");
4526
4527 if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
4528 ColumnDefault))
4529 CmdArgs.push_back("-fno-show-column");
4530
4531 Args.addOptOutFlag(CmdArgs, options::OPT_fspell_checking,
4532 options::OPT_fno_spell_checking);
4533
4534 Args.addLastArg(CmdArgs, options::OPT_warning_suppression_mappings_EQ);
4535}
4536
4538 const ArgList &Args, Arg *&Arg) {
4539 Arg = Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ,
4540 options::OPT_gno_split_dwarf);
4541 if (!Arg || Arg->getOption().matches(options::OPT_gno_split_dwarf))
4543
4544 if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
4546
4547 StringRef Value = Arg->getValue();
4548 if (Value == "split")
4550 if (Value == "single")
4552
4553 D.Diag(diag::err_drv_unsupported_option_argument)
4554 << Arg->getSpelling() << Arg->getValue();
4556}
4557
4558static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4559 const ArgList &Args, ArgStringList &CmdArgs,
4560 unsigned DwarfVersion) {
4561 auto *DwarfFormatArg =
4562 Args.getLastArg(options::OPT_gdwarf64, options::OPT_gdwarf32);
4563 if (!DwarfFormatArg)
4564 return;
4565
4566 if (DwarfFormatArg->getOption().matches(options::OPT_gdwarf64)) {
4567 if (DwarfVersion < 3)
4568 D.Diag(diag::err_drv_argument_only_allowed_with)
4569 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4570 else if (!T.isArch64Bit())
4571 D.Diag(diag::err_drv_argument_only_allowed_with)
4572 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4573 else if (!T.isOSBinFormatELF())
4574 D.Diag(diag::err_drv_argument_only_allowed_with)
4575 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4576 }
4577
4578 DwarfFormatArg->render(Args, CmdArgs);
4579}
4580
4581static void
4582renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4583 const ArgList &Args, bool IRInput, ArgStringList &CmdArgs,
4584 const InputInfo &Output,
4585 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4586 DwarfFissionKind &DwarfFission) {
4587 if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
4588 options::OPT_fno_debug_info_for_profiling, false) &&
4590 Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
4591 CmdArgs.push_back("-fdebug-info-for-profiling");
4592
4593 // The 'g' groups options involve a somewhat intricate sequence of decisions
4594 // about what to pass from the driver to the frontend, but by the time they
4595 // reach cc1 they've been factored into three well-defined orthogonal choices:
4596 // * what level of debug info to generate
4597 // * what dwarf version to write
4598 // * what debugger tuning to use
4599 // This avoids having to monkey around further in cc1 other than to disable
4600 // codeview if not running in a Windows environment. Perhaps even that
4601 // decision should be made in the driver as well though.
4602 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4603
4604 bool SplitDWARFInlining =
4605 Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
4606 options::OPT_fno_split_dwarf_inlining, false);
4607
4608 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4609 // object file generation and no IR generation, -gN should not be needed. So
4610 // allow -gsplit-dwarf with either -gN or IR input.
4611 if (IRInput || Args.hasArg(options::OPT_g_Group)) {
4612 Arg *SplitDWARFArg;
4613 DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
4614 if (DwarfFission != DwarfFissionKind::None &&
4615 !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
4616 DwarfFission = DwarfFissionKind::None;
4617 SplitDWARFInlining = false;
4618 }
4619 }
4620 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
4621 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4622
4623 // If the last option explicitly specified a debug-info level, use it.
4624 if (checkDebugInfoOption(A, Args, D, TC) &&
4625 A->getOption().matches(options::OPT_gN_Group)) {
4626 DebugInfoKind = debugLevelToInfoKind(*A);
4627 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4628 // complicated if you've disabled inline info in the skeleton CUs
4629 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4630 // line-tables-only, so let those compose naturally in that case.
4631 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4632 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4633 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4634 SplitDWARFInlining))
4635 DwarfFission = DwarfFissionKind::None;
4636 }
4637 }
4638
4639 // If a debugger tuning argument appeared, remember it.
4640 bool HasDebuggerTuning = false;
4641 if (const Arg *A =
4642 Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
4643 HasDebuggerTuning = true;
4644 if (checkDebugInfoOption(A, Args, D, TC)) {
4645 if (A->getOption().matches(options::OPT_glldb))
4646 DebuggerTuning = llvm::DebuggerKind::LLDB;
4647 else if (A->getOption().matches(options::OPT_gsce))
4648 DebuggerTuning = llvm::DebuggerKind::SCE;
4649 else if (A->getOption().matches(options::OPT_gdbx))
4650 DebuggerTuning = llvm::DebuggerKind::DBX;
4651 else
4652 DebuggerTuning = llvm::DebuggerKind::GDB;
4653 }
4654 }
4655
4656 // If a -gdwarf argument appeared, remember it.
4657 bool EmitDwarf = false;
4658 if (const Arg *A = getDwarfNArg(Args))
4659 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4660
4661 bool EmitCodeView = false;
4662 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
4663 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4664
4665 // If the user asked for debug info but did not explicitly specify -gcodeview
4666 // or -gdwarf, ask the toolchain for the default format.
4667 if (!EmitCodeView && !EmitDwarf &&
4668 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4669 switch (TC.getDefaultDebugFormat()) {
4670 case llvm::codegenoptions::DIF_CodeView:
4671 EmitCodeView = true;
4672 break;
4673 case llvm::codegenoptions::DIF_DWARF:
4674 EmitDwarf = true;
4675 break;
4676 }
4677 }
4678
4679 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4680 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4681 // be lower than what the user wanted.
4682 if (EmitDwarf) {
4683 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4684 // Clamp effective DWARF version to the max supported by the toolchain.
4685 EffectiveDWARFVersion =
4686 std::min(RequestedDWARFVersion, TC.getMaxDwarfVersion());
4687 } else {
4688 Args.ClaimAllArgs(options::OPT_fdebug_default_version);
4689 }
4690
4691 // -gline-directives-only supported only for the DWARF debug info.
4692 if (RequestedDWARFVersion == 0 &&
4693 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4694 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4695
4696 // strict DWARF is set to false by default. But for DBX, we need it to be set
4697 // as true by default.
4698 if (const Arg *A = Args.getLastArg(options::OPT_gstrict_dwarf))
4699 (void)checkDebugInfoOption(A, Args, D, TC);
4700 if (Args.hasFlag(options::OPT_gstrict_dwarf, options::OPT_gno_strict_dwarf,
4701 DebuggerTuning == llvm::DebuggerKind::DBX))
4702 CmdArgs.push_back("-gstrict-dwarf");
4703
4704 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4705 Args.ClaimAllArgs(options::OPT_g_flags_Group);
4706
4707 // Column info is included by default for everything except SCE and
4708 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4709 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4710 // practice, however, the Microsoft debuggers don't handle missing end columns
4711 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4712 // it's better not to include any column info.
4713 if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
4714 (void)checkDebugInfoOption(A, Args, D, TC);
4715 if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
4716 !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4717 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4718 DebuggerTuning != llvm::DebuggerKind::DBX)))
4719 CmdArgs.push_back("-gno-column-info");
4720
4721 // FIXME: Move backend command line options to the module.
4722 if (Args.hasFlag(options::OPT_gmodules, options::OPT_gno_modules, false)) {
4723 // If -gline-tables-only or -gline-directives-only is the last option it
4724 // wins.
4725 if (checkDebugInfoOption(Args.getLastArg(options::OPT_gmodules), Args, D,
4726 TC)) {
4727 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4728 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4729 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4730 CmdArgs.push_back("-dwarf-ext-refs");
4731 CmdArgs.push_back("-fmodule-format=obj");
4732 }
4733 }
4734 }
4735
4736 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4737 CmdArgs.push_back("-fsplit-dwarf-inlining");
4738
4739 // After we've dealt with all combinations of things that could
4740 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4741 // figure out if we need to "upgrade" it to standalone debug info.
4742 // We parse these two '-f' options whether or not they will be used,
4743 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4744 bool NeedFullDebug = Args.hasFlag(
4745 options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
4746 DebuggerTuning == llvm::DebuggerKind::LLDB ||
4748 if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
4749 (void)checkDebugInfoOption(A, Args, D, TC);
4750
4751 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4752 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4753 if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
4754 options::OPT_feliminate_unused_debug_types, false))
4755 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4756 else if (NeedFullDebug)
4757 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4758 }
4759
4760 if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
4761 false)) {
4762 // Source embedding is a vendor extension to DWARF v5. By now we have
4763 // checked if a DWARF version was stated explicitly, and have otherwise
4764 // fallen back to the target default, so if this is still not at least 5
4765 // we emit an error.
4766 const Arg *A = Args.getLastArg(options::OPT_gembed_source);
4767 if (RequestedDWARFVersion < 5)
4768 D.Diag(diag::err_drv_argument_only_allowed_with)
4769 << A->getAsString(Args) << "-gdwarf-5";
4770 else if (EffectiveDWARFVersion < 5)
4771 // The toolchain has reduced allowed dwarf version, so we can't enable
4772 // -gembed-source.
4773 D.Diag(diag::warn_drv_dwarf_version_limited_by_target)
4774 << A->getAsString(Args) << TC.getTripleString() << 5
4775 << EffectiveDWARFVersion;
4776 else if (checkDebugInfoOption(A, Args, D, TC))
4777 CmdArgs.push_back("-gembed-source");
4778 }
4779
4780 if (EmitCodeView) {
4781 CmdArgs.push_back("-gcodeview");
4782
4783 Args.addOptInFlag(CmdArgs, options::OPT_gcodeview_ghash,
4784 options::OPT_gno_codeview_ghash);
4785
4786 Args.addOptOutFlag(CmdArgs, options::OPT_gcodeview_command_line,
4787 options::OPT_gno_codeview_command_line);
4788 }
4789
4790 Args.addOptOutFlag(CmdArgs, options::OPT_ginline_line_tables,
4791 options::OPT_gno_inline_line_tables);
4792
4793 // When emitting remarks, we need at least debug lines in the output.
4794 if (willEmitRemarks(Args) &&
4795 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4796 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4797
4798 // Adjust the debug info kind for the given toolchain.
4799 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4800
4801 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4802 // set.
4803 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, EffectiveDWARFVersion,
4804 T.isOSAIX() && !HasDebuggerTuning
4805 ? llvm::DebuggerKind::Default
4806 : DebuggerTuning);
4807
4808 // -fdebug-macro turns on macro debug info generation.
4809 if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
4810 false))
4811 if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
4812 D, TC))
4813 CmdArgs.push_back("-debug-info-macro");
4814
4815 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4816 const auto *PubnamesArg =
4817 Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
4818 options::OPT_gpubnames, options::OPT_gno_pubnames);
4819 if (DwarfFission != DwarfFissionKind::None ||
4820 (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC))) {
4821 const bool OptionSet =
4822 (PubnamesArg &&
4823 (PubnamesArg->getOption().matches(options::OPT_gpubnames) ||
4824 PubnamesArg->getOption().matches(options::OPT_ggnu_pubnames)));
4825 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
4826 (!PubnamesArg ||
4827 (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
4828 !PubnamesArg->getOption().matches(options::OPT_gno_pubnames))))
4829 CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
4830 options::OPT_gpubnames)
4831 ? "-gpubnames"
4832 : "-ggnu-pubnames");
4833 }
4834 const auto *SimpleTemplateNamesArg =
4835 Args.getLastArg(options::OPT_gsimple_template_names,
4836 options::OPT_gno_simple_template_names);
4837 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4838 if (SimpleTemplateNamesArg &&
4839 checkDebugInfoOption(SimpleTemplateNamesArg, Args, D, TC)) {
4840 const auto &Opt = SimpleTemplateNamesArg->getOption();
4841 if (Opt.matches(options::OPT_gsimple_template_names)) {
4842 ForwardTemplateParams = true;
4843 CmdArgs.push_back("-gsimple-template-names=simple");
4844 }
4845 }
4846
4847 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
4848 bool UseDebugTemplateAlias =
4849 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
4850 if (const auto *DebugTemplateAlias = Args.getLastArg(
4851 options::OPT_gtemplate_alias, options::OPT_gno_template_alias)) {
4852 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
4853 // asks for it we should let them have it (if the target supports it).
4854 if (checkDebugInfoOption(DebugTemplateAlias, Args, D, TC)) {
4855 const auto &Opt = DebugTemplateAlias->getOption();
4856 UseDebugTemplateAlias = Opt.matches(options::OPT_gtemplate_alias);
4857 }
4858 }
4859 if (UseDebugTemplateAlias)
4860 CmdArgs.push_back("-gtemplate-alias");
4861
4862 if (const Arg *A = Args.getLastArg(options::OPT_gsrc_hash_EQ)) {
4863 StringRef v = A->getValue();
4864 CmdArgs.push_back(Args.MakeArgString("-gsrc-hash=" + v));
4865 }
4866
4867 Args.addOptInFlag(CmdArgs, options::OPT_fdebug_ranges_base_address,
4868 options::OPT_fno_debug_ranges_base_address);
4869
4870 // -gdwarf-aranges turns on the emission of the aranges section in the
4871 // backend.
4872 if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges);
4873 A && checkDebugInfoOption(A, Args, D, TC)) {
4874 CmdArgs.push_back("-mllvm");
4875 CmdArgs.push_back("-generate-arange-section");
4876 }
4877
4878 Args.addOptInFlag(CmdArgs, options::OPT_fforce_dwarf_frame,
4879 options::OPT_fno_force_dwarf_frame);
4880
4881 bool EnableTypeUnits = false;
4882 if (Args.hasFlag(options::OPT_fdebug_types_section,
4883 options::OPT_fno_debug_types_section, false)) {
4884 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4885 D.Diag(diag::err_drv_unsupported_opt_for_target)
4886 << Args.getLastArg(options::OPT_fdebug_types_section)
4887 ->getAsString(Args)
4888 << T.getTriple();
4889 } else if (checkDebugInfoOption(
4890 Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
4891 TC)) {
4892 EnableTypeUnits = true;
4893 CmdArgs.push_back("-mllvm");
4894 CmdArgs.push_back("-generate-type-units");
4895 }
4896 }
4897
4898 if (const Arg *A =
4899 Args.getLastArg(options::OPT_gomit_unreferenced_methods,
4900 options::OPT_gno_omit_unreferenced_methods))
4901 (void)checkDebugInfoOption(A, Args, D, TC);
4902 if (Args.hasFlag(options::OPT_gomit_unreferenced_methods,
4903 options::OPT_gno_omit_unreferenced_methods, false) &&
4904 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
4905 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
4906 !EnableTypeUnits) {
4907 CmdArgs.push_back("-gomit-unreferenced-methods");
4908 }
4909
4910 // To avoid join/split of directory+filename, the integrated assembler prefers
4911 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4912 // form before DWARF v5.
4913 if (!Args.hasFlag(options::OPT_fdwarf_directory_asm,
4914 options::OPT_fno_dwarf_directory_asm,
4915 TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4916 CmdArgs.push_back("-fno-dwarf-directory-asm");
4917
4918 // Decide how to render forward declarations of template instantiations.
4919 // SCE wants full descriptions, others just get them in the name.
4920 if (ForwardTemplateParams)
4921 CmdArgs.push_back("-debug-forward-template-params");
4922
4923 // Do we need to explicitly import anonymous namespaces into the parent
4924 // scope?
4925 if (DebuggerTuning == llvm::DebuggerKind::SCE)
4926 CmdArgs.push_back("-dwarf-explicit-import");
4927
4928 renderDwarfFormat(D, T, Args, CmdArgs, EffectiveDWARFVersion);
4929 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4930
4931 // This controls whether or not we perform JustMyCode instrumentation.
4932 if (Args.hasFlag(options::OPT_fjmc, options::OPT_fno_jmc, false)) {
4933 if (TC.getTriple().isOSBinFormatELF() ||
4934 TC.getTriple().isWindowsMSVCEnvironment()) {
4935 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
4936 CmdArgs.push_back("-fjmc");
4937 else if (D.IsCLMode())
4938 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
4939 << "'/Zi', '/Z7'";
4940 else
4941 D.Diag(clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
4942 << "-g";
4943 } else {
4944 D.Diag(clang::diag::warn_drv_fjmc_for_elf_only);
4945 }
4946 }
4947
4948 // Add in -fdebug-compilation-dir if necessary.
4949 const char *DebugCompilationDir =
4950 addDebugCompDirArg(Args, CmdArgs, D.getVFS());
4951
4952 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
4953
4954 // Add the output path to the object file for CodeView debug infos.
4955 if (EmitCodeView && Output.isFilename())
4956 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
4957 Output.getFilename());
4958}
4959
4960static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
4961 ArgStringList &CmdArgs) {
4962 unsigned RTOptionID = options::OPT__SLASH_MT;
4963
4964 if (Args.hasArg(options::OPT__SLASH_LDd))
4965 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4966 // but defining _DEBUG is sticky.
4967 RTOptionID = options::OPT__SLASH_MTd;
4968
4969 if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
4970 RTOptionID = A->getOption().getID();
4971
4972 if (Arg *A = Args.getLastArg(options::OPT_fms_runtime_lib_EQ)) {
4973 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4974 .Case("static", options::OPT__SLASH_MT)
4975 .Case("static_dbg", options::OPT__SLASH_MTd)
4976 .Case("dll", options::OPT__SLASH_MD)
4977 .Case("dll_dbg", options::OPT__SLASH_MDd)
4978 .Default(options::OPT__SLASH_MT);
4979 }
4980
4981 StringRef FlagForCRT;
4982 switch (RTOptionID) {
4983 case options::OPT__SLASH_MD:
4984 if (Args.hasArg(options::OPT__SLASH_LDd))
4985 CmdArgs.push_back("-D_DEBUG");
4986 CmdArgs.push_back("-D_MT");
4987 CmdArgs.push_back("-D_DLL");
4988 FlagForCRT = "--dependent-lib=msvcrt";
4989 break;
4990 case options::OPT__SLASH_MDd:
4991 CmdArgs.push_back("-D_DEBUG");
4992 CmdArgs.push_back("-D_MT");
4993 CmdArgs.push_back("-D_DLL");
4994 FlagForCRT = "--dependent-lib=msvcrtd";
4995 break;
4996 case options::OPT__SLASH_MT:
4997 if (Args.hasArg(options::OPT__SLASH_LDd))
4998 CmdArgs.push_back("-D_DEBUG");
4999 CmdArgs.push_back("-D_MT");
5000 CmdArgs.push_back("-flto-visibility-public-std");
5001 FlagForCRT = "--dependent-lib=libcmt";
5002 break;
5003 case options::OPT__SLASH_MTd:
5004 CmdArgs.push_back("-D_DEBUG");
5005 CmdArgs.push_back("-D_MT");
5006 CmdArgs.push_back("-flto-visibility-public-std");
5007 FlagForCRT = "--dependent-lib=libcmtd";
5008 break;
5009 default:
5010 llvm_unreachable("Unexpected option ID.");
5011 }
5012
5013 if (Args.hasArg(options::OPT_fms_omit_default_lib)) {
5014 CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5015 } else {
5016 CmdArgs.push_back(FlagForCRT.data());
5017
5018 // This provides POSIX compatibility (maps 'open' to '_open'), which most
5019 // users want. The /Za flag to cl.exe turns this off, but it's not
5020 // implemented in clang.
5021 CmdArgs.push_back("--dependent-lib=oldnames");
5022 }
5023
5024 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
5025 // even if the file doesn't actually refer to any of the routines because
5026 // the CRT itself has incomplete dependency markings.
5027 if (TC.getTriple().isWindowsArm64EC())
5028 CmdArgs.push_back("--dependent-lib=softintrin");
5029}
5030
5032 const InputInfo &Output, const InputInfoList &Inputs,
5033 const ArgList &Args, const char *LinkingOutput) const {
5034 const auto &TC = getToolChain();
5035 const llvm::Triple &RawTriple = TC.getTriple();
5036 const llvm::Triple &Triple = TC.getEffectiveTriple();
5037 const std::string &TripleStr = Triple.getTriple();
5038
5039 bool KernelOrKext =
5040 Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
5041 const Driver &D = TC.getDriver();
5042 ArgStringList CmdArgs;
5043
5044 assert(Inputs.size() >= 1 && "Must have at least one input.");
5045 // CUDA/HIP compilation may have multiple inputs (source file + results of
5046 // device-side compilations). OpenMP device jobs also take the host IR as a
5047 // second input. Module precompilation accepts a list of header files to
5048 // include as part of the module. API extraction accepts a list of header
5049 // files whose API information is emitted in the output. All other jobs are
5050 // expected to have exactly one input. SYCL compilation only expects a
5051 // single input.
5052 bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
5053 bool IsCudaDevice = JA.isDeviceOffloading(Action::OFK_Cuda);
5054 bool IsHIP = JA.isOffloading(Action::OFK_HIP);
5055 bool IsHIPDevice = JA.isDeviceOffloading(Action::OFK_HIP);
5056 bool IsSYCL = JA.isOffloading(Action::OFK_SYCL);
5057 bool IsSYCLDevice = JA.isDeviceOffloading(Action::OFK_SYCL);
5058 bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
5059 bool IsExtractAPI = isa<ExtractAPIJobAction>(JA);
5060 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
5062 bool IsHostOffloadingAction =
5065 (JA.isHostOffloading(C.getActiveOffloadKinds()) &&
5066 Args.hasFlag(options::OPT_offload_new_driver,
5067 options::OPT_no_offload_new_driver, false));
5068
5069 bool IsRDCMode =
5070 Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false);
5071
5072 auto LTOMode = IsDeviceOffloadAction ? D.getOffloadLTOMode() : D.getLTOMode();
5073 bool IsUsingLTO = LTOMode != LTOK_None;
5074
5075 // Extract API doesn't have a main input file, so invent a fake one as a
5076 // placeholder.
5077 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
5078 "extract-api");
5079
5080 const InputInfo &Input =
5081 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
5082
5083 InputInfoList ExtractAPIInputs;
5084 InputInfoList HostOffloadingInputs;
5085 const InputInfo *CudaDeviceInput = nullptr;
5086 const InputInfo *OpenMPDeviceInput = nullptr;
5087 for (const InputInfo &I : Inputs) {
5088 if (&I == &Input || I.getType() == types::TY_Nothing) {
5089 // This is the primary input or contains nothing.
5090 } else if (IsExtractAPI) {
5091 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
5092 if (I.getType() != ExpectedInputType) {
5093 D.Diag(diag::err_drv_extract_api_wrong_kind)
5094 << I.getFilename() << types::getTypeName(I.getType())
5095 << types::getTypeName(ExpectedInputType);
5096 }
5097 ExtractAPIInputs.push_back(I);
5098 } else if (IsHostOffloadingAction) {
5099 HostOffloadingInputs.push_back(I);
5100 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
5101 CudaDeviceInput = &I;
5102 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
5103 OpenMPDeviceInput = &I;
5104 } else {
5105 llvm_unreachable("unexpectedly given multiple inputs");
5106 }
5107 }
5108
5109 const llvm::Triple *AuxTriple =
5110 (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
5111 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
5112 bool IsIAMCU = RawTriple.isOSIAMCU();
5113
5114 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling in
5115 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
5116 // Windows), we need to pass Windows-specific flags to cc1.
5117 if (IsCuda || IsHIP || IsSYCL)
5118 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
5119
5120 // C++ is not supported for IAMCU.
5121 if (IsIAMCU && types::isCXX(Input.getType()))
5122 D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
5123
5124 // Invoke ourselves in -cc1 mode.
5125 //
5126 // FIXME: Implement custom jobs for internal actions.
5127 CmdArgs.push_back("-cc1");
5128
5129 // Add the "effective" target triple.
5130 CmdArgs.push_back("-triple");
5131 CmdArgs.push_back(Args.MakeArgString(TripleStr));
5132
5133 if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
5134 DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
5135 Args.ClaimAllArgs(options::OPT_MJ);
5136 } else if (const Arg *GenCDBFragment =
5137 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
5138 DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
5139 TripleStr, Output, Input, Args);
5140 Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
5141 }
5142
5143 if (IsCuda || IsHIP) {
5144 // We have to pass the triple of the host if compiling for a CUDA/HIP device
5145 // and vice-versa.
5146 std::string NormalizedTriple;
5149 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
5150 ->getTriple()
5151 .normalize();
5152 else {
5153 // Host-side compilation.
5154 NormalizedTriple =
5155 (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
5156 : C.getSingleOffloadToolChain<Action::OFK_HIP>())
5157 ->getTriple()
5158 .normalize();
5159 if (IsCuda) {
5160 // We need to figure out which CUDA version we're compiling for, as that
5161 // determines how we load and launch GPU kernels.
5162 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5163 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5164 assert(CTC && "Expected valid CUDA Toolchain.");
5165 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5166 CmdArgs.push_back(Args.MakeArgString(
5167 Twine("-target-sdk-version=") +
5168 CudaVersionToString(CTC->CudaInstallation.version())));
5169 // Unsized function arguments used for variadics were introduced in
5170 // CUDA-9.0. We still do not support generating code that actually uses
5171 // variadic arguments yet, but we do need to allow parsing them as
5172 // recent CUDA headers rely on that.
5173 // https://github.com/llvm/llvm-project/issues/58410
5174 if (CTC->CudaInstallation.version() >= CudaVersion::CUDA_90)
5175 CmdArgs.push_back("-fcuda-allow-variadic-functions");
5176 }
5177 }
5178 CmdArgs.push_back("-aux-triple");
5179 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
5180
5182 (getToolChain().getTriple().isAMDGPU() ||
5183 (getToolChain().getTriple().isSPIRV() &&
5184 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5185 // Device side compilation printf
5186 if (Args.getLastArg(options::OPT_mprintf_kind_EQ)) {
5187 CmdArgs.push_back(Args.MakeArgString(
5188 "-mprintf-kind=" +
5189 Args.getLastArgValue(options::OPT_mprintf_kind_EQ)));
5190 // Force compiler error on invalid conversion specifiers
5191 CmdArgs.push_back(
5192 Args.MakeArgString("-Werror=format-invalid-specifier"));
5193 }
5194 }
5195 }
5196
5197 // Unconditionally claim the printf option now to avoid unused diagnostic.
5198 if (const Arg *PF = Args.getLastArg(options::OPT_mprintf_kind_EQ))
5199 PF->claim();
5200
5201 if (IsSYCL) {
5202 if (IsSYCLDevice) {
5203 // Host triple is needed when doing SYCL device compilations.
5204 llvm::Triple AuxT = C.getDefaultToolChain().getTriple();
5205 std::string NormalizedTriple = AuxT.normalize();
5206 CmdArgs.push_back("-aux-triple");
5207 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
5208
5209 // We want to compile sycl kernels.
5210 CmdArgs.push_back("-fsycl-is-device");
5211
5212 // Set O2 optimization level by default
5213 if (!Args.getLastArg(options::OPT_O_Group))
5214 CmdArgs.push_back("-O2");
5215 } else {
5216 // Add any options that are needed specific to SYCL offload while
5217 // performing the host side compilation.
5218
5219 // Let the front-end host compilation flow know about SYCL offload
5220 // compilation.
5221 CmdArgs.push_back("-fsycl-is-host");
5222 }
5223
5224 // Set options for both host and device.
5225 Arg *SYCLStdArg = Args.getLastArg(options::OPT_sycl_std_EQ);
5226 if (SYCLStdArg) {
5227 SYCLStdArg->render(Args, CmdArgs);
5228 } else {
5229 // Ensure the default version in SYCL mode is 2020.
5230 CmdArgs.push_back("-sycl-std=2020");
5231 }
5232 }
5233
5234 if (Args.hasArg(options::OPT_fclangir))
5235 CmdArgs.push_back("-fclangir");
5236
5237 if (IsOpenMPDevice) {
5238 // We have to pass the triple of the host if compiling for an OpenMP device.
5239 std::string NormalizedTriple =
5240 C.getSingleOffloadToolChain<Action::OFK_Host>()
5241 ->getTriple()
5242 .normalize();
5243 CmdArgs.push_back("-aux-triple");
5244 CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
5245 }
5246
5247 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5248 Triple.getArch() == llvm::Triple::thumb)) {
5249 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5250 unsigned Version = 0;
5251 bool Failure =
5252 Triple.getArchName().substr(Offset).consumeInteger(10, Version);
5253 if (Failure || Version < 7)
5254 D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
5255 << TripleStr;
5256 }
5257
5258 // Push all default warning arguments that are specific to
5259 // the given target. These come before user provided warning options
5260 // are provided.
5261 TC.addClangWarningOptions(CmdArgs);
5262
5263 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5264 if (Triple.isSPIR() || Triple.isSPIRV())
5265 CmdArgs.push_back("-Wspir-compat");
5266
5267 // Select the appropriate action.
5268 RewriteKind rewriteKind = RK_None;
5269
5270 bool UnifiedLTO = false;
5271 if (IsUsingLTO) {
5272 UnifiedLTO = Args.hasFlag(options::OPT_funified_lto,
5273 options::OPT_fno_unified_lto, Triple.isPS());
5274 if (UnifiedLTO)
5275 CmdArgs.push_back("-funified-lto");
5276 }
5277
5278 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5279 // it claims when not running an assembler. Otherwise, clang would emit
5280 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5281 // flags while debugging something. That'd be somewhat inconvenient, and it's
5282 // also inconsistent with most other flags -- we don't warn on
5283 // -ffunction-sections not being used in -E mode either for example, even
5284 // though it's not really used either.
5285 if (!isa<AssembleJobAction>(JA)) {
5286 // The args claimed here should match the args used in
5287 // CollectArgsForIntegratedAssembler().
5288 if (TC.useIntegratedAs()) {
5289 Args.ClaimAllArgs(options::OPT_mrelax_all);
5290 Args.ClaimAllArgs(options::OPT_mno_relax_all);
5291 Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
5292 Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
5293 switch (C.getDefaultToolChain().getArch()) {
5294 case llvm::Triple::arm:
5295 case llvm::Triple::armeb:
5296 case llvm::Triple::thumb:
5297 case llvm::Triple::thumbeb:
5298 Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
5299 break;
5300 default:
5301 break;
5302 }
5303 }
5304 Args.ClaimAllArgs(options::OPT_Wa_COMMA);
5305 Args.ClaimAllArgs(options::OPT_Xassembler);
5306 Args.ClaimAllArgs(options::OPT_femit_dwarf_unwind_EQ);
5307 }
5308
5309 if (isa<AnalyzeJobAction>(JA)) {
5310 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5311 CmdArgs.push_back("-analyze");
5312 } else if (isa<MigrateJobAction>(JA)) {
5313 CmdArgs.push_back("-migrate");
5314 } else if (isa<PreprocessJobAction>(JA)) {
5315 if (Output.getType() == types::TY_Dependencies)
5316 CmdArgs.push_back("-Eonly");
5317 else {
5318 CmdArgs.push_back("-E");
5319 if (Args.hasArg(options::OPT_rewrite_objc) &&
5320 !Args.hasArg(options::OPT_g_Group))
5321 CmdArgs.push_back("-P");
5322 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5323 CmdArgs.push_back("-fdirectives-only");
5324 }
5325 } else if (isa<AssembleJobAction>(JA)) {
5326 CmdArgs.push_back("-emit-obj");
5327
5328 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5329
5330 // Also ignore explicit -force_cpusubtype_ALL option.
5331 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5332 } else if (isa<PrecompileJobAction>(JA)) {
5333 if (JA.getType() == types::TY_Nothing)
5334 CmdArgs.push_back("-fsyntax-only");
5335 else if (JA.getType() == types::TY_ModuleFile)
5336 CmdArgs.push_back("-emit-module-interface");
5337 else if (JA.getType() == types::TY_HeaderUnit)
5338 CmdArgs.push_back("-emit-header-unit");
5339 else
5340 CmdArgs.push_back("-emit-pch");
5341 } else if (isa<VerifyPCHJobAction>(JA)) {
5342 CmdArgs.push_back("-verify-pch");
5343 } else if (isa<ExtractAPIJobAction>(JA)) {
5344 assert(JA.getType() == types::TY_API_INFO &&
5345 "Extract API actions must generate a API information.");
5346 CmdArgs.push_back("-extract-api");
5347
5348 if (Arg *PrettySGFArg = Args.getLastArg(options::OPT_emit_pretty_sgf))
5349 PrettySGFArg->render(Args, CmdArgs);
5350
5351 Arg *SymbolGraphDirArg = Args.getLastArg(options::OPT_symbol_graph_dir_EQ);
5352
5353 if (Arg *ProductNameArg = Args.getLastArg(options::OPT_product_name_EQ))
5354 ProductNameArg->render(Args, CmdArgs);
5355 if (Arg *ExtractAPIIgnoresFileArg =
5356 Args.getLastArg(options::OPT_extract_api_ignores_EQ))
5357 ExtractAPIIgnoresFileArg->render(Args, CmdArgs);
5358 if (Arg *EmitExtensionSymbolGraphs =
5359 Args.getLastArg(options::OPT_emit_extension_symbol_graphs)) {
5360 if (!SymbolGraphDirArg)
5361 D.Diag(diag::err_drv_missing_symbol_graph_dir);
5362
5363 EmitExtensionSymbolGraphs->render(Args, CmdArgs);
5364 }
5365 if (SymbolGraphDirArg)
5366 SymbolGraphDirArg->render(Args, CmdArgs);
5367 } else {
5368 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5369 "Invalid action for clang tool.");
5370 if (JA.getType() == types::TY_Nothing) {
5371 CmdArgs.push_back("-fsyntax-only");
5372 } else if (JA.getType() == types::TY_LLVM_IR ||
5373 JA.getType() == types::TY_LTO_IR) {
5374 CmdArgs.push_back("-emit-llvm");
5375 } else if (JA.getType() == types::TY_LLVM_BC ||
5376 JA.getType() == types::TY_LTO_BC) {
5377 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5378 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(options::OPT_S) &&
5379 Args.hasArg(options::OPT_emit_llvm)) {
5380 CmdArgs.push_back("-emit-llvm");
5381 } else {
5382 CmdArgs.push_back("-emit-llvm-bc");
5383 }
5384 } else if (JA.getType() == types::TY_IFS ||
5385 JA.getType() == types::TY_IFS_CPP) {
5386 StringRef ArgStr =
5387 Args.hasArg(options::OPT_interface_stub_version_EQ)
5388 ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
5389 : "ifs-v1";
5390 CmdArgs.push_back("-emit-interface-stubs");
5391 CmdArgs.push_back(
5392 Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
5393 } else if (JA.getType() == types::TY_PP_Asm) {
5394 CmdArgs.push_back("-S");
5395 } else if (JA.getType() == types::TY_AST) {
5396 CmdArgs.push_back("-emit-pch");
5397 } else if (JA.getType() == types::TY_ModuleFile) {
5398 CmdArgs.push_back("-module-file-info");
5399 } else if (JA.getType() == types::TY_RewrittenObjC) {
5400 CmdArgs.push_back("-rewrite-objc");
5401 rewriteKind = RK_NonFragile;
5402 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5403 CmdArgs.push_back("-rewrite-objc");
5404 rewriteKind = RK_Fragile;
5405 } else if (JA.getType() == types::TY_CIR) {
5406 CmdArgs.push_back("-emit-cir");
5407 } else {
5408 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5409 }
5410
5411 // Preserve use-list order by default when emitting bitcode, so that
5412 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5413 // same result as running passes here. For LTO, we don't need to preserve
5414 // the use-list order, since serialization to bitcode is part of the flow.
5415 if (JA.getType() == types::TY_LLVM_BC)
5416 CmdArgs.push_back("-emit-llvm-uselists");
5417
5418 if (IsUsingLTO) {
5419 if (IsDeviceOffloadAction && !JA.isDeviceOffloading(Action::OFK_OpenMP) &&
5420 !Args.hasFlag(options::OPT_offload_new_driver,
5421 options::OPT_no_offload_new_driver, false) &&
5422 !Triple.isAMDGPU()) {
5423 D.Diag(diag::err_drv_unsupported_opt_for_target)
5424 << Args.getLastArg(options::OPT_foffload_lto,
5425 options::OPT_foffload_lto_EQ)
5426 ->getAsString(Args)
5427 << Triple.getTriple();
5428 } else if (Triple.isNVPTX() && !IsRDCMode &&
5430 D.Diag(diag::err_drv_unsupported_opt_for_language_mode)
5431 << Args.getLastArg(options::OPT_foffload_lto,
5432 options::OPT_foffload_lto_EQ)
5433 ->getAsString(Args)
5434 << "-fno-gpu-rdc";
5435 } else {
5436 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5437 CmdArgs.push_back(Args.MakeArgString(
5438 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5439 // PS4 uses the legacy LTO API, which does not support some of the
5440 // features enabled by -flto-unit.
5441 if (!RawTriple.isPS4() ||
5442 (D.getLTOMode() == LTOK_Full) || !UnifiedLTO)
5443 CmdArgs.push_back("-flto-unit");
5444 }
5445 }
5446 }
5447
5448 Args.AddLastArg(CmdArgs, options::OPT_dumpdir);
5449
5450 if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
5451 if (!types::isLLVMIR(Input.getType()))
5452 D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5453 Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
5454 }
5455
5456 if (Triple.isPPC())
5457 Args.addOptInFlag(CmdArgs, options::OPT_mregnames,
5458 options::OPT_mno_regnames);
5459
5460 if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
5461 Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
5462
5463 if (Args.getLastArg(options::OPT_save_temps_EQ))
5464 Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
5465
5466 auto *MemProfArg = Args.getLastArg(options::OPT_fmemory_profile,
5467 options::OPT_fmemory_profile_EQ,
5468 options::OPT_fno_memory_profile);
5469 if (MemProfArg &&
5470 !MemProfArg->getOption().matches(options::OPT_fno_memory_profile))
5471 MemProfArg->render(Args, CmdArgs);
5472
5473 if (auto *MemProfUseArg =
5474 Args.getLastArg(options::OPT_fmemory_profile_use_EQ)) {
5475 if (MemProfArg)
5476 D.Diag(diag::err_drv_argument_not_allowed_with)
5477 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5478 if (auto *PGOInstrArg = Args.getLastArg(options::OPT_fprofile_generate,
5479 options::OPT_fprofile_generate_EQ))
5480 D.Diag(diag::err_drv_argument_not_allowed_with)
5481 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5482 MemProfUseArg->render(Args, CmdArgs);
5483 }
5484
5485 // Embed-bitcode option.
5486 // Only white-listed flags below are allowed to be embedded.
5487 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5488 (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
5489 // Add flags implied by -fembed-bitcode.
5490 Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
5491 // Disable all llvm IR level optimizations.
5492 CmdArgs.push_back("-disable-llvm-passes");
5493
5494 // Render target options.
5495 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
5496
5497 // reject options that shouldn't be supported in bitcode
5498 // also reject kernel/kext
5499 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5500 options::OPT_mkernel,
5501 options::OPT_fapple_kext,
5502 options::OPT_ffunction_sections,
5503 options::OPT_fno_function_sections,
5504 options::OPT_fdata_sections,
5505 options::OPT_fno_data_sections,
5506 options::OPT_fbasic_block_sections_EQ,
5507 options::OPT_funique_internal_linkage_names,
5508 options::OPT_fno_unique_internal_linkage_names,
5509 options::OPT_funique_section_names,
5510 options::OPT_fno_unique_section_names,
5511 options::OPT_funique_basic_block_section_names,
5512 options::OPT_fno_unique_basic_block_section_names,
5513 options::OPT_mrestrict_it,
5514 options::OPT_mno_restrict_it,
5515 options::OPT_mstackrealign,
5516 options::OPT_mno_stackrealign,
5517 options::OPT_mstack_alignment,
5518 options::OPT_mcmodel_EQ,
5519 options::OPT_mlong_calls,
5520 options::OPT_mno_long_calls,
5521 options::OPT_ggnu_pubnames,
5522 options::OPT_gdwarf_aranges,
5523 options::OPT_fdebug_types_section,
5524 options::OPT_fno_debug_types_section,
5525 options::OPT_fdwarf_directory_asm,
5526 options::OPT_fno_dwarf_directory_asm,
5527 options::OPT_mrelax_all,
5528 options::OPT_mno_relax_all,
5529 options::OPT_ftrap_function_EQ,
5530 options::OPT_ffixed_r9,
5531 options::OPT_mfix_cortex_a53_835769,
5532 options::OPT_mno_fix_cortex_a53_835769,
5533 options::OPT_ffixed_x18,
5534 options::OPT_mglobal_merge,
5535 options::OPT_mno_global_merge,
5536 options::OPT_mred_zone,
5537 options::OPT_mno_red_zone,
5538 options::OPT_Wa_COMMA,
5539 options::OPT_Xassembler,
5540 options::OPT_mllvm,
5541 };
5542 for (const auto &A : Args)
5543 if (llvm::is_contained(kBitcodeOptionIgnorelist, A->getOption().getID()))
5544 D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5545
5546 // Render the CodeGen options that need to be passed.
5547 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5548 options::OPT_fno_optimize_sibling_calls);
5549
5551 CmdArgs, JA);
5552
5553 // Render ABI arguments
5554 switch (TC.getArch()) {
5555 default: break;
5556 case llvm::Triple::arm:
5557 case llvm::Triple::armeb:
5558 case llvm::Triple::thumbeb:
5559 RenderARMABI(D, Triple, Args, CmdArgs);
5560 break;
5561 case llvm::Triple::aarch64:
5562 case llvm::Triple::aarch64_32:
5563 case llvm::Triple::aarch64_be:
5564 RenderAArch64ABI(Triple, Args, CmdArgs);
5565 break;
5566 }
5567
5568 // Optimization level for CodeGen.
5569 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
5570 if (A->getOption().matches(options::OPT_O4)) {
5571 CmdArgs.push_back("-O3");
5572 D.Diag(diag::warn_O4_is_O3);
5573 } else {
5574 A->render(Args, CmdArgs);
5575 }
5576 }
5577
5578 // Input/Output file.
5579 if (Output.getType() == types::TY_Dependencies) {
5580 // Handled with other dependency code.
5581 } else if (Output.isFilename()) {
5582 CmdArgs.push_back("-o");
5583 CmdArgs.push_back(Output.getFilename());
5584 } else {
5585 assert(Output.isNothing() && "Input output.");
5586 }
5587
5588 for (const auto &II : Inputs) {
5589 addDashXForInput(Args, II, CmdArgs);
5590 if (II.isFilename())
5591 CmdArgs.push_back(II.getFilename());
5592 else
5593 II.getInputArg().renderAsInput(Args, CmdArgs);
5594 }
5595
5596 C.addCommand(std::make_unique<Command>(
5597 JA, *this, ResponseFileSupport::AtFileUTF8(), D.getClangProgramPath(),
5598 CmdArgs, Inputs, Output, D.getPrependArg()));
5599 return;
5600 }
5601
5602 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5603 CmdArgs.push_back("-fembed-bitcode=marker");
5604
5605 // We normally speed up the clang process a bit by skipping destructors at
5606 // exit, but when we're generating diagnostics we can rely on some of the
5607 // cleanup.
5608 if (!C.isForDiagnostics())
5609 CmdArgs.push_back("-disable-free");
5610 CmdArgs.push_back("-clear-ast-before-backend");
5611
5612#ifdef NDEBUG
5613 const bool IsAssertBuild = false;
5614#else
5615 const bool IsAssertBuild = true;
5616#endif
5617
5618 // Disable the verification pass in asserts builds unless otherwise specified.
5619 if (Args.hasFlag(options::OPT_fno_verify_intermediate_code,
5620 options::OPT_fverify_intermediate_code, !IsAssertBuild)) {
5621 CmdArgs.push_back("-disable-llvm-verifier");
5622 }
5623
5624 // Discard value names in assert builds unless otherwise specified.
5625 if (Args.hasFlag(options::OPT_fdiscard_value_names,
5626 options::OPT_fno_discard_value_names, !IsAssertBuild)) {
5627 if (Args.hasArg(options::OPT_fdiscard_value_names) &&
5628 llvm::any_of(Inputs, [](const clang::driver::InputInfo &II) {
5629 return types::isLLVMIR(II.getType());
5630 })) {
5631 D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
5632 }
5633 CmdArgs.push_back("-discard-value-names");
5634 }
5635
5636 // Set the main file name, so that debug info works even with
5637 // -save-temps.
5638 CmdArgs.push_back("-main-file-name");
5639 CmdArgs.push_back(getBaseInputName(Args, Input));
5640
5641 // Some flags which affect the language (via preprocessor
5642 // defines).
5643 if (Args.hasArg(options::OPT_static))
5644 CmdArgs.push_back("-static-define");
5645
5646 if (Args.hasArg(options::OPT_municode))
5647 CmdArgs.push_back("-DUNICODE");
5648
5649 if (isa<AnalyzeJobAction>(JA))
5650 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5651
5652 if (isa<AnalyzeJobAction>(JA) ||
5653 (isa<PreprocessJobAction>(JA) && Args.hasArg(options::OPT__analyze)))
5654 CmdArgs.push_back("-setup-static-analyzer");
5655
5656 // Enable compatilibily mode to avoid analyzer-config related errors.
5657 // Since we can't access frontend flags through hasArg, let's manually iterate
5658 // through them.
5659 bool FoundAnalyzerConfig = false;
5660 for (auto *Arg : Args.filtered(options::OPT_Xclang))
5661 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5662 FoundAnalyzerConfig = true;
5663 break;
5664 }
5665 if (!FoundAnalyzerConfig)
5666 for (auto *Arg : Args.filtered(options::OPT_Xanalyzer))
5667 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5668 FoundAnalyzerConfig = true;
5669 break;
5670 }
5671 if (FoundAnalyzerConfig)
5672 CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
5673
5675
5676 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5677 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5678 if (FunctionAlignment) {
5679 CmdArgs.push_back("-function-alignment");
5680 CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
5681 }
5682
5683 // We support -falign-loops=N where N is a power of 2. GCC supports more
5684 // forms.
5685 if (const Arg *A = Args.getLastArg(options::OPT_falign_loops_EQ)) {
5686 unsigned Value = 0;
5687 if (StringRef(A->getValue()).getAsInteger(10, Value) || Value > 65536)
5688 TC.getDriver().Diag(diag::err_drv_invalid_int_value)
5689 << A->getAsString(Args) << A->getValue();
5690 else if (Value & (Value - 1))
5691 TC.getDriver().Diag(diag::err_drv_alignment_not_power_of_two)
5692 << A->getAsString(Args) << A->getValue();
5693 // Treat =0 as unspecified (use the target preference).
5694 if (Value)
5695 CmdArgs.push_back(Args.MakeArgString("-falign-loops=" +
5696 Twine(std::min(Value, 65536u))));
5697 }
5698
5699 if (Triple.isOSzOS()) {
5700 // On z/OS some of the system header feature macros need to
5701 // be defined to enable most cross platform projects to build
5702 // successfully. Ths include the libc++ library. A
5703 // complicating factor is that users can define these
5704 // macros to the same or different values. We need to add
5705 // the definition for these macros to the compilation command
5706 // if the user hasn't already defined them.
5707
5708 auto findMacroDefinition = [&](const std::string &Macro) {
5709 auto MacroDefs = Args.getAllArgValues(options::OPT_D);
5710 return llvm::any_of(MacroDefs, [&](const std::string &M) {
5711 return M == Macro || M.find(Macro + '=') != std::string::npos;
5712 });
5713 };
5714
5715 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5716 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5717 CmdArgs.push_back("-D_UNIX03_WITHDRAWN");
5718 // _OPEN_DEFAULT is required for XL compat
5719 if (!findMacroDefinition("_OPEN_DEFAULT"))
5720 CmdArgs.push_back("-D_OPEN_DEFAULT");
5721 if (D.CCCIsCXX() || types::isCXX(Input.getType())) {
5722 // _XOPEN_SOURCE=600 is required for libcxx.
5723 if (!findMacroDefinition("_XOPEN_SOURCE"))
5724 CmdArgs.push_back("-D_XOPEN_SOURCE=600");
5725 }
5726 }
5727
5728 llvm::Reloc::Model RelocationModel;
5729 unsigned PICLevel;
5730 bool IsPIE;
5731 std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
5732 Arg *LastPICDataRelArg =
5733 Args.getLastArg(options::OPT_mno_pic_data_is_text_relative,
5734 options::OPT_mpic_data_is_text_relative);
5735 bool NoPICDataIsTextRelative = false;
5736 if (LastPICDataRelArg) {
5737 if (LastPICDataRelArg->getOption().matches(
5738 options::OPT_mno_pic_data_is_text_relative)) {
5739 NoPICDataIsTextRelative = true;
5740 if (!PICLevel)
5741 D.Diag(diag::err_drv_argument_only_allowed_with)
5742 << "-mno-pic-data-is-text-relative"
5743 << "-fpic/-fpie";
5744 }
5745 if (!Triple.isSystemZ())
5746 D.Diag(diag::err_drv_unsupported_opt_for_target)
5747 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5748 : "-mpic-data-is-text-relative")
5749 << RawTriple.str();
5750 }
5751
5752 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5753 RelocationModel == llvm::Reloc::ROPI_RWPI;
5754 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5755 RelocationModel == llvm::Reloc::ROPI_RWPI;
5756
5757 if (Args.hasArg(options::OPT_mcmse) &&
5758 !Args.hasArg(options::OPT_fallow_unsupported)) {
5759 if (IsROPI)
5760 D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
5761 if (IsRWPI)
5762 D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5763 }
5764
5765 if (IsROPI && types::isCXX(Input.getType()) &&
5766 !Args.hasArg(options::OPT_fallow_unsupported))
5767 D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
5768
5769 const char *RMName = RelocationModelName(RelocationModel);
5770 if (RMName) {
5771 CmdArgs.push_back("-mrelocation-model");
5772 CmdArgs.push_back(RMName);
5773 }
5774 if (PICLevel > 0) {
5775 CmdArgs.push_back("-pic-level");
5776 CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
5777 if (IsPIE)
5778 CmdArgs.push_back("-pic-is-pie");
5779 if (NoPICDataIsTextRelative)
5780 CmdArgs.push_back("-mcmodel=medium");
5781 }
5782
5783 if (RelocationModel == llvm::Reloc::ROPI ||
5784 RelocationModel == llvm::Reloc::ROPI_RWPI)
5785 CmdArgs.push_back("-fropi");
5786 if (RelocationModel == llvm::Reloc::RWPI ||
5787 RelocationModel == llvm::Reloc::ROPI_RWPI)
5788 CmdArgs.push_back("-frwpi");
5789
5790 if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
5791 CmdArgs.push_back("-meabi");
5792 CmdArgs.push_back(A->getValue());
5793 }
5794
5795 // -fsemantic-interposition is forwarded to CC1: set the
5796 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5797 // make default visibility external linkage definitions dso_preemptable.
5798 //
5799 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5800 // aliases (make default visibility external linkage definitions dso_local).
5801 // This is the CC1 default for ELF to match COFF/Mach-O.
5802 //
5803 // Otherwise use Clang's traditional behavior: like
5804 // -fno-semantic-interposition but local aliases are not used. So references
5805 // can be interposed if not optimized out.
5806 if (Triple.isOSBinFormatELF()) {
5807 Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
5808 options::OPT_fno_semantic_interposition);
5809 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5810 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5811 bool SupportsLocalAlias =
5812 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5813 if (!A)
5814 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5815 else if (A->getOption().matches(options::OPT_fsemantic_interposition))
5816 A->render(Args, CmdArgs);
5817 else if (!SupportsLocalAlias)
5818 CmdArgs.push_back("-fhalf-no-semantic-interposition");
5819 }
5820 }
5821
5822 {
5823 std::string Model;
5824 if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
5825 if (!TC.isThreadModelSupported(A->getValue()))
5826 D.Diag(diag::err_drv_invalid_thread_model_for_target)
5827 << A->getValue() << A->getAsString(Args);
5828 Model = A->getValue();
5829 } else
5830 Model = TC.getThreadModel();
5831 if (Model != "posix") {
5832 CmdArgs.push_back("-mthread-model");
5833 CmdArgs.push_back(Args.MakeArgString(Model));
5834 }
5835 }
5836
5837 if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
5838 StringRef Name = A->getValue();
5839 if (Name == "SVML") {
5840 if (Triple.getArch() != llvm::Triple::x86 &&
5841 Triple.getArch() != llvm::Triple::x86_64)
5842 D.Diag(diag::err_drv_unsupported_opt_for_target)
5843 << Name << Triple.getArchName();
5844 } else if (Name == "LIBMVEC-X86") {
5845 if (Triple.getArch() != llvm::Triple::x86 &&
5846 Triple.getArch() != llvm::Triple::x86_64)
5847 D.Diag(diag::err_drv_unsupported_opt_for_target)
5848 << Name << Triple.getArchName();
5849 } else if (Name == "SLEEF" || Name == "ArmPL") {
5850 if (Triple.getArch() != llvm::Triple::aarch64 &&
5851 Triple.getArch() != llvm::Triple::aarch64_be &&
5852 Triple.getArch() != llvm::Triple::riscv64)
5853 D.Diag(diag::err_drv_unsupported_opt_for_target)
5854 << Name << Triple.getArchName();
5855 }
5856 A->render(Args, CmdArgs);
5857 }
5858
5859 if (Args.hasFlag(options::OPT_fmerge_all_constants,
5860 options::OPT_fno_merge_all_constants, false))
5861 CmdArgs.push_back("-fmerge-all-constants");
5862
5863 Args.addOptOutFlag(CmdArgs, options::OPT_fdelete_null_pointer_checks,
5864 options::OPT_fno_delete_null_pointer_checks);
5865
5866 // LLVM Code Generator Options.
5867
5868 if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ_quadword_atomics)) {
5869 if (!Triple.isOSAIX() || Triple.isPPC32())
5870 D.Diag(diag::err_drv_unsupported_opt_for_target)
5871 << A->getSpelling() << RawTriple.str();
5872 CmdArgs.push_back("-mabi=quadword-atomics");
5873 }
5874
5875 if (Arg *A = Args.getLastArg(options::OPT_mlong_double_128)) {
5876 // Emit the unsupported option error until the Clang's library integration
5877 // support for 128-bit long double is available for AIX.
5878 if (Triple.isOSAIX())
5879 D.Diag(diag::err_drv_unsupported_opt_for_target)
5880 << A->getSpelling() << RawTriple.str();
5881 }
5882
5883 if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
5884 StringRef V = A->getValue(), V1 = V;
5885 unsigned Size;
5886 if (V1.consumeInteger(10, Size) || !V1.empty())
5887 D.Diag(diag::err_drv_invalid_argument_to_option)
5888 << V << A->getOption().getName();
5889 else
5890 CmdArgs.push_back(Args.MakeArgString("-fwarn-stack-size=" + V));
5891 }
5892
5893 Args.addOptOutFlag(CmdArgs, options::OPT_fjump_tables,
5894 options::OPT_fno_jump_tables);
5895 Args.addOptInFlag(CmdArgs, options::OPT_fprofile_sample_accurate,
5896 options::OPT_fno_profile_sample_accurate);
5897 Args.addOptOutFlag(CmdArgs, options::OPT_fpreserve_as_comments,
5898 options::OPT_fno_preserve_as_comments);
5899
5900 if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
5901 CmdArgs.push_back("-mregparm");
5902 CmdArgs.push_back(A->getValue());
5903 }
5904
5905 if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
5906 options::OPT_msvr4_struct_return)) {
5907 if (!TC.getTriple().isPPC32()) {
5908 D.Diag(diag::err_drv_unsupported_opt_for_target)
5909 << A->getSpelling() << RawTriple.str();
5910 } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
5911 CmdArgs.push_back("-maix-struct-return");
5912 } else {
5913 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5914 CmdArgs.push_back("-msvr4-struct-return");
5915 }
5916 }
5917
5918 if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
5919 options::OPT_freg_struct_return)) {
5920 if (TC.getArch() != llvm::Triple::x86) {
5921 D.Diag(diag::err_drv_unsupported_opt_for_target)
5922 << A->getSpelling() << RawTriple.str();
5923 } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
5924 CmdArgs.push_back("-fpcc-struct-return");
5925 } else {
5926 assert(A->getOption().matches(options::OPT_freg_struct_return));
5927 CmdArgs.push_back("-freg-struct-return");
5928 }
5929 }
5930
5931 if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) {
5932 if (Triple.getArch() == llvm::Triple::m68k)
5933 CmdArgs.push_back("-fdefault-calling-conv=rtdcall");
5934 else
5935 CmdArgs.push_back("-fdefault-calling-conv=stdcall");
5936 }
5937
5938 if (Args.hasArg(options::OPT_fenable_matrix)) {
5939 // enable-matrix is needed by both the LangOpts and by LLVM.
5940 CmdArgs.push_back("-fenable-matrix");
5941 CmdArgs.push_back("-mllvm");
5942 CmdArgs.push_back("-enable-matrix");
5943 }
5944
5946 getFramePointerKind(Args, RawTriple);
5947 const char *FPKeepKindStr = nullptr;
5948 switch (FPKeepKind) {
5950 FPKeepKindStr = "-mframe-pointer=none";
5951 break;
5953 FPKeepKindStr = "-mframe-pointer=reserved";
5954 break;
5956 FPKeepKindStr = "-mframe-pointer=non-leaf";
5957 break;
5959 FPKeepKindStr = "-mframe-pointer=all";
5960 break;
5961 }
5962 assert(FPKeepKindStr && "unknown FramePointerKind");
5963 CmdArgs.push_back(FPKeepKindStr);
5964
5965 Args.addOptOutFlag(CmdArgs, options::OPT_fzero_initialized_in_bss,
5966 options::OPT_fno_zero_initialized_in_bss);
5967
5968 bool OFastEnabled = isOptimizationLevelFast(Args);
5969 if (OFastEnabled)
5970 D.Diag(diag::warn_drv_deprecated_arg_ofast);
5971 // If -Ofast is the optimization level, then -fstrict-aliasing should be
5972 // enabled. This alias option is being used to simplify the hasFlag logic.
5973 OptSpecifier StrictAliasingAliasOption =
5974 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
5975 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
5976 // doesn't do any TBAA.
5977 if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
5978 options::OPT_fno_strict_aliasing, !IsWindowsMSVC))
5979 CmdArgs.push_back("-relaxed-aliasing");
5980 if (Args.hasFlag(options::OPT_fno_pointer_tbaa, options::OPT_fpointer_tbaa,
5981 false))
5982 CmdArgs.push_back("-no-pointer-tbaa");
5983 if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
5984 options::OPT_fno_struct_path_tbaa, true))
5985 CmdArgs.push_back("-no-struct-path-tbaa");
5986 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_enums,
5987 options::OPT_fno_strict_enums);
5988 Args.addOptOutFlag(CmdArgs, options::OPT_fstrict_return,
5989 options::OPT_fno_strict_return);
5990 Args.addOptInFlag(CmdArgs, options::OPT_fallow_editor_placeholders,
5991 options::OPT_fno_allow_editor_placeholders);
5992 Args.addOptInFlag(CmdArgs, options::OPT_fstrict_vtable_pointers,
5993 options::OPT_fno_strict_vtable_pointers);
5994 Args.addOptInFlag(CmdArgs, options::OPT_fforce_emit_vtables,
5995 options::OPT_fno_force_emit_vtables);
5996 Args.addOptOutFlag(CmdArgs, options::OPT_foptimize_sibling_calls,
5997 options::OPT_fno_optimize_sibling_calls);
5998 Args.addOptOutFlag(CmdArgs, options::OPT_fescaping_block_tail_calls,
5999 options::OPT_fno_escaping_block_tail_calls);
6000
6001 Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
6002 options::OPT_fno_fine_grained_bitfield_accesses);
6003
6004 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6005 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6006
6007 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6008 options::OPT_fno_experimental_omit_vtable_rtti);
6009
6010 Args.AddLastArg(CmdArgs, options::OPT_fdisable_block_signature_string,
6011 options::OPT_fno_disable_block_signature_string);
6012
6013 // Handle segmented stacks.
6014 Args.addOptInFlag(CmdArgs, options::OPT_fsplit_stack,
6015 options::OPT_fno_split_stack);
6016
6017 // -fprotect-parens=0 is default.
6018 if (Args.hasFlag(options::OPT_fprotect_parens,
6019 options::OPT_fno_protect_parens, false))
6020 CmdArgs.push_back("-fprotect-parens");
6021
6022 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
6023
6024 if (Arg *A = Args.getLastArg(options::OPT_fextend_args_EQ)) {
6025 const llvm::Triple::ArchType Arch = TC.getArch();
6026 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
6027 StringRef V = A->getValue();
6028 if (V == "64")
6029 CmdArgs.push_back("-fextend-arguments=64");
6030 else if (V != "32")
6031 D.Diag(diag::err_drv_invalid_argument_to_option)
6032 << A->getValue() << A->getOption().getName();
6033 } else
6034 D.Diag(diag::err_drv_unsupported_opt_for_target)
6035 << A->getOption().getName() << TripleStr;
6036 }
6037
6038 if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
6039 if (TC.getArch() == llvm::Triple::avr)
6040 A->render(Args, CmdArgs);
6041 else
6042 D.Diag(diag::err_drv_unsupported_opt_for_target)
6043 << A->getAsString(Args) << TripleStr;
6044 }
6045
6046 if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
6047 if (TC.getTriple().isX86())
6048 A->render(Args, CmdArgs);
6049 else if (TC.getTriple().isPPC() &&
6050 (A->getOption().getID() != options::OPT_mlong_double_80))
6051 A->render(Args, CmdArgs);
6052 else
6053 D.Diag(diag::err_drv_unsupported_opt_for_target)
6054 << A->getAsString(Args) << TripleStr;
6055 }
6056
6057 // Decide whether to use verbose asm. Verbose assembly is the default on
6058 // toolchains which have the integrated assembler on by default.
6059 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
6060 if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
6061 IsIntegratedAssemblerDefault))
6062 CmdArgs.push_back("-fno-verbose-asm");
6063
6064 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
6065 // use that to indicate the MC default in the backend.
6066 if (Arg *A = Args.getLastArg(options::OPT_fbinutils_version_EQ)) {
6067 StringRef V = A->getValue();
6068 unsigned Num;
6069 if (V == "none")
6070 A->render(Args, CmdArgs);
6071 else if (!V.consumeInteger(10, Num) && Num > 0 &&
6072 (V.empty() || (V.consume_front(".") &&
6073 !V.consumeInteger(10, Num) && V.empty())))
6074 A->render(Args, CmdArgs);
6075 else
6076 D.Diag(diag::err_drv_invalid_argument_to_option)
6077 << A->getValue() << A->getOption().getName();
6078 }
6079
6080 // If toolchain choose to use MCAsmParser for inline asm don't pass the
6081 // option to disable integrated-as explicitly.
6083 CmdArgs.push_back("-no-integrated-as");
6084
6085 if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
6086 CmdArgs.push_back("-mdebug-pass");
6087 CmdArgs.push_back("Structure");
6088 }
6089 if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
6090 CmdArgs.push_back("-mdebug-pass");
6091 CmdArgs.push_back("Arguments");
6092 }
6093
6094 // Enable -mconstructor-aliases except on darwin, where we have to work around
6095 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
6096 // code, where aliases aren't supported.
6097 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
6098 CmdArgs.push_back("-mconstructor-aliases");
6099
6100 // Darwin's kernel doesn't support guard variables; just die if we
6101 // try to use them.
6102 if (KernelOrKext && RawTriple.isOSDarwin())
6103 CmdArgs.push_back("-fforbid-guard-variables");
6104
6105 if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
6106 Triple.isWindowsGNUEnvironment())) {
6107 CmdArgs.push_back("-mms-bitfields");
6108 }
6109
6110 if (Triple.isWindowsGNUEnvironment()) {
6111 Args.addOptOutFlag(CmdArgs, options::OPT_fauto_import,
6112 options::OPT_fno_auto_import);
6113 }
6114
6115 if (Args.hasFlag(options::OPT_fms_volatile, options::OPT_fno_ms_volatile,
6116 Triple.isX86() && IsWindowsMSVC))
6117 CmdArgs.push_back("-fms-volatile");
6118
6119 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
6120 // defaults to -fno-direct-access-external-data. Pass the option if different
6121 // from the default.
6122 if (Arg *A = Args.getLastArg(options::OPT_fdirect_access_external_data,
6123 options::OPT_fno_direct_access_external_data)) {
6124 if (A->getOption().matches(options::OPT_fdirect_access_external_data) !=
6125 (PICLevel == 0))
6126 A->render(Args, CmdArgs);
6127 } else if (PICLevel == 0 && Triple.isLoongArch()) {
6128 // Some targets default to -fno-direct-access-external-data even for
6129 // -fno-pic.
6130 CmdArgs.push_back("-fno-direct-access-external-data");
6131 }
6132
6133 if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
6134 CmdArgs.push_back("-fno-plt");
6135 }
6136
6137 // -fhosted is default.
6138 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
6139 // use Freestanding.
6140 bool Freestanding =
6141 Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
6142 KernelOrKext;
6143 if (Freestanding)
6144 CmdArgs.push_back("-ffreestanding");
6145
6146 Args.AddLastArg(CmdArgs, options::OPT_fno_knr_functions);
6147
6148 // This is a coarse approximation of what llvm-gcc actually does, both
6149 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
6150 // complicated ways.
6151 auto SanitizeArgs = TC.getSanitizerArgs(Args);
6152
6153 bool IsAsyncUnwindTablesDefault =
6155 bool IsSyncUnwindTablesDefault =
6157
6158 bool AsyncUnwindTables = Args.hasFlag(
6159 options::OPT_fasynchronous_unwind_tables,
6160 options::OPT_fno_asynchronous_unwind_tables,
6161 (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6162 !Freestanding);
6163 bool UnwindTables =
6164 Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
6165 IsSyncUnwindTablesDefault && !Freestanding);
6166 if (AsyncUnwindTables)
6167 CmdArgs.push_back("-funwind-tables=2");
6168 else if (UnwindTables)
6169 CmdArgs.push_back("-funwind-tables=1");
6170
6171 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6172 // `--gpu-use-aux-triple-only` is specified.
6173 if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
6174 (IsCudaDevice || IsHIPDevice || IsSYCLDevice)) {
6175 const ArgList &HostArgs =
6176 C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
6177 std::string HostCPU =
6178 getCPUName(D, HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
6179 if (!HostCPU.empty()) {
6180 CmdArgs.push_back("-aux-target-cpu");
6181 CmdArgs.push_back(Args.MakeArgString(HostCPU));
6182 }
6183 getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
6184 /*ForAS*/ false, /*IsAux*/ true);
6185 }
6186
6187 TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
6188
6189 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6190
6191 if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
6192 StringRef Value = A->getValue();
6193 unsigned TLSSize = 0;
6194 Value.getAsInteger(10, TLSSize);
6195 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6196 D.Diag(diag::err_drv_unsupported_opt_for_target)
6197 << A->getOption().getName() << TripleStr;
6198 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6199 D.Diag(diag::err_drv_invalid_int_value)
6200 << A->getOption().getName() << Value;
6201 Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
6202 }
6203
6204 if (isTLSDESCEnabled(TC, Args))
6205 CmdArgs.push_back("-enable-tlsdesc");
6206
6207 // Add the target cpu
6208 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ false);
6209 if (!CPU.empty()) {
6210 CmdArgs.push_back("-target-cpu");
6211 CmdArgs.push_back(Args.MakeArgString(CPU));
6212 }
6213
6214 RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
6215
6216 // Add clang-cl arguments.
6217 types::ID InputType = Input.getType();
6218 if (D.IsCLMode())
6219 AddClangCLArgs(Args, InputType, CmdArgs);
6220
6221 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6222 llvm::codegenoptions::NoDebugInfo;
6224 renderDebugOptions(TC, D, RawTriple, Args, types::isLLVMIR(InputType),
6225 CmdArgs, Output, DebugInfoKind, DwarfFission);
6226
6227 // Add the split debug info name to the command lines here so we
6228 // can propagate it to the backend.
6229 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6230 (TC.getTriple().isOSBinFormatELF() ||
6231 TC.getTriple().isOSBinFormatWasm() ||
6232 TC.getTriple().isOSBinFormatCOFF()) &&
6233 (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
6234 isa<BackendJobAction>(JA));
6235 if (SplitDWARF) {
6236 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6237 CmdArgs.push_back("-split-dwarf-file");
6238 CmdArgs.push_back(SplitDWARFOut);
6239 if (DwarfFission == DwarfFissionKind::Split) {
6240 CmdArgs.push_back("-split-dwarf-output");
6241 CmdArgs.push_back(SplitDWARFOut);
6242 }
6243 }
6244
6245 // Pass the linker version in use.
6246 if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
6247 CmdArgs.push_back("-target-linker-version");
6248 CmdArgs.push_back(A->getValue());
6249 }
6250
6251 // Explicitly error on some things we know we don't support and can't just
6252 // ignore.
6253 if (!Args.hasArg(options::OPT_fallow_unsupported)) {
6254 Arg *Unsupported;
6255 if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
6256 TC.getArch() == llvm::Triple::x86) {
6257 if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
6258 (Unsupported = Args.getLastArg(options::OPT_mkernel)))
6259 D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6260 << Unsupported->getOption().getName();
6261 }
6262 // The faltivec option has been superseded by the maltivec option.
6263 if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
6264 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6265 << Unsupported->getOption().getName()
6266 << "please use -maltivec and include altivec.h explicitly";
6267 if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
6268 D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
6269 << Unsupported->getOption().getName() << "please use -mno-altivec";
6270 }
6271
6272 Args.AddAllArgs(CmdArgs, options::OPT_v);
6273
6274 if (Args.getLastArg(options::OPT_H)) {
6275 CmdArgs.push_back("-H");
6276 CmdArgs.push_back("-sys-header-deps");
6277 }
6278 Args.AddAllArgs(CmdArgs, options::OPT_fshow_skipped_includes);
6279
6280 if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
6281 CmdArgs.push_back("-header-include-file");
6282 CmdArgs.push_back(!D.CCPrintHeadersFilename.empty()
6283 ? D.CCPrintHeadersFilename.c_str()
6284 : "-");
6285 CmdArgs.push_back("-sys-header-deps");
6286 CmdArgs.push_back(Args.MakeArgString(
6287 "-header-include-format=" +
6288 std::string(headerIncludeFormatKindToString(D.CCPrintHeadersFormat))));
6289 CmdArgs.push_back(
6290 Args.MakeArgString("-header-include-filtering=" +
6292 D.CCPrintHeadersFiltering))));
6293 }
6294 Args.AddLastArg(CmdArgs, options::OPT_P);
6295 Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
6296
6297 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6298 CmdArgs.push_back("-diagnostic-log-file");
6299 CmdArgs.push_back(!D.CCLogDiagnosticsFilename.empty()
6300 ? D.CCLogDiagnosticsFilename.c_str()
6301 : "-");
6302 }
6303
6304 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6305 // crashes.
6306 if (D.CCGenDiagnostics)
6307 CmdArgs.push_back("-disable-pragma-debug-crash");
6308
6309 // Allow backend to put its diagnostic files in the same place as frontend
6310 // crash diagnostics files.
6311 if (Args.hasArg(options::OPT_fcrash_diagnostics_dir)) {
6312 StringRef Dir = Args.getLastArgValue(options::OPT_fcrash_diagnostics_dir);
6313 CmdArgs.push_back("-mllvm");
6314 CmdArgs.push_back(Args.MakeArgString("-crash-diagnostics-dir=" + Dir));
6315 }
6316
6317 bool UseSeparateSections = isUseSeparateSections(Triple);
6318
6319 if (Args.hasFlag(options::OPT_ffunction_sections,
6320 options::OPT_fno_function_sections, UseSeparateSections)) {
6321 CmdArgs.push_back("-ffunction-sections");
6322 }
6323
6324 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_address_map,
6325 options::OPT_fno_basic_block_address_map)) {
6326 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6327 if (A->getOption().matches(options::OPT_fbasic_block_address_map))
6328 A->render(Args, CmdArgs);
6329 } else {
6330 D.Diag(diag::err_drv_unsupported_opt_for_target)
6331 << A->getAsString(Args) << TripleStr;
6332 }
6333 }
6334
6335 if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
6336 StringRef Val = A->getValue();
6337 if (Val == "labels") {
6338 D.Diag(diag::warn_drv_deprecated_arg)
6339 << A->getAsString(Args) << /*hasReplacement=*/true
6340 << "-fbasic-block-address-map";
6341 CmdArgs.push_back("-fbasic-block-address-map");
6342 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6343 if (Val != "all" && Val != "none" && !Val.starts_with("list="))
6344 D.Diag(diag::err_drv_invalid_value)
6345 << A->getAsString(Args) << A->getValue();
6346 else
6347 A->render(Args, CmdArgs);
6348 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6349 // "all" is not supported on AArch64 since branch relaxation creates new
6350 // basic blocks for some cross-section branches.
6351 if (Val != "labels" && Val != "none" && !Val.starts_with("list="))
6352 D.Diag(diag::err_drv_invalid_value)
6353 << A->getAsString(Args) << A->getValue();
6354 else
6355 A->render(Args, CmdArgs);
6356 } else if (Triple.isNVPTX()) {
6357 // Do not pass the option to the GPU compilation. We still want it enabled
6358 // for the host-side compilation, so seeing it here is not an error.
6359 } else if (Val != "none") {
6360 // =none is allowed everywhere. It's useful for overriding the option
6361 // and is the same as not specifying the option.
6362 D.Diag(diag::err_drv_unsupported_opt_for_target)
6363 << A->getAsString(Args) << TripleStr;
6364 }
6365 }
6366
6367 bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
6368 if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
6369 UseSeparateSections || HasDefaultDataSections)) {
6370 CmdArgs.push_back("-fdata-sections");
6371 }
6372
6373 Args.addOptOutFlag(CmdArgs, options::OPT_funique_section_names,
6374 options::OPT_fno_unique_section_names);
6375 Args.addOptInFlag(CmdArgs, options::OPT_fseparate_named_sections,
6376 options::OPT_fno_separate_named_sections);
6377 Args.addOptInFlag(CmdArgs, options::OPT_funique_internal_linkage_names,
6378 options::OPT_fno_unique_internal_linkage_names);
6379 Args.addOptInFlag(CmdArgs, options::OPT_funique_basic_block_section_names,
6380 options::OPT_fno_unique_basic_block_section_names);
6381
6382 if (Arg *A = Args.getLastArg(options::OPT_fsplit_machine_functions,
6383 options::OPT_fno_split_machine_functions)) {
6384 if (!A->getOption().matches(options::OPT_fno_split_machine_functions)) {
6385 // This codegen pass is only available on x86 and AArch64 ELF targets.
6386 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
6387 A->render(Args, CmdArgs);
6388 else
6389 D.Diag(diag::err_drv_unsupported_opt_for_target)
6390 << A->getAsString(Args) << TripleStr;
6391 }
6392 }
6393
6394 Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
6395 options::OPT_finstrument_functions_after_inlining,
6396 options::OPT_finstrument_function_entry_bare);
6397 Args.AddLastArg(CmdArgs, options::OPT_fconvergent_functions,
6398 options::OPT_fno_convergent_functions);
6399
6400 // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support
6401 // for sampling, overhead of call arc collection is way too high and there's
6402 // no way to collect the output.
6403 if (!Triple.isNVPTX() && !Triple.isAMDGCN())
6404 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanitizeArgs, CmdArgs);
6405
6406 Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
6407
6408 if (getLastProfileSampleUseArg(Args) &&
6409 Args.hasArg(options::OPT_fsample_profile_use_profi)) {
6410 CmdArgs.push_back("-mllvm");
6411 CmdArgs.push_back("-sample-profile-use-profi");
6412 }
6413
6414 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6415 if (RawTriple.isPS() &&
6416 !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
6417 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6418 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6419 }
6420
6421 // Pass options for controlling the default header search paths.
6422 if (Args.hasArg(options::OPT_nostdinc)) {
6423 CmdArgs.push_back("-nostdsysteminc");
6424 CmdArgs.push_back("-nobuiltininc");
6425 } else {
6426 if (Args.hasArg(options::OPT_nostdlibinc))
6427 CmdArgs.push_back("-nostdsysteminc");
6428 Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
6429 Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
6430 }
6431
6432 // Pass the path to compiler resource files.
6433 CmdArgs.push_back("-resource-dir");
6434 CmdArgs.push_back(D.ResourceDir.c_str());
6435
6436 Args.AddLastArg(CmdArgs, options::OPT_working_directory);
6437
6438 RenderARCMigrateToolOptions(D, Args, CmdArgs);
6439
6440 // Add preprocessing options like -I, -D, etc. if we are using the
6441 // preprocessor.
6442 //
6443 // FIXME: Support -fpreprocessed
6445 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6446
6447 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6448 // that "The compiler can only warn and ignore the option if not recognized".
6449 // When building with ccache, it will pass -D options to clang even on
6450 // preprocessed inputs and configure concludes that -fPIC is not supported.
6451 Args.ClaimAllArgs(options::OPT_D);
6452
6453 // Manually translate -O4 to -O3; let clang reject others.
6454 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
6455 if (A->getOption().matches(options::OPT_O4)) {
6456 CmdArgs.push_back("-O3");
6457 D.Diag(diag::warn_O4_is_O3);
6458 } else {
6459 A->render(Args, CmdArgs);
6460 }
6461 }
6462
6463 // Warn about ignored options to clang.
6464 for (const Arg *A :
6465 Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6466 D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6467 A->claim();
6468 }
6469
6470 for (const Arg *A :
6471 Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
6472 D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
6473 A->claim();
6474 }
6475
6476 claimNoWarnArgs(Args);
6477
6478 Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
6479
6480 for (const Arg *A :
6481 Args.filtered(options::OPT_W_Group, options::OPT__SLASH_wd)) {
6482 A->claim();
6483 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6484 unsigned WarningNumber;
6485 if (StringRef(A->getValue()).getAsInteger(10, WarningNumber)) {
6486 D.Diag(diag::err_drv_invalid_int_value)
6487 << A->getAsString(Args) << A->getValue();
6488 continue;
6489 }
6490
6491 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6492 CmdArgs.push_back(Args.MakeArgString(
6493 "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6494 }
6495 continue;
6496 }
6497 A->render(Args, CmdArgs);
6498 }
6499
6500 Args.AddAllArgs(CmdArgs, options::OPT_Wsystem_headers_in_module_EQ);
6501
6502 if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
6503 CmdArgs.push_back("-pedantic");
6504 Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
6505 Args.AddLastArg(CmdArgs, options::OPT_w);
6506
6507 Args.addOptInFlag(CmdArgs, options::OPT_ffixed_point,
6508 options::OPT_fno_fixed_point);
6509
6510 if (Arg *A = Args.getLastArg(options::OPT_fcxx_abi_EQ))
6511 A->render(Args, CmdArgs);
6512
6513 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_relative_cxx_abi_vtables,
6514 options::OPT_fno_experimental_relative_cxx_abi_vtables);
6515
6516 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_omit_vtable_rtti,
6517 options::OPT_fno_experimental_omit_vtable_rtti);
6518
6519 if (Arg *A = Args.getLastArg(options::OPT_ffuchsia_api_level_EQ))
6520 A->render(Args, CmdArgs);
6521
6522 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6523 // (-ansi is equivalent to -std=c89 or -std=c++98).
6524 //
6525 // If a std is supplied, only add -trigraphs if it follows the
6526 // option.
6527 bool ImplyVCPPCVer = false;
6528 bool ImplyVCPPCXXVer = false;
6529 const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
6530 if (Std) {
6531 if (Std->getOption().matches(options::OPT_ansi))
6532 if (types::isCXX(InputType))
6533 CmdArgs.push_back("-std=c++98");
6534 else
6535 CmdArgs.push_back("-std=c89");
6536 else
6537 Std->render(Args, CmdArgs);
6538
6539 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6540 if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
6541 options::OPT_ftrigraphs,
6542 options::OPT_fno_trigraphs))
6543 if (A != Std)
6544 A->render(Args, CmdArgs);
6545 } else {
6546 // Honor -std-default.
6547 //
6548 // FIXME: Clang doesn't correctly handle -std= when the input language
6549 // doesn't match. For the time being just ignore this for C++ inputs;
6550 // eventually we want to do all the standard defaulting here instead of
6551 // splitting it between the driver and clang -cc1.
6552 if (!types::isCXX(InputType)) {
6553 if (!Args.hasArg(options::OPT__SLASH_std)) {
6554 Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
6555 /*Joined=*/true);
6556 } else
6557 ImplyVCPPCVer = true;
6558 }
6559 else if (IsWindowsMSVC)
6560 ImplyVCPPCXXVer = true;
6561
6562 Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
6563 options::OPT_fno_trigraphs);
6564 }
6565
6566 // GCC's behavior for -Wwrite-strings is a bit strange:
6567 // * In C, this "warning flag" changes the types of string literals from
6568 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6569 // for the discarded qualifier.
6570 // * In C++, this is just a normal warning flag.
6571 //
6572 // Implementing this warning correctly in C is hard, so we follow GCC's
6573 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6574 // a non-const char* in C, rather than using this crude hack.
6575 if (!types::isCXX(InputType)) {
6576 // FIXME: This should behave just like a warning flag, and thus should also
6577 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6578 Arg *WriteStrings =
6579 Args.getLastArg(options::OPT_Wwrite_strings,
6580 options::OPT_Wno_write_strings, options::OPT_w);
6581 if (WriteStrings &&
6582 WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
6583 CmdArgs.push_back("-fconst-strings");
6584 }
6585
6586 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6587 // during C++ compilation, which it is by default. GCC keeps this define even
6588 // in the presence of '-w', match this behavior bug-for-bug.
6589 if (types::isCXX(InputType) &&
6590 Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
6591 true)) {
6592 CmdArgs.push_back("-fdeprecated-macro");
6593 }
6594
6595 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6596 if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
6597 if (Asm->getOption().matches(options::OPT_fasm))
6598 CmdArgs.push_back("-fgnu-keywords");
6599 else
6600 CmdArgs.push_back("-fno-gnu-keywords");
6601 }
6602
6603 if (!ShouldEnableAutolink(Args, TC, JA))
6604 CmdArgs.push_back("-fno-autolink");
6605
6606 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_depth_EQ);
6607 Args.AddLastArg(CmdArgs, options::OPT_foperator_arrow_depth_EQ);
6608 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_depth_EQ);
6609 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_steps_EQ);
6610
6611 Args.AddLastArg(CmdArgs, options::OPT_fexperimental_library);
6612
6613 if (Args.hasArg(options::OPT_fexperimental_new_constant_interpreter))
6614 CmdArgs.push_back("-fexperimental-new-constant-interpreter");
6615
6616 if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
6617 CmdArgs.push_back("-fbracket-depth");
6618 CmdArgs.push_back(A->getValue());
6619 }
6620
6621 if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
6622 options::OPT_Wlarge_by_value_copy_def)) {
6623 if (A->getNumValues()) {
6624 StringRef bytes = A->getValue();
6625 CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
6626 } else
6627 CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
6628 }
6629
6630 if (Args.hasArg(options::OPT_relocatable_pch))
6631 CmdArgs.push_back("-relocatable-pch");
6632
6633 if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
6634 static const char *kCFABIs[] = {
6635 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6636 };
6637
6638 if (!llvm::is_contained(kCFABIs, StringRef(A->getValue())))
6639 D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6640 else
6641 A->render(Args, CmdArgs);
6642 }
6643
6644 if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
6645 CmdArgs.push_back("-fconstant-string-class");
6646 CmdArgs.push_back(A->getValue());
6647 }
6648
6649 if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
6650 CmdArgs.push_back("-ftabstop");
6651 CmdArgs.push_back(A->getValue());
6652 }
6653
6654 Args.addOptInFlag(CmdArgs, options::OPT_fstack_size_section,
6655 options::OPT_fno_stack_size_section);
6656
6657 if (Args.hasArg(options::OPT_fstack_usage)) {
6658 CmdArgs.push_back("-stack-usage-file");
6659
6660 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
6661 SmallString<128> OutputFilename(OutputOpt->getValue());
6662 llvm::sys::path::replace_extension(OutputFilename, "su");
6663 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
6664 } else
6665 CmdArgs.push_back(
6666 Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6667 }
6668
6669 CmdArgs.push_back("-ferror-limit");
6670 if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
6671 CmdArgs.push_back(A->getValue());
6672 else
6673 CmdArgs.push_back("19");
6674
6675 Args.AddLastArg(CmdArgs, options::OPT_fconstexpr_backtrace_limit_EQ);
6676 Args.AddLastArg(CmdArgs, options::OPT_fmacro_backtrace_limit_EQ);
6677 Args.AddLastArg(CmdArgs, options::OPT_ftemplate_backtrace_limit_EQ);
6678 Args.AddLastArg(CmdArgs, options::OPT_fspell_checking_limit_EQ);
6679 Args.AddLastArg(CmdArgs, options::OPT_fcaret_diagnostics_max_lines_EQ);
6680
6681 // Pass -fmessage-length=.
6682 unsigned MessageLength = 0;
6683 if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
6684 StringRef V(A->getValue());
6685 if (V.getAsInteger(0, MessageLength))
6686 D.Diag(diag::err_drv_invalid_argument_to_option)
6687 << V << A->getOption().getName();
6688 } else {
6689 // If -fmessage-length=N was not specified, determine whether this is a
6690 // terminal and, if so, implicitly define -fmessage-length appropriately.
6691 MessageLength = llvm::sys::Process::StandardErrColumns();
6692 }
6693 if (MessageLength != 0)
6694 CmdArgs.push_back(
6695 Args.MakeArgString("-fmessage-length=" + Twine(MessageLength)));
6696
6697 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_EQ))
6698 CmdArgs.push_back(
6699 Args.MakeArgString("-frandomize-layout-seed=" + Twine(A->getValue(0))));
6700
6701 if (Arg *A = Args.getLastArg(options::OPT_frandomize_layout_seed_file_EQ))
6702 CmdArgs.push_back(Args.MakeArgString("-frandomize-layout-seed-file=" +
6703 Twine(A->getValue(0))));
6704
6705 // -fvisibility= and -fvisibility-ms-compat are of a piece.
6706 if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
6707 options::OPT_fvisibility_ms_compat)) {
6708 if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
6709 A->render(Args, CmdArgs);
6710 } else {
6711 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6712 CmdArgs.push_back("-fvisibility=hidden");
6713 CmdArgs.push_back("-ftype-visibility=default");
6714 }
6715 } else if (IsOpenMPDevice) {
6716 // When compiling for the OpenMP device we want protected visibility by
6717 // default. This prevents the device from accidentally preempting code on
6718 // the host, makes the system more robust, and improves performance.
6719 CmdArgs.push_back("-fvisibility=protected");
6720 }
6721
6722 // PS4/PS5 process these options in addClangTargetOptions.
6723 if (!RawTriple.isPS()) {
6724 if (const Arg *A =
6725 Args.getLastArg(options::OPT_fvisibility_from_dllstorageclass,
6726 options::OPT_fno_visibility_from_dllstorageclass)) {
6727 if (A->getOption().matches(
6728 options::OPT_fvisibility_from_dllstorageclass)) {
6729 CmdArgs.push_back("-fvisibility-from-dllstorageclass");
6730 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_dllexport_EQ);
6731 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_nodllstorageclass_EQ);
6732 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_externs_dllimport_EQ);
6733 Args.AddLastArg(CmdArgs,
6734 options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6735 }
6736 }
6737 }
6738
6739 if (Args.hasFlag(options::OPT_fvisibility_inlines_hidden,
6740 options::OPT_fno_visibility_inlines_hidden, false))
6741 CmdArgs.push_back("-fvisibility-inlines-hidden");
6742
6743 Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden_static_local_var,
6744 options::OPT_fno_visibility_inlines_hidden_static_local_var);
6745
6746 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
6747 // -fvisibility-global-new-delete=force-hidden.
6748 if (const Arg *A =
6749 Args.getLastArg(options::OPT_fvisibility_global_new_delete_hidden)) {
6750 D.Diag(diag::warn_drv_deprecated_arg)
6751 << A->getAsString(Args) << /*hasReplacement=*/true
6752 << "-fvisibility-global-new-delete=force-hidden";
6753 }
6754
6755 if (const Arg *A =
6756 Args.getLastArg(options::OPT_fvisibility_global_new_delete_EQ,
6757 options::OPT_fvisibility_global_new_delete_hidden)) {
6758 if (A->getOption().matches(options::OPT_fvisibility_global_new_delete_EQ)) {
6759 A->render(Args, CmdArgs);
6760 } else {
6761 assert(A->getOption().matches(
6762 options::OPT_fvisibility_global_new_delete_hidden));
6763 CmdArgs.push_back("-fvisibility-global-new-delete=force-hidden");
6764 }
6765 }
6766
6767 Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
6768
6769 if (Args.hasFlag(options::OPT_fnew_infallible,
6770 options::OPT_fno_new_infallible, false))
6771 CmdArgs.push_back("-fnew-infallible");
6772
6773 if (Args.hasFlag(options::OPT_fno_operator_names,
6774 options::OPT_foperator_names, false))
6775 CmdArgs.push_back("-fno-operator-names");
6776
6777 // Forward -f (flag) options which we can pass directly.
6778 Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
6779 Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
6780 Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
6781 Args.AddLastArg(CmdArgs, options::OPT_fzero_call_used_regs_EQ);
6782 Args.AddLastArg(CmdArgs, options::OPT_fraw_string_literals,
6783 options::OPT_fno_raw_string_literals);
6784
6785 if (Args.hasFlag(options::OPT_femulated_tls, options::OPT_fno_emulated_tls,
6786 Triple.hasDefaultEmulatedTLS()))
6787 CmdArgs.push_back("-femulated-tls");
6788
6789 Args.addOptInFlag(CmdArgs, options::OPT_fcheck_new,
6790 options::OPT_fno_check_new);
6791
6792 if (Arg *A = Args.getLastArg(options::OPT_fzero_call_used_regs_EQ)) {
6793 // FIXME: There's no reason for this to be restricted to X86. The backend
6794 // code needs to be changed to include the appropriate function calls
6795 // automatically.
6796 if (!Triple.isX86() && !Triple.isAArch64())
6797 D.Diag(diag::err_drv_unsupported_opt_for_target)
6798 << A->getAsString(Args) << TripleStr;
6799 }
6800
6801 // AltiVec-like language extensions aren't relevant for assembling.
6802 if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
6803 Args.AddLastArg(CmdArgs, options::OPT_fzvector);
6804
6805 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
6806 Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
6807
6808 // Forward flags for OpenMP. We don't do this if the current action is an
6809 // device offloading action other than OpenMP.
6810 if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
6811 options::OPT_fno_openmp, false) &&
6812 !Args.hasFlag(options::OPT_foffload_via_llvm,
6813 options::OPT_fno_offload_via_llvm, false) &&
6816 switch (D.getOpenMPRuntime(Args)) {
6817 case Driver::OMPRT_OMP:
6819 // Clang can generate useful OpenMP code for these two runtime libraries.
6820 CmdArgs.push_back("-fopenmp");
6821
6822 // If no option regarding the use of TLS in OpenMP codegeneration is
6823 // given, decide a default based on the target. Otherwise rely on the
6824 // options and pass the right information to the frontend.
6825 if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
6826 options::OPT_fnoopenmp_use_tls, /*Default=*/true))
6827 CmdArgs.push_back("-fnoopenmp-use-tls");
6828 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6829 options::OPT_fno_openmp_simd);
6830 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_enable_irbuilder);
6831 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6832 if (!Args.hasFlag(options::OPT_fopenmp_extensions,
6833 options::OPT_fno_openmp_extensions, /*Default=*/true))
6834 CmdArgs.push_back("-fno-openmp-extensions");
6835 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
6836 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
6837 Args.AddAllArgs(CmdArgs,
6838 options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
6839 if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
6840 options::OPT_fno_openmp_optimistic_collapse,
6841 /*Default=*/false))
6842 CmdArgs.push_back("-fopenmp-optimistic-collapse");
6843
6844 // When in OpenMP offloading mode with NVPTX target, forward
6845 // cuda-mode flag
6846 if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
6847 options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
6848 CmdArgs.push_back("-fopenmp-cuda-mode");
6849
6850 // When in OpenMP offloading mode, enable debugging on the device.
6851 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_target_debug_EQ);
6852 if (Args.hasFlag(options::OPT_fopenmp_target_debug,
6853 options::OPT_fno_openmp_target_debug, /*Default=*/false))
6854 CmdArgs.push_back("-fopenmp-target-debug");
6855
6856 // When in OpenMP offloading mode, forward assumptions information about
6857 // thread and team counts in the device.
6858 if (Args.hasFlag(options::OPT_fopenmp_assume_teams_oversubscription,
6859 options::OPT_fno_openmp_assume_teams_oversubscription,
6860 /*Default=*/false))
6861 CmdArgs.push_back("-fopenmp-assume-teams-oversubscription");
6862 if (Args.hasFlag(options::OPT_fopenmp_assume_threads_oversubscription,
6863 options::OPT_fno_openmp_assume_threads_oversubscription,
6864 /*Default=*/false))
6865 CmdArgs.push_back("-fopenmp-assume-threads-oversubscription");
6866 if (Args.hasArg(options::OPT_fopenmp_assume_no_thread_state))
6867 CmdArgs.push_back("-fopenmp-assume-no-thread-state");
6868 if (Args.hasArg(options::OPT_fopenmp_assume_no_nested_parallelism))
6869 CmdArgs.push_back("-fopenmp-assume-no-nested-parallelism");
6870 if (Args.hasArg(options::OPT_fopenmp_offload_mandatory))
6871 CmdArgs.push_back("-fopenmp-offload-mandatory");
6872 if (Args.hasArg(options::OPT_fopenmp_force_usm))
6873 CmdArgs.push_back("-fopenmp-force-usm");
6874 break;
6875 default:
6876 // By default, if Clang doesn't know how to generate useful OpenMP code
6877 // for a specific runtime library, we just don't pass the '-fopenmp' flag
6878 // down to the actual compilation.
6879 // FIXME: It would be better to have a mode which *only* omits IR
6880 // generation based on the OpenMP support so that we get consistent
6881 // semantic analysis, etc.
6882 break;
6883 }
6884 } else {
6885 Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
6886 options::OPT_fno_openmp_simd);
6887 Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
6888 Args.addOptOutFlag(CmdArgs, options::OPT_fopenmp_extensions,
6889 options::OPT_fno_openmp_extensions);
6890 }
6891 // Forward the offload runtime change to code generation, liboffload implies
6892 // new driver. Otherwise, check if we should forward the new driver to change
6893 // offloading code generation.
6894 if (Args.hasFlag(options::OPT_foffload_via_llvm,
6895 options::OPT_fno_offload_via_llvm, false)) {
6896 CmdArgs.append({"--offload-new-driver", "-foffload-via-llvm"});
6897 } else if (Args.hasFlag(options::OPT_offload_new_driver,
6898 options::OPT_no_offload_new_driver, false)) {
6899 CmdArgs.push_back("--offload-new-driver");
6900 }
6901
6902 const XRayArgs &XRay = TC.getXRayArgs();
6903 XRay.addArgs(TC, Args, CmdArgs, InputType);
6904
6905 for (const auto &Filename :
6906 Args.getAllArgValues(options::OPT_fprofile_list_EQ)) {
6907 if (D.getVFS().exists(Filename))
6908 CmdArgs.push_back(Args.MakeArgString("-fprofile-list=" + Filename));
6909 else
6910 D.Diag(clang::diag::err_drv_no_such_file) << Filename;
6911 }
6912
6913 if (Arg *A = Args.getLastArg(options::OPT_fpatchable_function_entry_EQ)) {
6914 StringRef S0 = A->getValue(), S = S0;
6915 unsigned Size, Offset = 0;
6916 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
6917 !Triple.isX86() &&
6918 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
6919 Triple.getArch() == llvm::Triple::ppc64)))
6920 D.Diag(diag::err_drv_unsupported_opt_for_target)
6921 << A->getAsString(Args) << TripleStr;
6922 else if (S.consumeInteger(10, Size) ||
6923 (!S.empty() && (!S.consume_front(",") ||
6924 S.consumeInteger(10, Offset) || !S.empty())))
6925 D.Diag(diag::err_drv_invalid_argument_to_option)
6926 << S0 << A->getOption().getName();
6927 else if (Size < Offset)
6928 D.Diag(diag::err_drv_unsupported_fpatchable_function_entry_argument);
6929 else {
6930 CmdArgs.push_back(Args.MakeArgString(A->getSpelling() + Twine(Size)));
6931 CmdArgs.push_back(Args.MakeArgString(
6932 "-fpatchable-function-entry-offset=" + Twine(Offset)));
6933 }
6934 }
6935
6936 Args.AddLastArg(CmdArgs, options::OPT_fms_hotpatch);
6937
6938 if (TC.SupportsProfiling()) {
6939 Args.AddLastArg(CmdArgs, options::OPT_pg);
6940
6941 llvm::Triple::ArchType Arch = TC.getArch();
6942 if (Arg *A = Args.getLastArg(options::OPT_mfentry)) {
6943 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
6944 A->render(Args, CmdArgs);
6945 else
6946 D.Diag(diag::err_drv_unsupported_opt_for_target)
6947 << A->getAsString(Args) << TripleStr;
6948 }
6949 if (Arg *A = Args.getLastArg(options::OPT_mnop_mcount)) {
6950 if (Arch == llvm::Triple::systemz)
6951 A->render(Args, CmdArgs);
6952 else
6953 D.Diag(diag::err_drv_unsupported_opt_for_target)
6954 << A->getAsString(Args) << TripleStr;
6955 }
6956 if (Arg *A = Args.getLastArg(options::OPT_mrecord_mcount)) {
6957 if (Arch == llvm::Triple::systemz)
6958 A->render(Args, CmdArgs);
6959 else
6960 D.Diag(diag::err_drv_unsupported_opt_for_target)
6961 << A->getAsString(Args) << TripleStr;
6962 }
6963 }
6964
6965 if (Arg *A = Args.getLastArgNoClaim(options::OPT_pg)) {
6966 if (TC.getTriple().isOSzOS()) {
6967 D.Diag(diag::err_drv_unsupported_opt_for_target)
6968 << A->getAsString(Args) << TripleStr;
6969 }
6970 }
6971 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p)) {
6972 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
6973 D.Diag(diag::err_drv_unsupported_opt_for_target)
6974 << A->getAsString(Args) << TripleStr;
6975 }
6976 }
6977 if (Arg *A = Args.getLastArgNoClaim(options::OPT_p, options::OPT_pg)) {
6978 if (A->getOption().matches(options::OPT_p)) {
6979 A->claim();
6980 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(options::OPT_pg))
6981 CmdArgs.push_back("-pg");
6982 }
6983 }
6984
6985 // Reject AIX-specific link options on other targets.
6986 if (!TC.getTriple().isOSAIX()) {
6987 for (const Arg *A : Args.filtered(options::OPT_b, options::OPT_K,
6988 options::OPT_mxcoff_build_id_EQ)) {
6989 D.Diag(diag::err_drv_unsupported_opt_for_target)
6990 << A->getSpelling() << TripleStr;
6991 }
6992 }
6993
6994 if (Args.getLastArg(options::OPT_fapple_kext) ||
6995 (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
6996 CmdArgs.push_back("-fapple-kext");
6997
6998 Args.AddLastArg(CmdArgs, options::OPT_altivec_src_compat);
6999 Args.AddLastArg(CmdArgs, options::OPT_flax_vector_conversions_EQ);
7000 Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
7001 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
7002 Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
7003 Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
7004 Args.AddLastArg(CmdArgs, options::OPT_ftime_report_EQ);
7005 Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
7006 Args.AddLastArg(CmdArgs, options::OPT_malign_double);
7007 Args.AddLastArg(CmdArgs, options::OPT_fno_temp_file);
7008
7009 if (const char *Name = C.getTimeTraceFile(&JA)) {
7010 CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
7011 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
7012 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_verbose);
7013 }
7014
7015 if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
7016 CmdArgs.push_back("-ftrapv-handler");
7017 CmdArgs.push_back(A->getValue());
7018 }
7019
7020 Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
7021
7022 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
7023 // clang and flang.
7025
7026 Args.AddLastArg(CmdArgs, options::OPT_ffinite_loops,
7027 options::OPT_fno_finite_loops);
7028
7029 Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
7030 Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
7031 options::OPT_fno_unroll_loops);
7032
7033 Args.AddLastArg(CmdArgs, options::OPT_fstrict_flex_arrays_EQ);
7034
7035 Args.AddLastArg(CmdArgs, options::OPT_pthread);
7036
7037 Args.addOptInFlag(CmdArgs, options::OPT_mspeculative_load_hardening,
7038 options::OPT_mno_speculative_load_hardening);
7039
7040 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
7041 RenderSCPOptions(TC, Args, CmdArgs);
7042 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
7043
7044 Args.AddLastArg(CmdArgs, options::OPT_fswift_async_fp_EQ);
7045
7046 Args.addOptInFlag(CmdArgs, options::OPT_mstackrealign,
7047 options::OPT_mno_stackrealign);
7048
7049 if (Args.hasArg(options::OPT_mstack_alignment)) {
7050 StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
7051 CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
7052 }
7053
7054 if (Args.hasArg(options::OPT_mstack_probe_size)) {
7055 StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
7056
7057 if (!Size.empty())
7058 CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
7059 else
7060 CmdArgs.push_back("-mstack-probe-size=0");
7061 }
7062
7063 Args.addOptOutFlag(CmdArgs, options::OPT_mstack_arg_probe,
7064 options::OPT_mno_stack_arg_probe);
7065
7066 if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
7067 options::OPT_mno_restrict_it)) {
7068 if (A->getOption().matches(options::OPT_mrestrict_it)) {
7069 CmdArgs.push_back("-mllvm");
7070 CmdArgs.push_back("-arm-restrict-it");
7071 } else {
7072 CmdArgs.push_back("-mllvm");
7073 CmdArgs.push_back("-arm-default-it");
7074 }
7075 }
7076
7077 // Forward -cl options to -cc1
7078 RenderOpenCLOptions(Args, CmdArgs, InputType);
7079
7080 // Forward hlsl options to -cc1
7081 RenderHLSLOptions(Args, CmdArgs, InputType);
7082
7083 // Forward OpenACC options to -cc1
7084 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
7085
7086 if (IsHIP) {
7087 if (Args.hasFlag(options::OPT_fhip_new_launch_api,
7088 options::OPT_fno_hip_new_launch_api, true))
7089 CmdArgs.push_back("-fhip-new-launch-api");
7090 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
7091 options::OPT_fno_gpu_allow_device_init);
7092 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
7093 Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
7094 Args.addOptInFlag(CmdArgs, options::OPT_fhip_kernel_arg_name,
7095 options::OPT_fno_hip_kernel_arg_name);
7096 }
7097
7098 if (IsCuda || IsHIP) {
7099 if (IsRDCMode)
7100 CmdArgs.push_back("-fgpu-rdc");
7101 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_defer_diag,
7102 options::OPT_fno_gpu_defer_diag);
7103 if (Args.hasFlag(options::OPT_fgpu_exclude_wrong_side_overloads,
7104 options::OPT_fno_gpu_exclude_wrong_side_overloads,
7105 false)) {
7106 CmdArgs.push_back("-fgpu-exclude-wrong-side-overloads");
7107 CmdArgs.push_back("-fgpu-defer-diag");
7108 }
7109 }
7110
7111 // Forward -nogpulib to -cc1.
7112 if (Args.hasArg(options::OPT_nogpulib))
7113 CmdArgs.push_back("-nogpulib");
7114
7115 if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
7116 CmdArgs.push_back(
7117 Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
7118
7119 if (Arg *SA = Args.getLastArg(options::OPT_mcf_branch_label_scheme_EQ))
7120 CmdArgs.push_back(Args.MakeArgString(Twine("-mcf-branch-label-scheme=") +
7121 SA->getValue()));
7122 }
7123
7124 if (Arg *A = Args.getLastArg(options::OPT_mfunction_return_EQ))
7125 CmdArgs.push_back(
7126 Args.MakeArgString(Twine("-mfunction-return=") + A->getValue()));
7127
7128 Args.AddLastArg(CmdArgs, options::OPT_mindirect_branch_cs_prefix);
7129
7130 // Forward -f options with positive and negative forms; we translate these by
7131 // hand. Do not propagate PGO options to the GPU-side compilations as the
7132 // profile info is for the host-side compilation only.
7133 if (!(IsCudaDevice || IsHIPDevice)) {
7134 if (Arg *A = getLastProfileSampleUseArg(Args)) {
7135 auto *PGOArg = Args.getLastArg(
7136 options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
7137 options::OPT_fcs_profile_generate,
7138 options::OPT_fcs_profile_generate_EQ, options::OPT_fprofile_use,
7139 options::OPT_fprofile_use_EQ);
7140 if (PGOArg)
7141 D.Diag(diag::err_drv_argument_not_allowed_with)
7142 << "SampleUse with PGO options";
7143
7144 StringRef fname = A->getValue();
7145 if (!llvm::sys::fs::exists(fname))
7146 D.Diag(diag::err_drv_no_such_file) << fname;
7147 else
7148 A->render(Args, CmdArgs);
7149 }
7150 Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
7151
7152 if (Args.hasFlag(options::OPT_fpseudo_probe_for_profiling,
7153 options::OPT_fno_pseudo_probe_for_profiling, false)) {
7154 CmdArgs.push_back("-fpseudo-probe-for-profiling");
7155 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7156 // off.
7157 if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
7158 options::OPT_fno_unique_internal_linkage_names, true))
7159 CmdArgs.push_back("-funique-internal-linkage-names");
7160 }
7161 }
7162 RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
7163
7164 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7165 options::OPT_fno_assume_sane_operator_new);
7166
7167 if (Args.hasFlag(options::OPT_fapinotes, options::OPT_fno_apinotes, false))
7168 CmdArgs.push_back("-fapinotes");
7169 if (Args.hasFlag(options::OPT_fapinotes_modules,
7170 options::OPT_fno_apinotes_modules, false))
7171 CmdArgs.push_back("-fapinotes-modules");
7172 Args.AddLastArg(CmdArgs, options::OPT_fapinotes_swift_version);
7173
7174 // -fblocks=0 is default.
7175 if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
7176 TC.IsBlocksDefault()) ||
7177 (Args.hasArg(options::OPT_fgnu_runtime) &&
7178 Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
7179 !Args.hasArg(options::OPT_fno_blocks))) {
7180 CmdArgs.push_back("-fblocks");
7181
7182 if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7183 CmdArgs.push_back("-fblocks-runtime-optional");
7184 }
7185
7186 // -fencode-extended-block-signature=1 is default.
7188 CmdArgs.push_back("-fencode-extended-block-signature");
7189
7190 if (Args.hasFlag(options::OPT_fcoro_aligned_allocation,
7191 options::OPT_fno_coro_aligned_allocation, false) &&
7192 types::isCXX(InputType))
7193 CmdArgs.push_back("-fcoro-aligned-allocation");
7194
7195 Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
7196 options::OPT_fno_double_square_bracket_attributes);
7197
7198 Args.addOptOutFlag(CmdArgs, options::OPT_faccess_control,
7199 options::OPT_fno_access_control);
7200 Args.addOptOutFlag(CmdArgs, options::OPT_felide_constructors,
7201 options::OPT_fno_elide_constructors);
7202
7203 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7204
7205 if (KernelOrKext || (types::isCXX(InputType) &&
7206 (RTTIMode == ToolChain::RM_Disabled)))
7207 CmdArgs.push_back("-fno-rtti");
7208
7209 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7210 if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
7211 TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7212 CmdArgs.push_back("-fshort-enums");
7213
7214 RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7215
7216 // -fuse-cxa-atexit is default.
7217 if (!Args.hasFlag(
7218 options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
7219 !RawTriple.isOSAIX() && !RawTriple.isOSWindows() &&
7220 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7221 RawTriple.hasEnvironment())) ||
7222 KernelOrKext)
7223 CmdArgs.push_back("-fno-use-cxa-atexit");
7224
7225 if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
7226 options::OPT_fno_register_global_dtors_with_atexit,
7227 RawTriple.isOSDarwin() && !KernelOrKext))
7228 CmdArgs.push_back("-fregister-global-dtors-with-atexit");
7229
7230 Args.addOptInFlag(CmdArgs, options::OPT_fuse_line_directives,
7231 options::OPT_fno_use_line_directives);
7232
7233 // -fno-minimize-whitespace is default.
7234 if (Args.hasFlag(options::OPT_fminimize_whitespace,
7235 options::OPT_fno_minimize_whitespace, false)) {
7236 types::ID InputType = Inputs[0].getType();
7237 if (!isDerivedFromC(InputType))
7238 D.Diag(diag::err_drv_opt_unsupported_input_type)
7239 << "-fminimize-whitespace" << types::getTypeName(InputType);
7240 CmdArgs.push_back("-fminimize-whitespace");
7241 }
7242
7243 // -fno-keep-system-includes is default.
7244 if (Args.hasFlag(options::OPT_fkeep_system_includes,
7245 options::OPT_fno_keep_system_includes, false)) {
7246 types::ID InputType = Inputs[0].getType();
7247 if (!isDerivedFromC(InputType))
7248 D.Diag(diag::err_drv_opt_unsupported_input_type)
7249 << "-fkeep-system-includes" << types::getTypeName(InputType);
7250 CmdArgs.push_back("-fkeep-system-includes");
7251 }
7252
7253 // -fms-extensions=0 is default.
7254 if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
7255 IsWindowsMSVC))
7256 CmdArgs.push_back("-fms-extensions");
7257
7258 // -fms-compatibility=0 is default.
7259 bool IsMSVCCompat = Args.hasFlag(
7260 options::OPT_fms_compatibility, options::OPT_fno_ms_compatibility,
7261 (IsWindowsMSVC && Args.hasFlag(options::OPT_fms_extensions,
7262 options::OPT_fno_ms_extensions, true)));
7263 if (IsMSVCCompat) {
7264 CmdArgs.push_back("-fms-compatibility");
7265 if (!types::isCXX(Input.getType()) &&
7266 Args.hasArg(options::OPT_fms_define_stdc))
7267 CmdArgs.push_back("-fms-define-stdc");
7268 }
7269
7270 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7271 Args.hasArg(options::OPT_fms_runtime_lib_EQ))
7272 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
7273
7274 // Handle -fgcc-version, if present.
7275 VersionTuple GNUCVer;
7276 if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
7277 // Check that the version has 1 to 3 components and the minor and patch
7278 // versions fit in two decimal digits.
7279 StringRef Val = A->getValue();
7280 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7281 bool Invalid = GNUCVer.tryParse(Val);
7282 unsigned Minor = GNUCVer.getMinor().value_or(0);
7283 unsigned Patch = GNUCVer.getSubminor().value_or(0);
7284 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7285 D.Diag(diag::err_drv_invalid_value)
7286 << A->getAsString(Args) << A->getValue();
7287 }
7288 } else if (!IsMSVCCompat) {
7289 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7290 GNUCVer = VersionTuple(4, 2, 1);
7291 }
7292 if (!GNUCVer.empty()) {
7293 CmdArgs.push_back(
7294 Args.MakeArgString("-fgnuc-version=" + GNUCVer.getAsString()));
7295 }
7296
7297 VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
7298 if (!MSVT.empty())
7299 CmdArgs.push_back(
7300 Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
7301
7302 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7303 if (ImplyVCPPCVer) {
7304 StringRef LanguageStandard;
7305 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7306 Std = StdArg;
7307 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7308 .Case("c11", "-std=c11")
7309 .Case("c17", "-std=c17")
7310 .Default("");
7311 if (LanguageStandard.empty())
7312 D.Diag(clang::diag::warn_drv_unused_argument)
7313 << StdArg->getAsString(Args);
7314 }
7315 CmdArgs.push_back(LanguageStandard.data());
7316 }
7317 if (ImplyVCPPCXXVer) {
7318 StringRef LanguageStandard;
7319 if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
7320 Std = StdArg;
7321 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7322 .Case("c++14", "-std=c++14")
7323 .Case("c++17", "-std=c++17")
7324 .Case("c++20", "-std=c++20")
7325 // TODO add c++23 and c++26 when MSVC supports it.
7326 .Case("c++23preview", "-std=c++23")
7327 .Case("c++latest", "-std=c++26")
7328 .Default("");
7329 if (LanguageStandard.empty())
7330 D.Diag(clang::diag::warn_drv_unused_argument)
7331 << StdArg->getAsString(Args);
7332 }
7333
7334 if (LanguageStandard.empty()) {
7335 if (IsMSVC2015Compatible)
7336 LanguageStandard = "-std=c++14";
7337 else
7338 LanguageStandard = "-std=c++11";
7339 }
7340
7341 CmdArgs.push_back(LanguageStandard.data());
7342 }
7343
7344 Args.addOptInFlag(CmdArgs, options::OPT_fborland_extensions,
7345 options::OPT_fno_borland_extensions);
7346
7347 // -fno-declspec is default, except for PS4/PS5.
7348 if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
7349 RawTriple.isPS()))
7350 CmdArgs.push_back("-fdeclspec");
7351 else if (Args.hasArg(options::OPT_fno_declspec))
7352 CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
7353
7354 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7355 // than 19.
7356 if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
7357 options::OPT_fno_threadsafe_statics,
7358 !types::isOpenCL(InputType) &&
7359 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7360 CmdArgs.push_back("-fno-threadsafe-statics");
7361
7362 if (!Args.hasFlag(options::OPT_fms_tls_guards, options::OPT_fno_ms_tls_guards,
7363 true))
7364 CmdArgs.push_back("-fno-ms-tls-guards");
7365
7366 // Add -fno-assumptions, if it was specified.
7367 if (!Args.hasFlag(options::OPT_fassumptions, options::OPT_fno_assumptions,
7368 true))
7369 CmdArgs.push_back("-fno-assumptions");
7370
7371 // -fgnu-keywords default varies depending on language; only pass if
7372 // specified.
7373 Args.AddLastArg(CmdArgs, options::OPT_fgnu_keywords,
7374 options::OPT_fno_gnu_keywords);
7375
7376 Args.addOptInFlag(CmdArgs, options::OPT_fgnu89_inline,
7377 options::OPT_fno_gnu89_inline);
7378
7379 const Arg *InlineArg = Args.getLastArg(options::OPT_finline_functions,
7380 options::OPT_finline_hint_functions,
7381 options::OPT_fno_inline_functions);
7382 if (Arg *A = Args.getLastArg(options::OPT_finline, options::OPT_fno_inline)) {
7383 if (A->getOption().matches(options::OPT_fno_inline))
7384 A->render(Args, CmdArgs);
7385 } else if (InlineArg) {
7386 InlineArg->render(Args, CmdArgs);
7387 }
7388
7389 Args.AddLastArg(CmdArgs, options::OPT_finline_max_stacksize_EQ);
7390
7391 // FIXME: Find a better way to determine whether we are in C++20.
7392 bool HaveCxx20 =
7393 Std &&
7394 (Std->containsValue("c++2a") || Std->containsValue("gnu++2a") ||
7395 Std->containsValue("c++20") || Std->containsValue("gnu++20") ||
7396 Std->containsValue("c++2b") || Std->containsValue("gnu++2b") ||
7397 Std->containsValue("c++23") || Std->containsValue("gnu++23") ||
7398 Std->containsValue("c++2c") || Std->containsValue("gnu++2c") ||
7399 Std->containsValue("c++26") || Std->containsValue("gnu++26") ||
7400 Std->containsValue("c++latest") || Std->containsValue("gnu++latest"));
7401 bool HaveModules =
7402 RenderModulesOptions(C, D, Args, Input, Output, HaveCxx20, CmdArgs);
7403
7404 // -fdelayed-template-parsing is default when targeting MSVC.
7405 // Many old Windows SDK versions require this to parse.
7406 //
7407 // According to
7408 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7409 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7410 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7411 // not enable -fdelayed-template-parsing by default after C++20.
7412 //
7413 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7414 // able to disable this by default at some point.
7415 if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
7416 options::OPT_fno_delayed_template_parsing,
7417 IsWindowsMSVC && !HaveCxx20)) {
7418 if (HaveCxx20)
7419 D.Diag(clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7420
7421 CmdArgs.push_back("-fdelayed-template-parsing");
7422 }
7423
7424 if (Args.hasFlag(options::OPT_fpch_validate_input_files_content,
7425 options::OPT_fno_pch_validate_input_files_content, false))
7426 CmdArgs.push_back("-fvalidate-ast-input-files-content");
7427 if (Args.hasFlag(options::OPT_fpch_instantiate_templates,
7428 options::OPT_fno_pch_instantiate_templates, false))
7429 CmdArgs.push_back("-fpch-instantiate-templates");
7430 if (Args.hasFlag(options::OPT_fpch_codegen, options::OPT_fno_pch_codegen,
7431 false))
7432 CmdArgs.push_back("-fmodules-codegen");
7433 if (Args.hasFlag(options::OPT_fpch_debuginfo, options::OPT_fno_pch_debuginfo,
7434 false))
7435 CmdArgs.push_back("-fmodules-debuginfo");
7436
7437 ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, Inputs, CmdArgs, rewriteKind);
7438 RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
7439 Input, CmdArgs);
7440
7441 if (types::isObjC(Input.getType()) &&
7442 Args.hasFlag(options::OPT_fobjc_encode_cxx_class_template_spec,
7443 options::OPT_fno_objc_encode_cxx_class_template_spec,
7444 !Runtime.isNeXTFamily()))
7445 CmdArgs.push_back("-fobjc-encode-cxx-class-template-spec");
7446
7447 if (Args.hasFlag(options::OPT_fapplication_extension,
7448 options::OPT_fno_application_extension, false))
7449 CmdArgs.push_back("-fapplication-extension");
7450
7451 // Handle GCC-style exception args.
7452 bool EH = false;
7453 if (!C.getDriver().IsCLMode())
7454 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
7455
7456 // Handle exception personalities
7457 Arg *A = Args.getLastArg(
7458 options::OPT_fsjlj_exceptions, options::OPT_fseh_exceptions,
7459 options::OPT_fdwarf_exceptions, options::OPT_fwasm_exceptions);
7460 if (A) {
7461 const Option &Opt = A->getOption();
7462 if (Opt.matches(options::OPT_fsjlj_exceptions))
7463 CmdArgs.push_back("-exception-model=sjlj");
7464 if (Opt.matches(options::OPT_fseh_exceptions))
7465 CmdArgs.push_back("-exception-model=seh");
7466 if (Opt.matches(options::OPT_fdwarf_exceptions))
7467 CmdArgs.push_back("-exception-model=dwarf");
7468 if (Opt.matches(options::OPT_fwasm_exceptions))
7469 CmdArgs.push_back("-exception-model=wasm");
7470 } else {
7471 switch (TC.GetExceptionModel(Args)) {
7472 default:
7473 break;
7474 case llvm::ExceptionHandling::DwarfCFI:
7475 CmdArgs.push_back("-exception-model=dwarf");
7476 break;
7477 case llvm::ExceptionHandling::SjLj:
7478 CmdArgs.push_back("-exception-model=sjlj");
7479 break;
7480 case llvm::ExceptionHandling::WinEH:
7481 CmdArgs.push_back("-exception-model=seh");
7482 break;
7483 }
7484 }
7485
7486 // C++ "sane" operator new.
7487 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_sane_operator_new,
7488 options::OPT_fno_assume_sane_operator_new);
7489
7490 // -fassume-unique-vtables is on by default.
7491 Args.addOptOutFlag(CmdArgs, options::OPT_fassume_unique_vtables,
7492 options::OPT_fno_assume_unique_vtables);
7493
7494 // -frelaxed-template-template-args is deprecated.
7495 if (Arg *A =
7496 Args.getLastArg(options::OPT_frelaxed_template_template_args,
7497 options::OPT_fno_relaxed_template_template_args)) {
7498 if (A->getOption().matches(
7499 options::OPT_fno_relaxed_template_template_args)) {
7500 D.Diag(diag::warn_drv_deprecated_arg_no_relaxed_template_template_args);
7501 CmdArgs.push_back("-fno-relaxed-template-template-args");
7502 } else {
7503 D.Diag(diag::warn_drv_deprecated_arg)
7504 << A->getAsString(Args) << /*hasReplacement=*/false;
7505 }
7506 }
7507
7508 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
7509 // by default.
7510 Args.addLastArg(CmdArgs, options::OPT_fsized_deallocation,
7511 options::OPT_fno_sized_deallocation);
7512
7513 // -faligned-allocation is on by default in C++17 onwards and otherwise off
7514 // by default.
7515 if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
7516 options::OPT_fno_aligned_allocation,
7517 options::OPT_faligned_new_EQ)) {
7518 if (A->getOption().matches(options::OPT_fno_aligned_allocation))
7519 CmdArgs.push_back("-fno-aligned-allocation");
7520 else
7521 CmdArgs.push_back("-faligned-allocation");
7522 }
7523
7524 // The default new alignment can be specified using a dedicated option or via
7525 // a GCC-compatible option that also turns on aligned allocation.
7526 if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
7527 options::OPT_faligned_new_EQ))
7528 CmdArgs.push_back(
7529 Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
7530
7531 // -fconstant-cfstrings is default, and may be subject to argument translation
7532 // on Darwin.
7533 if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
7534 options::OPT_fno_constant_cfstrings, true) ||
7535 !Args.hasFlag(options::OPT_mconstant_cfstrings,
7536 options::OPT_mno_constant_cfstrings, true))
7537 CmdArgs.push_back("-fno-constant-cfstrings");
7538
7539 Args.addOptInFlag(CmdArgs, options::OPT_fpascal_strings,
7540 options::OPT_fno_pascal_strings);
7541
7542 // Honor -fpack-struct= and -fpack-struct, if given. Note that
7543 // -fno-pack-struct doesn't apply to -fpack-struct=.
7544 if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
7545 std::string PackStructStr = "-fpack-struct=";
7546 PackStructStr += A->getValue();
7547 CmdArgs.push_back(Args.MakeArgString(PackStructStr));
7548 } else if (Args.hasFlag(options::OPT_fpack_struct,
7549 options::OPT_fno_pack_struct, false)) {
7550 CmdArgs.push_back("-fpack-struct=1");
7551 }
7552
7553 // Handle -fmax-type-align=N and -fno-type-align
7554 bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
7555 if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
7556 if (!SkipMaxTypeAlign) {
7557 std::string MaxTypeAlignStr = "-fmax-type-align=";
7558 MaxTypeAlignStr += A->getValue();
7559 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
7560 }
7561 } else if (RawTriple.isOSDarwin()) {
7562 if (!SkipMaxTypeAlign) {
7563 std::string MaxTypeAlignStr = "-fmax-type-align=16";
7564 CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
7565 }
7566 }
7567
7568 if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
7569 CmdArgs.push_back("-Qn");
7570
7571 // -fno-common is the default, set -fcommon only when that flag is set.
7572 Args.addOptInFlag(CmdArgs, options::OPT_fcommon, options::OPT_fno_common);
7573
7574 // -fsigned-bitfields is default, and clang doesn't yet support
7575 // -funsigned-bitfields.
7576 if (!Args.hasFlag(options::OPT_fsigned_bitfields,
7577 options::OPT_funsigned_bitfields, true))
7578 D.Diag(diag::warn_drv_clang_unsupported)
7579 << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
7580
7581 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
7582 if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope, true))
7583 D.Diag(diag::err_drv_clang_unsupported)
7584 << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
7585
7586 // -finput_charset=UTF-8 is default. Reject others
7587 if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
7588 StringRef value = inputCharset->getValue();
7589 if (!value.equals_insensitive("utf-8"))
7590 D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
7591 << value;
7592 }
7593
7594 // -fexec_charset=UTF-8 is default. Reject others
7595 if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
7596 StringRef value = execCharset->getValue();
7597 if (!value.equals_insensitive("utf-8"))
7598 D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
7599 << value;
7600 }
7601
7602 RenderDiagnosticsOptions(D, Args, CmdArgs);
7603
7604 Args.addOptInFlag(CmdArgs, options::OPT_fasm_blocks,
7605 options::OPT_fno_asm_blocks);
7606
7607 Args.addOptOutFlag(CmdArgs, options::OPT_fgnu_inline_asm,
7608 options::OPT_fno_gnu_inline_asm);
7609
7610 // Enable vectorization per default according to the optimization level
7611 // selected. For optimization levels that want vectorization we use the alias
7612 // option to simplify the hasFlag logic.
7613 bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
7614 OptSpecifier VectorizeAliasOption =
7615 EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
7616 if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
7617 options::OPT_fno_vectorize, EnableVec))
7618 CmdArgs.push_back("-vectorize-loops");
7619
7620 // -fslp-vectorize is enabled based on the optimization level selected.
7621 bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
7622 OptSpecifier SLPVectAliasOption =
7623 EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
7624 if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
7625 options::OPT_fno_slp_vectorize, EnableSLPVec))
7626 CmdArgs.push_back("-vectorize-slp");
7627
7628 ParseMPreferVectorWidth(D, Args, CmdArgs);
7629
7630 Args.AddLastArg(CmdArgs, options::OPT_fshow_overloads_EQ);
7631 Args.AddLastArg(CmdArgs,
7632 options::OPT_fsanitize_undefined_strip_path_components_EQ);
7633
7634 // -fdollars-in-identifiers default varies depending on platform and
7635 // language; only pass if specified.
7636 if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
7637 options::OPT_fno_dollars_in_identifiers)) {
7638 if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
7639 CmdArgs.push_back("-fdollars-in-identifiers");
7640 else
7641 CmdArgs.push_back("-fno-dollars-in-identifiers");
7642 }
7643
7644 Args.addOptInFlag(CmdArgs, options::OPT_fapple_pragma_pack,
7645 options::OPT_fno_apple_pragma_pack);
7646
7647 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
7648 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
7649 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
7650
7651 bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
7652 options::OPT_fno_rewrite_imports, false);
7653 if (RewriteImports)
7654 CmdArgs.push_back("-frewrite-imports");
7655
7656 Args.addOptInFlag(CmdArgs, options::OPT_fdirectives_only,
7657 options::OPT_fno_directives_only);
7658
7659 // Enable rewrite includes if the user's asked for it or if we're generating
7660 // diagnostics.
7661 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
7662 // nice to enable this when doing a crashdump for modules as well.
7663 if (Args.hasFlag(options::OPT_frewrite_includes,
7664 options::OPT_fno_rewrite_includes, false) ||
7665 (C.isForDiagnostics() && !HaveModules))
7666 CmdArgs.push_back("-frewrite-includes");
7667
7668 if (Args.hasFlag(options::OPT_fzos_extensions,
7669 options::OPT_fno_zos_extensions, false))
7670 CmdArgs.push_back("-fzos-extensions");
7671 else if (Args.hasArg(options::OPT_fno_zos_extensions))
7672 CmdArgs.push_back("-fno-zos-extensions");
7673
7674 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
7675 if (Arg *A = Args.getLastArg(options::OPT_traditional,
7676 options::OPT_traditional_cpp)) {
7677 if (isa<PreprocessJobAction>(JA))
7678 CmdArgs.push_back("-traditional-cpp");
7679 else
7680 D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
7681 }
7682
7683 Args.AddLastArg(CmdArgs, options::OPT_dM);
7684 Args.AddLastArg(CmdArgs, options::OPT_dD);
7685 Args.AddLastArg(CmdArgs, options::OPT_dI);
7686
7687 Args.AddLastArg(CmdArgs, options::OPT_fmax_tokens_EQ);
7688
7689 // Handle serialized diagnostics.
7690 if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
7691 CmdArgs.push_back("-serialize-diagnostic-file");
7692 CmdArgs.push_back(Args.MakeArgString(A->getValue()));
7693 }
7694
7695 if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
7696 CmdArgs.push_back("-fretain-comments-from-system-headers");
7697
7698 // Forward -fcomment-block-commands to -cc1.
7699 Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
7700 // Forward -fparse-all-comments to -cc1.
7701 Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
7702
7703 // Turn -fplugin=name.so into -load name.so
7704 for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
7705 CmdArgs.push_back("-load");
7706 CmdArgs.push_back(A->getValue());
7707 A->claim();
7708 }
7709
7710 // Turn -fplugin-arg-pluginname-key=value into
7711 // -plugin-arg-pluginname key=value
7712 // GCC has an actual plugin_argument struct with key/value pairs that it
7713 // passes to its plugins, but we don't, so just pass it on as-is.
7714 //
7715 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
7716 // argument key are allowed to contain dashes. GCC therefore only
7717 // allows dashes in the key. We do the same.
7718 for (const Arg *A : Args.filtered(options::OPT_fplugin_arg)) {
7719 auto ArgValue = StringRef(A->getValue());
7720 auto FirstDashIndex = ArgValue.find('-');
7721 StringRef PluginName = ArgValue.substr(0, FirstDashIndex);
7722 StringRef Arg = ArgValue.substr(FirstDashIndex + 1);
7723
7724 A->claim();
7725 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
7726 if (PluginName.empty()) {
7727 D.Diag(diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
7728 } else {
7729 D.Diag(diag::warn_drv_missing_plugin_arg)
7730 << PluginName << A->getAsString(Args);
7731 }
7732 continue;
7733 }
7734
7735 CmdArgs.push_back(Args.MakeArgString(Twine("-plugin-arg-") + PluginName));
7736 CmdArgs.push_back(Args.MakeArgString(Arg));
7737 }
7738
7739 // Forward -fpass-plugin=name.so to -cc1.
7740 for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
7741 CmdArgs.push_back(
7742 Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
7743 A->claim();
7744 }
7745
7746 // Forward --vfsoverlay to -cc1.
7747 for (const Arg *A : Args.filtered(options::OPT_vfsoverlay)) {
7748 CmdArgs.push_back("--vfsoverlay");
7749 CmdArgs.push_back(A->getValue());
7750 A->claim();
7751 }
7752
7753 Args.addOptInFlag(CmdArgs, options::OPT_fsafe_buffer_usage_suggestions,
7754 options::OPT_fno_safe_buffer_usage_suggestions);
7755
7756 Args.addOptInFlag(CmdArgs, options::OPT_fexperimental_late_parse_attributes,
7757 options::OPT_fno_experimental_late_parse_attributes);
7758
7759 // Setup statistics file output.
7760 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
7761 if (!StatsFile.empty()) {
7762 CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
7763 if (D.CCPrintInternalStats)
7764 CmdArgs.push_back("-stats-file-append");
7765 }
7766
7767 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
7768 // parser.
7769 for (auto Arg : Args.filtered(options::OPT_Xclang)) {
7770 Arg->claim();
7771 // -finclude-default-header flag is for preprocessor,
7772 // do not pass it to other cc1 commands when save-temps is enabled
7773 if (C.getDriver().isSaveTempsEnabled() &&
7774 !isa<PreprocessJobAction>(JA)) {
7775 if (StringRef(Arg->getValue()) == "-finclude-default-header")
7776 continue;
7777 }
7778 CmdArgs.push_back(Arg->getValue());
7779 }
7780 for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
7781 A->claim();
7782
7783 // We translate this by hand to the -cc1 argument, since nightly test uses
7784 // it and developers have been trained to spell it with -mllvm. Both
7785 // spellings are now deprecated and should be removed.
7786 if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
7787 CmdArgs.push_back("-disable-llvm-optzns");
7788 } else {
7789 A->render(Args, CmdArgs);
7790 }
7791 }
7792
7793 // This needs to run after -Xclang argument forwarding to pick up the target
7794 // features enabled through -Xclang -target-feature flags.
7795 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
7796
7797 // With -save-temps, we want to save the unoptimized bitcode output from the
7798 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
7799 // by the frontend.
7800 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
7801 // has slightly different breakdown between stages.
7802 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
7803 // pristine IR generated by the frontend. Ideally, a new compile action should
7804 // be added so both IR can be captured.
7805 if ((C.getDriver().isSaveTempsEnabled() ||
7807 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
7808 isa<CompileJobAction>(JA))
7809 CmdArgs.push_back("-disable-llvm-passes");
7810
7811 Args.AddAllArgs(CmdArgs, options::OPT_undef);
7812
7813 const char *Exec = D.getClangProgramPath();
7814
7815 // Optionally embed the -cc1 level arguments into the debug info or a
7816 // section, for build analysis.
7817 // Also record command line arguments into the debug info if
7818 // -grecord-gcc-switches options is set on.
7819 // By default, -gno-record-gcc-switches is set on and no recording.
7820 auto GRecordSwitches = false;
7821 auto FRecordSwitches = false;
7822 if (shouldRecordCommandLine(TC, Args, FRecordSwitches, GRecordSwitches)) {
7823 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
7824 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
7825 CmdArgs.push_back("-dwarf-debug-flags");
7826 CmdArgs.push_back(FlagsArgString);
7827 }
7828 if (FRecordSwitches) {
7829 CmdArgs.push_back("-record-command-line");
7830 CmdArgs.push_back(FlagsArgString);
7831 }
7832 }
7833
7834 // Host-side offloading compilation receives all device-side outputs. Include
7835 // them in the host compilation depending on the target. If the host inputs
7836 // are not empty we use the new-driver scheme, otherwise use the old scheme.
7837 if ((IsCuda || IsHIP) && CudaDeviceInput) {
7838 CmdArgs.push_back("-fcuda-include-gpubinary");
7839 CmdArgs.push_back(CudaDeviceInput->getFilename());
7840 } else if (!HostOffloadingInputs.empty()) {
7841 if ((IsCuda || IsHIP) && !IsRDCMode) {
7842 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
7843 CmdArgs.push_back("-fcuda-include-gpubinary");
7844 CmdArgs.push_back(HostOffloadingInputs.front().getFilename());
7845 } else {
7846 for (const InputInfo Input : HostOffloadingInputs)
7847 CmdArgs.push_back(Args.MakeArgString("-fembed-offload-object=" +
7848 TC.getInputFilename(Input)));
7849 }
7850 }
7851
7852 if (IsCuda) {
7853 if (Args.hasFlag(options::OPT_fcuda_short_ptr,
7854 options::OPT_fno_cuda_short_ptr, false))
7855 CmdArgs.push_back("-fcuda-short-ptr");
7856 }
7857
7858 if (IsCuda || IsHIP) {
7859 // Determine the original source input.
7860 const Action *SourceAction = &JA;
7861 while (SourceAction->getKind() != Action::InputClass) {
7862 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7863 SourceAction = SourceAction->getInputs()[0];
7864 }
7865 auto CUID = cast<InputAction>(SourceAction)->getId();
7866 if (!CUID.empty())
7867 CmdArgs.push_back(Args.MakeArgString(Twine("-cuid=") + Twine(CUID)));
7868
7869 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
7870 // be overriden by -fno-gpu-approx-transcendentals.
7871 bool UseApproxTranscendentals = Args.hasFlag(
7872 options::OPT_ffast_math, options::OPT_fno_fast_math, false);
7873 if (Args.hasFlag(options::OPT_fgpu_approx_transcendentals,
7874 options::OPT_fno_gpu_approx_transcendentals,
7875 UseApproxTranscendentals))
7876 CmdArgs.push_back("-fgpu-approx-transcendentals");
7877 } else {
7878 Args.claimAllArgs(options::OPT_fgpu_approx_transcendentals,
7879 options::OPT_fno_gpu_approx_transcendentals);
7880 }
7881
7882 if (IsHIP) {
7883 CmdArgs.push_back("-fcuda-allow-variadic-functions");
7884 Args.AddLastArg(CmdArgs, options::OPT_fgpu_default_stream_EQ);
7885 }
7886
7887 Args.AddAllArgs(CmdArgs,
7888 options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
7889
7890 Args.AddLastArg(CmdArgs, options::OPT_foffload_uniform_block,
7891 options::OPT_fno_offload_uniform_block);
7892
7893 Args.AddLastArg(CmdArgs, options::OPT_foffload_implicit_host_device_templates,
7894 options::OPT_fno_offload_implicit_host_device_templates);
7895
7896 if (IsCudaDevice || IsHIPDevice) {
7897 StringRef InlineThresh =
7898 Args.getLastArgValue(options::OPT_fgpu_inline_threshold_EQ);
7899 if (!InlineThresh.empty()) {
7900 std::string ArgStr =
7901 std::string("-inline-threshold=") + InlineThresh.str();
7902 CmdArgs.append({"-mllvm", Args.MakeArgStringRef(ArgStr)});
7903 }
7904 }
7905
7906 if (IsHIPDevice)
7907 Args.addOptOutFlag(CmdArgs,
7908 options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
7909 options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
7910
7911 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
7912 // to specify the result of the compile phase on the host, so the meaningful
7913 // device declarations can be identified. Also, -fopenmp-is-target-device is
7914 // passed along to tell the frontend that it is generating code for a device,
7915 // so that only the relevant declarations are emitted.
7916 if (IsOpenMPDevice) {
7917 CmdArgs.push_back("-fopenmp-is-target-device");
7918 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
7919 if (Args.hasArg(options::OPT_foffload_via_llvm))
7920 CmdArgs.push_back("-fcuda-is-device");
7921
7922 if (OpenMPDeviceInput) {
7923 CmdArgs.push_back("-fopenmp-host-ir-file-path");
7924 CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
7925 }
7926 }
7927
7928 if (Triple.isAMDGPU()) {
7930
7931 Args.addOptInFlag(CmdArgs, options::OPT_munsafe_fp_atomics,
7932 options::OPT_mno_unsafe_fp_atomics);
7933 Args.addOptOutFlag(CmdArgs, options::OPT_mamdgpu_ieee,
7934 options::OPT_mno_amdgpu_ieee);
7935 }
7936
7937 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
7938
7939 bool VirtualFunctionElimination =
7940 Args.hasFlag(options::OPT_fvirtual_function_elimination,
7941 options::OPT_fno_virtual_function_elimination, false);
7942 if (VirtualFunctionElimination) {
7943 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
7944 // in the future).
7945 if (LTOMode != LTOK_Full)
7946 D.Diag(diag::err_drv_argument_only_allowed_with)
7947 << "-fvirtual-function-elimination"
7948 << "-flto=full";
7949
7950 CmdArgs.push_back("-fvirtual-function-elimination");
7951 }
7952
7953 // VFE requires whole-program-vtables, and enables it by default.
7954 bool WholeProgramVTables = Args.hasFlag(
7955 options::OPT_fwhole_program_vtables,
7956 options::OPT_fno_whole_program_vtables, VirtualFunctionElimination);
7957 if (VirtualFunctionElimination && !WholeProgramVTables) {
7958 D.Diag(diag::err_drv_argument_not_allowed_with)
7959 << "-fno-whole-program-vtables"
7960 << "-fvirtual-function-elimination";
7961 }
7962
7963 if (WholeProgramVTables) {
7964 // PS4 uses the legacy LTO API, which does not support this feature in
7965 // ThinLTO mode.
7966 bool IsPS4 = getToolChain().getTriple().isPS4();
7967
7968 // Check if we passed LTO options but they were suppressed because this is a
7969 // device offloading action, or we passed device offload LTO options which
7970 // were suppressed because this is not the device offload action.
7971 // Check if we are using PS4 in regular LTO mode.
7972 // Otherwise, issue an error.
7973
7974 auto OtherLTOMode =
7975 IsDeviceOffloadAction ? D.getLTOMode() : D.getOffloadLTOMode();
7976 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
7977
7978 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
7979 (IsPS4 && !UnifiedLTO && (D.getLTOMode() != LTOK_Full)))
7980 D.Diag(diag::err_drv_argument_only_allowed_with)
7981 << "-fwhole-program-vtables"
7982 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
7983
7984 // Propagate -fwhole-program-vtables if this is an LTO compile.
7985 if (IsUsingLTO)
7986 CmdArgs.push_back("-fwhole-program-vtables");
7987 }
7988
7989 bool DefaultsSplitLTOUnit =
7990 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
7991 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
7992 (!Triple.isPS4() && UnifiedLTO);
7993 bool SplitLTOUnit =
7994 Args.hasFlag(options::OPT_fsplit_lto_unit,
7995 options::OPT_fno_split_lto_unit, DefaultsSplitLTOUnit);
7996 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
7997 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
7998 << "-fsanitize=cfi";
7999 if (SplitLTOUnit)
8000 CmdArgs.push_back("-fsplit-lto-unit");
8001
8002 if (Arg *A = Args.getLastArg(options::OPT_ffat_lto_objects,
8003 options::OPT_fno_fat_lto_objects)) {
8004 if (IsUsingLTO && A->getOption().matches(options::OPT_ffat_lto_objects)) {
8005 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
8006 if (!Triple.isOSBinFormatELF()) {
8007 D.Diag(diag::err_drv_unsupported_opt_for_target)
8008 << A->getAsString(Args) << TC.getTripleString();
8009 }
8010 CmdArgs.push_back(Args.MakeArgString(
8011 Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
8012 CmdArgs.push_back("-flto-unit");
8013 CmdArgs.push_back("-ffat-lto-objects");
8014 A->render(Args, CmdArgs);
8015 }
8016 }
8017
8018 if (Arg *A = Args.getLastArg(options::OPT_fglobal_isel,
8019 options::OPT_fno_global_isel)) {
8020 CmdArgs.push_back("-mllvm");
8021 if (A->getOption().matches(options::OPT_fglobal_isel)) {
8022 CmdArgs.push_back("-global-isel=1");
8023
8024 // GISel is on by default on AArch64 -O0, so don't bother adding
8025 // the fallback remarks for it. Other combinations will add a warning of
8026 // some kind.
8027 bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
8028 bool IsOptLevelSupported = false;
8029
8030 Arg *A = Args.getLastArg(options::OPT_O_Group);
8031 if (Triple.getArch() == llvm::Triple::aarch64) {
8032 if (!A || A->getOption().matches(options::OPT_O0))
8033 IsOptLevelSupported = true;
8034 }
8035 if (!IsArchSupported || !IsOptLevelSupported) {
8036 CmdArgs.push_back("-mllvm");
8037 CmdArgs.push_back("-global-isel-abort=2");
8038
8039 if (!IsArchSupported)
8040 D.Diag(diag::warn_drv_global_isel_incomplete) << Triple.getArchName();
8041 else
8042 D.Diag(diag::warn_drv_global_isel_incomplete_opt);
8043 }
8044 } else {
8045 CmdArgs.push_back("-global-isel=0");
8046 }
8047 }
8048
8049 if (const Arg *A =
8050 Args.getLastArg(options::OPT_forder_file_instrumentation)) {
8051 D.Diag(diag::warn_drv_deprecated_arg)
8052 << A->getAsString(Args) << /*hasReplacement=*/true
8053 << "-mllvm -pgo-temporal-instrumentation";
8054 CmdArgs.push_back("-forder-file-instrumentation");
8055 // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
8056 // on, we need to pass these flags as linker flags and that will be handled
8057 // outside of the compiler.
8058 if (!IsUsingLTO) {
8059 CmdArgs.push_back("-mllvm");
8060 CmdArgs.push_back("-enable-order-file-instrumentation");
8061 }
8062 }
8063
8064 if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
8065 options::OPT_fno_force_enable_int128)) {
8066 if (A->getOption().matches(options::OPT_fforce_enable_int128))
8067 CmdArgs.push_back("-fforce-enable-int128");
8068 }
8069
8070 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_static_consts,
8071 options::OPT_fno_keep_static_consts);
8072 Args.addOptInFlag(CmdArgs, options::OPT_fkeep_persistent_storage_variables,
8073 options::OPT_fno_keep_persistent_storage_variables);
8074 Args.addOptInFlag(CmdArgs, options::OPT_fcomplete_member_pointers,
8075 options::OPT_fno_complete_member_pointers);
8076 if (Arg *A = Args.getLastArg(options::OPT_cxx_static_destructors_EQ))
8077 A->render(Args, CmdArgs);
8078
8079 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
8080
8081 addOutlineAtomicsArgs(D, getToolChain(), Args, CmdArgs, Triple);
8082
8083 if (Triple.isAArch64() &&
8084 (Args.hasArg(options::OPT_mno_fmv) ||
8085 (Triple.isAndroid() && Triple.isAndroidVersionLT(23)) ||
8086 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
8087 // Disable Function Multiversioning on AArch64 target.
8088 CmdArgs.push_back("-target-feature");
8089 CmdArgs.push_back("-fmv");
8090 }
8091
8092 if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
8093 (TC.getTriple().isOSBinFormatELF() ||
8094 TC.getTriple().isOSBinFormatCOFF()) &&
8095 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
8096 !TC.getTriple().isOSNetBSD() &&
8097 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
8098 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
8099 CmdArgs.push_back("-faddrsig");
8100
8101 if ((Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
8102 (EH || UnwindTables || AsyncUnwindTables ||
8103 DebugInfoKind != llvm::codegenoptions::NoDebugInfo))
8104 CmdArgs.push_back("-D__GCC_HAVE_DWARF2_CFI_ASM=1");
8105
8106 if (Arg *A = Args.getLastArg(options::OPT_fsymbol_partition_EQ)) {
8107 std::string Str = A->getAsString(Args);
8108 if (!TC.getTriple().isOSBinFormatELF())
8109 D.Diag(diag::err_drv_unsupported_opt_for_target)
8110 << Str << TC.getTripleString();
8111 CmdArgs.push_back(Args.MakeArgString(Str));
8112 }
8113
8114 // Add the "-o out -x type src.c" flags last. This is done primarily to make
8115 // the -cc1 command easier to edit when reproducing compiler crashes.
8116 if (Output.getType() == types::TY_Dependencies) {
8117 // Handled with other dependency code.
8118 } else if (Output.isFilename()) {
8119 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
8120 Output.getType() == clang::driver::types::TY_IFS) {
8121 SmallString<128> OutputFilename(Output.getFilename());
8122 llvm::sys::path::replace_extension(OutputFilename, "ifs");
8123 CmdArgs.push_back("-o");
8124 CmdArgs.push_back(Args.MakeArgString(OutputFilename));
8125 } else {
8126 CmdArgs.push_back("-o");
8127 CmdArgs.push_back(Output.getFilename());
8128 }
8129 } else {
8130 assert(Output.isNothing() && "Invalid output.");
8131 }
8132
8133 addDashXForInput(Args, Input, CmdArgs);
8134
8135 ArrayRef<InputInfo> FrontendInputs = Input;
8136 if (IsExtractAPI)
8137 FrontendInputs = ExtractAPIInputs;
8138 else if (Input.isNothing())
8139 FrontendInputs = {};
8140
8141 for (const InputInfo &Input : FrontendInputs) {
8142 if (Input.isFilename())
8143 CmdArgs.push_back(Input.getFilename());
8144 else
8145 Input.getInputArg().renderAsInput(Args, CmdArgs);
8146 }
8147
8148 if (D.CC1Main && !D.CCGenDiagnostics) {
8149 // Invoke the CC1 directly in this process
8150 C.addCommand(std::make_unique<CC1Command>(
8151 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8152 Output, D.getPrependArg()));
8153 } else {
8154 C.addCommand(std::make_unique<Command>(
8155 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8156 Output, D.getPrependArg()));
8157 }
8158
8159 // Make the compile command echo its inputs for /showFilenames.
8160 if (Output.getType() == types::TY_Object &&
8161 Args.hasFlag(options::OPT__SLASH_showFilenames,
8162 options::OPT__SLASH_showFilenames_, false)) {
8163 C.getJobs().getJobs().back()->PrintInputFilenames = true;
8164 }
8165
8166 if (Arg *A = Args.getLastArg(options::OPT_pg))
8167 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8168 !Args.hasArg(options::OPT_mfentry))
8169 D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8170 << A->getAsString(Args);
8171
8172 // Claim some arguments which clang supports automatically.
8173
8174 // -fpch-preprocess is used with gcc to add a special marker in the output to
8175 // include the PCH file.
8176 Args.ClaimAllArgs(options::OPT_fpch_preprocess);
8177
8178 // Claim some arguments which clang doesn't support, but we don't
8179 // care to warn the user about.
8180 Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
8181 Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
8182
8183 // Disable warnings for clang -E -emit-llvm foo.c
8184 Args.ClaimAllArgs(options::OPT_emit_llvm);
8185}
8186
8187Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8188 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8189 // as it is for other tools. Some operations on a Tool actually test
8190 // whether that tool is Clang based on the Tool's Name as a string.
8191 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8192
8194
8195/// Add options related to the Objective-C runtime/ABI.
8196///
8197/// Returns true if the runtime is non-fragile.
8198ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8199 const InputInfoList &inputs,
8200 ArgStringList &cmdArgs,
8201 RewriteKind rewriteKind) const {
8202 // Look for the controlling runtime option.
8203 Arg *runtimeArg =
8204 args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
8205 options::OPT_fobjc_runtime_EQ);
8206
8207 // Just forward -fobjc-runtime= to the frontend. This supercedes
8208 // options about fragility.
8209 if (runtimeArg &&
8210 runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
8211 ObjCRuntime runtime;
8212 StringRef value = runtimeArg->getValue();
8213 if (runtime.tryParse(value)) {
8214 getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
8215 << value;
8216 }
8217 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8218 (runtime.getVersion() >= VersionTuple(2, 0)))
8219 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8220 !getToolChain().getTriple().isOSBinFormatCOFF()) {
8222 diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8223 << runtime.getVersion().getMajor();
8224 }
8225
8226 runtimeArg->render(args, cmdArgs);
8227 return runtime;
8228 }
8229
8230 // Otherwise, we'll need the ABI "version". Version numbers are
8231 // slightly confusing for historical reasons:
8232 // 1 - Traditional "fragile" ABI
8233 // 2 - Non-fragile ABI, version 1
8234 // 3 - Non-fragile ABI, version 2
8235 unsigned objcABIVersion = 1;
8236 // If -fobjc-abi-version= is present, use that to set the version.
8237 if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
8238 StringRef value = abiArg->getValue();
8239 if (value == "1")
8240 objcABIVersion = 1;
8241 else if (value == "2")
8242 objcABIVersion = 2;
8243 else if (value == "3")
8244 objcABIVersion = 3;
8245 else
8246 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
8247 } else {
8248 // Otherwise, determine if we are using the non-fragile ABI.
8249 bool nonFragileABIIsDefault =
8250 (rewriteKind == RK_NonFragile ||
8251 (rewriteKind == RK_None &&
8253 if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
8254 options::OPT_fno_objc_nonfragile_abi,
8255 nonFragileABIIsDefault)) {
8256// Determine the non-fragile ABI version to use.
8257#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8258 unsigned nonFragileABIVersion = 1;
8259#else
8260 unsigned nonFragileABIVersion = 2;
8261#endif
8262
8263 if (Arg *abiArg =
8264 args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8265 StringRef value = abiArg->getValue();
8266 if (value == "1")
8267 nonFragileABIVersion = 1;
8268 else if (value == "2")
8269 nonFragileABIVersion = 2;
8270 else
8271 getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
8272 << value;
8273 }
8274
8275 objcABIVersion = 1 + nonFragileABIVersion;
8276 } else {
8277 objcABIVersion = 1;
8278 }
8279 }
8280
8281 // We don't actually care about the ABI version other than whether
8282 // it's non-fragile.
8283 bool isNonFragile = objcABIVersion != 1;
8284
8285 // If we have no runtime argument, ask the toolchain for its default runtime.
8286 // However, the rewriter only really supports the Mac runtime, so assume that.
8287 ObjCRuntime runtime;
8288 if (!runtimeArg) {
8289 switch (rewriteKind) {
8290 case RK_None:
8291 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8292 break;
8293 case RK_Fragile:
8294 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8295 break;
8296 case RK_NonFragile:
8297 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8298 break;
8299 }
8300
8301 // -fnext-runtime
8302 } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
8303 // On Darwin, make this use the default behavior for the toolchain.
8304 if (getToolChain().getTriple().isOSDarwin()) {
8305 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8306
8307 // Otherwise, build for a generic macosx port.
8308 } else {
8309 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8310 }
8311
8312 // -fgnu-runtime
8313 } else {
8314 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8315 // Legacy behaviour is to target the gnustep runtime if we are in
8316 // non-fragile mode or the GCC runtime in fragile mode.
8317 if (isNonFragile)
8318 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8319 else
8320 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8321 }
8322
8323 if (llvm::any_of(inputs, [](const InputInfo &input) {
8324 return types::isObjC(input.getType());
8325 }))
8326 cmdArgs.push_back(
8327 args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
8328 return runtime;
8329}
8330
8331static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8332 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8333 I += HaveDash;
8334 return !HaveDash;
8335}
8336
8337namespace {
8338struct EHFlags {
8339 bool Synch = false;
8340 bool Asynch = false;
8341 bool NoUnwindC = false;
8342};
8343} // end anonymous namespace
8344
8345/// /EH controls whether to run destructor cleanups when exceptions are
8346/// thrown. There are three modifiers:
8347/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8348/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8349/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8350/// - c: Assume that extern "C" functions are implicitly nounwind.
8351/// The default is /EHs-c-, meaning cleanups are disabled.
8352static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8353 bool isWindowsMSVC) {
8354 EHFlags EH;
8355
8356 std::vector<std::string> EHArgs =
8357 Args.getAllArgValues(options::OPT__SLASH_EH);
8358 for (const auto &EHVal : EHArgs) {
8359 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8360 switch (EHVal[I]) {
8361 case 'a':
8362 EH.Asynch = maybeConsumeDash(EHVal, I);
8363 if (EH.Asynch) {
8364 // Async exceptions are Windows MSVC only.
8365 if (!isWindowsMSVC) {
8366 EH.Asynch = false;
8367 D.Diag(clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8368 continue;
8369 }
8370 EH.Synch = false;
8371 }
8372 continue;
8373 case 'c':
8374 EH.NoUnwindC = maybeConsumeDash(EHVal, I);
8375 continue;
8376 case 's':
8377 EH.Synch = maybeConsumeDash(EHVal, I);
8378 if (EH.Synch)
8379 EH.Asynch = false;
8380 continue;
8381 default:
8382 break;
8383 }
8384 D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8385 break;
8386 }
8387 }
8388 // The /GX, /GX- flags are only processed if there are not /EH flags.
8389 // The default is that /GX is not specified.
8390 if (EHArgs.empty() &&
8391 Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
8392 /*Default=*/false)) {
8393 EH.Synch = true;
8394 EH.NoUnwindC = true;
8395 }
8396
8397 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8398 EH.Synch = false;
8399 EH.NoUnwindC = false;
8400 EH.Asynch = false;
8401 }
8402
8403 return EH;
8404}
8405
8406void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8407 ArgStringList &CmdArgs) const {
8408 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8409
8410 ProcessVSRuntimeLibrary(getToolChain(), Args, CmdArgs);
8411
8412 if (Arg *ShowIncludes =
8413 Args.getLastArg(options::OPT__SLASH_showIncludes,
8414 options::OPT__SLASH_showIncludes_user)) {
8415 CmdArgs.push_back("--show-includes");
8416 if (ShowIncludes->getOption().matches(options::OPT__SLASH_showIncludes))
8417 CmdArgs.push_back("-sys-header-deps");
8418 }
8419
8420 // This controls whether or not we emit RTTI data for polymorphic types.
8421 if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
8422 /*Default=*/false))
8423 CmdArgs.push_back("-fno-rtti-data");
8424
8425 // This controls whether or not we emit stack-protector instrumentation.
8426 // In MSVC, Buffer Security Check (/GS) is on by default.
8427 if (!isNVPTX && Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
8428 /*Default=*/true)) {
8429 CmdArgs.push_back("-stack-protector");
8430 CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
8431 }
8432
8433 const Driver &D = getToolChain().getDriver();
8434
8435 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
8436 EHFlags EH = parseClangCLEHFlags(D, Args, IsWindowsMSVC);
8437 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
8438 if (types::isCXX(InputType))
8439 CmdArgs.push_back("-fcxx-exceptions");
8440 CmdArgs.push_back("-fexceptions");
8441 if (EH.Asynch)
8442 CmdArgs.push_back("-fasync-exceptions");
8443 }
8444 if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
8445 CmdArgs.push_back("-fexternc-nounwind");
8446
8447 // /EP should expand to -E -P.
8448 if (Args.hasArg(options::OPT__SLASH_EP)) {
8449 CmdArgs.push_back("-E");
8450 CmdArgs.push_back("-P");
8451 }
8452
8453 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
8454 options::OPT__SLASH_Zc_dllexportInlines,
8455 false)) {
8456 CmdArgs.push_back("-fno-dllexport-inlines");
8457 }
8458
8459 if (Args.hasFlag(options::OPT__SLASH_Zc_wchar_t_,
8460 options::OPT__SLASH_Zc_wchar_t, false)) {
8461 CmdArgs.push_back("-fno-wchar");
8462 }
8463
8464 if (Args.hasArg(options::OPT__SLASH_kernel)) {
8465 llvm::Triple::ArchType Arch = getToolChain().getArch();
8466 std::vector<std::string> Values =
8467 Args.getAllArgValues(options::OPT__SLASH_arch);
8468 if (!Values.empty()) {
8469 llvm::SmallSet<std::string, 4> SupportedArches;
8470 if (Arch == llvm::Triple::x86)
8471 SupportedArches.insert("IA32");
8472
8473 for (auto &V : Values)
8474 if (!SupportedArches.contains(V))
8475 D.Diag(diag::err_drv_argument_not_allowed_with)
8476 << std::string("/arch:").append(V) << "/kernel";
8477 }
8478
8479 CmdArgs.push_back("-fno-rtti");
8480 if (Args.hasFlag(options::OPT__SLASH_GR, options::OPT__SLASH_GR_, false))
8481 D.Diag(diag::err_drv_argument_not_allowed_with) << "/GR"
8482 << "/kernel";
8483 }
8484
8485 Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
8486 Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
8487 if (MostGeneralArg && BestCaseArg)
8488 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8489 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
8490
8491 if (MostGeneralArg) {
8492 Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
8493 Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
8494 Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
8495
8496 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
8497 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
8498 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
8499 D.Diag(clang::diag::err_drv_argument_not_allowed_with)
8500 << FirstConflict->getAsString(Args)
8501 << SecondConflict->getAsString(Args);
8502
8503 if (SingleArg)
8504 CmdArgs.push_back("-fms-memptr-rep=single");
8505 else if (MultipleArg)
8506 CmdArgs.push_back("-fms-memptr-rep=multiple");
8507 else
8508 CmdArgs.push_back("-fms-memptr-rep=virtual");
8509 }
8510
8511 if (Args.hasArg(options::OPT_regcall4))
8512 CmdArgs.push_back("-regcall4");
8513
8514 // Parse the default calling convention options.
8515 if (Arg *CCArg =
8516 Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
8517 options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
8518 options::OPT__SLASH_Gregcall)) {
8519 unsigned DCCOptId = CCArg->getOption().getID();
8520 const char *DCCFlag = nullptr;
8521 bool ArchSupported = !isNVPTX;
8522 llvm::Triple::ArchType Arch = getToolChain().getArch();
8523 switch (DCCOptId) {
8524 case options::OPT__SLASH_Gd:
8525 DCCFlag = "-fdefault-calling-conv=cdecl";
8526 break;
8527 case options::OPT__SLASH_Gr:
8528 ArchSupported = Arch == llvm::Triple::x86;
8529 DCCFlag = "-fdefault-calling-conv=fastcall";
8530 break;
8531 case options::OPT__SLASH_Gz:
8532 ArchSupported = Arch == llvm::Triple::x86;
8533 DCCFlag = "-fdefault-calling-conv=stdcall";
8534 break;
8535 case options::OPT__SLASH_Gv:
8536 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8537 DCCFlag = "-fdefault-calling-conv=vectorcall";
8538 break;
8539 case options::OPT__SLASH_Gregcall:
8540 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8541 DCCFlag = "-fdefault-calling-conv=regcall";
8542 break;
8543 }
8544
8545 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
8546 if (ArchSupported && DCCFlag)
8547 CmdArgs.push_back(DCCFlag);
8548 }
8549
8550 if (Args.hasArg(options::OPT__SLASH_Gregcall4))
8551 CmdArgs.push_back("-regcall4");
8552
8553 Args.AddLastArg(CmdArgs, options::OPT_vtordisp_mode_EQ);
8554
8555 if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
8556 CmdArgs.push_back("-fdiagnostics-format");
8557 CmdArgs.push_back("msvc");
8558 }
8559
8560 if (Args.hasArg(options::OPT__SLASH_kernel))
8561 CmdArgs.push_back("-fms-kernel");
8562
8563 for (const Arg *A : Args.filtered(options::OPT__SLASH_guard)) {
8564 StringRef GuardArgs = A->getValue();
8565 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
8566 // "ehcont-".
8567 if (GuardArgs.equals_insensitive("cf")) {
8568 // Emit CFG instrumentation and the table of address-taken functions.
8569 CmdArgs.push_back("-cfguard");
8570 } else if (GuardArgs.equals_insensitive("cf,nochecks")) {
8571 // Emit only the table of address-taken functions.
8572 CmdArgs.push_back("-cfguard-no-checks");
8573 } else if (GuardArgs.equals_insensitive("ehcont")) {
8574 // Emit EH continuation table.
8575 CmdArgs.push_back("-ehcontguard");
8576 } else if (GuardArgs.equals_insensitive("cf-") ||
8577 GuardArgs.equals_insensitive("ehcont-")) {
8578 // Do nothing, but we might want to emit a security warning in future.
8579 } else {
8580 D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
8581 }
8582 A->claim();
8583 }
8584}
8585
8586const char *Clang::getBaseInputName(const ArgList &Args,
8587 const InputInfo &Input) {
8588 return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
8589}
8590
8591const char *Clang::getBaseInputStem(const ArgList &Args,
8592 const InputInfoList &Inputs) {
8593 const char *Str = getBaseInputName(Args, Inputs[0]);
8594
8595 if (const char *End = strrchr(Str, '.'))
8596 return Args.MakeArgString(std::string(Str, End));
8597
8598 return Str;
8599}
8600
8601const char *Clang::getDependencyFileName(const ArgList &Args,
8602 const InputInfoList &Inputs) {
8603 // FIXME: Think about this more.
8604
8605 if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
8606 SmallString<128> OutputFilename(OutputOpt->getValue());
8607 llvm::sys::path::replace_extension(OutputFilename, llvm::Twine('d'));
8608 return Args.MakeArgString(OutputFilename);
8609 }
8610
8611 return Args.MakeArgString(Twine(getBaseInputStem(Args, Inputs)) + ".d");
8612}
8613
8614// Begin ClangAs
8615
8616void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
8617 ArgStringList &CmdArgs) const {
8618 StringRef CPUName;
8619 StringRef ABIName;
8620 const llvm::Triple &Triple = getToolChain().getTriple();
8621 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
8622
8623 CmdArgs.push_back("-target-abi");
8624 CmdArgs.push_back(ABIName.data());
8625}
8626
8627void ClangAs::AddX86TargetArgs(const ArgList &Args,
8628 ArgStringList &CmdArgs) const {
8629 addX86AlignBranchArgs(getToolChain().getDriver(), Args, CmdArgs,
8630 /*IsLTO=*/false);
8631
8632 if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
8633 StringRef Value = A->getValue();
8634 if (Value == "intel" || Value == "att") {
8635 CmdArgs.push_back("-mllvm");
8636 CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
8637 } else {
8638 getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
8639 << A->getSpelling() << Value;
8640 }
8641 }
8642}
8643
8644void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
8645 ArgStringList &CmdArgs) const {
8646 CmdArgs.push_back("-target-abi");
8647 CmdArgs.push_back(loongarch::getLoongArchABI(getToolChain().getDriver(), Args,
8648 getToolChain().getTriple())
8649 .data());
8650}
8651
8652void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
8653 ArgStringList &CmdArgs) const {
8654 const llvm::Triple &Triple = getToolChain().getTriple();
8655 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
8656
8657 CmdArgs.push_back("-target-abi");
8658 CmdArgs.push_back(ABIName.data());
8659
8660 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8661 options::OPT_mno_default_build_attributes, true)) {
8662 CmdArgs.push_back("-mllvm");
8663 CmdArgs.push_back("-riscv-add-build-attributes");
8664 }
8665}
8666
8668 const InputInfo &Output, const InputInfoList &Inputs,
8669 const ArgList &Args,
8670 const char *LinkingOutput) const {
8671 ArgStringList CmdArgs;
8672
8673 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
8674 const InputInfo &Input = Inputs[0];
8675
8676 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
8677 const std::string &TripleStr = Triple.getTriple();
8678 const auto &D = getToolChain().getDriver();
8679
8680 // Don't warn about "clang -w -c foo.s"
8681 Args.ClaimAllArgs(options::OPT_w);
8682 // and "clang -emit-llvm -c foo.s"
8683 Args.ClaimAllArgs(options::OPT_emit_llvm);
8684
8685 claimNoWarnArgs(Args);
8686
8687 // Invoke ourselves in -cc1as mode.
8688 //
8689 // FIXME: Implement custom jobs for internal actions.
8690 CmdArgs.push_back("-cc1as");
8691
8692 // Add the "effective" target triple.
8693 CmdArgs.push_back("-triple");
8694 CmdArgs.push_back(Args.MakeArgString(TripleStr));
8695
8697
8698 // Set the output mode, we currently only expect to be used as a real
8699 // assembler.
8700 CmdArgs.push_back("-filetype");
8701 CmdArgs.push_back("obj");
8702
8703 // Set the main file name, so that debug info works even with
8704 // -save-temps or preprocessed assembly.
8705 CmdArgs.push_back("-main-file-name");
8706 CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
8707
8708 // Add the target cpu
8709 std::string CPU = getCPUName(D, Args, Triple, /*FromAs*/ true);
8710 if (!CPU.empty()) {
8711 CmdArgs.push_back("-target-cpu");
8712 CmdArgs.push_back(Args.MakeArgString(CPU));
8713 }
8714
8715 // Add the target features
8716 getTargetFeatures(D, Triple, Args, CmdArgs, true);
8717
8718 // Ignore explicit -force_cpusubtype_ALL option.
8719 (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
8720
8721 // Pass along any -I options so we get proper .include search paths.
8722 Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
8723
8724 // Pass along any --embed-dir or similar options so we get proper embed paths.
8725 Args.AddAllArgs(CmdArgs, options::OPT_embed_dir_EQ);
8726
8727 // Determine the original source input.
8728 auto FindSource = [](const Action *S) -> const Action * {
8729 while (S->getKind() != Action::InputClass) {
8730 assert(!S->getInputs().empty() && "unexpected root action!");
8731 S = S->getInputs()[0];
8732 }
8733 return S;
8734 };
8735 const Action *SourceAction = FindSource(&JA);
8736
8737 // Forward -g and handle debug info related flags, assuming we are dealing
8738 // with an actual assembly file.
8739 bool WantDebug = false;
8740 Args.ClaimAllArgs(options::OPT_g_Group);
8741 if (Arg *A = Args.getLastArg(options::OPT_g_Group))
8742 WantDebug = !A->getOption().matches(options::OPT_g0) &&
8743 !A->getOption().matches(options::OPT_ggdb0);
8744
8745 // If a -gdwarf argument appeared, remember it.
8746 bool EmitDwarf = false;
8747 if (const Arg *A = getDwarfNArg(Args))
8748 EmitDwarf = checkDebugInfoOption(A, Args, D, getToolChain());
8749
8750 bool EmitCodeView = false;
8751 if (const Arg *A = Args.getLastArg(options::OPT_gcodeview))
8752 EmitCodeView = checkDebugInfoOption(A, Args, D, getToolChain());
8753
8754 // If the user asked for debug info but did not explicitly specify -gcodeview
8755 // or -gdwarf, ask the toolchain for the default format.
8756 if (!EmitCodeView && !EmitDwarf && WantDebug) {
8757 switch (getToolChain().getDefaultDebugFormat()) {
8758 case llvm::codegenoptions::DIF_CodeView:
8759 EmitCodeView = true;
8760 break;
8761 case llvm::codegenoptions::DIF_DWARF:
8762 EmitDwarf = true;
8763 break;
8764 }
8765 }
8766
8767 // If the arguments don't imply DWARF, don't emit any debug info here.
8768 if (!EmitDwarf)
8769 WantDebug = false;
8770
8771 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
8772 llvm::codegenoptions::NoDebugInfo;
8773
8774 // Add the -fdebug-compilation-dir flag if needed.
8775 const char *DebugCompilationDir =
8776 addDebugCompDirArg(Args, CmdArgs, C.getDriver().getVFS());
8777
8778 if (SourceAction->getType() == types::TY_Asm ||
8779 SourceAction->getType() == types::TY_PP_Asm) {
8780 // You might think that it would be ok to set DebugInfoKind outside of
8781 // the guard for source type, however there is a test which asserts
8782 // that some assembler invocation receives no -debug-info-kind,
8783 // and it's not clear whether that test is just overly restrictive.
8784 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
8785 : llvm::codegenoptions::NoDebugInfo);
8786
8787 addDebugPrefixMapArg(getToolChain().getDriver(), getToolChain(), Args,
8788 CmdArgs);
8789
8790 // Set the AT_producer to the clang version when using the integrated
8791 // assembler on assembly source files.
8792 CmdArgs.push_back("-dwarf-debug-producer");
8793 CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
8794
8795 // And pass along -I options
8796 Args.AddAllArgs(CmdArgs, options::OPT_I);
8797 }
8798 const unsigned DwarfVersion = getDwarfVersion(getToolChain(), Args);
8799 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
8800 llvm::DebuggerKind::Default);
8801 renderDwarfFormat(D, Triple, Args, CmdArgs, DwarfVersion);
8803
8804 // Handle -fPIC et al -- the relocation-model affects the assembler
8805 // for some targets.
8806 llvm::Reloc::Model RelocationModel;
8807 unsigned PICLevel;
8808 bool IsPIE;
8809 std::tie(RelocationModel, PICLevel, IsPIE) =
8810 ParsePICArgs(getToolChain(), Args);
8811
8812 const char *RMName = RelocationModelName(RelocationModel);
8813 if (RMName) {
8814 CmdArgs.push_back("-mrelocation-model");
8815 CmdArgs.push_back(RMName);
8816 }
8817
8818 // Optionally embed the -cc1as level arguments into the debug info, for build
8819 // analysis.
8820 if (getToolChain().UseDwarfDebugFlags()) {
8821 ArgStringList OriginalArgs;
8822 for (const auto &Arg : Args)
8823 Arg->render(Args, OriginalArgs);
8824
8825 SmallString<256> Flags;
8826 const char *Exec = getToolChain().getDriver().getClangProgramPath();
8827 escapeSpacesAndBackslashes(Exec, Flags);
8828 for (const char *OriginalArg : OriginalArgs) {
8829 SmallString<128> EscapedArg;
8830 escapeSpacesAndBackslashes(OriginalArg, EscapedArg);
8831 Flags += " ";
8832 Flags += EscapedArg;
8833 }
8834 CmdArgs.push_back("-dwarf-debug-flags");
8835 CmdArgs.push_back(Args.MakeArgString(Flags));
8836 }
8837
8838 // FIXME: Add -static support, once we have it.
8839
8840 // Add target specific flags.
8841 switch (getToolChain().getArch()) {
8842 default:
8843 break;
8844
8845 case llvm::Triple::mips:
8846 case llvm::Triple::mipsel:
8847 case llvm::Triple::mips64:
8848 case llvm::Triple::mips64el:
8849 AddMIPSTargetArgs(Args, CmdArgs);
8850 break;
8851
8852 case llvm::Triple::x86:
8853 case llvm::Triple::x86_64:
8854 AddX86TargetArgs(Args, CmdArgs);
8855 break;
8856
8857 case llvm::Triple::arm:
8858 case llvm::Triple::armeb:
8859 case llvm::Triple::thumb:
8860 case llvm::Triple::thumbeb:
8861 // This isn't in AddARMTargetArgs because we want to do this for assembly
8862 // only, not C/C++.
8863 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8864 options::OPT_mno_default_build_attributes, true)) {
8865 CmdArgs.push_back("-mllvm");
8866 CmdArgs.push_back("-arm-add-build-attributes");
8867 }
8868 break;
8869
8870 case llvm::Triple::aarch64:
8871 case llvm::Triple::aarch64_32:
8872 case llvm::Triple::aarch64_be:
8873 if (Args.hasArg(options::OPT_mmark_bti_property)) {
8874 CmdArgs.push_back("-mllvm");
8875 CmdArgs.push_back("-aarch64-mark-bti-property");
8876 }
8877 break;
8878
8879 case llvm::Triple::loongarch32:
8880 case llvm::Triple::loongarch64:
8881 AddLoongArchTargetArgs(Args, CmdArgs);
8882 break;
8883
8884 case llvm::Triple::riscv32:
8885 case llvm::Triple::riscv64:
8886 AddRISCVTargetArgs(Args, CmdArgs);
8887 break;
8888
8889 case llvm::Triple::hexagon:
8890 if (Args.hasFlag(options::OPT_mdefault_build_attributes,
8891 options::OPT_mno_default_build_attributes, true)) {
8892 CmdArgs.push_back("-mllvm");
8893 CmdArgs.push_back("-hexagon-add-build-attributes");
8894 }
8895 break;
8896 }
8897
8898 // Consume all the warning flags. Usually this would be handled more
8899 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
8900 // doesn't handle that so rather than warning about unused flags that are
8901 // actually used, we'll lie by omission instead.
8902 // FIXME: Stop lying and consume only the appropriate driver flags
8903 Args.ClaimAllArgs(options::OPT_W_Group);
8904
8905 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
8906 getToolChain().getDriver());
8907
8908 Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
8909
8910 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
8911 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
8912 Output.getFilename());
8913
8914 // Fixup any previous commands that use -object-file-name because when we
8915 // generated them, the final .obj name wasn't yet known.
8916 for (Command &J : C.getJobs()) {
8917 if (SourceAction != FindSource(&J.getSource()))
8918 continue;
8919 auto &JArgs = J.getArguments();
8920 for (unsigned I = 0; I < JArgs.size(); ++I) {
8921 if (StringRef(JArgs[I]).starts_with("-object-file-name=") &&
8922 Output.isFilename()) {
8923 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
8924 addDebugObjectName(Args, NewArgs, DebugCompilationDir,
8925 Output.getFilename());
8926 NewArgs.append(JArgs.begin() + I + 1, JArgs.end());
8927 J.replaceArguments(NewArgs);
8928 break;
8929 }
8930 }
8931 }
8932
8933 assert(Output.isFilename() && "Unexpected lipo output.");
8934 CmdArgs.push_back("-o");
8935 CmdArgs.push_back(Output.getFilename());
8936
8937 const llvm::Triple &T = getToolChain().getTriple();
8938 Arg *A;
8940 T.isOSBinFormatELF()) {
8941 CmdArgs.push_back("-split-dwarf-output");
8942 CmdArgs.push_back(SplitDebugName(JA, Args, Input, Output));
8943 }
8944
8945 if (Triple.isAMDGPU())
8946 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
8947
8948 assert(Input.isFilename() && "Invalid input.");
8949 CmdArgs.push_back(Input.getFilename());
8950
8951 const char *Exec = getToolChain().getDriver().getClangProgramPath();
8952 if (D.CC1Main && !D.CCGenDiagnostics) {
8953 // Invoke cc1as directly in this process.
8954 C.addCommand(std::make_unique<CC1Command>(
8955 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8956 Output, D.getPrependArg()));
8957 } else {
8958 C.addCommand(std::make_unique<Command>(
8959 JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs,
8960 Output, D.getPrependArg()));
8961 }
8962}
8963
8964// Begin OffloadBundler
8966 const InputInfo &Output,
8967 const InputInfoList &Inputs,
8968 const llvm::opt::ArgList &TCArgs,
8969 const char *LinkingOutput) const {
8970 // The version with only one output is expected to refer to a bundling job.
8971 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
8972
8973 // The bundling command looks like this:
8974 // clang-offload-bundler -type=bc
8975 // -targets=host-triple,openmp-triple1,openmp-triple2
8976 // -output=output_file
8977 // -input=unbundle_file_host
8978 // -input=unbundle_file_tgt1
8979 // -input=unbundle_file_tgt2
8980
8981 ArgStringList CmdArgs;
8982
8983 // Get the type.
8984 CmdArgs.push_back(TCArgs.MakeArgString(
8985 Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
8986
8987 assert(JA.getInputs().size() == Inputs.size() &&
8988 "Not have inputs for all dependence actions??");
8989
8990 // Get the targets.
8991 SmallString<128> Triples;
8992 Triples += "-targets=";
8993 for (unsigned I = 0; I < Inputs.size(); ++I) {
8994 if (I)
8995 Triples += ',';
8996
8997 // Find ToolChain for this input.
8999 const ToolChain *CurTC = &getToolChain();
9000 const Action *CurDep = JA.getInputs()[I];
9001
9002 if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
9003 CurTC = nullptr;
9004 OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
9005 assert(CurTC == nullptr && "Expected one dependence!");
9006 CurKind = A->getOffloadingDeviceKind();
9007 CurTC = TC;
9008 });
9009 }
9010 Triples += Action::GetOffloadKindName(CurKind);
9011 Triples += '-';
9012 Triples += CurTC->getTriple().normalize();
9013 if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&
9014 !StringRef(CurDep->getOffloadingArch()).empty()) {
9015 Triples += '-';
9016 Triples += CurDep->getOffloadingArch();
9017 }
9018
9019 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
9020 // with each toolchain.
9021 StringRef GPUArchName;
9022 if (CurKind == Action::OFK_OpenMP) {
9023 // Extract GPUArch from -march argument in TC argument list.
9024 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
9025 auto ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
9026 auto Arch = ArchStr.starts_with_insensitive("-march=");
9027 if (Arch) {
9028 GPUArchName = ArchStr.substr(7);
9029 Triples += "-";
9030 break;
9031 }
9032 }
9033 Triples += GPUArchName.str();
9034 }
9035 }
9036 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
9037
9038 // Get bundled file command.
9039 CmdArgs.push_back(
9040 TCArgs.MakeArgString(Twine("-output=") + Output.getFilename()));
9041
9042 // Get unbundled files command.
9043 for (unsigned I = 0; I < Inputs.size(); ++I) {
9045 UB += "-input=";
9046
9047 // Find ToolChain for this input.
9048 const ToolChain *CurTC = &getToolChain();
9049 if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
9050 CurTC = nullptr;
9051 OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
9052 assert(CurTC == nullptr && "Expected one dependence!");
9053 CurTC = TC;
9054 });
9055 UB += C.addTempFile(
9056 C.getArgs().MakeArgString(CurTC->getInputFilename(Inputs[I])));
9057 } else {
9058 UB += CurTC->getInputFilename(Inputs[I]);
9059 }
9060 CmdArgs.push_back(TCArgs.MakeArgString(UB));
9061 }
9062 addOffloadCompressArgs(TCArgs, CmdArgs);
9063 // All the inputs are encoded as commands.
9064 C.addCommand(std::make_unique<Command>(
9065 JA, *this, ResponseFileSupport::None(),
9066 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9067 CmdArgs, std::nullopt, Output));
9068}
9069
9071 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
9072 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
9073 const char *LinkingOutput) const {
9074 // The version with multiple outputs is expected to refer to a unbundling job.
9075 auto &UA = cast<OffloadUnbundlingJobAction>(JA);
9076
9077 // The unbundling command looks like this:
9078 // clang-offload-bundler -type=bc
9079 // -targets=host-triple,openmp-triple1,openmp-triple2
9080 // -input=input_file
9081 // -output=unbundle_file_host
9082 // -output=unbundle_file_tgt1
9083 // -output=unbundle_file_tgt2
9084 // -unbundle
9085
9086 ArgStringList CmdArgs;
9087
9088 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
9089 InputInfo Input = Inputs.front();
9090
9091 // Get the type.
9092 CmdArgs.push_back(TCArgs.MakeArgString(
9093 Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
9094
9095 // Get the targets.
9096 SmallString<128> Triples;
9097 Triples += "-targets=";
9098 auto DepInfo = UA.getDependentActionsInfo();
9099 for (unsigned I = 0; I < DepInfo.size(); ++I) {
9100 if (I)
9101 Triples += ',';
9102
9103 auto &Dep = DepInfo[I];
9104 Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
9105 Triples += '-';
9106 Triples += Dep.DependentToolChain->getTriple().normalize();
9107 if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
9108 Dep.DependentOffloadKind == Action::OFK_Cuda) &&
9109 !Dep.DependentBoundArch.empty()) {
9110 Triples += '-';
9111 Triples += Dep.DependentBoundArch;
9112 }
9113 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
9114 // with each toolchain.
9115 StringRef GPUArchName;
9116 if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {
9117 // Extract GPUArch from -march argument in TC argument list.
9118 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
9119 StringRef ArchStr = StringRef(TCArgs.getArgString(ArgIndex));
9120 auto Arch = ArchStr.starts_with_insensitive("-march=");
9121 if (Arch) {
9122 GPUArchName = ArchStr.substr(7);
9123 Triples += "-";
9124 break;
9125 }
9126 }
9127 Triples += GPUArchName.str();
9128 }
9129 }
9130
9131 CmdArgs.push_back(TCArgs.MakeArgString(Triples));
9132
9133 // Get bundled file command.
9134 CmdArgs.push_back(
9135 TCArgs.MakeArgString(Twine("-input=") + Input.getFilename()));
9136
9137 // Get unbundled files command.
9138 for (unsigned I = 0; I < Outputs.size(); ++I) {
9140 UB += "-output=";
9141 UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
9142 CmdArgs.push_back(TCArgs.MakeArgString(UB));
9143 }
9144 CmdArgs.push_back("-unbundle");
9145 CmdArgs.push_back("-allow-missing-bundles");
9146 if (TCArgs.hasArg(options::OPT_v))
9147 CmdArgs.push_back("-verbose");
9148
9149 // All the inputs are encoded as commands.
9150 C.addCommand(std::make_unique<Command>(
9151 JA, *this, ResponseFileSupport::None(),
9152 TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9153 CmdArgs, std::nullopt, Outputs));
9154}
9155
9157 const InputInfo &Output,
9158 const InputInfoList &Inputs,
9159 const llvm::opt::ArgList &Args,
9160 const char *LinkingOutput) const {
9161 ArgStringList CmdArgs;
9162
9163 // Add the output file name.
9164 assert(Output.isFilename() && "Invalid output.");
9165 CmdArgs.push_back("-o");
9166 CmdArgs.push_back(Output.getFilename());
9167
9168 // Create the inputs to bundle the needed metadata.
9169 for (const InputInfo &Input : Inputs) {
9170 const Action *OffloadAction = Input.getAction();
9172 const ArgList &TCArgs =
9173 C.getArgsForToolChain(TC, OffloadAction->getOffloadingArch(),
9175 StringRef File = C.getArgs().MakeArgString(TC->getInputFilename(Input));
9176 StringRef Arch = OffloadAction->getOffloadingArch()
9178 : TCArgs.getLastArgValue(options::OPT_march_EQ);
9179 StringRef Kind =
9181
9182 ArgStringList Features;
9183 SmallVector<StringRef> FeatureArgs;
9184 getTargetFeatures(TC->getDriver(), TC->getTriple(), TCArgs, Features,
9185 false);
9186 llvm::copy_if(Features, std::back_inserter(FeatureArgs),
9187 [](StringRef Arg) { return !Arg.starts_with("-target"); });
9188
9189 // TODO: We need to pass in the full target-id and handle it properly in the
9190 // linker wrapper.
9192 "file=" + File.str(),
9193 "triple=" + TC->getTripleString(),
9194 "arch=" + Arch.str(),
9195 "kind=" + Kind.str(),
9196 };
9197
9198 if (TC->getDriver().isUsingOffloadLTO())
9199 for (StringRef Feature : FeatureArgs)
9200 Parts.emplace_back("feature=" + Feature.str());
9201
9202 CmdArgs.push_back(Args.MakeArgString("--image=" + llvm::join(Parts, ",")));
9203 }
9204
9205 C.addCommand(std::make_unique<Command>(
9206 JA, *this, ResponseFileSupport::None(),
9207 Args.MakeArgString(getToolChain().GetProgramPath(getShortName())),
9208 CmdArgs, Inputs, Output));
9209}
9210
9212 const InputInfo &Output,
9213 const InputInfoList &Inputs,
9214 const ArgList &Args,
9215 const char *LinkingOutput) const {
9216 const Driver &D = getToolChain().getDriver();
9217 const llvm::Triple TheTriple = getToolChain().getTriple();
9218 ArgStringList CmdArgs;
9219
9220 // Pass the CUDA path to the linker wrapper tool.
9222 auto TCRange = C.getOffloadToolChains(Kind);
9223 for (auto &I : llvm::make_range(TCRange)) {
9224 const ToolChain *TC = I.second;
9225 if (TC->getTriple().isNVPTX()) {
9226 CudaInstallationDetector CudaInstallation(D, TheTriple, Args);
9227 if (CudaInstallation.isValid())
9228 CmdArgs.push_back(Args.MakeArgString(
9229 "--cuda-path=" + CudaInstallation.getInstallPath()));
9230 break;
9231 }
9232 }
9233 }
9234
9235 // Pass in the optimization level to use for LTO.
9236 if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
9237 StringRef OOpt;
9238 if (A->getOption().matches(options::OPT_O4) ||
9239 A->getOption().matches(options::OPT_Ofast))
9240 OOpt = "3";
9241 else if (A->getOption().matches(options::OPT_O)) {
9242 OOpt = A->getValue();
9243 if (OOpt == "g")
9244 OOpt = "1";
9245 else if (OOpt == "s" || OOpt == "z")
9246 OOpt = "2";
9247 } else if (A->getOption().matches(options::OPT_O0))
9248 OOpt = "0";
9249 if (!OOpt.empty())
9250 CmdArgs.push_back(Args.MakeArgString(Twine("--opt-level=O") + OOpt));
9251 }
9252
9253 CmdArgs.push_back(
9254 Args.MakeArgString("--host-triple=" + TheTriple.getTriple()));
9255 if (Args.hasArg(options::OPT_v))
9256 CmdArgs.push_back("--wrapper-verbose");
9257
9258 if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
9259 if (!A->getOption().matches(options::OPT_g0))
9260 CmdArgs.push_back("--device-debug");
9261 }
9262
9263 // code-object-version=X needs to be passed to clang-linker-wrapper to ensure
9264 // that it is used by lld.
9265 if (const Arg *A = Args.getLastArg(options::OPT_mcode_object_version_EQ)) {
9266 CmdArgs.push_back(Args.MakeArgString("-mllvm"));
9267 CmdArgs.push_back(Args.MakeArgString(
9268 Twine("--amdhsa-code-object-version=") + A->getValue()));
9269 }
9270
9271 for (const auto &A : Args.getAllArgValues(options::OPT_Xcuda_ptxas))
9272 CmdArgs.push_back(Args.MakeArgString("--ptxas-arg=" + A));
9273
9274 // Forward remarks passes to the LLVM backend in the wrapper.
9275 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_EQ))
9276 CmdArgs.push_back(Args.MakeArgString(Twine("--offload-opt=-pass-remarks=") +
9277 A->getValue()));
9278 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_missed_EQ))
9279 CmdArgs.push_back(Args.MakeArgString(
9280 Twine("--offload-opt=-pass-remarks-missed=") + A->getValue()));
9281 if (const Arg *A = Args.getLastArg(options::OPT_Rpass_analysis_EQ))
9282 CmdArgs.push_back(Args.MakeArgString(
9283 Twine("--offload-opt=-pass-remarks-analysis=") + A->getValue()));
9284 if (Args.getLastArg(options::OPT_save_temps_EQ))
9285 CmdArgs.push_back("--save-temps");
9286
9287 // Construct the link job so we can wrap around it.
9288 Linker->ConstructJob(C, JA, Output, Inputs, Args, LinkingOutput);
9289 const auto &LinkCommand = C.getJobs().getJobs().back();
9290
9291 // Forward -Xoffload-linker<-triple> arguments to the device link job.
9292 for (Arg *A : Args.filtered(options::OPT_Xoffload_linker)) {
9293 StringRef Val = A->getValue(0);
9294 if (Val.empty())
9295 CmdArgs.push_back(
9296 Args.MakeArgString(Twine("--device-linker=") + A->getValue(1)));
9297 else
9298 CmdArgs.push_back(Args.MakeArgString(
9299 "--device-linker=" +
9300 ToolChain::getOpenMPTriple(Val.drop_front()).getTriple() + "=" +
9301 A->getValue(1)));
9302 }
9303 Args.ClaimAllArgs(options::OPT_Xoffload_linker);
9304
9305 // Embed bitcode instead of an object in JIT mode.
9306 if (Args.hasFlag(options::OPT_fopenmp_target_jit,
9307 options::OPT_fno_openmp_target_jit, false))
9308 CmdArgs.push_back("--embed-bitcode");
9309
9310 // Forward `-mllvm` arguments to the LLVM invocations if present.
9311 for (Arg *A : Args.filtered(options::OPT_mllvm)) {
9312 CmdArgs.push_back("-mllvm");
9313 CmdArgs.push_back(A->getValue());
9314 A->claim();
9315 }
9316
9317 // Pass in the C library for GPUs if present and not disabled.
9318 if (!Args.hasArg(options::OPT_nostdlib, options::OPT_r, options::OPT_nogpulib,
9319 options::OPT_nodefaultlibs, options::OPT_nolibc,
9320 options::OPT_nogpulibc)) {
9321 forAllAssociatedToolChains(C, JA, getToolChain(), [&](const ToolChain &TC) {
9322 // The device C library is only available for NVPTX and AMDGPU targets
9323 // currently.
9324 if (!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU())
9325 return;
9326 bool HasLibC = TC.getStdlibIncludePath().has_value();
9327 if (HasLibC) {
9328 CmdArgs.push_back(Args.MakeArgString(
9329 "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
9330 CmdArgs.push_back(Args.MakeArgString(
9331 "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
9332 }
9333 auto HasCompilerRT = getToolChain().getVFS().exists(
9334 TC.getCompilerRT(Args, "builtins", ToolChain::FT_Static));
9335 if (HasCompilerRT)
9336 CmdArgs.push_back(
9337 Args.MakeArgString("--device-linker=" + TC.getTripleString() + "=" +
9338 "-lclang_rt.builtins"));
9339 });
9340 }
9341
9342 // If we disable the GPU C library support it needs to be forwarded to the
9343 // link job.
9344 if (!Args.hasFlag(options::OPT_gpulibc, options::OPT_nogpulibc, true))
9345 CmdArgs.push_back("--device-compiler=-nolibc");
9346
9347 // Add the linker arguments to be forwarded by the wrapper.
9348 CmdArgs.push_back(Args.MakeArgString(Twine("--linker-path=") +
9349 LinkCommand->getExecutable()));
9350 for (const char *LinkArg : LinkCommand->getArguments())
9351 CmdArgs.push_back(LinkArg);
9352
9353 addOffloadCompressArgs(Args, CmdArgs);
9354
9355 const char *Exec =
9356 Args.MakeArgString(getToolChain().GetProgramPath("clang-linker-wrapper"));
9357
9358 // Replace the executable and arguments of the link job with the
9359 // wrapper.
9360 LinkCommand->replaceExecutable(Exec);
9361 LinkCommand->replaceArguments(CmdArgs);
9362}
#define V(N, I)
Definition: ASTContext.h:3443
StringRef P
static StringRef bytes(const std::vector< T, Allocator > &v)
Definition: ASTWriter.cpp:131
const Decl * D
IndirectLocalPath & Path
Expr * E
static std::string ComplexRangeKindToStr(LangOptions::ComplexRangeKind Range)
Definition: Clang.cpp:2849
static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
The -mprefer-vector-width option accepts either a positive integer or the string "none".
Definition: Clang.cpp:279
static void RenderDebugInfoCompressionArgs(const ArgList &Args, ArgStringList &CmdArgs, const Driver &D, const ToolChain &TC)
Definition: Clang.cpp:887
static bool checkDebugInfoOption(const Arg *A, const ArgList &Args, const Driver &D, const ToolChain &TC)
Definition: Clang.cpp:877
static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition: Clang.cpp:3870
static bool shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime, const llvm::Triple &Triple)
Definition: Clang.cpp:299
static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T, ArgStringList &CmdArgs)
Definition: Clang.cpp:4309
static std::string RenderComplexRangeOption(LangOptions::ComplexRangeKind Range)
Definition: Clang.cpp:2882
static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind, unsigned DwarfVersion, llvm::DebuggerKind DebuggerTuning)
Definition: Clang.cpp:851
static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Clang.cpp:4960
static void renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T, const ArgList &Args, bool IRInput, ArgStringList &CmdArgs, const InputInfo &Output, llvm::codegenoptions::DebugInfoKind &DebugInfoKind, DwarfFissionKind &DwarfFission)
Definition: Clang.cpp:4582
static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec)
Vectorize at all optimization levels greater than 1 except for -Oz.
Definition: Clang.cpp:517
static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Clang.cpp:4438
static bool maybeHasClangPchSignature(const Driver &D, StringRef Path)
Definition: Clang.cpp:942
static bool addExceptionArgs(const ArgList &Args, types::ID InputType, const ToolChain &TC, bool KernelOrKext, const ObjCRuntime &objcRuntime, ArgStringList &CmdArgs)
Adds exception related arguments to the driver command arguments.
Definition: Clang.cpp:319
static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args)
Definition: Clang.cpp:75
void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs)
Definition: Clang.cpp:1476
static bool isSignedCharDefault(const llvm::Triple &Triple)
Definition: Clang.cpp:1331
static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args, bool isWindowsMSVC)
/EH controls whether to run destructor cleanups when exceptions are thrown.
Definition: Clang.cpp:8352
static bool gchProbe(const Driver &D, StringRef Path)
Definition: Clang.cpp:959
static void RenderOpenACCOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition: Clang.cpp:3936
static void EmitComplexRangeDiag(const Driver &D, std::string str1, std::string str2)
Definition: Clang.cpp:2874
static bool CheckARMImplicitITArg(StringRef Value)
Definition: Clang.cpp:2530
static bool hasMultipleInvocations(const llvm::Triple &Triple, const ArgList &Args)
Definition: Clang.cpp:1366
static void handleAMDGPUCodeObjectVersionOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs, bool IsCC1As=false)
Definition: Clang.cpp:919
static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Clang.cpp:3953
static void addDashXForInput(const ArgList &Args, const InputInfo &Input, ArgStringList &CmdArgs)
Add -x lang to CmdArgs for Input.
Definition: Clang.cpp:548
static void ParseMRecip(const Driver &D, const ArgList &Args, ArgStringList &OutStrings)
The -mrecip flag requires processing of many optional parameters.
Definition: Clang.cpp:170
static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs, types::ID InputType)
Definition: Clang.cpp:3914
static void renderDwarfFormat(const Driver &D, const llvm::Triple &T, const ArgList &Args, ArgStringList &CmdArgs, unsigned DwarfVersion)
Definition: Clang.cpp:4558
static void RenderObjCOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T, const ArgList &Args, ObjCRuntime &Runtime, bool InferCovariantReturns, const InputInfo &Input, ArgStringList &CmdArgs)
Definition: Clang.cpp:4345
static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Add a CC1 and CC1AS option to specify the coverage file path prefix map.
Definition: Clang.cpp:500
static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs, StringRef Value)
Definition: Clang.cpp:2535
static bool checkRemarksOptions(const Driver &D, const ArgList &Args, const llvm::Triple &Triple)
Definition: Clang.cpp:1377
static void CollectArgsForIntegratedAssembler(Compilation &C, const ArgList &Args, ArgStringList &CmdArgs, const Driver &D)
Definition: Clang.cpp:2541
static bool RenderModulesOptions(Compilation &C, const Driver &D, const ArgList &Args, const InputInfo &Input, const InputInfo &Output, bool HaveStd20, ArgStringList &CmdArgs)
Definition: Clang.cpp:4081
static void forAllAssociatedToolChains(Compilation &C, const JobAction &JA, const ToolChain &RegularToolChain, llvm::function_ref< void(const ToolChain &)> Work)
Apply Work on the current tool chain RegularToolChain and any other offloading tool chain that is ass...
Definition: Clang.cpp:102
static bool isValidSymbolName(StringRef S)
Definition: Clang.cpp:3591
static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs)
Add a CC1 and CC1AS option to specify the macro file path prefix map.
Definition: Clang.cpp:485
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input, const InputInfo &Output, const JobAction &JA)
Definition: Clang.cpp:1393
static std::string ComplexArithmeticStr(LangOptions::ComplexRangeKind Range)
Definition: Clang.cpp:2868
static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs, const char *DebugCompilationDir, const char *OutputFileName)
Definition: Clang.cpp:430
static bool getRefinementStep(StringRef In, const Driver &D, const Arg &A, size_t &Position)
This is a helper function for validating the optional refinement step parameter in reciprocal argumen...
Definition: Clang.cpp:142
static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool isAArch64)
Definition: Clang.cpp:1553
static void RenderSSPOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, bool KernelOrKext)
Definition: Clang.cpp:3601
static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Clang.cpp:4025
static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Clang.cpp:3782
static void RenderTrivialAutoVarInitOptions(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Definition: Clang.cpp:3799
static bool maybeConsumeDash(const std::string &EH, size_t &I)
Definition: Clang.cpp:8331
static const char * addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs, const llvm::vfs::FileSystem &VFS)
Add a CC1 option to specify the debug compilation directory.
Definition: Clang.cpp:412
static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args)
Definition: Clang.cpp:90
static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC, const JobAction &JA)
Definition: Clang.cpp:395
static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs)
Add a CC1 and CC1AS option to specify the debug file path prefix map.
Definition: Clang.cpp:464
static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs, const llvm::Triple &Triple, const InputInfo &Input)
Definition: Clang.cpp:3522
static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D, bool OFastEnabled, const ArgList &Args, ArgStringList &CmdArgs, const JobAction &JA)
Definition: Clang.cpp:2889
static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C, const JobAction &JA, const InputInfo &Output, const ArgList &Args, SanitizerArgs &SanArgs, ArgStringList &CmdArgs)
Definition: Clang.cpp:578
static void handlePAuthABI(const ArgList &DriverArgs, ArgStringList &CC1Args)
Definition: Clang.cpp:1517
clang::CodeGenOptions::FramePointerKind getFramePointerKind(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition: CommonArgs.cpp:216
StringRef Filename
Definition: Format.cpp:3051
Defines enums used when emitting included header information.
LangStandard::Kind Std
Defines the clang::LangOptions interface.
llvm::MachO::Target Target
Definition: MachO.h:51
Defines types useful for describing an Objective-C runtime.
SourceRange Range
Definition: SemaObjC.cpp:758
Defines version macros and version-related utility functions for Clang.
do v
Definition: arm_acle.h:91
int64_t getID() const
Definition: DeclBase.cpp:1175
static StringRef getWarningOptionForGroup(diag::Group)
Given a group ID, returns the flag that toggles the group.
ComplexRangeKind
Controls the various implementations for complex multiplication and.
Definition: LangOptions.h:441
@ CX_Full
Implementation of complex division and multiplication using a call to runtime library functions(gener...
Definition: LangOptions.h:447
@ CX_Basic
Implementation of complex division and multiplication using algebraic formulas at source precision.
Definition: LangOptions.h:466
@ CX_Promoted
Implementation of complex division using algebraic formulas at higher precision.
Definition: LangOptions.h:461
@ CX_None
No range rule is enabled.
Definition: LangOptions.h:469
@ CX_Improved
Implementation of complex division offering an improved handling for overflow in intermediate calcula...
Definition: LangOptions.h:452
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:28
bool allowsWeak() const
Does this runtime allow the use of __weak?
Definition: ObjCRuntime.h:299
bool isLegacyDispatchDefaultForArch(llvm::Triple::ArchType Arch)
The default dispatch mechanism to use for the specified architecture.
Definition: ObjCRuntime.h:100
Kind getKind() const
Definition: ObjCRuntime.h:77
bool isNeXTFamily() const
Is this runtime basically of the NeXT family of runtimes?
Definition: ObjCRuntime.h:143
const VersionTuple & getVersion() const
Definition: ObjCRuntime.h:78
bool tryParse(StringRef input)
Try to parse an Objective-C runtime specification from the given string.
Definition: ObjCRuntime.cpp:48
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition: ObjCRuntime.h:82
std::string getAsString() const
Definition: ObjCRuntime.cpp:23
@ MacOSX
'macosx' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the non-fragile AB...
Definition: ObjCRuntime.h:35
@ FragileMacOSX
'macosx-fragile' is the Apple-provided NeXT-derived runtime on Mac OS X platforms that use the fragil...
Definition: ObjCRuntime.h:40
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
Definition: ObjCRuntime.h:56
@ GCC
'gcc' is the Objective-C runtime shipped with GCC, implementing a fragile Objective-C ABI
Definition: ObjCRuntime.h:53
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
Scope(Scope *Parent, unsigned ScopeFlags, DiagnosticsEngine &Diag)
Definition: Scope.h:257
Action - Represent an abstract compilation step to perform.
Definition: Action.h:47
const char * getOffloadingArch() const
Definition: Action.h:212
types::ID getType() const
Definition: Action.h:149
const ToolChain * getOffloadingToolChain() const
Definition: Action.h:213
static std::string GetOffloadingFileNamePrefix(OffloadKind Kind, StringRef NormalizedTriple, bool CreatePrefixForHost=false)
Return a string that can be used as prefix in order to generate unique files for each offloading kind...
Definition: Action.cpp:144
ActionClass getKind() const
Definition: Action.h:148
static StringRef GetOffloadKindName(OffloadKind Kind)
Return a string containing a offload kind name.
Definition: Action.cpp:160
OffloadKind getOffloadingDeviceKind() const
Definition: Action.h:211
bool isHostOffloading(unsigned int OKind) const
Check if this action have any offload kinds.
Definition: Action.h:219
bool isDeviceOffloading(OffloadKind OKind) const
Definition: Action.h:222
ActionList & getInputs()
Definition: Action.h:151
bool isOffloading(OffloadKind OKind) const
Definition: Action.h:225
Command - An executable path/name and argument vector to execute.
Definition: Job.h:106
Compilation - A set of tasks to perform for a single driver invocation.
Definition: Compilation.h:45
A class to find a viable CUDA installation.
Definition: Cuda.h:27
StringRef getInstallPath() const
Get the detected Cuda installation path.
Definition: Cuda.h:66
bool isValid() const
Check whether we detected a valid Cuda install.
Definition: Cuda.h:56
Distro - Helper class for detecting and classifying Linux distributions.
Definition: Distro.h:23
bool IsGentoo() const
Definition: Distro.h:140
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
Definition: Driver.h:77
static bool getDefaultModuleCachePath(SmallVectorImpl< char > &Result)
Compute the default -fmodule-cache-path.
Definition: Clang.cpp:4049
const char * getClangProgramPath() const
Get the path to the main clang executable.
Definition: Driver.h:425
DiagnosticBuilder Diag(unsigned DiagID) const
Definition: Driver.h:144
bool isUsingOffloadLTO() const
Returns true if we are performing any kind of offload LTO.
Definition: Driver.h:726
llvm::vfs::FileSystem & getVFS() const
Definition: Driver.h:405
@ OMPRT_IOMP5
The legacy name for the LLVM OpenMP runtime from when it was the Intel OpenMP runtime.
Definition: Driver.h:140
@ OMPRT_OMP
The LLVM OpenMP runtime.
Definition: Driver.h:130
InputInfo - Wrapper for information about an input source.
Definition: InputInfo.h:22
const char * getBaseInput() const
Definition: InputInfo.h:78
const llvm::opt::Arg & getInputArg() const
Definition: InputInfo.h:87
const char * getFilename() const
Definition: InputInfo.h:83
bool isNothing() const
Definition: InputInfo.h:74
const Action * getAction() const
The action for which this InputInfo was created. May be null.
Definition: InputInfo.h:80
bool isFilename() const
Definition: InputInfo.h:75
types::ID getType() const
Definition: InputInfo.h:77
An offload action combines host or/and device actions according to the programming model implementati...
Definition: Action.h:269
ToolChain - Access to tools for a single platform.
Definition: ToolChain.h:92
virtual std::string GetGlobalDebugPathRemapping() const
Add an additional -fdebug-prefix-map entry.
Definition: ToolChain.h:582
virtual void addClangWarningOptions(llvm::opt::ArgStringList &CC1Args) const
Add warning options that need to be passed to cc1 for this target.
Definition: ToolChain.cpp:1167
virtual unsigned getMaxDwarfVersion() const
Definition: ToolChain.h:591
virtual void adjustDebugInfoKind(llvm::codegenoptions::DebugInfoKind &DebugInfoKind, const llvm::opt::ArgList &Args) const
Adjust debug information kind considering all passed options.
Definition: ToolChain.h:611
virtual bool useIntegratedAs() const
Check if the toolchain should use the integrated assembler.
Definition: ToolChain.cpp:157
static llvm::Triple getOpenMPTriple(StringRef TripleStr)
Definition: ToolChain.h:809
virtual llvm::DenormalMode getDefaultDenormalModeForType(const llvm::opt::ArgList &DriverArgs, const JobAction &JA, const llvm::fltSemantics *FPType=nullptr) const
Returns the output denormal handling type in the default floating point environment for the given FPT...
Definition: ToolChain.h:801
virtual UnwindTableLevel getDefaultUnwindTableLevel(const llvm::opt::ArgList &Args) const
How detailed should the unwind tables be by default.
Definition: ToolChain.cpp:533
virtual std::string getInputFilename(const InputInfo &Input) const
Some toolchains need to modify the file name, for example to replace the extension for object files w...
Definition: ToolChain.cpp:528
virtual llvm::codegenoptions::DebugInfoFormat getDefaultDebugFormat() const
Get the default debug info format. Typically, this is DWARF.
Definition: ToolChain.h:573
virtual bool supportsDebugInfoOption(const llvm::opt::Arg *) const
Does this toolchain supports given debug info option or not.
Definition: ToolChain.h:605
virtual bool IsObjCNonFragileABIDefault() const
IsObjCNonFragileABIDefault - Does this tool chain set -fobjc-nonfragile-abi by default.
Definition: ToolChain.h:467
virtual bool isThreadModelSupported(const StringRef Model) const
isThreadModelSupported() - Does this target support a thread model?
Definition: ToolChain.cpp:1078
llvm::Triple::ArchType getArch() const
Definition: ToolChain.h:268
const Driver & getDriver() const
Definition: ToolChain.h:252
RTTIMode getRTTIMode() const
Definition: ToolChain.h:326
llvm::vfs::FileSystem & getVFS() const
Definition: ToolChain.cpp:153
static bool needsGCovInstrumentation(const llvm::opt::ArgList &Args)
Returns true if gcov instrumentation (-fprofile-arcs or –coverage) is on.
Definition: ToolChain.cpp:933
const XRayArgs & getXRayArgs() const
Definition: ToolChain.cpp:384
virtual llvm::DebuggerKind getDefaultDebuggerTuning() const
Definition: ToolChain.h:600
void AddClangCXXStdlibIsystemArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIsystemArgs - Add the clang -cc1 level arguments to set the specified include paths ...
Definition: ToolChain.cpp:1349
const llvm::Triple & getEffectiveTriple() const
Get the toolchain's effective clang triple.
Definition: ToolChain.h:282
virtual LangOptions::TrivialAutoVarInitKind GetDefaultTrivialAutoVarInit() const
Get the default trivial automatic variable initialization.
Definition: ToolChain.h:488
virtual llvm::ExceptionHandling GetExceptionModel(const llvm::opt::ArgList &Args) const
GetExceptionModel - Return the tool chain exception model.
Definition: ToolChain.cpp:1074
virtual bool IsMathErrnoDefault() const
IsMathErrnoDefault - Does this tool chain use -fmath-errno by default.
Definition: ToolChain.h:459
virtual std::string getThreadModel() const
getThreadModel() - Which thread model does this target use?
Definition: ToolChain.h:622
virtual bool GetDefaultStandaloneDebug() const
Definition: ToolChain.h:597
const llvm::Triple & getTriple() const
Definition: ToolChain.h:254
bool defaultToIEEELongDouble() const
Check whether use IEEE binary128 as long double format by default.
Definition: ToolChain.cpp:195
virtual void AddCudaIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific CUDA includes.
Definition: ToolChain.cpp:1482
virtual std::string getCompilerRT(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
Definition: ToolChain.cpp:754
virtual LangOptions::StackProtectorMode GetDefaultStackProtectorLevel(bool KernelOrKext) const
GetDefaultStackProtectorLevel - Get the default stack protector level for this tool chain.
Definition: ToolChain.h:482
virtual bool hasBlocksRuntime() const
hasBlocksRuntime - Given that the user is compiling with -fblocks, does this tool chain guarantee the...
Definition: ToolChain.h:662
virtual bool UseDwarfDebugFlags() const
UseDwarfDebugFlags - Embed the compile options to clang into the Dwarf compile unit information.
Definition: ToolChain.h:579
virtual bool SupportsProfiling() const
SupportsProfiling - Does this tool chain support -pg.
Definition: ToolChain.h:567
virtual void AddHIPIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific HIP includes.
Definition: ToolChain.cpp:1485
virtual bool canSplitThinLTOUnit() const
Returns true when it's possible to split LTO unit to use whole program devirtualization and CFI santi...
Definition: ToolChain.h:796
virtual void AddClangCXXStdlibIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
AddClangCXXStdlibIncludeArgs - Add the clang -cc1 level arguments to set the include paths to use for...
Definition: ToolChain.cpp:1335
virtual VersionTuple computeMSVCVersion(const Driver *D, const llvm::opt::ArgList &Args) const
On Windows, returns the MSVC compatibility version.
Definition: ToolChain.cpp:1513
virtual void addSYCLIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use system-specific SYCL includes.
Definition: ToolChain.cpp:1488
virtual bool UseObjCMixedDispatch() const
UseObjCMixedDispatchDefault - When using non-legacy dispatch, should the mixed dispatch method be use...
Definition: ToolChain.h:471
virtual void AddIAMCUIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add arguments to use MCU GCC toolchain includes.
Definition: ToolChain.cpp:1496
std::optional< std::string > getStdlibIncludePath() const
Definition: ToolChain.cpp:895
std::string getTripleString() const
Definition: ToolChain.h:277
virtual void addClangCC1ASTargetOptions(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CC1ASArgs) const
Add options that need to be passed to cc1as for this target.
Definition: ToolChain.cpp:1164
virtual bool IsIntegratedAssemblerDefault() const
IsIntegratedAssemblerDefault - Does this tool chain enable -integrated-as by default.
Definition: ToolChain.h:434
SanitizerArgs getSanitizerArgs(const llvm::opt::ArgList &JobArgs) const
Definition: ToolChain.cpp:378
virtual CXXStdlibType GetCXXStdlibType(const llvm::opt::ArgList &Args) const
Definition: ToolChain.cpp:1239
virtual void CheckObjCARC() const
Complain if this tool chain doesn't support Objective-C ARC.
Definition: ToolChain.h:570
virtual void addClangTargetOptions(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args, Action::OffloadKind DeviceOffloadKind) const
Add options that need to be passed to cc1 for this target.
Definition: ToolChain.cpp:1160
virtual void AddClangSystemIncludeArgs(const llvm::opt::ArgList &DriverArgs, llvm::opt::ArgStringList &CC1Args) const
Add the clang cc1 arguments for system include paths.
Definition: ToolChain.cpp:1155
virtual bool IsEncodeExtendedBlockSignatureDefault() const
IsEncodeExtendedBlockSignatureDefault - Does this tool chain enable -fencode-extended-block-signature...
Definition: ToolChain.h:463
virtual bool IsBlocksDefault() const
IsBlocksDefault - Does this tool chain enable -fblocks by default.
Definition: ToolChain.h:430
std::string getCompilerRTBasename(const llvm::opt::ArgList &Args, StringRef Component, FileType Type=ToolChain::FT_Static) const
Definition: ToolChain.cpp:713
virtual const llvm::Triple * getAuxTriple() const
Get the toolchain's aux triple, if it has one.
Definition: ToolChain.h:261
virtual bool parseInlineAsmUsingAsmParser() const
Check if the toolchain should use AsmParser to parse inlineAsm when integrated assembler is not defau...
Definition: ToolChain.h:456
virtual ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const
getDefaultObjCRuntime - Return the default Objective-C runtime for this platform.
Definition: ToolChain.cpp:1068
Tool - Information on a specific compilation tool.
Definition: Tool.h:32
const ToolChain & getToolChain() const
Definition: Tool.h:52
virtual void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const =0
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
const char * getShortName() const
Definition: Tool.h:50
void addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, types::ID InputType) const
Definition: XRayArgs.cpp:180
static std::optional< unsigned > getSmallDataThreshold(const llvm::opt::ArgList &Args)
Definition: Hexagon.cpp:534
void AddLoongArchTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition: Clang.cpp:8644
void AddX86TargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition: Clang.cpp:8627
void AddRISCVTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition: Clang.cpp:8652
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition: Clang.cpp:8667
void AddMIPSTargetArgs(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs) const
Definition: Clang.cpp:8616
static const char * getBaseInputName(const llvm::opt::ArgList &Args, const InputInfo &Input)
Definition: Clang.cpp:8586
Clang(const ToolChain &TC, bool HasIntegratedBackend=true)
Definition: Clang.cpp:8187
static const char * getDependencyFileName(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition: Clang.cpp:8601
static const char * getBaseInputStem(const llvm::opt::ArgList &Args, const InputInfoList &Inputs)
Definition: Clang.cpp:8591
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition: Clang.cpp:5031
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition: Clang.cpp:9211
void ConstructJobMultipleOutputs(Compilation &C, const JobAction &JA, const InputInfoList &Outputs, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
Construct jobs to perform the action JA, writing to the Outputs and with Inputs, and add the jobs to ...
Definition: Clang.cpp:9070
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition: Clang.cpp:8965
void ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs, const char *LinkingOutput) const override
ConstructJob - Construct jobs to perform the action JA, writing to Output and with Inputs,...
Definition: Clang.cpp:9156
void addSanitizerArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
void addProfileRTArgs(const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
bool isHardTPSupported(const llvm::Triple &Triple)
Definition: ARM.cpp:208
FloatABI getARMFloatABI(const ToolChain &TC, const llvm::opt::ArgList &Args)
StringRef getLoongArchABI(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
std::string postProcessTargetCPUString(const std::string &CPU, const llvm::Triple &Triple)
Definition: LoongArch.cpp:306
mips::FloatABI getMipsFloatABI(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
bool hasCompactBranches(StringRef &CPU)
Definition: Mips.cpp:436
void getMipsCPUAndABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple, StringRef &CPUName, StringRef &ABIName)
FloatABI getPPCFloatABI(const Driver &D, const llvm::opt::ArgList &Args)
std::string getRISCVArch(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
Definition: RISCV.cpp:249
StringRef getRISCVABI(const llvm::opt::ArgList &Args, const llvm::Triple &Triple)
FloatABI getSparcFloatABI(const Driver &D, const llvm::opt::ArgList &Args)
FloatABI getSystemZFloatABI(const Driver &D, const llvm::opt::ArgList &Args)
void addX86AlignBranchArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool IsLTO, const StringRef PluginOptPrefix="")
void addMachineOutlinerArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple, bool IsLTO, const StringRef PluginOptPrefix="")
unsigned ParseFunctionAlignment(const ToolChain &TC, const llvm::opt::ArgList &Args)
void addOffloadCompressArgs(const llvm::opt::ArgList &TCArgs, llvm::opt::ArgStringList &CmdArgs)
void addMCModel(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &Triple, const llvm::Reloc::Model &RelocationModel, llvm::opt::ArgStringList &CmdArgs)
llvm::opt::Arg * getLastProfileSampleUseArg(const llvm::opt::ArgList &Args)
const char * SplitDebugName(const JobAction &JA, const llvm::opt::ArgList &Args, const InputInfo &Input, const InputInfo &Output)
void addOutlineAtomicsArgs(const Driver &D, const ToolChain &TC, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const llvm::Triple &Triple)
void getTargetFeatures(const Driver &D, const llvm::Triple &Triple, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, bool ForAS, bool IsAux=false)
void handleColorDiagnosticsArgs(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Handle the -f{no}-color-diagnostics and -f{no}-diagnostics-colors options.
std::string getCPUName(const Driver &D, const llvm::opt::ArgList &Args, const llvm::Triple &T, bool FromAs=false)
bool shouldRecordCommandLine(const ToolChain &TC, const llvm::opt::ArgList &Args, bool &FRecordCommandLine, bool &GRecordCommandLine)
Check if the command line should be recorded in the object file.
bool isUseSeparateSections(const llvm::Triple &Triple)
Definition: CommonArgs.cpp:823
void addDirectoryList(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs, const char *ArgName, const char *EnvVar)
EnvVar is split by system delimiter for environment variables.
llvm::SmallString< 256 > getCXX20NamedModuleOutputPath(const llvm::opt::ArgList &Args, const char *BaseInput)
bool haveAMDGPUCodeObjectVersionArgument(const Driver &D, const llvm::opt::ArgList &Args)
bool isTLSDESCEnabled(const ToolChain &TC, const llvm::opt::ArgList &Args)
Definition: CommonArgs.cpp:827
void addDebugInfoKind(llvm::opt::ArgStringList &CmdArgs, llvm::codegenoptions::DebugInfoKind DebugInfoKind)
llvm::codegenoptions::DebugInfoKind debugLevelToInfoKind(const llvm::opt::Arg &A)
llvm::opt::Arg * getLastCSProfileGenerateArg(const llvm::opt::ArgList &Args)
llvm::opt::Arg * getLastProfileUseArg(const llvm::opt::ArgList &Args)
DwarfFissionKind getDebugFissionKind(const Driver &D, const llvm::opt::ArgList &Args, llvm::opt::Arg *&Arg)
const char * renderEscapedCommandLine(const ToolChain &TC, const llvm::opt::ArgList &Args)
Join the args in the given ArgList, escape spaces and backslashes and return the joined string.
void renderCommonIntegerOverflowOptions(const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
std::tuple< llvm::Reloc::Model, unsigned, bool > ParsePICArgs(const ToolChain &ToolChain, const llvm::opt::ArgList &Args)
void claimNoWarnArgs(const llvm::opt::ArgList &Args)
unsigned DwarfVersionNum(StringRef ArgValue)
unsigned getDwarfVersion(const ToolChain &TC, const llvm::opt::ArgList &Args)
unsigned getAMDGPUCodeObjectVersion(const Driver &D, const llvm::opt::ArgList &Args)
const llvm::opt::Arg * getDwarfNArg(const llvm::opt::ArgList &Args)
SmallString< 128 > getStatsFileName(const llvm::opt::ArgList &Args, const InputInfo &Output, const InputInfo &Input, const Driver &D)
Handles the -save-stats option and returns the filename to save statistics to.
void escapeSpacesAndBackslashes(const char *Arg, llvm::SmallVectorImpl< char > &Res)
Add backslashes to escape spaces and other backslashes.
bool isObjCAutoRefCount(const llvm::opt::ArgList &Args)
const char * RelocationModelName(llvm::Reloc::Model Model)
void addOpenMPHostOffloadingArgs(const Compilation &C, const JobAction &JA, const llvm::opt::ArgList &Args, llvm::opt::ArgStringList &CmdArgs)
Adds offloading options for OpenMP host compilation to CmdArgs.
bool isHLSL(ID Id)
isHLSL - Is this an HLSL input.
Definition: Types.cpp:293
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
Definition: Types.cpp:216
ID getPreprocessedType(ID Id)
getPreprocessedType - Get the ID of the type for this input when it has been preprocessed,...
Definition: Types.cpp:53
bool isLLVMIR(ID Id)
Is this LLVM IR.
Definition: Types.cpp:256
const char * getTypeName(ID Id)
getTypeName - Return the name of the type for Id.
Definition: Types.cpp:49
bool isOpenCL(ID Id)
isOpenCL - Is this an "OpenCL" input.
Definition: Types.cpp:229
bool isSrcFile(ID Id)
isSrcFile - Is this a source file, i.e.
Definition: Types.cpp:295
const char * getTypeTempSuffix(ID Id, bool CLStyle=false)
getTypeTempSuffix - Return the suffix to use when creating a temp file of this type,...
Definition: Types.cpp:80
bool isCXX(ID Id)
isCXX - Is this a "C++" input (C++ and Obj-C++ sources and headers).
Definition: Types.cpp:231
bool isOptimizationLevelFast(const llvm::opt::ArgList &Args)
bool willEmitRemarks(const llvm::opt::ArgList &Args)
@ Quoted
'#include ""' paths, added by 'gcc -iquote'.
The JSON file list parser is used to communicate input to InstallAPI.
std::optional< diag::Group > diagGroupFromCLWarningID(unsigned)
For cl.exe warning IDs that cleany map to clang diagnostic groups, returns the corresponding group.
Definition: CLWarnings.cpp:20
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
void quoteMakeTarget(StringRef Target, SmallVectorImpl< char > &Res)
Quote target names for inclusion in GNU Make dependency files.
Definition: MakeSupport.cpp:11
const char * headerIncludeFormatKindToString(HeaderIncludeFormatKind K)
Definition: HeaderInclude.h:48
const char * headerIncludeFilteringKindToString(HeaderIncludeFilteringKind K)
Definition: HeaderInclude.h:61
@ Asm
Assembly: we accept this only so that we can preprocess it.
@ Result
The result type of a method or function.
const char * CudaVersionToString(CudaVersion V)
Definition: Cuda.cpp:52
const FunctionProtoType * T
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number,...
Definition: Version.cpp:96
static constexpr ResponseFileSupport None()
Returns a ResponseFileSupport indicating that response files are not supported.
Definition: Job.h:78
static constexpr ResponseFileSupport AtFileUTF8()
Definition: Job.h:85