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