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