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 "Arch/AArch64.h"
11#include "Arch/ARM.h"
12#include "Arch/LoongArch.h"
13#include "Arch/Mips.h"
14#include "Arch/PPC.h"
15#include "Arch/RISCV.h"
16#include "Arch/Sparc.h"
17#include "Arch/SystemZ.h"
18#include "Hexagon.h"
19#include "PS4CPU.h"
20#include "ToolChains/Cuda.h"
21#include "clang/Basic/CLWarnings.h"
22#include "clang/Basic/CodeGenOptions.h"
23#include "clang/Basic/HeaderInclude.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/MakeSupport.h"
26#include "clang/Basic/ObjCRuntime.h"
27#include "clang/Basic/Version.h"
28#include "clang/Config/config.h"
29#include "clang/Driver/Action.h"
30#include "clang/Driver/CommonArgs.h"
31#include "clang/Driver/Distro.h"
32#include "clang/Driver/InputInfo.h"
33#include "clang/Driver/SanitizerArgs.h"
34#include "clang/Driver/Types.h"
35#include "clang/Driver/XRayArgs.h"
36#include "clang/Options/OptionUtils.h"
37#include "clang/Options/Options.h"
38#include "llvm/ADT/ScopeExit.h"
39#include "llvm/ADT/SmallSet.h"
40#include "llvm/ADT/StringExtras.h"
41#include "llvm/BinaryFormat/Magic.h"
42#include "llvm/Config/llvm-config.h"
43#include "llvm/Frontend/Debug/Options.h"
44#include "llvm/Object/ObjectFile.h"
45#include "llvm/Option/ArgList.h"
46#include "llvm/ProfileData/InstrProfReader.h"
47#include "llvm/Support/CodeGen.h"
48#include "llvm/Support/Compiler.h"
49#include "llvm/Support/Compression.h"
50#include "llvm/Support/Error.h"
51#include "llvm/Support/FileSystem.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/Path.h"
54#include "llvm/Support/Process.h"
55#include "llvm/Support/YAMLParser.h"
56#include "llvm/TargetParser/AArch64TargetParser.h"
57#include "llvm/TargetParser/ARMTargetParserCommon.h"
58#include "llvm/TargetParser/Host.h"
59#include "llvm/TargetParser/LoongArchTargetParser.h"
60#include "llvm/TargetParser/PPCTargetParser.h"
61#include "llvm/TargetParser/RISCVISAInfo.h"
62#include "llvm/TargetParser/RISCVTargetParser.h"
63#include <cctype>
64
65using namespace clang::driver;
66using namespace clang::driver::tools;
67using namespace clang;
68using namespace llvm::opt;
69
70static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
71 if (Arg *A = Args.getLastArg(Ids: options::OPT_C, Ids: options::OPT_CC,
72 Ids: options::OPT_fminimize_whitespace,
73 Ids: options::OPT_fno_minimize_whitespace,
74 Ids: options::OPT_fkeep_system_includes,
75 Ids: options::OPT_fno_keep_system_includes)) {
76 if (!Args.hasArg(Ids: options::OPT_E) && !Args.hasArg(Ids: options::OPT__SLASH_P) &&
77 !Args.hasArg(Ids: options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
78 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
79 << A->getBaseArg().getAsString(Args)
80 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
81 }
82 }
83}
84
85static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
86 // In gcc, only ARM checks this, but it seems reasonable to check universally.
87 if (Args.hasArg(Ids: options::OPT_static))
88 if (const Arg *A =
89 Args.getLastArg(Ids: options::OPT_dynamic, Ids: options::OPT_mdynamic_no_pic))
90 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
91 << "-static";
92}
93
94/// Apply \a Work on the current tool chain \a RegularToolChain and any other
95/// offloading tool chain that is associated with the current action \a JA.
96static void
97forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
98 const ToolChain &RegularToolChain,
99 llvm::function_ref<void(const ToolChain &)> Work) {
100 // Apply Work on the current/regular tool chain.
101 Work(RegularToolChain);
102
103 // Apply Work on all the offloading tool chains associated with the current
104 // action.
105 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,
106 Action::OFK_HIP, Action::OFK_SYCL}) {
107 if (JA.isHostOffloading(OKind: Kind)) {
108 auto TCs = C.getOffloadToolChains(Kind);
109 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
110 Work(*II->second);
111 } else if (JA.isDeviceOffloading(OKind: Kind))
112 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
113 }
114}
115
116static bool
117shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
118 const llvm::Triple &Triple) {
119 // We use the zero-cost exception tables for Objective-C if the non-fragile
120 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
121 // later.
122 if (runtime.isNonFragile())
123 return true;
124
125 if (!Triple.isMacOSX())
126 return false;
127
128 return (!Triple.isMacOSXVersionLT(Major: 10, Minor: 5) &&
129 (Triple.getArch() == llvm::Triple::x86_64 ||
130 Triple.getArch() == llvm::Triple::arm));
131}
132
133/// Adds exception related arguments to the driver command arguments. There's a
134/// main flag, -fexceptions and also language specific flags to enable/disable
135/// C++ and Objective-C exceptions. This makes it possible to for example
136/// disable C++ exceptions but enable Objective-C exceptions.
137static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
138 const ToolChain &TC, bool KernelOrKext,
139 const ObjCRuntime &objcRuntime,
140 ArgStringList &CmdArgs) {
141 const llvm::Triple &Triple = TC.getTriple();
142
143 if (KernelOrKext) {
144 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
145 // arguments now to avoid warnings about unused arguments.
146 Args.ClaimAllArgs(Id0: options::OPT_fexceptions);
147 Args.ClaimAllArgs(Id0: options::OPT_fno_exceptions);
148 Args.ClaimAllArgs(Id0: options::OPT_fobjc_exceptions);
149 Args.ClaimAllArgs(Id0: options::OPT_fno_objc_exceptions);
150 Args.ClaimAllArgs(Id0: options::OPT_fcxx_exceptions);
151 Args.ClaimAllArgs(Id0: options::OPT_fno_cxx_exceptions);
152 Args.ClaimAllArgs(Id0: options::OPT_fasync_exceptions);
153 Args.ClaimAllArgs(Id0: options::OPT_fno_async_exceptions);
154 return false;
155 }
156
157 // See if the user explicitly enabled exceptions.
158 bool EH = Args.hasFlag(Pos: options::OPT_fexceptions, Neg: options::OPT_fno_exceptions,
159 Default: false);
160
161 // Async exceptions are Windows MSVC only.
162 if (Triple.isWindowsMSVCEnvironment()) {
163 bool EHa = Args.hasFlag(Pos: options::OPT_fasync_exceptions,
164 Neg: options::OPT_fno_async_exceptions, Default: false);
165 if (EHa) {
166 CmdArgs.push_back(Elt: "-fasync-exceptions");
167 EH = true;
168 }
169 }
170
171 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
172 // is not necessarily sensible, but follows GCC.
173 if (types::isObjC(Id: InputType) &&
174 Args.hasFlag(Pos: options::OPT_fobjc_exceptions,
175 Neg: options::OPT_fno_objc_exceptions, Default: true)) {
176 CmdArgs.push_back(Elt: "-fobjc-exceptions");
177
178 EH |= shouldUseExceptionTablesForObjCExceptions(runtime: objcRuntime, Triple);
179 }
180
181 if (types::isCXX(Id: InputType)) {
182 // Disable C++ EH by default on XCore and PS4/PS5.
183 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
184 !Triple.isPS() && !Triple.isDriverKit();
185 Arg *ExceptionArg = Args.getLastArg(
186 Ids: options::OPT_fcxx_exceptions, Ids: options::OPT_fno_cxx_exceptions,
187 Ids: options::OPT_fexceptions, Ids: options::OPT_fno_exceptions);
188 if (ExceptionArg)
189 CXXExceptionsEnabled =
190 ExceptionArg->getOption().matches(ID: options::OPT_fcxx_exceptions) ||
191 ExceptionArg->getOption().matches(ID: options::OPT_fexceptions);
192
193 if (CXXExceptionsEnabled) {
194 CmdArgs.push_back(Elt: "-fcxx-exceptions");
195
196 EH = true;
197 }
198 }
199
200 // OPT_fignore_exceptions means exception could still be thrown,
201 // but no clean up or catch would happen in current module.
202 // So we do not set EH to false.
203 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fignore_exceptions);
204
205 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fassume_nothrow_exception_dtor,
206 Neg: options::OPT_fno_assume_nothrow_exception_dtor);
207
208 if (EH)
209 CmdArgs.push_back(Elt: "-fexceptions");
210 return EH;
211}
212
213static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
214 const JobAction &JA) {
215 bool Default = true;
216 if (TC.getTriple().isOSDarwin()) {
217 // The native darwin assembler doesn't support the linker_option directives,
218 // so we disable them if we think the .s file will be passed to it.
219 Default = TC.useIntegratedAs();
220 }
221 // The linker_option directives are intended for host compilation.
222 if (JA.isDeviceOffloading(OKind: Action::OFK_Cuda) ||
223 JA.isDeviceOffloading(OKind: Action::OFK_HIP))
224 Default = false;
225 return Args.hasFlag(Pos: options::OPT_fautolink, Neg: options::OPT_fno_autolink,
226 Default);
227}
228
229/// Add a CC1 option to specify the debug compilation directory.
230static const char *addDebugCompDirArg(const ArgList &Args,
231 ArgStringList &CmdArgs,
232 const llvm::vfs::FileSystem &VFS) {
233 std::string DebugCompDir;
234 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffile_compilation_dir_EQ,
235 Ids: options::OPT_fdebug_compilation_dir_EQ))
236 DebugCompDir = A->getValue();
237
238 if (DebugCompDir.empty()) {
239 if (llvm::ErrorOr<std::string> CWD = VFS.getCurrentWorkingDirectory())
240 DebugCompDir = std::move(*CWD);
241 else
242 return nullptr;
243 }
244 CmdArgs.push_back(
245 Elt: Args.MakeArgString(Str: "-fdebug-compilation-dir=" + DebugCompDir));
246 StringRef Path(CmdArgs.back());
247 return Path.substr(Start: Path.find(C: '=') + 1).data();
248}
249
250static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
251 const char *DebugCompilationDir,
252 const char *OutputFileName) {
253 // No need to generate a value for -object-file-name if it was provided.
254 for (auto *Arg : Args.filtered(Ids: options::OPT_Xclang))
255 if (StringRef(Arg->getValue()).starts_with(Prefix: "-object-file-name"))
256 return;
257
258 if (Args.hasArg(Ids: options::OPT_object_file_name_EQ))
259 return;
260
261 SmallString<128> ObjFileNameForDebug(OutputFileName);
262 if (ObjFileNameForDebug != "-" &&
263 !llvm::sys::path::is_absolute(path: ObjFileNameForDebug) &&
264 (!DebugCompilationDir ||
265 llvm::sys::path::is_absolute(path: DebugCompilationDir))) {
266 // Make the path absolute in the debug infos like MSVC does.
267 llvm::sys::fs::make_absolute(path&: ObjFileNameForDebug);
268 }
269 // If the object file name is a relative path, then always use Windows
270 // backslash style as -object-file-name is used for embedding object file path
271 // in codeview and it can only be generated when targeting on Windows.
272 // Otherwise, just use native absolute path.
273 llvm::sys::path::Style Style =
274 llvm::sys::path::is_absolute(path: ObjFileNameForDebug)
275 ? llvm::sys::path::Style::native
276 : llvm::sys::path::Style::windows_backslash;
277 llvm::sys::path::remove_dots(path&: ObjFileNameForDebug, /*remove_dot_dot=*/true,
278 style: Style);
279 CmdArgs.push_back(
280 Elt: Args.MakeArgString(Str: Twine("-object-file-name=") + ObjFileNameForDebug));
281}
282
283/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
284static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
285 const ArgList &Args, ArgStringList &CmdArgs) {
286 auto AddOneArg = [&](StringRef Map, StringRef Name) {
287 if (!Map.contains(C: '='))
288 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option) << Map << Name;
289 else
290 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fdebug-prefix-map=" + Map));
291 };
292
293 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
294 Ids: options::OPT_fdebug_prefix_map_EQ)) {
295 AddOneArg(A->getValue(), A->getOption().getName());
296 A->claim();
297 }
298 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
299 if (GlobalRemapEntry.empty())
300 return;
301 AddOneArg(GlobalRemapEntry, "environment");
302}
303
304/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
305static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
306 ArgStringList &CmdArgs) {
307 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
308 Ids: options::OPT_fmacro_prefix_map_EQ)) {
309 StringRef Map = A->getValue();
310 if (!Map.contains(C: '='))
311 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
312 << Map << A->getOption().getName();
313 else
314 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fmacro-prefix-map=" + Map));
315 A->claim();
316 }
317}
318
319/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
320static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
321 ArgStringList &CmdArgs) {
322 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
323 Ids: options::OPT_fcoverage_prefix_map_EQ)) {
324 StringRef Map = A->getValue();
325 if (!Map.contains(C: '='))
326 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
327 << Map << A->getOption().getName();
328 else
329 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fcoverage-prefix-map=" + Map));
330 A->claim();
331 }
332}
333
334/// Add -x lang to \p CmdArgs for \p Input.
335static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
336 ArgStringList &CmdArgs) {
337 // When using -verify-pch, we don't want to provide the type
338 // 'precompiled-header' if it was inferred from the file extension
339 if (Args.hasArg(Ids: options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
340 return;
341
342 CmdArgs.push_back(Elt: "-x");
343 if (Args.hasArg(Ids: options::OPT_rewrite_objc))
344 CmdArgs.push_back(Elt: types::getTypeName(Id: types::TY_ObjCXX));
345 else {
346 // Map the driver type to the frontend type. This is mostly an identity
347 // mapping, except that the distinction between module interface units
348 // and other source files does not exist at the frontend layer.
349 const char *ClangType;
350 switch (Input.getType()) {
351 case types::TY_CXXModule:
352 ClangType = "c++";
353 break;
354 case types::TY_PP_CXXModule:
355 ClangType = "c++-cpp-output";
356 break;
357 default:
358 ClangType = types::getTypeName(Id: Input.getType());
359 break;
360 }
361 CmdArgs.push_back(Elt: ClangType);
362 }
363}
364
365static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
366 const JobAction &JA, const InputInfo &Output,
367 const ArgList &Args, SanitizerArgs &SanArgs,
368 ArgStringList &CmdArgs) {
369 const Driver &D = TC.getDriver();
370 const llvm::Triple &T = TC.getTriple();
371 auto *PGOGenerateArg = Args.getLastArg(Ids: options::OPT_fprofile_generate,
372 Ids: options::OPT_fprofile_generate_EQ,
373 Ids: options::OPT_fno_profile_generate);
374 if (PGOGenerateArg &&
375 PGOGenerateArg->getOption().matches(ID: options::OPT_fno_profile_generate))
376 PGOGenerateArg = nullptr;
377
378 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
379
380 auto *ProfileGenerateArg = Args.getLastArg(
381 Ids: options::OPT_fprofile_instr_generate,
382 Ids: options::OPT_fprofile_instr_generate_EQ,
383 Ids: options::OPT_fno_profile_instr_generate);
384 if (ProfileGenerateArg &&
385 ProfileGenerateArg->getOption().matches(
386 ID: options::OPT_fno_profile_instr_generate))
387 ProfileGenerateArg = nullptr;
388
389 if (PGOGenerateArg && ProfileGenerateArg)
390 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
391 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
392
393 auto *ProfileUseArg = getLastProfileUseArg(Args);
394
395 if (PGOGenerateArg && ProfileUseArg)
396 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
397 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
398
399 if (ProfileGenerateArg && ProfileUseArg)
400 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
401 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
402
403 if (CSPGOGenerateArg && PGOGenerateArg) {
404 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
405 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
406 PGOGenerateArg = nullptr;
407 }
408
409 if (TC.getTriple().isOSAIX()) {
410 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
411 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
412 << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
413 }
414
415 if (ProfileGenerateArg) {
416 if (ProfileGenerateArg->getOption().matches(
417 ID: options::OPT_fprofile_instr_generate_EQ))
418 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-path=") +
419 ProfileGenerateArg->getValue()));
420 // The default is to use Clang Instrumentation.
421 CmdArgs.push_back(Elt: "-fprofile-instrument=clang");
422 if (TC.getTriple().isWindowsMSVCEnvironment() &&
423 Args.hasFlag(Pos: options::OPT_frtlib_defaultlib,
424 Neg: options::OPT_fno_rtlib_defaultlib, Default: true)) {
425 // Add dependent lib for clang_rt.profile
426 CmdArgs.push_back(Elt: Args.MakeArgString(
427 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "profile")));
428 }
429 }
430
431 if (auto *ColdFuncCoverageArg = Args.getLastArg(
432 Ids: options::OPT_fprofile_generate_cold_function_coverage,
433 Ids: options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
434 SmallString<128> Path(
435 ColdFuncCoverageArg->getOption().matches(
436 ID: options::OPT_fprofile_generate_cold_function_coverage_EQ)
437 ? ColdFuncCoverageArg->getValue()
438 : "");
439 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
440 // FIXME: Idealy the file path should be passed through
441 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
442 // shared with other profile use path(see PGOOptions), we need to refactor
443 // PGOOptions to make it work.
444 CmdArgs.push_back(Elt: "-mllvm");
445 CmdArgs.push_back(Elt: Args.MakeArgString(
446 Str: Twine("--instrument-cold-function-only-path=") + Path));
447 CmdArgs.push_back(Elt: "-mllvm");
448 CmdArgs.push_back(Elt: "--pgo-instrument-cold-function-only");
449 CmdArgs.push_back(Elt: "-mllvm");
450 CmdArgs.push_back(Elt: "--pgo-function-entry-coverage");
451 CmdArgs.push_back(Elt: "-fprofile-instrument=sample-coldcov");
452 }
453
454 if (auto *A = Args.getLastArg(Ids: options::OPT_ftemporal_profile)) {
455 if (!PGOGenerateArg && !CSPGOGenerateArg)
456 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
457 << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
458 CmdArgs.push_back(Elt: "-mllvm");
459 CmdArgs.push_back(Elt: "--pgo-temporal-instrumentation");
460 }
461
462 Arg *PGOGenArg = nullptr;
463 if (PGOGenerateArg) {
464 assert(!CSPGOGenerateArg);
465 PGOGenArg = PGOGenerateArg;
466 CmdArgs.push_back(Elt: "-fprofile-instrument=llvm");
467 }
468 if (CSPGOGenerateArg) {
469 assert(!PGOGenerateArg);
470 PGOGenArg = CSPGOGenerateArg;
471 CmdArgs.push_back(Elt: "-fprofile-instrument=csllvm");
472 }
473 if (PGOGenArg) {
474 if (TC.getTriple().isWindowsMSVCEnvironment() &&
475 Args.hasFlag(Pos: options::OPT_frtlib_defaultlib,
476 Neg: options::OPT_fno_rtlib_defaultlib, Default: true)) {
477 // Add dependent lib for clang_rt.profile
478 CmdArgs.push_back(Elt: Args.MakeArgString(
479 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "profile")));
480 }
481 if (PGOGenArg->getOption().matches(
482 ID: PGOGenerateArg ? options::OPT_fprofile_generate_EQ
483 : options::OPT_fcs_profile_generate_EQ)) {
484 SmallString<128> Path(PGOGenArg->getValue());
485 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
486 CmdArgs.push_back(
487 Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-path=") + Path));
488 }
489 }
490
491 if (ProfileUseArg) {
492 SmallString<128> UsePathBuf;
493 StringRef UsePath;
494 if (ProfileUseArg->getOption().matches(ID: options::OPT_fprofile_instr_use_EQ))
495 UsePath = ProfileUseArg->getValue();
496 else if ((ProfileUseArg->getOption().matches(
497 ID: options::OPT_fprofile_use_EQ) ||
498 ProfileUseArg->getOption().matches(
499 ID: options::OPT_fprofile_instr_use))) {
500 UsePathBuf =
501 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue();
502 if (UsePathBuf.empty() || llvm::sys::fs::is_directory(Path: UsePathBuf))
503 llvm::sys::path::append(path&: UsePathBuf, a: "default.profdata");
504 UsePath = UsePathBuf;
505 }
506 auto ReaderOrErr =
507 llvm::IndexedInstrProfReader::create(Path: UsePath, FS&: D.getVFS());
508 if (auto E = ReaderOrErr.takeError()) {
509 auto DiagID = D.getDiags().getCustomDiagID(
510 L: DiagnosticsEngine::Error, FormatString: "Error in reading profile %0: %1");
511 llvm::handleAllErrors(E: std::move(E), Handlers: [&](const llvm::ErrorInfoBase &EI) {
512 D.Diag(DiagID) << UsePath.str() << EI.message();
513 });
514 } else {
515 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
516 std::move(ReaderOrErr.get());
517 StringRef UseKind;
518 // Currently memprof profiles are only added at the IR level. Mark the
519 // profile type as IR in that case as well and the subsequent matching
520 // needs to detect which is available (might be one or both).
521 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
522 if (PGOReader->hasCSIRLevelProfile())
523 UseKind = "csllvm";
524 else
525 UseKind = "llvm";
526 } else
527 UseKind = "clang";
528
529 CmdArgs.push_back(
530 Elt: Args.MakeArgString(Str: "-fprofile-instrument-use=" + UseKind));
531 CmdArgs.push_back(
532 Elt: Args.MakeArgString(Str: "-fprofile-instrument-use-path=" + UsePath));
533 }
534 }
535
536 bool EmitCovNotes = Args.hasFlag(Pos: options::OPT_ftest_coverage,
537 Neg: options::OPT_fno_test_coverage, Default: false) ||
538 Args.hasArg(Ids: options::OPT_coverage);
539 bool EmitCovData = TC.needsGCovInstrumentation(Args);
540
541 if (Args.hasFlag(Pos: options::OPT_fcoverage_mapping,
542 Neg: options::OPT_fno_coverage_mapping, Default: false)) {
543 if (!ProfileGenerateArg)
544 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
545 << "-fcoverage-mapping"
546 << "-fprofile-instr-generate";
547
548 CmdArgs.push_back(Elt: "-fcoverage-mapping");
549 }
550
551 if (Args.hasFlag(Pos: options::OPT_fmcdc_coverage, Neg: options::OPT_fno_mcdc_coverage,
552 Default: false)) {
553 if (!Args.hasFlag(Pos: options::OPT_fcoverage_mapping,
554 Neg: options::OPT_fno_coverage_mapping, Default: false))
555 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
556 << "-fcoverage-mcdc"
557 << "-fcoverage-mapping";
558
559 CmdArgs.push_back(Elt: "-fcoverage-mcdc");
560 }
561
562 StringRef CoverageCompDir;
563 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffile_compilation_dir_EQ,
564 Ids: options::OPT_fcoverage_compilation_dir_EQ))
565 CoverageCompDir = A->getValue();
566 if (CoverageCompDir.empty()) {
567 if (auto CWD = D.getVFS().getCurrentWorkingDirectory())
568 CmdArgs.push_back(
569 Elt: Args.MakeArgString(Str: Twine("-fcoverage-compilation-dir=") + *CWD));
570 } else
571 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fcoverage-compilation-dir=") +
572 CoverageCompDir));
573
574 if (Args.hasArg(Ids: options::OPT_fprofile_exclude_files_EQ)) {
575 auto *Arg = Args.getLastArg(Ids: options::OPT_fprofile_exclude_files_EQ);
576 if (!Args.hasArg(Ids: options::OPT_coverage))
577 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
578 << "-fprofile-exclude-files="
579 << "--coverage";
580
581 StringRef v = Arg->getValue();
582 CmdArgs.push_back(
583 Elt: Args.MakeArgString(Str: Twine("-fprofile-exclude-files=" + v)));
584 }
585
586 if (Args.hasArg(Ids: options::OPT_fprofile_filter_files_EQ)) {
587 auto *Arg = Args.getLastArg(Ids: options::OPT_fprofile_filter_files_EQ);
588 if (!Args.hasArg(Ids: options::OPT_coverage))
589 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
590 << "-fprofile-filter-files="
591 << "--coverage";
592
593 StringRef v = Arg->getValue();
594 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fprofile-filter-files=" + v)));
595 }
596
597 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_update_EQ)) {
598 StringRef Val = A->getValue();
599 if (Val == "atomic" || Val == "prefer-atomic")
600 CmdArgs.push_back(Elt: "-fprofile-update=atomic");
601 else if (Val != "single")
602 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
603 << A->getSpelling() << Val;
604 }
605 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_continuous)) {
606 if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
607 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
608 << A->getSpelling()
609 << "-fprofile-generate, -fprofile-instr-generate, or "
610 "-fcs-profile-generate";
611 else {
612 CmdArgs.push_back(Elt: "-fprofile-continuous");
613 // Platforms that require a bias variable:
614 if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
615 CmdArgs.push_back(Elt: "-mllvm");
616 CmdArgs.push_back(Elt: "-runtime-counter-relocation");
617 }
618 // -fprofile-instr-generate does not decide the profile file name in the
619 // FE, and so it does not define the filename symbol
620 // (__llvm_profile_filename). Instead, the runtime uses the name
621 // "default.profraw" for the profile file. When continuous mode is ON, we
622 // will create the filename symbol so that we can insert the "%c"
623 // modifier.
624 if (ProfileGenerateArg &&
625 (ProfileGenerateArg->getOption().matches(
626 ID: options::OPT_fprofile_instr_generate) ||
627 (ProfileGenerateArg->getOption().matches(
628 ID: options::OPT_fprofile_instr_generate_EQ) &&
629 strlen(s: ProfileGenerateArg->getValue()) == 0)))
630 CmdArgs.push_back(Elt: "-fprofile-instrument-path=default.profraw");
631 }
632 }
633
634 int FunctionGroups = 1;
635 int SelectedFunctionGroup = 0;
636 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_function_groups)) {
637 StringRef Val = A->getValue();
638 if (Val.getAsInteger(Radix: 0, Result&: FunctionGroups) || FunctionGroups < 1)
639 D.Diag(DiagID: diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
640 }
641 if (const auto *A =
642 Args.getLastArg(Ids: options::OPT_fprofile_selected_function_group)) {
643 StringRef Val = A->getValue();
644 if (Val.getAsInteger(Radix: 0, Result&: SelectedFunctionGroup) ||
645 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
646 D.Diag(DiagID: diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
647 }
648 if (FunctionGroups != 1)
649 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-function-groups=" +
650 Twine(FunctionGroups)));
651 if (SelectedFunctionGroup != 0)
652 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-selected-function-group=" +
653 Twine(SelectedFunctionGroup)));
654
655 // Leave -fprofile-dir= an unused argument unless .gcda emission is
656 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
657 // the flag used. There is no -fno-profile-dir, so the user has no
658 // targeted way to suppress the warning.
659 Arg *FProfileDir = nullptr;
660 if (Args.hasArg(Ids: options::OPT_fprofile_arcs) ||
661 Args.hasArg(Ids: options::OPT_coverage))
662 FProfileDir = Args.getLastArg(Ids: options::OPT_fprofile_dir);
663
664 // Put the .gcno and .gcda files (if needed) next to the primary output file,
665 // or fall back to a file in the current directory for `clang -c --coverage
666 // d/a.c` in the absence of -o.
667 if (EmitCovNotes || EmitCovData) {
668 SmallString<128> CoverageFilename;
669 if (Arg *DumpDir = Args.getLastArgNoClaim(Ids: options::OPT_dumpdir)) {
670 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
671 // path separator.
672 CoverageFilename = DumpDir->getValue();
673 CoverageFilename += llvm::sys::path::filename(path: Output.getBaseInput());
674 } else if (Arg *FinalOutput =
675 C.getArgs().getLastArg(Ids: options::OPT__SLASH_Fo)) {
676 CoverageFilename = FinalOutput->getValue();
677 } else if (Arg *FinalOutput = C.getArgs().getLastArg(Ids: options::OPT_o)) {
678 CoverageFilename = FinalOutput->getValue();
679 } else {
680 CoverageFilename = llvm::sys::path::filename(path: Output.getBaseInput());
681 }
682 if (llvm::sys::path::is_relative(path: CoverageFilename))
683 (void)D.getVFS().makeAbsolute(Path&: CoverageFilename);
684 llvm::sys::path::replace_extension(path&: CoverageFilename, extension: "gcno");
685 if (EmitCovNotes) {
686 CmdArgs.push_back(
687 Elt: Args.MakeArgString(Str: "-coverage-notes-file=" + CoverageFilename));
688 }
689
690 if (EmitCovData) {
691 if (FProfileDir) {
692 SmallString<128> Gcno = std::move(CoverageFilename);
693 CoverageFilename = FProfileDir->getValue();
694 llvm::sys::path::append(path&: CoverageFilename, a: Gcno);
695 }
696 llvm::sys::path::replace_extension(path&: CoverageFilename, extension: "gcda");
697 CmdArgs.push_back(
698 Elt: Args.MakeArgString(Str: "-coverage-data-file=" + CoverageFilename));
699 }
700 }
701}
702
703static void
704RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
705 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
706 unsigned DwarfVersion,
707 llvm::DebuggerKind DebuggerTuning) {
708 addDebugInfoKind(CmdArgs, DebugInfoKind);
709 if (DwarfVersion > 0)
710 CmdArgs.push_back(
711 Elt: Args.MakeArgString(Str: "-dwarf-version=" + Twine(DwarfVersion)));
712 switch (DebuggerTuning) {
713 case llvm::DebuggerKind::GDB:
714 CmdArgs.push_back(Elt: "-debugger-tuning=gdb");
715 break;
716 case llvm::DebuggerKind::LLDB:
717 CmdArgs.push_back(Elt: "-debugger-tuning=lldb");
718 break;
719 case llvm::DebuggerKind::SCE:
720 CmdArgs.push_back(Elt: "-debugger-tuning=sce");
721 break;
722 case llvm::DebuggerKind::DBX:
723 CmdArgs.push_back(Elt: "-debugger-tuning=dbx");
724 break;
725 default:
726 break;
727 }
728}
729
730static void RenderDebugInfoCompressionArgs(const ArgList &Args,
731 ArgStringList &CmdArgs,
732 const Driver &D,
733 const ToolChain &TC) {
734 const Arg *A = Args.getLastArg(Ids: options::OPT_gz_EQ);
735 if (!A)
736 return;
737 if (checkDebugInfoOption(A, Args, D, TC)) {
738 StringRef Value = A->getValue();
739 if (Value == "none") {
740 CmdArgs.push_back(Elt: "--compress-debug-sections=none");
741 } else if (Value == "zlib") {
742 if (llvm::compression::zlib::isAvailable()) {
743 CmdArgs.push_back(
744 Elt: Args.MakeArgString(Str: "--compress-debug-sections=" + Twine(Value)));
745 } else {
746 D.Diag(DiagID: diag::warn_debug_compression_unavailable) << "zlib";
747 }
748 } else if (Value == "zstd") {
749 if (llvm::compression::zstd::isAvailable()) {
750 CmdArgs.push_back(
751 Elt: Args.MakeArgString(Str: "--compress-debug-sections=" + Twine(Value)));
752 } else {
753 D.Diag(DiagID: diag::warn_debug_compression_unavailable) << "zstd";
754 }
755 } else {
756 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
757 << A->getSpelling() << Value;
758 }
759 }
760}
761
762static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
763 const ArgList &Args,
764 ArgStringList &CmdArgs,
765 bool IsCC1As = false) {
766 // If no version was requested by the user, use the default value from the
767 // back end. This is consistent with the value returned from
768 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
769 // requiring the corresponding llvm to have the AMDGPU target enabled,
770 // provided the user (e.g. front end tests) can use the default.
771 if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
772 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
773 CmdArgs.insert(I: CmdArgs.begin() + 1,
774 Elt: Args.MakeArgString(Str: Twine("--amdhsa-code-object-version=") +
775 Twine(CodeObjVer)));
776 CmdArgs.insert(I: CmdArgs.begin() + 1, Elt: "-mllvm");
777 // -cc1as does not accept -mcode-object-version option.
778 if (!IsCC1As)
779 CmdArgs.insert(I: CmdArgs.begin() + 1,
780 Elt: Args.MakeArgString(Str: Twine("-mcode-object-version=") +
781 Twine(CodeObjVer)));
782 }
783}
784
785static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
786 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
787 D.getVFS().getBufferForFile(Name: Path);
788 if (!MemBuf)
789 return false;
790 llvm::file_magic Magic = llvm::identify_magic(magic: (*MemBuf)->getBuffer());
791 if (Magic == llvm::file_magic::unknown)
792 return false;
793 // Return true for both raw Clang AST files and object files which may
794 // contain a __clangast section.
795 if (Magic == llvm::file_magic::clang_ast)
796 return true;
797 Expected<std::unique_ptr<llvm::object::ObjectFile>> Obj =
798 llvm::object::ObjectFile::createObjectFile(Object: **MemBuf, Type: Magic);
799 return !Obj.takeError();
800}
801
802static bool gchProbe(const Driver &D, StringRef Path) {
803 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
804 if (!Status)
805 return false;
806
807 if (Status->isDirectory()) {
808 std::error_code EC;
809 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Dir: Path, EC), DE;
810 !EC && DI != DE; DI = DI.increment(EC)) {
811 if (maybeHasClangPchSignature(D, Path: DI->path()))
812 return true;
813 }
814 D.Diag(DiagID: diag::warn_drv_pch_ignoring_gch_dir) << Path;
815 return false;
816 }
817
818 if (maybeHasClangPchSignature(D, Path))
819 return true;
820 D.Diag(DiagID: diag::warn_drv_pch_ignoring_gch_file) << Path;
821 return false;
822}
823
824void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
825 const Driver &D, const ArgList &Args,
826 ArgStringList &CmdArgs,
827 const InputInfo &Output,
828 const InputInfoList &Inputs) const {
829 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
830
831 CheckPreprocessingOptions(D, Args);
832
833 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_C);
834 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_CC);
835
836 // Handle dependency file generation.
837 Arg *ArgM = Args.getLastArg(Ids: options::OPT_MM);
838 if (!ArgM)
839 ArgM = Args.getLastArg(Ids: options::OPT_M);
840 Arg *ArgMD = Args.getLastArg(Ids: options::OPT_MMD);
841 if (!ArgMD)
842 ArgMD = Args.getLastArg(Ids: options::OPT_MD);
843
844 // -M and -MM imply -w.
845 if (ArgM)
846 CmdArgs.push_back(Elt: "-w");
847 else
848 ArgM = ArgMD;
849
850 if (ArgM) {
851 if (!JA.isDeviceOffloading(OKind: Action::OFK_HIP)) {
852 // Determine the output location.
853 const char *DepFile;
854 if (Arg *MF = Args.getLastArg(Ids: options::OPT_MF)) {
855 DepFile = MF->getValue();
856 C.addFailureResultFile(Name: DepFile, JA: &JA);
857 } else if (Output.getType() == types::TY_Dependencies) {
858 DepFile = Output.getFilename();
859 } else if (!ArgMD) {
860 DepFile = "-";
861 } else {
862 DepFile = getDependencyFileName(Args, Inputs);
863 C.addFailureResultFile(Name: DepFile, JA: &JA);
864 }
865 CmdArgs.push_back(Elt: "-dependency-file");
866 CmdArgs.push_back(Elt: DepFile);
867 }
868 // Cmake generates dependency files using all compilation options specified
869 // by users. Claim those not used for dependency files.
870 if (JA.isOffloading(OKind: Action::OFK_HIP)) {
871 Args.ClaimAllArgs(Id0: options::OPT_offload_compress);
872 Args.ClaimAllArgs(Id0: options::OPT_no_offload_compress);
873 Args.ClaimAllArgs(Id0: options::OPT_offload_jobs_EQ);
874 }
875
876 bool HasTarget = false;
877 for (const Arg *A : Args.filtered(Ids: options::OPT_MT, Ids: options::OPT_MQ)) {
878 HasTarget = true;
879 A->claim();
880 if (A->getOption().matches(ID: options::OPT_MT)) {
881 A->render(Args, Output&: CmdArgs);
882 } else {
883 CmdArgs.push_back(Elt: "-MT");
884 SmallString<128> Quoted;
885 quoteMakeTarget(Target: A->getValue(), Res&: Quoted);
886 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Quoted));
887 }
888 }
889
890 // Add a default target if one wasn't specified.
891 if (!HasTarget) {
892 const char *DepTarget;
893
894 // If user provided -o, that is the dependency target, except
895 // when we are only generating a dependency file.
896 Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o, Ids: options::OPT__SLASH_Fo);
897 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
898 DepTarget = OutputOpt->getValue();
899 } else {
900 // Otherwise derive from the base input.
901 //
902 // FIXME: This should use the computed output file location.
903 SmallString<128> P(Inputs[0].getBaseInput());
904 llvm::sys::path::replace_extension(path&: P, extension: "o");
905 DepTarget = Args.MakeArgString(Str: llvm::sys::path::filename(path: P));
906 }
907
908 CmdArgs.push_back(Elt: "-MT");
909 SmallString<128> Quoted;
910 quoteMakeTarget(Target: DepTarget, Res&: Quoted);
911 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Quoted));
912 }
913
914 if (ArgM->getOption().matches(ID: options::OPT_M) ||
915 ArgM->getOption().matches(ID: options::OPT_MD))
916 CmdArgs.push_back(Elt: "-sys-header-deps");
917 if ((isa<PrecompileJobAction>(Val: JA) &&
918 !Args.hasArg(Ids: options::OPT_fno_module_file_deps)) ||
919 Args.hasArg(Ids: options::OPT_fmodule_file_deps))
920 CmdArgs.push_back(Elt: "-module-file-deps");
921 }
922
923 if (Args.hasArg(Ids: options::OPT_MG)) {
924 if (!ArgM || ArgM->getOption().matches(ID: options::OPT_MD) ||
925 ArgM->getOption().matches(ID: options::OPT_MMD))
926 D.Diag(DiagID: diag::err_drv_mg_requires_m_or_mm);
927 CmdArgs.push_back(Elt: "-MG");
928 }
929
930 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_MP);
931 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_MV);
932
933 // Add offload include arguments specific for CUDA/HIP/SYCL. This must happen
934 // before we -I or -include anything else, because we must pick up the
935 // CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL installation,
936 // rather than from e.g. /usr/local/include.
937 if (JA.isOffloading(OKind: Action::OFK_Cuda))
938 getToolChain().AddCudaIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
939 if (JA.isOffloading(OKind: Action::OFK_HIP))
940 getToolChain().AddHIPIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
941 if (JA.isOffloading(OKind: Action::OFK_SYCL))
942 getToolChain().addSYCLIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
943
944 // If we are offloading to a target via OpenMP we need to include the
945 // openmp_wrappers folder which contains alternative system headers.
946 if (JA.isDeviceOffloading(OKind: Action::OFK_OpenMP) &&
947 !Args.hasArg(Ids: options::OPT_nostdinc) &&
948 Args.hasFlag(Pos: options::OPT_offload_inc, Neg: options::OPT_no_offload_inc,
949 Default: true) &&
950 getToolChain().getTriple().isGPU()) {
951 if (!Args.hasArg(Ids: options::OPT_nobuiltininc)) {
952 // Add openmp_wrappers/* to our system include path. This lets us wrap
953 // standard library headers.
954 SmallString<128> P(D.ResourceDir);
955 llvm::sys::path::append(path&: P, a: "include");
956 llvm::sys::path::append(path&: P, a: "openmp_wrappers");
957 CmdArgs.push_back(Elt: "-internal-isystem");
958 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
959 }
960
961 CmdArgs.push_back(Elt: "-include");
962 CmdArgs.push_back(Elt: "__clang_openmp_device_functions.h");
963 }
964
965 if (Args.hasArg(Ids: options::OPT_foffload_via_llvm)) {
966 // Add llvm_wrappers/* to our system include path. This lets us wrap
967 // standard library headers and other headers.
968 SmallString<128> P(D.ResourceDir);
969 llvm::sys::path::append(path&: P, a: "include", b: "llvm_offload_wrappers");
970 CmdArgs.append(IL: {"-internal-isystem", Args.MakeArgString(Str: P), "-include"});
971 if (JA.isDeviceOffloading(OKind: Action::OFK_OpenMP))
972 CmdArgs.push_back(Elt: "__llvm_offload_device.h");
973 else
974 CmdArgs.push_back(Elt: "__llvm_offload_host.h");
975 }
976
977 // Add -i* options, and automatically translate to
978 // -include-pch/-include-pth for transparent PCH support. It's
979 // wonky, but we include looking for .gch so we can support seamless
980 // replacement into a build system already set up to be generating
981 // .gch files.
982
983 if (getToolChain().getDriver().IsCLMode()) {
984 const Arg *YcArg = Args.getLastArg(Ids: options::OPT__SLASH_Yc);
985 const Arg *YuArg = Args.getLastArg(Ids: options::OPT__SLASH_Yu);
986 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
987 JA.getKind() <= Action::AssembleJobClass) {
988 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-building-pch-with-obj"));
989 // -fpch-instantiate-templates is the default when creating
990 // precomp using /Yc
991 if (Args.hasFlag(Pos: options::OPT_fpch_instantiate_templates,
992 Neg: options::OPT_fno_pch_instantiate_templates, Default: true))
993 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fpch-instantiate-templates"));
994 }
995 if (YcArg || YuArg) {
996 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
997 if (!isa<PrecompileJobAction>(Val: JA)) {
998 CmdArgs.push_back(Elt: "-include-pch");
999 CmdArgs.push_back(Elt: Args.MakeArgString(Str: D.GetClPchPath(
1000 C, BaseName: !ThroughHeader.empty()
1001 ? ThroughHeader
1002 : llvm::sys::path::filename(path: Inputs[0].getBaseInput()))));
1003 }
1004
1005 if (ThroughHeader.empty()) {
1006 CmdArgs.push_back(Elt: Args.MakeArgString(
1007 Str: Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1008 } else {
1009 CmdArgs.push_back(
1010 Elt: Args.MakeArgString(Str: Twine("-pch-through-header=") + ThroughHeader));
1011 }
1012 }
1013 }
1014
1015 bool RenderedImplicitInclude = false;
1016 for (const Arg *A : Args.filtered(Ids: options::OPT_clang_i_Group)) {
1017 if (A->getOption().matches(ID: options::OPT_include) &&
1018 D.getProbePrecompiled()) {
1019 // Handling of gcc-style gch precompiled headers.
1020 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1021 RenderedImplicitInclude = true;
1022
1023 bool FoundPCH = false;
1024 SmallString<128> P(A->getValue());
1025 // We want the files to have a name like foo.h.pch. Add a dummy extension
1026 // so that replace_extension does the right thing.
1027 P += ".dummy";
1028 llvm::sys::path::replace_extension(path&: P, extension: "pch");
1029 if (D.getVFS().exists(Path: P))
1030 FoundPCH = true;
1031
1032 if (!FoundPCH) {
1033 // For GCC compat, probe for a file or directory ending in .gch instead.
1034 llvm::sys::path::replace_extension(path&: P, extension: "gch");
1035 FoundPCH = gchProbe(D, Path: P.str());
1036 }
1037
1038 if (FoundPCH) {
1039 if (IsFirstImplicitInclude) {
1040 A->claim();
1041 CmdArgs.push_back(Elt: "-include-pch");
1042 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1043 continue;
1044 } else {
1045 // Ignore the PCH if not first on command line and emit warning.
1046 D.Diag(DiagID: diag::warn_drv_pch_not_first_include) << P
1047 << A->getAsString(Args);
1048 }
1049 }
1050 } else if (A->getOption().matches(ID: options::OPT_isystem_after)) {
1051 // Handling of paths which must come late. These entries are handled by
1052 // the toolchain itself after the resource dir is inserted in the right
1053 // search order.
1054 // Do not claim the argument so that the use of the argument does not
1055 // silently go unnoticed on toolchains which do not honour the option.
1056 continue;
1057 } else if (A->getOption().matches(ID: options::OPT_stdlibxx_isystem)) {
1058 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1059 continue;
1060 } else if (A->getOption().matches(ID: options::OPT_ibuiltininc)) {
1061 // This is used only by the driver. No need to pass to cc1.
1062 continue;
1063 }
1064
1065 // Not translated, render as usual.
1066 A->claim();
1067 A->render(Args, Output&: CmdArgs);
1068 }
1069
1070 if (C.isOffloadingHostKind(Kind: Action::OFK_Cuda) ||
1071 JA.isDeviceOffloading(OKind: Action::OFK_Cuda)) {
1072 // Collect all enabled NVPTX architectures.
1073 std::set<unsigned> ArchIDs;
1074 for (auto &I : llvm::make_range(p: C.getOffloadToolChains(Kind: Action::OFK_Cuda))) {
1075 const ToolChain *TC = I.second;
1076 for (StringRef Arch :
1077 D.getOffloadArchs(C, Args: C.getArgs(), Kind: Action::OFK_Cuda, TC: *TC)) {
1078 OffloadArch OA = StringToOffloadArch(S: Arch);
1079 if (IsNVIDIAOffloadArch(A: OA))
1080 ArchIDs.insert(x: CudaArchToID(Arch: OA));
1081 }
1082 }
1083
1084 if (!ArchIDs.empty()) {
1085 SmallString<128> List;
1086 llvm::raw_svector_ostream OS(List);
1087 llvm::interleave(c: ArchIDs, os&: OS, separator: ",");
1088 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-D__CUDA_ARCH_LIST__=" + List));
1089 }
1090 }
1091
1092 Args.addAllArgs(Output&: CmdArgs,
1093 Ids: {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1094 options::OPT_F, options::OPT_embed_dir_EQ});
1095
1096 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1097
1098 // FIXME: There is a very unfortunate problem here, some troubled
1099 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1100 // really support that we would have to parse and then translate
1101 // those options. :(
1102 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Wp_COMMA,
1103 Id1: options::OPT_Xpreprocessor);
1104
1105 // -I- is a deprecated GCC feature, reject it.
1106 if (Arg *A = Args.getLastArg(Ids: options::OPT_I_))
1107 D.Diag(DiagID: diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1108
1109 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1110 // -isysroot to the CC1 invocation.
1111 StringRef sysroot = C.getSysRoot();
1112 if (sysroot != "") {
1113 if (!Args.hasArg(Ids: options::OPT_isysroot)) {
1114 CmdArgs.push_back(Elt: "-isysroot");
1115 CmdArgs.push_back(Elt: C.getArgs().MakeArgString(Str: sysroot));
1116 }
1117 }
1118
1119 // Parse additional include paths from environment variables.
1120 // FIXME: We should probably sink the logic for handling these from the
1121 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1122 // CPATH - included following the user specified includes (but prior to
1123 // builtin and standard includes).
1124 addDirectoryList(Args, CmdArgs, ArgName: "-I", EnvVar: "CPATH");
1125 // C_INCLUDE_PATH - system includes enabled when compiling C.
1126 addDirectoryList(Args, CmdArgs, ArgName: "-c-isystem", EnvVar: "C_INCLUDE_PATH");
1127 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1128 addDirectoryList(Args, CmdArgs, ArgName: "-cxx-isystem", EnvVar: "CPLUS_INCLUDE_PATH");
1129 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1130 addDirectoryList(Args, CmdArgs, ArgName: "-objc-isystem", EnvVar: "OBJC_INCLUDE_PATH");
1131 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1132 addDirectoryList(Args, CmdArgs, ArgName: "-objcxx-isystem", EnvVar: "OBJCPLUS_INCLUDE_PATH");
1133
1134 // While adding the include arguments, we also attempt to retrieve the
1135 // arguments of related offloading toolchains or arguments that are specific
1136 // of an offloading programming model.
1137
1138 // Add C++ include arguments, if needed.
1139 if (types::isCXX(Id: Inputs[0].getType())) {
1140 bool HasStdlibxxIsystem = Args.hasArg(Ids: options::OPT_stdlibxx_isystem);
1141 forAllAssociatedToolChains(
1142 C, JA, RegularToolChain: getToolChain(),
1143 Work: [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1144 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(DriverArgs: Args, CC1Args&: CmdArgs)
1145 : TC.AddClangCXXStdlibIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1146 });
1147 }
1148
1149 // If we are compiling for a GPU target we want to override the system headers
1150 // with ones created by the 'libc' project if present.
1151 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1152 // OffloadKind as an argument.
1153 if (!Args.hasArg(Ids: options::OPT_nostdinc) &&
1154 Args.hasFlag(Pos: options::OPT_offload_inc, Neg: options::OPT_no_offload_inc,
1155 Default: true) &&
1156 !Args.hasArg(Ids: options::OPT_nobuiltininc) &&
1157 (C.getActiveOffloadKinds() == Action::OFK_OpenMP)) {
1158 // TODO: CUDA / HIP include their own headers for some common functions
1159 // implemented here. We'll need to clean those up so they do not conflict.
1160 SmallString<128> P(D.ResourceDir);
1161 llvm::sys::path::append(path&: P, a: "include");
1162 llvm::sys::path::append(path&: P, a: "llvm_libc_wrappers");
1163 CmdArgs.push_back(Elt: "-internal-isystem");
1164 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1165 }
1166
1167 // Add system include arguments for all targets but IAMCU.
1168 if (!IsIAMCU)
1169 forAllAssociatedToolChains(C, JA, RegularToolChain: getToolChain(),
1170 Work: [&Args, &CmdArgs](const ToolChain &TC) {
1171 TC.AddClangSystemIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1172 });
1173 else {
1174 // For IAMCU add special include arguments.
1175 getToolChain().AddIAMCUIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1176 }
1177
1178 addMacroPrefixMapArg(D, Args, CmdArgs);
1179 addCoveragePrefixMapArg(D, Args, CmdArgs);
1180
1181 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffile_reproducible,
1182 Ids: options::OPT_fno_file_reproducible);
1183
1184 if (const char *Epoch = std::getenv(name: "SOURCE_DATE_EPOCH")) {
1185 CmdArgs.push_back(Elt: "-source-date-epoch");
1186 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Epoch));
1187 }
1188
1189 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdefine_target_os_macros,
1190 Neg: options::OPT_fno_define_target_os_macros);
1191}
1192
1193// FIXME: Move to target hook.
1194static bool isSignedCharDefault(const llvm::Triple &Triple) {
1195 switch (Triple.getArch()) {
1196 default:
1197 return true;
1198
1199 case llvm::Triple::aarch64:
1200 case llvm::Triple::aarch64_32:
1201 case llvm::Triple::aarch64_be:
1202 case llvm::Triple::arm:
1203 case llvm::Triple::armeb:
1204 case llvm::Triple::thumb:
1205 case llvm::Triple::thumbeb:
1206 if (Triple.isOSDarwin() || Triple.isOSWindows())
1207 return true;
1208 return false;
1209
1210 case llvm::Triple::ppc:
1211 case llvm::Triple::ppc64:
1212 if (Triple.isOSDarwin())
1213 return true;
1214 return false;
1215
1216 case llvm::Triple::csky:
1217 case llvm::Triple::hexagon:
1218 case llvm::Triple::msp430:
1219 case llvm::Triple::ppcle:
1220 case llvm::Triple::ppc64le:
1221 case llvm::Triple::riscv32:
1222 case llvm::Triple::riscv64:
1223 case llvm::Triple::riscv32be:
1224 case llvm::Triple::riscv64be:
1225 case llvm::Triple::systemz:
1226 case llvm::Triple::xcore:
1227 case llvm::Triple::xtensa:
1228 return false;
1229 }
1230}
1231
1232static bool hasMultipleInvocations(const llvm::Triple &Triple,
1233 const ArgList &Args) {
1234 // Supported only on Darwin where we invoke the compiler multiple times
1235 // followed by an invocation to lipo.
1236 if (!Triple.isOSDarwin())
1237 return false;
1238 // If more than one "-arch <arch>" is specified, we're targeting multiple
1239 // architectures resulting in a fat binary.
1240 return Args.getAllArgValues(Id: options::OPT_arch).size() > 1;
1241}
1242
1243static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1244 const llvm::Triple &Triple) {
1245 // When enabling remarks, we need to error if:
1246 // * The remark file is specified but we're targeting multiple architectures,
1247 // which means more than one remark file is being generated.
1248 bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1249 bool hasExplicitOutputFile =
1250 Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ);
1251 if (hasMultipleInvocations && hasExplicitOutputFile) {
1252 D.Diag(DiagID: diag::err_drv_invalid_output_with_multiple_archs)
1253 << "-foptimization-record-file";
1254 return false;
1255 }
1256 return true;
1257}
1258
1259static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1260 const llvm::Triple &Triple,
1261 const InputInfo &Input,
1262 const InputInfo &Output, const JobAction &JA) {
1263 StringRef Format = "yaml";
1264 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsave_optimization_record_EQ))
1265 Format = A->getValue();
1266
1267 CmdArgs.push_back(Elt: "-opt-record-file");
1268
1269 const Arg *A = Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ);
1270 if (A) {
1271 CmdArgs.push_back(Elt: A->getValue());
1272 } else {
1273 bool hasMultipleArchs =
1274 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1275 Args.getAllArgValues(Id: options::OPT_arch).size() > 1;
1276
1277 SmallString<128> F;
1278
1279 if (Args.hasArg(Ids: options::OPT_c) || Args.hasArg(Ids: options::OPT_S)) {
1280 if (Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o))
1281 F = FinalOutput->getValue();
1282 } else {
1283 if (Format != "yaml" && // For YAML, keep the original behavior.
1284 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1285 Output.isFilename())
1286 F = Output.getFilename();
1287 }
1288
1289 if (F.empty()) {
1290 // Use the input filename.
1291 F = llvm::sys::path::stem(path: Input.getBaseInput());
1292
1293 // If we're compiling for an offload architecture (i.e. a CUDA device),
1294 // we need to make the file name for the device compilation different
1295 // from the host compilation.
1296 if (!JA.isDeviceOffloading(OKind: Action::OFK_None) &&
1297 !JA.isDeviceOffloading(OKind: Action::OFK_Host)) {
1298 llvm::sys::path::replace_extension(path&: F, extension: "");
1299 F += Action::GetOffloadingFileNamePrefix(Kind: JA.getOffloadingDeviceKind(),
1300 NormalizedTriple: Triple.normalize());
1301 F += "-";
1302 F += JA.getOffloadingArch();
1303 }
1304 }
1305
1306 // If we're having more than one "-arch", we should name the files
1307 // differently so that every cc1 invocation writes to a different file.
1308 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1309 // name from the triple.
1310 if (hasMultipleArchs) {
1311 // First, remember the extension.
1312 SmallString<64> OldExtension = llvm::sys::path::extension(path: F);
1313 // then, remove it.
1314 llvm::sys::path::replace_extension(path&: F, extension: "");
1315 // attach -<arch> to it.
1316 F += "-";
1317 F += Triple.getArchName();
1318 // put back the extension.
1319 llvm::sys::path::replace_extension(path&: F, extension: OldExtension);
1320 }
1321
1322 SmallString<32> Extension;
1323 Extension += "opt.";
1324 Extension += Format;
1325
1326 llvm::sys::path::replace_extension(path&: F, extension: Extension);
1327 CmdArgs.push_back(Elt: Args.MakeArgString(Str: F));
1328 }
1329
1330 if (const Arg *A =
1331 Args.getLastArg(Ids: options::OPT_foptimization_record_passes_EQ)) {
1332 CmdArgs.push_back(Elt: "-opt-record-passes");
1333 CmdArgs.push_back(Elt: A->getValue());
1334 }
1335
1336 if (!Format.empty()) {
1337 CmdArgs.push_back(Elt: "-opt-record-format");
1338 CmdArgs.push_back(Elt: Format.data());
1339 }
1340}
1341
1342void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1343 if (!Args.hasFlag(Pos: options::OPT_faapcs_bitfield_width,
1344 Neg: options::OPT_fno_aapcs_bitfield_width, Default: true))
1345 CmdArgs.push_back(Elt: "-fno-aapcs-bitfield-width");
1346
1347 if (Args.getLastArg(Ids: options::OPT_ForceAAPCSBitfieldLoad))
1348 CmdArgs.push_back(Elt: "-faapcs-bitfield-load");
1349}
1350
1351namespace {
1352void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1353 const ArgList &Args, ArgStringList &CmdArgs) {
1354 // Select the ABI to use.
1355 // FIXME: Support -meabi.
1356 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1357 const char *ABIName = nullptr;
1358 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ))
1359 ABIName = A->getValue();
1360 else
1361 ABIName = llvm::ARM::computeDefaultTargetABI(TT: Triple).data();
1362
1363 CmdArgs.push_back(Elt: "-target-abi");
1364 CmdArgs.push_back(Elt: ABIName);
1365}
1366
1367void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1368 auto StrictAlignIter =
1369 llvm::find_if(Range: llvm::reverse(C&: CmdArgs), P: [](StringRef Arg) {
1370 return Arg == "+strict-align" || Arg == "-strict-align";
1371 });
1372 if (StrictAlignIter != CmdArgs.rend() &&
1373 StringRef(*StrictAlignIter) == "+strict-align")
1374 CmdArgs.push_back(Elt: "-Wunaligned-access");
1375}
1376}
1377
1378static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1379 ArgStringList &CmdArgs, bool isAArch64) {
1380 const llvm::Triple &Triple = TC.getEffectiveTriple();
1381 const Arg *A = isAArch64
1382 ? Args.getLastArg(Ids: options::OPT_msign_return_address_EQ,
1383 Ids: options::OPT_mbranch_protection_EQ)
1384 : Args.getLastArg(Ids: options::OPT_mbranch_protection_EQ);
1385 if (!A) {
1386 if (Triple.isOSOpenBSD() && isAArch64) {
1387 CmdArgs.push_back(Elt: "-msign-return-address=non-leaf");
1388 CmdArgs.push_back(Elt: "-msign-return-address-key=a_key");
1389 CmdArgs.push_back(Elt: "-mbranch-target-enforce");
1390 }
1391 return;
1392 }
1393
1394 const Driver &D = TC.getDriver();
1395 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1396 D.Diag(DiagID: diag::warn_incompatible_branch_protection_option)
1397 << Triple.getArchName();
1398
1399 StringRef Scope, Key;
1400 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1401
1402 if (A->getOption().matches(ID: options::OPT_msign_return_address_EQ)) {
1403 Scope = A->getValue();
1404 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1405 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1406 << A->getSpelling() << Scope;
1407 Key = "a_key";
1408 IndirectBranches = Triple.isOSOpenBSD() && isAArch64;
1409 BranchProtectionPAuthLR = false;
1410 GuardedControlStack = false;
1411 } else {
1412 StringRef DiagMsg;
1413 llvm::ARM::ParsedBranchProtection PBP;
1414 bool EnablePAuthLR = false;
1415
1416 // To know if we need to enable PAuth-LR As part of the standard branch
1417 // protection option, it needs to be determined if the feature has been
1418 // activated in the `march` argument. This information is stored within the
1419 // CmdArgs variable and can be found using a search.
1420 if (isAArch64) {
1421 auto isPAuthLR = [](const char *member) {
1422 llvm::AArch64::ExtensionInfo pauthlr_extension =
1423 llvm::AArch64::getExtensionByID(ExtID: llvm::AArch64::AEK_PAUTHLR);
1424 return pauthlr_extension.PosTargetFeature == member;
1425 };
1426
1427 if (llvm::any_of(Range&: CmdArgs, P: isPAuthLR))
1428 EnablePAuthLR = true;
1429 }
1430 if (!llvm::ARM::parseBranchProtection(Spec: A->getValue(), PBP, Err&: DiagMsg,
1431 EnablePAuthLR))
1432 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1433 << A->getSpelling() << DiagMsg;
1434 if (!isAArch64 && PBP.Key == "b_key")
1435 D.Diag(DiagID: diag::warn_unsupported_branch_protection)
1436 << "b-key" << A->getAsString(Args);
1437 Scope = PBP.Scope;
1438 Key = PBP.Key;
1439 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1440 IndirectBranches = PBP.BranchTargetEnforcement;
1441 GuardedControlStack = PBP.GuardedControlStack;
1442 }
1443
1444 Arg *PtrauthReturnsArg = Args.getLastArg(Ids: options::OPT_fptrauth_returns,
1445 Ids: options::OPT_fno_ptrauth_returns);
1446 bool HasPtrauthReturns =
1447 PtrauthReturnsArg &&
1448 PtrauthReturnsArg->getOption().matches(ID: options::OPT_fptrauth_returns);
1449 // GCS is currently untested with ptrauth-returns, but enabling this could be
1450 // allowed in future after testing with a suitable system.
1451 if (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack) {
1452 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1453 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
1454 << A->getAsString(Args) << Triple.getTriple();
1455 else if (HasPtrauthReturns)
1456 D.Diag(DiagID: diag::err_drv_incompatible_options)
1457 << A->getAsString(Args) << "-fptrauth-returns";
1458 }
1459
1460 CmdArgs.push_back(
1461 Elt: Args.MakeArgString(Str: Twine("-msign-return-address=") + Scope));
1462 if (Scope != "none")
1463 CmdArgs.push_back(
1464 Elt: Args.MakeArgString(Str: Twine("-msign-return-address-key=") + Key));
1465 if (BranchProtectionPAuthLR)
1466 CmdArgs.push_back(
1467 Elt: Args.MakeArgString(Str: Twine("-mbranch-protection-pauth-lr")));
1468 if (IndirectBranches)
1469 CmdArgs.push_back(Elt: "-mbranch-target-enforce");
1470
1471 if (GuardedControlStack)
1472 CmdArgs.push_back(Elt: "-mguarded-control-stack");
1473}
1474
1475void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1476 ArgStringList &CmdArgs, bool KernelOrKext) const {
1477 RenderARMABI(D: getToolChain().getDriver(), Triple, Args, CmdArgs);
1478
1479 // Determine floating point ABI from the options & target defaults.
1480 arm::FloatABI ABI = arm::getARMFloatABI(TC: getToolChain(), Args);
1481 if (ABI == arm::FloatABI::Soft) {
1482 // Floating point operations and argument passing are soft.
1483 // FIXME: This changes CPP defines, we need -target-soft-float.
1484 CmdArgs.push_back(Elt: "-msoft-float");
1485 CmdArgs.push_back(Elt: "-mfloat-abi");
1486 CmdArgs.push_back(Elt: "soft");
1487 } else if (ABI == arm::FloatABI::SoftFP) {
1488 // Floating point operations are hard, but argument passing is soft.
1489 CmdArgs.push_back(Elt: "-mfloat-abi");
1490 CmdArgs.push_back(Elt: "soft");
1491 } else {
1492 // Floating point operations and argument passing are hard.
1493 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1494 CmdArgs.push_back(Elt: "-mfloat-abi");
1495 CmdArgs.push_back(Elt: "hard");
1496 }
1497
1498 // Forward the -mglobal-merge option for explicit control over the pass.
1499 if (Arg *A = Args.getLastArg(Ids: options::OPT_mglobal_merge,
1500 Ids: options::OPT_mno_global_merge)) {
1501 CmdArgs.push_back(Elt: "-mllvm");
1502 if (A->getOption().matches(ID: options::OPT_mno_global_merge))
1503 CmdArgs.push_back(Elt: "-arm-global-merge=false");
1504 else
1505 CmdArgs.push_back(Elt: "-arm-global-merge=true");
1506 }
1507
1508 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
1509 Neg: options::OPT_mno_implicit_float, Default: true))
1510 CmdArgs.push_back(Elt: "-no-implicit-float");
1511
1512 if (Args.getLastArg(Ids: options::OPT_mcmse))
1513 CmdArgs.push_back(Elt: "-mcmse");
1514
1515 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1516
1517 // Enable/disable return address signing and indirect branch targets.
1518 CollectARMPACBTIOptions(TC: getToolChain(), Args, CmdArgs, isAArch64: false /*isAArch64*/);
1519
1520 AddUnalignedAccessWarning(CmdArgs);
1521}
1522
1523void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1524 const ArgList &Args, bool KernelOrKext,
1525 ArgStringList &CmdArgs) const {
1526 const ToolChain &TC = getToolChain();
1527
1528 // Add the target features
1529 getTargetFeatures(D: TC.getDriver(), Triple: EffectiveTriple, Args, CmdArgs, ForAS: false);
1530
1531 // Add target specific flags.
1532 switch (TC.getArch()) {
1533 default:
1534 break;
1535
1536 case llvm::Triple::arm:
1537 case llvm::Triple::armeb:
1538 case llvm::Triple::thumb:
1539 case llvm::Triple::thumbeb:
1540 // Use the effective triple, which takes into account the deployment target.
1541 AddARMTargetArgs(Triple: EffectiveTriple, Args, CmdArgs, KernelOrKext);
1542 break;
1543
1544 case llvm::Triple::aarch64:
1545 case llvm::Triple::aarch64_32:
1546 case llvm::Triple::aarch64_be:
1547 AddAArch64TargetArgs(Args, CmdArgs);
1548 break;
1549
1550 case llvm::Triple::loongarch32:
1551 case llvm::Triple::loongarch64:
1552 AddLoongArchTargetArgs(Args, CmdArgs);
1553 break;
1554
1555 case llvm::Triple::mips:
1556 case llvm::Triple::mipsel:
1557 case llvm::Triple::mips64:
1558 case llvm::Triple::mips64el:
1559 AddMIPSTargetArgs(Args, CmdArgs);
1560 break;
1561
1562 case llvm::Triple::ppc:
1563 case llvm::Triple::ppcle:
1564 case llvm::Triple::ppc64:
1565 case llvm::Triple::ppc64le:
1566 AddPPCTargetArgs(Args, CmdArgs);
1567 break;
1568
1569 case llvm::Triple::riscv32:
1570 case llvm::Triple::riscv64:
1571 case llvm::Triple::riscv32be:
1572 case llvm::Triple::riscv64be:
1573 AddRISCVTargetArgs(Args, CmdArgs);
1574 break;
1575
1576 case llvm::Triple::sparc:
1577 case llvm::Triple::sparcel:
1578 case llvm::Triple::sparcv9:
1579 AddSparcTargetArgs(Args, CmdArgs);
1580 break;
1581
1582 case llvm::Triple::systemz:
1583 AddSystemZTargetArgs(Args, CmdArgs);
1584 break;
1585
1586 case llvm::Triple::x86:
1587 case llvm::Triple::x86_64:
1588 AddX86TargetArgs(Args, CmdArgs);
1589 break;
1590
1591 case llvm::Triple::lanai:
1592 AddLanaiTargetArgs(Args, CmdArgs);
1593 break;
1594
1595 case llvm::Triple::hexagon:
1596 AddHexagonTargetArgs(Args, CmdArgs);
1597 break;
1598
1599 case llvm::Triple::wasm32:
1600 case llvm::Triple::wasm64:
1601 AddWebAssemblyTargetArgs(Args, CmdArgs);
1602 break;
1603
1604 case llvm::Triple::ve:
1605 AddVETargetArgs(Args, CmdArgs);
1606 break;
1607 }
1608}
1609
1610namespace {
1611void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1612 ArgStringList &CmdArgs) {
1613 const char *ABIName = nullptr;
1614 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ))
1615 ABIName = A->getValue();
1616 else if (Triple.isOSDarwin())
1617 ABIName = "darwinpcs";
1618 // TODO: we probably want to have some target hook here.
1619 else if (Triple.isOSLinux() &&
1620 Triple.getEnvironment() == llvm::Triple::PAuthTest)
1621 ABIName = "pauthtest";
1622 else
1623 ABIName = "aapcs";
1624
1625 CmdArgs.push_back(Elt: "-target-abi");
1626 CmdArgs.push_back(Elt: ABIName);
1627}
1628}
1629
1630void Clang::AddAArch64TargetArgs(const ArgList &Args,
1631 ArgStringList &CmdArgs) const {
1632 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1633
1634 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true) ||
1635 Args.hasArg(Ids: options::OPT_mkernel) ||
1636 Args.hasArg(Ids: options::OPT_fapple_kext))
1637 CmdArgs.push_back(Elt: "-disable-red-zone");
1638
1639 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
1640 Neg: options::OPT_mno_implicit_float, Default: true))
1641 CmdArgs.push_back(Elt: "-no-implicit-float");
1642
1643 RenderAArch64ABI(Triple, Args, CmdArgs);
1644
1645 // Forward the -mglobal-merge option for explicit control over the pass.
1646 if (Arg *A = Args.getLastArg(Ids: options::OPT_mglobal_merge,
1647 Ids: options::OPT_mno_global_merge)) {
1648 CmdArgs.push_back(Elt: "-mllvm");
1649 if (A->getOption().matches(ID: options::OPT_mno_global_merge))
1650 CmdArgs.push_back(Elt: "-aarch64-enable-global-merge=false");
1651 else
1652 CmdArgs.push_back(Elt: "-aarch64-enable-global-merge=true");
1653 }
1654
1655 // Handle -msve_vector_bits=<bits>
1656 auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,
1657 StringRef VScaleMax) {
1658 StringRef Val = A->getValue();
1659 const Driver &D = getToolChain().getDriver();
1660 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1661 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1662 Val == "1024+" || Val == "2048+") {
1663 unsigned Bits = 0;
1664 if (!Val.consume_back(Suffix: "+")) {
1665 bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits);
1666 (void)Invalid;
1667 assert(!Invalid && "Failed to parse value");
1668 CmdArgs.push_back(
1669 Elt: Args.MakeArgString(Str: VScaleMax + llvm::Twine(Bits / 128)));
1670 }
1671
1672 bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits);
1673 (void)Invalid;
1674 assert(!Invalid && "Failed to parse value");
1675
1676 CmdArgs.push_back(
1677 Elt: Args.MakeArgString(Str: VScaleMin + llvm::Twine(Bits / 128)));
1678 } else if (Val == "scalable") {
1679 // Silently drop requests for vector-length agnostic code as it's implied.
1680 } else {
1681 // Handle the unsupported values passed to msve-vector-bits.
1682 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1683 << A->getSpelling() << Val;
1684 }
1685 };
1686 if (Arg *A = Args.getLastArg(Ids: options::OPT_msve_vector_bits_EQ))
1687 HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");
1688 if (Arg *A = Args.getLastArg(Ids: options::OPT_msve_streaming_vector_bits_EQ))
1689 HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");
1690
1691 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1692
1693 if (auto TuneCPU = aarch64::getAArch64TargetTuneCPU(Args, Triple)) {
1694 CmdArgs.push_back(Elt: "-tune-cpu");
1695 CmdArgs.push_back(Elt: Args.MakeArgString(Str: *TuneCPU));
1696 }
1697
1698 AddUnalignedAccessWarning(CmdArgs);
1699
1700 if (Triple.isOSDarwin() ||
1701 (Triple.isOSLinux() &&
1702 Triple.getEnvironment() == llvm::Triple::PAuthTest)) {
1703 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_intrinsics,
1704 Neg: options::OPT_fno_ptrauth_intrinsics);
1705 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_calls,
1706 Neg: options::OPT_fno_ptrauth_calls);
1707 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_returns,
1708 Neg: options::OPT_fno_ptrauth_returns);
1709 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_auth_traps,
1710 Neg: options::OPT_fno_ptrauth_auth_traps);
1711 Args.addOptInFlag(
1712 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtable_pointer_address_discrimination,
1713 Neg: options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1714 Args.addOptInFlag(
1715 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtable_pointer_type_discrimination,
1716 Neg: options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1717 Args.addOptInFlag(
1718 Output&: CmdArgs, Pos: options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1719 Neg: options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1720 Args.addOptInFlag(
1721 Output&: CmdArgs, Pos: options::OPT_fptrauth_function_pointer_type_discrimination,
1722 Neg: options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1723 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_indirect_gotos,
1724 Neg: options::OPT_fno_ptrauth_indirect_gotos);
1725 }
1726 if (Triple.isOSLinux() &&
1727 Triple.getEnvironment() == llvm::Triple::PAuthTest) {
1728 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_init_fini,
1729 Neg: options::OPT_fno_ptrauth_init_fini);
1730 Args.addOptInFlag(
1731 Output&: CmdArgs, Pos: options::OPT_fptrauth_init_fini_address_discrimination,
1732 Neg: options::OPT_fno_ptrauth_init_fini_address_discrimination);
1733 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_elf_got,
1734 Neg: options::OPT_fno_ptrauth_elf_got);
1735 }
1736 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_faarch64_jump_table_hardening,
1737 Neg: options::OPT_fno_aarch64_jump_table_hardening);
1738
1739 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_isa,
1740 Neg: options::OPT_fno_ptrauth_objc_isa);
1741 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_interface_sel,
1742 Neg: options::OPT_fno_ptrauth_objc_interface_sel);
1743 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_class_ro,
1744 Neg: options::OPT_fno_ptrauth_objc_class_ro);
1745
1746 // Enable/disable return address signing and indirect branch targets.
1747 CollectARMPACBTIOptions(TC: getToolChain(), Args, CmdArgs, isAArch64: true /*isAArch64*/);
1748}
1749
1750void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1751 ArgStringList &CmdArgs) const {
1752 const llvm::Triple &Triple = getToolChain().getTriple();
1753
1754 CmdArgs.push_back(Elt: "-target-abi");
1755 CmdArgs.push_back(
1756 Elt: loongarch::getLoongArchABI(D: getToolChain().getDriver(), Args, Triple)
1757 .data());
1758
1759 // Handle -mtune.
1760 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
1761 std::string TuneCPU = A->getValue();
1762 TuneCPU = loongarch::postProcessTargetCPUString(CPU: TuneCPU, Triple);
1763 CmdArgs.push_back(Elt: "-tune-cpu");
1764 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
1765 }
1766
1767 if (Arg *A = Args.getLastArg(Ids: options::OPT_mannotate_tablejump,
1768 Ids: options::OPT_mno_annotate_tablejump)) {
1769 if (A->getOption().matches(ID: options::OPT_mannotate_tablejump)) {
1770 CmdArgs.push_back(Elt: "-mllvm");
1771 CmdArgs.push_back(Elt: "-loongarch-annotate-tablejump");
1772 }
1773 }
1774}
1775
1776void Clang::AddMIPSTargetArgs(const ArgList &Args,
1777 ArgStringList &CmdArgs) const {
1778 const Driver &D = getToolChain().getDriver();
1779 StringRef CPUName;
1780 StringRef ABIName;
1781 const llvm::Triple &Triple = getToolChain().getTriple();
1782 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1783
1784 CmdArgs.push_back(Elt: "-target-abi");
1785 CmdArgs.push_back(Elt: ABIName.data());
1786
1787 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1788 if (ABI == mips::FloatABI::Soft) {
1789 // Floating point operations and argument passing are soft.
1790 CmdArgs.push_back(Elt: "-msoft-float");
1791 CmdArgs.push_back(Elt: "-mfloat-abi");
1792 CmdArgs.push_back(Elt: "soft");
1793 } else {
1794 // Floating point operations and argument passing are hard.
1795 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1796 CmdArgs.push_back(Elt: "-mfloat-abi");
1797 CmdArgs.push_back(Elt: "hard");
1798 }
1799
1800 if (Arg *A = Args.getLastArg(Ids: options::OPT_mldc1_sdc1,
1801 Ids: options::OPT_mno_ldc1_sdc1)) {
1802 if (A->getOption().matches(ID: options::OPT_mno_ldc1_sdc1)) {
1803 CmdArgs.push_back(Elt: "-mllvm");
1804 CmdArgs.push_back(Elt: "-mno-ldc1-sdc1");
1805 }
1806 }
1807
1808 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcheck_zero_division,
1809 Ids: options::OPT_mno_check_zero_division)) {
1810 if (A->getOption().matches(ID: options::OPT_mno_check_zero_division)) {
1811 CmdArgs.push_back(Elt: "-mllvm");
1812 CmdArgs.push_back(Elt: "-mno-check-zero-division");
1813 }
1814 }
1815
1816 if (Args.getLastArg(Ids: options::OPT_mfix4300)) {
1817 CmdArgs.push_back(Elt: "-mllvm");
1818 CmdArgs.push_back(Elt: "-mfix4300");
1819 }
1820
1821 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
1822 StringRef v = A->getValue();
1823 CmdArgs.push_back(Elt: "-mllvm");
1824 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mips-ssection-threshold=" + v));
1825 A->claim();
1826 }
1827
1828 Arg *GPOpt = Args.getLastArg(Ids: options::OPT_mgpopt, Ids: options::OPT_mno_gpopt);
1829 Arg *ABICalls =
1830 Args.getLastArg(Ids: options::OPT_mabicalls, Ids: options::OPT_mno_abicalls);
1831
1832 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1833 // -mgpopt is the default for static, -fno-pic environments but these two
1834 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1835 // the only case where -mllvm -mgpopt is passed.
1836 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1837 // passed explicitly when compiling something with -mabicalls
1838 // (implictly) in affect. Currently the warning is in the backend.
1839 //
1840 // When the ABI in use is N64, we also need to determine the PIC mode that
1841 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1842 bool NoABICalls =
1843 ABICalls && ABICalls->getOption().matches(ID: options::OPT_mno_abicalls);
1844
1845 llvm::Reloc::Model RelocationModel;
1846 unsigned PICLevel;
1847 bool IsPIE;
1848 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
1849 ParsePICArgs(ToolChain: getToolChain(), Args);
1850
1851 NoABICalls = NoABICalls ||
1852 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1853
1854 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(ID: options::OPT_mgpopt);
1855 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1856 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1857 CmdArgs.push_back(Elt: "-mllvm");
1858 CmdArgs.push_back(Elt: "-mgpopt");
1859
1860 Arg *LocalSData = Args.getLastArg(Ids: options::OPT_mlocal_sdata,
1861 Ids: options::OPT_mno_local_sdata);
1862 Arg *ExternSData = Args.getLastArg(Ids: options::OPT_mextern_sdata,
1863 Ids: options::OPT_mno_extern_sdata);
1864 Arg *EmbeddedData = Args.getLastArg(Ids: options::OPT_membedded_data,
1865 Ids: options::OPT_mno_embedded_data);
1866 if (LocalSData) {
1867 CmdArgs.push_back(Elt: "-mllvm");
1868 if (LocalSData->getOption().matches(ID: options::OPT_mlocal_sdata)) {
1869 CmdArgs.push_back(Elt: "-mlocal-sdata=1");
1870 } else {
1871 CmdArgs.push_back(Elt: "-mlocal-sdata=0");
1872 }
1873 LocalSData->claim();
1874 }
1875
1876 if (ExternSData) {
1877 CmdArgs.push_back(Elt: "-mllvm");
1878 if (ExternSData->getOption().matches(ID: options::OPT_mextern_sdata)) {
1879 CmdArgs.push_back(Elt: "-mextern-sdata=1");
1880 } else {
1881 CmdArgs.push_back(Elt: "-mextern-sdata=0");
1882 }
1883 ExternSData->claim();
1884 }
1885
1886 if (EmbeddedData) {
1887 CmdArgs.push_back(Elt: "-mllvm");
1888 if (EmbeddedData->getOption().matches(ID: options::OPT_membedded_data)) {
1889 CmdArgs.push_back(Elt: "-membedded-data=1");
1890 } else {
1891 CmdArgs.push_back(Elt: "-membedded-data=0");
1892 }
1893 EmbeddedData->claim();
1894 }
1895
1896 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1897 D.Diag(DiagID: diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1898
1899 if (GPOpt)
1900 GPOpt->claim();
1901
1902 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcompact_branches_EQ)) {
1903 StringRef Val = StringRef(A->getValue());
1904 if (mips::hasCompactBranches(CPU&: CPUName)) {
1905 if (Val == "never" || Val == "always" || Val == "optimal") {
1906 CmdArgs.push_back(Elt: "-mllvm");
1907 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mips-compact-branches=" + Val));
1908 } else
1909 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1910 << A->getSpelling() << Val;
1911 } else
1912 D.Diag(DiagID: diag::warn_target_unsupported_compact_branches) << CPUName;
1913 }
1914
1915 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrelax_pic_calls,
1916 Ids: options::OPT_mno_relax_pic_calls)) {
1917 if (A->getOption().matches(ID: options::OPT_mno_relax_pic_calls)) {
1918 CmdArgs.push_back(Elt: "-mllvm");
1919 CmdArgs.push_back(Elt: "-mips-jalr-reloc=0");
1920 }
1921 }
1922}
1923
1924void Clang::AddPPCTargetArgs(const ArgList &Args,
1925 ArgStringList &CmdArgs) const {
1926 const Driver &D = getToolChain().getDriver();
1927 const llvm::Triple &T = getToolChain().getTriple();
1928 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
1929 CmdArgs.push_back(Elt: "-tune-cpu");
1930 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, CPUName: A->getValue());
1931 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU.str()));
1932 }
1933
1934 // Select the ABI to use.
1935 const char *ABIName = nullptr;
1936 if (T.isOSBinFormatELF()) {
1937 switch (getToolChain().getArch()) {
1938 case llvm::Triple::ppc64: {
1939 if (T.isPPC64ELFv2ABI())
1940 ABIName = "elfv2";
1941 else
1942 ABIName = "elfv1";
1943 break;
1944 }
1945 case llvm::Triple::ppc64le:
1946 ABIName = "elfv2";
1947 break;
1948 default:
1949 break;
1950 }
1951 }
1952
1953 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
1954 bool VecExtabi = false;
1955 for (const Arg *A : Args.filtered(Ids: options::OPT_mabi_EQ)) {
1956 StringRef V = A->getValue();
1957 if (V == "ieeelongdouble") {
1958 IEEELongDouble = true;
1959 A->claim();
1960 } else if (V == "ibmlongdouble") {
1961 IEEELongDouble = false;
1962 A->claim();
1963 } else if (V == "vec-default") {
1964 VecExtabi = false;
1965 A->claim();
1966 } else if (V == "vec-extabi") {
1967 VecExtabi = true;
1968 A->claim();
1969 } else if (V == "elfv1") {
1970 ABIName = "elfv1";
1971 A->claim();
1972 } else if (V == "elfv2") {
1973 ABIName = "elfv2";
1974 A->claim();
1975 } else if (V != "altivec")
1976 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1977 // the option if given as we don't have backend support for any targets
1978 // that don't use the altivec abi.
1979 ABIName = A->getValue();
1980 }
1981 if (IEEELongDouble)
1982 CmdArgs.push_back(Elt: "-mabi=ieeelongdouble");
1983 if (VecExtabi) {
1984 if (!T.isOSAIX())
1985 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
1986 << "-mabi=vec-extabi" << T.str();
1987 CmdArgs.push_back(Elt: "-mabi=vec-extabi");
1988 }
1989
1990 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true))
1991 CmdArgs.push_back(Elt: "-disable-red-zone");
1992
1993 ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
1994 if (FloatABI == ppc::FloatABI::Soft) {
1995 // Floating point operations and argument passing are soft.
1996 CmdArgs.push_back(Elt: "-msoft-float");
1997 CmdArgs.push_back(Elt: "-mfloat-abi");
1998 CmdArgs.push_back(Elt: "soft");
1999 } else {
2000 // Floating point operations and argument passing are hard.
2001 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2002 CmdArgs.push_back(Elt: "-mfloat-abi");
2003 CmdArgs.push_back(Elt: "hard");
2004 }
2005
2006 if (ABIName) {
2007 CmdArgs.push_back(Elt: "-target-abi");
2008 CmdArgs.push_back(Elt: ABIName);
2009 }
2010}
2011
2012void Clang::AddRISCVTargetArgs(const ArgList &Args,
2013 ArgStringList &CmdArgs) const {
2014 const llvm::Triple &Triple = getToolChain().getTriple();
2015 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2016
2017 CmdArgs.push_back(Elt: "-target-abi");
2018 CmdArgs.push_back(Elt: ABIName.data());
2019
2020 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
2021 CmdArgs.push_back(Elt: "-msmall-data-limit");
2022 CmdArgs.push_back(Elt: A->getValue());
2023 }
2024
2025 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
2026 Neg: options::OPT_mno_implicit_float, Default: true))
2027 CmdArgs.push_back(Elt: "-no-implicit-float");
2028
2029 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2030 CmdArgs.push_back(Elt: "-tune-cpu");
2031 if (strcmp(s1: A->getValue(), s2: "native") == 0)
2032 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::getHostCPUName()));
2033 else
2034 CmdArgs.push_back(Elt: A->getValue());
2035 }
2036
2037 // Handle -mrvv-vector-bits=<bits>
2038 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrvv_vector_bits_EQ)) {
2039 StringRef Val = A->getValue();
2040 const Driver &D = getToolChain().getDriver();
2041
2042 // Get minimum VLen from march.
2043 unsigned MinVLen = 0;
2044 std::string Arch = riscv::getRISCVArch(Args, Triple);
2045 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2046 Arch, /*EnableExperimentalExtensions*/ EnableExperimentalExtension: true);
2047 // Ignore parsing error.
2048 if (!errorToBool(Err: ISAInfo.takeError()))
2049 MinVLen = (*ISAInfo)->getMinVLen();
2050
2051 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2052 // as integer as long as we have a MinVLen.
2053 unsigned Bits = 0;
2054 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2055 Bits = MinVLen;
2056 } else if (!Val.getAsInteger(Radix: 10, Result&: Bits)) {
2057 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2058 // at least MinVLen.
2059 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2060 Bits > 65536 || !llvm::isPowerOf2_32(Value: Bits))
2061 Bits = 0;
2062 }
2063
2064 // If we got a valid value try to use it.
2065 if (Bits != 0) {
2066 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2067 CmdArgs.push_back(
2068 Elt: Args.MakeArgString(Str: "-mvscale-max=" + llvm::Twine(VScaleMin)));
2069 CmdArgs.push_back(
2070 Elt: Args.MakeArgString(Str: "-mvscale-min=" + llvm::Twine(VScaleMin)));
2071 } else if (Val != "scalable") {
2072 // Handle the unsupported values passed to mrvv-vector-bits.
2073 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2074 << A->getSpelling() << Val;
2075 }
2076 }
2077}
2078
2079void Clang::AddSparcTargetArgs(const ArgList &Args,
2080 ArgStringList &CmdArgs) const {
2081 sparc::FloatABI FloatABI =
2082 sparc::getSparcFloatABI(D: getToolChain().getDriver(), Args);
2083
2084 if (FloatABI == sparc::FloatABI::Soft) {
2085 // Floating point operations and argument passing are soft.
2086 CmdArgs.push_back(Elt: "-msoft-float");
2087 CmdArgs.push_back(Elt: "-mfloat-abi");
2088 CmdArgs.push_back(Elt: "soft");
2089 } else {
2090 // Floating point operations and argument passing are hard.
2091 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2092 CmdArgs.push_back(Elt: "-mfloat-abi");
2093 CmdArgs.push_back(Elt: "hard");
2094 }
2095
2096 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2097 StringRef Name = A->getValue();
2098 std::string TuneCPU;
2099 if (Name == "native")
2100 TuneCPU = std::string(llvm::sys::getHostCPUName());
2101 else
2102 TuneCPU = std::string(Name);
2103
2104 CmdArgs.push_back(Elt: "-tune-cpu");
2105 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
2106 }
2107}
2108
2109void Clang::AddSystemZTargetArgs(const ArgList &Args,
2110 ArgStringList &CmdArgs) const {
2111 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2112 CmdArgs.push_back(Elt: "-tune-cpu");
2113 if (strcmp(s1: A->getValue(), s2: "native") == 0)
2114 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::getHostCPUName()));
2115 else
2116 CmdArgs.push_back(Elt: A->getValue());
2117 }
2118
2119 bool HasBackchain =
2120 Args.hasFlag(Pos: options::OPT_mbackchain, Neg: options::OPT_mno_backchain, Default: false);
2121 bool HasPackedStack = Args.hasFlag(Pos: options::OPT_mpacked_stack,
2122 Neg: options::OPT_mno_packed_stack, Default: false);
2123 systemz::FloatABI FloatABI =
2124 systemz::getSystemZFloatABI(D: getToolChain().getDriver(), Args);
2125 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2126 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2127 const Driver &D = getToolChain().getDriver();
2128 D.Diag(DiagID: diag::err_drv_unsupported_opt)
2129 << "-mpacked-stack -mbackchain -mhard-float";
2130 }
2131 if (HasBackchain)
2132 CmdArgs.push_back(Elt: "-mbackchain");
2133 if (HasPackedStack)
2134 CmdArgs.push_back(Elt: "-mpacked-stack");
2135 if (HasSoftFloat) {
2136 // Floating point operations and argument passing are soft.
2137 CmdArgs.push_back(Elt: "-msoft-float");
2138 CmdArgs.push_back(Elt: "-mfloat-abi");
2139 CmdArgs.push_back(Elt: "soft");
2140 }
2141}
2142
2143void Clang::AddX86TargetArgs(const ArgList &Args,
2144 ArgStringList &CmdArgs) const {
2145 const Driver &D = getToolChain().getDriver();
2146 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2147
2148 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true) ||
2149 Args.hasArg(Ids: options::OPT_mkernel) ||
2150 Args.hasArg(Ids: options::OPT_fapple_kext))
2151 CmdArgs.push_back(Elt: "-disable-red-zone");
2152
2153 if (!Args.hasFlag(Pos: options::OPT_mtls_direct_seg_refs,
2154 Neg: options::OPT_mno_tls_direct_seg_refs, Default: true))
2155 CmdArgs.push_back(Elt: "-mno-tls-direct-seg-refs");
2156
2157 // Default to avoid implicit floating-point for kernel/kext code, but allow
2158 // that to be overridden with -mno-soft-float.
2159 bool NoImplicitFloat = (Args.hasArg(Ids: options::OPT_mkernel) ||
2160 Args.hasArg(Ids: options::OPT_fapple_kext));
2161 if (Arg *A = Args.getLastArg(
2162 Ids: options::OPT_msoft_float, Ids: options::OPT_mno_soft_float,
2163 Ids: options::OPT_mimplicit_float, Ids: options::OPT_mno_implicit_float)) {
2164 const Option &O = A->getOption();
2165 NoImplicitFloat = (O.matches(ID: options::OPT_mno_implicit_float) ||
2166 O.matches(ID: options::OPT_msoft_float));
2167 }
2168 if (NoImplicitFloat)
2169 CmdArgs.push_back(Elt: "-no-implicit-float");
2170
2171 if (Arg *A = Args.getLastArg(Ids: options::OPT_masm_EQ)) {
2172 StringRef Value = A->getValue();
2173 if (Value == "intel" || Value == "att") {
2174 CmdArgs.push_back(Elt: "-mllvm");
2175 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
2176 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-inline-asm=" + Value));
2177 } else {
2178 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2179 << A->getSpelling() << Value;
2180 }
2181 } else if (D.IsCLMode()) {
2182 CmdArgs.push_back(Elt: "-mllvm");
2183 CmdArgs.push_back(Elt: "-x86-asm-syntax=intel");
2184 }
2185
2186 if (Arg *A = Args.getLastArg(Ids: options::OPT_mskip_rax_setup,
2187 Ids: options::OPT_mno_skip_rax_setup))
2188 if (A->getOption().matches(ID: options::OPT_mskip_rax_setup))
2189 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mskip-rax-setup"));
2190
2191 // Set flags to support MCU ABI.
2192 if (Args.hasFlag(Pos: options::OPT_miamcu, Neg: options::OPT_mno_iamcu, Default: false)) {
2193 CmdArgs.push_back(Elt: "-mfloat-abi");
2194 CmdArgs.push_back(Elt: "soft");
2195 CmdArgs.push_back(Elt: "-mstack-alignment=4");
2196 }
2197
2198 // Handle -mtune.
2199
2200 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2201 std::string TuneCPU;
2202 if (!Args.hasArg(Ids: options::OPT_march_EQ) && !getToolChain().getTriple().isPS())
2203 TuneCPU = "generic";
2204
2205 // Override based on -mtune.
2206 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2207 StringRef Name = A->getValue();
2208
2209 if (Name == "native") {
2210 Name = llvm::sys::getHostCPUName();
2211 if (!Name.empty())
2212 TuneCPU = std::string(Name);
2213 } else
2214 TuneCPU = std::string(Name);
2215 }
2216
2217 if (!TuneCPU.empty()) {
2218 CmdArgs.push_back(Elt: "-tune-cpu");
2219 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
2220 }
2221}
2222
2223void Clang::AddHexagonTargetArgs(const ArgList &Args,
2224 ArgStringList &CmdArgs) const {
2225 CmdArgs.push_back(Elt: "-mqdsp6-compat");
2226 CmdArgs.push_back(Elt: "-Wreturn-type");
2227
2228 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2229 CmdArgs.push_back(Elt: "-mllvm");
2230 CmdArgs.push_back(
2231 Elt: Args.MakeArgString(Str: "-hexagon-small-data-threshold=" + Twine(*G)));
2232 }
2233
2234 if (!Args.hasArg(Ids: options::OPT_fno_short_enums))
2235 CmdArgs.push_back(Elt: "-fshort-enums");
2236 if (Args.getLastArg(Ids: options::OPT_mieee_rnd_near)) {
2237 CmdArgs.push_back(Elt: "-mllvm");
2238 CmdArgs.push_back(Elt: "-enable-hexagon-ieee-rnd-near");
2239 }
2240 CmdArgs.push_back(Elt: "-mllvm");
2241 CmdArgs.push_back(Elt: "-machine-sink-split=0");
2242}
2243
2244void Clang::AddLanaiTargetArgs(const ArgList &Args,
2245 ArgStringList &CmdArgs) const {
2246 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ)) {
2247 StringRef CPUName = A->getValue();
2248
2249 CmdArgs.push_back(Elt: "-target-cpu");
2250 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPUName));
2251 }
2252 if (Arg *A = Args.getLastArg(Ids: options::OPT_mregparm_EQ)) {
2253 StringRef Value = A->getValue();
2254 // Only support mregparm=4 to support old usage. Report error for all other
2255 // cases.
2256 int Mregparm;
2257 if (Value.getAsInteger(Radix: 10, Result&: Mregparm)) {
2258 if (Mregparm != 4) {
2259 getToolChain().getDriver().Diag(
2260 DiagID: diag::err_drv_unsupported_option_argument)
2261 << A->getSpelling() << Value;
2262 }
2263 }
2264 }
2265}
2266
2267void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2268 ArgStringList &CmdArgs) const {
2269 // Default to "hidden" visibility.
2270 if (!Args.hasArg(Ids: options::OPT_fvisibility_EQ,
2271 Ids: options::OPT_fvisibility_ms_compat))
2272 CmdArgs.push_back(Elt: "-fvisibility=hidden");
2273}
2274
2275void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2276 // Floating point operations and argument passing are hard.
2277 CmdArgs.push_back(Elt: "-mfloat-abi");
2278 CmdArgs.push_back(Elt: "hard");
2279}
2280
2281void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2282 StringRef Target, const InputInfo &Output,
2283 const InputInfo &Input, const ArgList &Args) const {
2284 // If this is a dry run, do not create the compilation database file.
2285 if (C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH))
2286 return;
2287
2288 using llvm::yaml::escape;
2289 const Driver &D = getToolChain().getDriver();
2290
2291 if (!CompilationDatabase) {
2292 std::error_code EC;
2293 auto File = std::make_unique<llvm::raw_fd_ostream>(
2294 args&: Filename, args&: EC,
2295 args: llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2296 if (EC) {
2297 D.Diag(DiagID: clang::diag::err_drv_compilationdatabase) << Filename
2298 << EC.message();
2299 return;
2300 }
2301 CompilationDatabase = std::move(File);
2302 }
2303 auto &CDB = *CompilationDatabase;
2304 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2305 if (!CWD)
2306 CWD = ".";
2307 CDB << "{ \"directory\": \"" << escape(Input: *CWD) << "\"";
2308 CDB << ", \"file\": \"" << escape(Input: Input.getFilename()) << "\"";
2309 if (Output.isFilename())
2310 CDB << ", \"output\": \"" << escape(Input: Output.getFilename()) << "\"";
2311 CDB << ", \"arguments\": [\"" << escape(Input: D.ClangExecutable) << "\"";
2312 SmallString<128> Buf;
2313 Buf = "-x";
2314 Buf += types::getTypeName(Id: Input.getType());
2315 CDB << ", \"" << escape(Input: Buf) << "\"";
2316 if (!D.SysRoot.empty() && !Args.hasArg(Ids: options::OPT__sysroot_EQ)) {
2317 Buf = "--sysroot=";
2318 Buf += D.SysRoot;
2319 CDB << ", \"" << escape(Input: Buf) << "\"";
2320 }
2321 CDB << ", \"" << escape(Input: Input.getFilename()) << "\"";
2322 if (Output.isFilename())
2323 CDB << ", \"-o\", \"" << escape(Input: Output.getFilename()) << "\"";
2324 for (auto &A: Args) {
2325 auto &O = A->getOption();
2326 // Skip language selection, which is positional.
2327 if (O.getID() == options::OPT_x)
2328 continue;
2329 // Skip writing dependency output and the compilation database itself.
2330 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2331 continue;
2332 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2333 continue;
2334 // Skip inputs.
2335 if (O.getKind() == Option::InputClass)
2336 continue;
2337 // Skip output.
2338 if (O.getID() == options::OPT_o)
2339 continue;
2340 // All other arguments are quoted and appended.
2341 ArgStringList ASL;
2342 A->render(Args, Output&: ASL);
2343 for (auto &it: ASL)
2344 CDB << ", \"" << escape(Input: it) << "\"";
2345 }
2346 Buf = "--target=";
2347 Buf += Target;
2348 CDB << ", \"" << escape(Input: Buf) << "\"]},\n";
2349}
2350
2351void Clang::DumpCompilationDatabaseFragmentToDir(
2352 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2353 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2354 // If this is a dry run, do not create the compilation database file.
2355 if (C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH))
2356 return;
2357
2358 if (CompilationDatabase)
2359 DumpCompilationDatabase(C, Filename: "", Target, Output, Input, Args);
2360
2361 SmallString<256> Path = Dir;
2362 const auto &Driver = C.getDriver();
2363 Driver.getVFS().makeAbsolute(Path);
2364 auto Err = llvm::sys::fs::create_directory(path: Path, /*IgnoreExisting=*/true);
2365 if (Err) {
2366 Driver.Diag(DiagID: diag::err_drv_compilationdatabase) << Dir << Err.message();
2367 return;
2368 }
2369
2370 llvm::sys::path::append(
2371 path&: Path,
2372 a: Twine(llvm::sys::path::filename(path: Input.getFilename())) + ".%%%%.json");
2373 int FD;
2374 SmallString<256> TempPath;
2375 Err = llvm::sys::fs::createUniqueFile(Model: Path, ResultFD&: FD, ResultPath&: TempPath,
2376 Flags: llvm::sys::fs::OF_Text);
2377 if (Err) {
2378 Driver.Diag(DiagID: diag::err_drv_compilationdatabase) << Path << Err.message();
2379 return;
2380 }
2381 CompilationDatabase =
2382 std::make_unique<llvm::raw_fd_ostream>(args&: FD, /*shouldClose=*/args: true);
2383 DumpCompilationDatabase(C, Filename: "", Target, Output, Input, Args);
2384}
2385
2386static bool CheckARMImplicitITArg(StringRef Value) {
2387 return Value == "always" || Value == "never" || Value == "arm" ||
2388 Value == "thumb";
2389}
2390
2391static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2392 StringRef Value) {
2393 CmdArgs.push_back(Elt: "-mllvm");
2394 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-arm-implicit-it=" + Value));
2395}
2396
2397static void CollectArgsForIntegratedAssembler(Compilation &C,
2398 const ArgList &Args,
2399 ArgStringList &CmdArgs,
2400 const Driver &D) {
2401 // Default to -mno-relax-all.
2402 //
2403 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2404 // cannot be done by assembler branch relaxation as it needs a free temporary
2405 // register. Because of this, branch relaxation is handled by a MachineIR pass
2406 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2407 // MachineIR branch relaxation inaccurate and it will miss cases where an
2408 // indirect branch is necessary.
2409 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mrelax_all,
2410 Neg: options::OPT_mno_relax_all);
2411
2412 // Only default to -mincremental-linker-compatible if we think we are
2413 // targeting the MSVC linker.
2414 bool DefaultIncrementalLinkerCompatible =
2415 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2416 if (Args.hasFlag(Pos: options::OPT_mincremental_linker_compatible,
2417 Neg: options::OPT_mno_incremental_linker_compatible,
2418 Default: DefaultIncrementalLinkerCompatible))
2419 CmdArgs.push_back(Elt: "-mincremental-linker-compatible");
2420
2421 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_femit_dwarf_unwind_EQ);
2422
2423 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_femit_compact_unwind_non_canonical,
2424 Neg: options::OPT_fno_emit_compact_unwind_non_canonical);
2425
2426 // If you add more args here, also add them to the block below that
2427 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2428
2429 // When passing -I arguments to the assembler we sometimes need to
2430 // unconditionally take the next argument. For example, when parsing
2431 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2432 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2433 // arg after parsing the '-I' arg.
2434 bool TakeNextArg = false;
2435
2436 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2437 bool IsELF = Triple.isOSBinFormatELF();
2438 bool Crel = false, ExperimentalCrel = false;
2439 StringRef RelocSectionSym;
2440 bool SFrame = false, ExperimentalSFrame = false;
2441 bool ImplicitMapSyms = false;
2442 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2443 bool UseNoExecStack = false;
2444 bool Msa = false;
2445 const char *MipsTargetFeature = nullptr;
2446 llvm::SmallVector<const char *> SparcTargetFeatures;
2447 StringRef ImplicitIt;
2448 for (const Arg *A :
2449 Args.filtered(Ids: options::OPT_Wa_COMMA, Ids: options::OPT_Xassembler,
2450 Ids: options::OPT_mimplicit_it_EQ)) {
2451 A->claim();
2452
2453 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2454 switch (C.getDefaultToolChain().getArch()) {
2455 case llvm::Triple::arm:
2456 case llvm::Triple::armeb:
2457 case llvm::Triple::thumb:
2458 case llvm::Triple::thumbeb:
2459 // Only store the value; the last value set takes effect.
2460 ImplicitIt = A->getValue();
2461 if (!CheckARMImplicitITArg(Value: ImplicitIt))
2462 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2463 << A->getSpelling() << ImplicitIt;
2464 continue;
2465 default:
2466 break;
2467 }
2468 }
2469
2470 for (StringRef Value : A->getValues()) {
2471 if (TakeNextArg) {
2472 CmdArgs.push_back(Elt: Value.data());
2473 TakeNextArg = false;
2474 continue;
2475 }
2476
2477 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2478 Value == "-mbig-obj")
2479 continue; // LLVM handles bigobj automatically
2480
2481 auto Equal = Value.split(Separator: '=');
2482 auto checkArg = [&](bool ValidTarget,
2483 std::initializer_list<const char *> Set) {
2484 if (!ValidTarget) {
2485 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2486 << (Twine("-Wa,") + Equal.first + "=").str()
2487 << Triple.getTriple();
2488 } else if (!llvm::is_contained(Set, Element: Equal.second)) {
2489 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2490 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2491 }
2492 };
2493 switch (C.getDefaultToolChain().getArch()) {
2494 default:
2495 break;
2496 case llvm::Triple::x86:
2497 case llvm::Triple::x86_64:
2498 if (Equal.first == "-mrelax-relocations" ||
2499 Equal.first == "--mrelax-relocations") {
2500 UseRelaxRelocations = Equal.second == "yes";
2501 checkArg(IsELF, {"yes", "no"});
2502 continue;
2503 }
2504 if (Value == "-msse2avx") {
2505 CmdArgs.push_back(Elt: "-msse2avx");
2506 continue;
2507 }
2508 break;
2509 case llvm::Triple::wasm32:
2510 case llvm::Triple::wasm64:
2511 if (Value == "--no-type-check") {
2512 CmdArgs.push_back(Elt: "-mno-type-check");
2513 continue;
2514 }
2515 break;
2516 case llvm::Triple::thumb:
2517 case llvm::Triple::thumbeb:
2518 case llvm::Triple::arm:
2519 case llvm::Triple::armeb:
2520 if (Equal.first == "-mimplicit-it") {
2521 // Only store the value; the last value set takes effect.
2522 ImplicitIt = Equal.second;
2523 checkArg(true, {"always", "never", "arm", "thumb"});
2524 continue;
2525 }
2526 if (Value == "-mthumb")
2527 // -mthumb has already been processed in ComputeLLVMTriple()
2528 // recognize but skip over here.
2529 continue;
2530 break;
2531 case llvm::Triple::aarch64:
2532 case llvm::Triple::aarch64_be:
2533 case llvm::Triple::aarch64_32:
2534 if (Equal.first == "-mmapsyms") {
2535 ImplicitMapSyms = Equal.second == "implicit";
2536 checkArg(IsELF, {"default", "implicit"});
2537 continue;
2538 }
2539 break;
2540 case llvm::Triple::mips:
2541 case llvm::Triple::mipsel:
2542 case llvm::Triple::mips64:
2543 case llvm::Triple::mips64el:
2544 if (Value == "--trap") {
2545 CmdArgs.push_back(Elt: "-target-feature");
2546 CmdArgs.push_back(Elt: "+use-tcc-in-div");
2547 continue;
2548 }
2549 if (Value == "--break") {
2550 CmdArgs.push_back(Elt: "-target-feature");
2551 CmdArgs.push_back(Elt: "-use-tcc-in-div");
2552 continue;
2553 }
2554 if (Value.starts_with(Prefix: "-msoft-float")) {
2555 CmdArgs.push_back(Elt: "-target-feature");
2556 CmdArgs.push_back(Elt: "+soft-float");
2557 continue;
2558 }
2559 if (Value.starts_with(Prefix: "-mhard-float")) {
2560 CmdArgs.push_back(Elt: "-target-feature");
2561 CmdArgs.push_back(Elt: "-soft-float");
2562 continue;
2563 }
2564 if (Value == "-mmsa") {
2565 Msa = true;
2566 continue;
2567 }
2568 if (Value == "-mno-msa") {
2569 Msa = false;
2570 continue;
2571 }
2572 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2573 .Case(S: "-mips1", Value: "+mips1")
2574 .Case(S: "-mips2", Value: "+mips2")
2575 .Case(S: "-mips3", Value: "+mips3")
2576 .Case(S: "-mips4", Value: "+mips4")
2577 .Case(S: "-mips5", Value: "+mips5")
2578 .Case(S: "-mips32", Value: "+mips32")
2579 .Case(S: "-mips32r2", Value: "+mips32r2")
2580 .Case(S: "-mips32r3", Value: "+mips32r3")
2581 .Case(S: "-mips32r5", Value: "+mips32r5")
2582 .Case(S: "-mips32r6", Value: "+mips32r6")
2583 .Case(S: "-mips64", Value: "+mips64")
2584 .Case(S: "-mips64r2", Value: "+mips64r2")
2585 .Case(S: "-mips64r3", Value: "+mips64r3")
2586 .Case(S: "-mips64r5", Value: "+mips64r5")
2587 .Case(S: "-mips64r6", Value: "+mips64r6")
2588 .Default(Value: nullptr);
2589 if (MipsTargetFeature)
2590 continue;
2591 break;
2592
2593 case llvm::Triple::sparc:
2594 case llvm::Triple::sparcel:
2595 case llvm::Triple::sparcv9:
2596 if (Value == "--undeclared-regs") {
2597 // LLVM already allows undeclared use of G registers, so this option
2598 // becomes a no-op. This solely exists for GNU compatibility.
2599 // TODO implement --no-undeclared-regs
2600 continue;
2601 }
2602 SparcTargetFeatures =
2603 llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2604 .Case(S: "-Av8", Value: {"-v8plus"})
2605 .Case(S: "-Av8plus", Value: {"+v8plus", "+v9"})
2606 .Case(S: "-Av8plusa", Value: {"+v8plus", "+v9", "+vis"})
2607 .Case(S: "-Av8plusb", Value: {"+v8plus", "+v9", "+vis", "+vis2"})
2608 .Case(S: "-Av8plusd", Value: {"+v8plus", "+v9", "+vis", "+vis2", "+vis3"})
2609 .Case(S: "-Av9", Value: {"+v9"})
2610 .Case(S: "-Av9a", Value: {"+v9", "+vis"})
2611 .Case(S: "-Av9b", Value: {"+v9", "+vis", "+vis2"})
2612 .Case(S: "-Av9d", Value: {"+v9", "+vis", "+vis2", "+vis3"})
2613 .Default(Value: {});
2614 if (!SparcTargetFeatures.empty())
2615 continue;
2616 break;
2617 }
2618
2619 if (Value == "-force_cpusubtype_ALL") {
2620 // Do nothing, this is the default and we don't support anything else.
2621 } else if (Value == "-L") {
2622 CmdArgs.push_back(Elt: "-msave-temp-labels");
2623 } else if (Value == "--fatal-warnings") {
2624 CmdArgs.push_back(Elt: "-massembler-fatal-warnings");
2625 } else if (Value == "--no-warn" || Value == "-W") {
2626 CmdArgs.push_back(Elt: "-massembler-no-warn");
2627 } else if (Value == "--noexecstack") {
2628 UseNoExecStack = true;
2629 } else if (Value.starts_with(Prefix: "-compress-debug-sections") ||
2630 Value.starts_with(Prefix: "--compress-debug-sections") ||
2631 Value == "-nocompress-debug-sections" ||
2632 Value == "--nocompress-debug-sections") {
2633 CmdArgs.push_back(Elt: Value.data());
2634 } else if (Value == "--crel") {
2635 Crel = true;
2636 } else if (Value == "--no-crel") {
2637 Crel = false;
2638 } else if (Value == "--allow-experimental-crel") {
2639 ExperimentalCrel = true;
2640 } else if (Value.starts_with(Prefix: "--reloc-section-sym=")) {
2641 RelocSectionSym = Value.substr(Start: strlen(s: "--reloc-section-sym="));
2642 } else if (Value.starts_with(Prefix: "-I")) {
2643 CmdArgs.push_back(Elt: Value.data());
2644 // We need to consume the next argument if the current arg is a plain
2645 // -I. The next arg will be the include directory.
2646 if (Value == "-I")
2647 TakeNextArg = true;
2648 } else if (Value.starts_with(Prefix: "-gdwarf-")) {
2649 // "-gdwarf-N" options are not cc1as options.
2650 unsigned DwarfVersion = DwarfVersionNum(ArgValue: Value);
2651 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2652 CmdArgs.push_back(Elt: Value.data());
2653 } else {
2654 RenderDebugEnablingArgs(Args, CmdArgs,
2655 DebugInfoKind: llvm::codegenoptions::DebugInfoConstructor,
2656 DwarfVersion, DebuggerTuning: llvm::DebuggerKind::Default);
2657 }
2658 } else if (Value == "--gsframe") {
2659 SFrame = true;
2660 } else if (Value == "--allow-experimental-sframe") {
2661 ExperimentalSFrame = true;
2662 } else if (Value.starts_with(Prefix: "-mcpu") || Value.starts_with(Prefix: "-mfpu") ||
2663 Value.starts_with(Prefix: "-mhwdiv") || Value.starts_with(Prefix: "-march")) {
2664 // Do nothing, we'll validate it later.
2665 } else if (Value == "-defsym" || Value == "--defsym") {
2666 if (A->getNumValues() != 2) {
2667 D.Diag(DiagID: diag::err_drv_defsym_invalid_format) << Value;
2668 break;
2669 }
2670 const char *S = A->getValue(N: 1);
2671 auto Pair = StringRef(S).split(Separator: '=');
2672 auto Sym = Pair.first;
2673 auto SVal = Pair.second;
2674
2675 if (Sym.empty() || SVal.empty()) {
2676 D.Diag(DiagID: diag::err_drv_defsym_invalid_format) << S;
2677 break;
2678 }
2679 int64_t IVal;
2680 if (SVal.getAsInteger(Radix: 0, Result&: IVal)) {
2681 D.Diag(DiagID: diag::err_drv_defsym_invalid_symval) << SVal;
2682 break;
2683 }
2684 CmdArgs.push_back(Elt: "--defsym");
2685 TakeNextArg = true;
2686 } else if (Value == "-fdebug-compilation-dir") {
2687 CmdArgs.push_back(Elt: "-fdebug-compilation-dir");
2688 TakeNextArg = true;
2689 } else if (Value.consume_front(Prefix: "-fdebug-compilation-dir=")) {
2690 // The flag is a -Wa / -Xassembler argument and Options doesn't
2691 // parse the argument, so this isn't automatically aliased to
2692 // -fdebug-compilation-dir (without '=') here.
2693 CmdArgs.push_back(Elt: "-fdebug-compilation-dir");
2694 CmdArgs.push_back(Elt: Value.data());
2695 } else if (Value == "--version") {
2696 D.PrintVersion(C, OS&: llvm::outs());
2697 } else {
2698 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2699 << A->getSpelling() << Value;
2700 }
2701 }
2702 }
2703 if (ImplicitIt.size())
2704 AddARMImplicitITArgs(Args, CmdArgs, Value: ImplicitIt);
2705 if (Crel) {
2706 if (!ExperimentalCrel)
2707 D.Diag(DiagID: diag::err_drv_experimental_crel);
2708 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2709 CmdArgs.push_back(Elt: "--crel");
2710 } else {
2711 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2712 << "-Wa,--crel" << D.getTargetTriple();
2713 }
2714 }
2715 if (!RelocSectionSym.empty()) {
2716 if (RelocSectionSym != "all" && RelocSectionSym != "internal" &&
2717 RelocSectionSym != "none")
2718 D.Diag(DiagID: diag::err_drv_invalid_value)
2719 << ("-Wa,--reloc-section-sym=" + RelocSectionSym).str()
2720 << RelocSectionSym;
2721 else if (Triple.isOSBinFormatELF())
2722 CmdArgs.push_back(
2723 Elt: Args.MakeArgString(Str: "--reloc-section-sym=" + RelocSectionSym));
2724 else
2725 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2726 << "-Wa,--reloc-section-sym" << D.getTargetTriple();
2727 }
2728 if (SFrame) {
2729 if (Triple.isOSBinFormatELF() && Triple.isX86()) {
2730 if (!ExperimentalSFrame)
2731 D.Diag(DiagID: diag::err_drv_experimental_sframe);
2732 else
2733 CmdArgs.push_back(Elt: "--gsframe");
2734 } else {
2735 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2736 << "-Wa,--gsframe" << D.getTargetTriple();
2737 }
2738 }
2739 if (ImplicitMapSyms)
2740 CmdArgs.push_back(Elt: "-mmapsyms=implicit");
2741 if (Msa)
2742 CmdArgs.push_back(Elt: "-mmsa");
2743 if (!UseRelaxRelocations)
2744 CmdArgs.push_back(Elt: "-mrelax-relocations=no");
2745 if (UseNoExecStack)
2746 CmdArgs.push_back(Elt: "-mnoexecstack");
2747 if (MipsTargetFeature != nullptr) {
2748 CmdArgs.push_back(Elt: "-target-feature");
2749 CmdArgs.push_back(Elt: MipsTargetFeature);
2750 }
2751
2752 for (const char *Feature : SparcTargetFeatures) {
2753 CmdArgs.push_back(Elt: "-target-feature");
2754 CmdArgs.push_back(Elt: Feature);
2755 }
2756
2757 // forward -fembed-bitcode to assmebler
2758 if (C.getDriver().embedBitcodeEnabled() ||
2759 C.getDriver().embedBitcodeMarkerOnly())
2760 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fembed_bitcode_EQ);
2761
2762 if (const char *AsSecureLogFile = getenv(name: "AS_SECURE_LOG_FILE")) {
2763 CmdArgs.push_back(Elt: "-as-secure-log-file");
2764 CmdArgs.push_back(Elt: Args.MakeArgString(Str: AsSecureLogFile));
2765 }
2766}
2767
2768static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2769 bool OFastEnabled, const ArgList &Args,
2770 ArgStringList &CmdArgs,
2771 const JobAction &JA) {
2772 // List of veclibs which when used with -fveclib imply -fno-math-errno.
2773 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2774 llvm::StringLiteral("SLEEF")};
2775 bool NoMathErrnoWasImpliedByVecLib = false;
2776 const Arg *VecLibArg = nullptr;
2777 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
2778 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
2779
2780 // Handle various floating point optimization flags, mapping them to the
2781 // appropriate LLVM code generation flags. This is complicated by several
2782 // "umbrella" flags, so we do this by stepping through the flags incrementally
2783 // adjusting what we think is enabled/disabled, then at the end setting the
2784 // LLVM flags based on the final state.
2785 bool HonorINFs = true;
2786 bool HonorNaNs = true;
2787 bool ApproxFunc = false;
2788 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2789 bool MathErrno = TC.IsMathErrnoDefault();
2790 bool AssociativeMath = false;
2791 bool ReciprocalMath = false;
2792 bool SignedZeros = true;
2793 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2794 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2795 // overriden by ffp-exception-behavior?
2796 bool RoundingFPMath = false;
2797 // -ffp-model values: strict, fast, precise
2798 StringRef FPModel = "";
2799 // -ffp-exception-behavior options: strict, maytrap, ignore
2800 StringRef FPExceptionBehavior = "";
2801 // -ffp-eval-method options: double, extended, source
2802 StringRef FPEvalMethod = "";
2803 llvm::DenormalMode DenormalFPMath =
2804 TC.getDefaultDenormalModeForType(DriverArgs: Args, JA);
2805 llvm::DenormalMode DenormalFP32Math =
2806 TC.getDefaultDenormalModeForType(DriverArgs: Args, JA, FPType: &llvm::APFloat::IEEEsingle());
2807
2808 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2809 // If one wasn't given by the user, don't pass it here.
2810 StringRef FPContract;
2811 StringRef LastSeenFfpContractOption;
2812 StringRef LastFpContractOverrideOption;
2813 bool SeenUnsafeMathModeOption = false;
2814 if (!JA.isDeviceOffloading(OKind: Action::OFK_Cuda) &&
2815 !JA.isOffloading(OKind: Action::OFK_HIP))
2816 FPContract = "on";
2817 bool StrictFPModel = false;
2818 StringRef Float16ExcessPrecision = "";
2819 StringRef BFloat16ExcessPrecision = "";
2820 LangOptions::ComplexRangeKind Range = LangOptions::ComplexRangeKind::CX_None;
2821 std::string ComplexRangeStr;
2822 StringRef LastComplexRangeOption;
2823
2824 // Lambda to set fast-math options. This is also used by -ffp-model=fast
2825 auto applyFastMath = [&](bool Aggressive, StringRef CallerOption) {
2826 if (Aggressive) {
2827 HonorINFs = false;
2828 HonorNaNs = false;
2829 setComplexRange(D, NewOpt: CallerOption, NewRange: LangOptions::ComplexRangeKind::CX_Basic,
2830 LastOpt&: LastComplexRangeOption, Range);
2831 } else {
2832 HonorINFs = true;
2833 HonorNaNs = true;
2834 setComplexRange(D, NewOpt: CallerOption,
2835 NewRange: LangOptions::ComplexRangeKind::CX_Promoted,
2836 LastOpt&: LastComplexRangeOption, Range);
2837 }
2838 MathErrno = false;
2839 AssociativeMath = true;
2840 ReciprocalMath = true;
2841 ApproxFunc = true;
2842 SignedZeros = false;
2843 TrappingMath = false;
2844 RoundingFPMath = false;
2845 FPExceptionBehavior = "";
2846 FPContract = "fast";
2847 SeenUnsafeMathModeOption = true;
2848 };
2849
2850 // Lambda to consolidate common handling for fp-contract
2851 auto restoreFPContractState = [&]() {
2852 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2853 // For other targets, if the state has been changed by one of the
2854 // unsafe-math umbrella options a subsequent -fno-fast-math or
2855 // -fno-unsafe-math-optimizations option reverts to the last value seen for
2856 // the -ffp-contract option or "on" if we have not seen the -ffp-contract
2857 // option. If we have not seen an unsafe-math option or -ffp-contract,
2858 // we leave the FPContract state unchanged.
2859 if (!JA.isDeviceOffloading(OKind: Action::OFK_Cuda) &&
2860 !JA.isOffloading(OKind: Action::OFK_HIP)) {
2861 if (LastSeenFfpContractOption != "")
2862 FPContract = LastSeenFfpContractOption;
2863 else if (SeenUnsafeMathModeOption)
2864 FPContract = "on";
2865 }
2866 // In this case, we're reverting to the last explicit fp-contract option
2867 // or the platform default
2868 LastFpContractOverrideOption = "";
2869 };
2870
2871 if (const Arg *A = Args.getLastArg(Ids: options::OPT_flimited_precision_EQ)) {
2872 CmdArgs.push_back(Elt: "-mlimit-float-precision");
2873 CmdArgs.push_back(Elt: A->getValue());
2874 }
2875
2876 for (const Arg *A : Args) {
2877 llvm::scope_exit CheckMathErrnoForVecLib(
2878 [&, MathErrnoBeforeArg = MathErrno] {
2879 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
2880 ArgThatEnabledMathErrnoAfterVecLib = A;
2881 });
2882
2883 switch (A->getOption().getID()) {
2884 // If this isn't an FP option skip the claim below
2885 default: continue;
2886
2887 case options::OPT_fcx_limited_range:
2888 setComplexRange(D, NewOpt: A->getSpelling(),
2889 NewRange: LangOptions::ComplexRangeKind::CX_Basic,
2890 LastOpt&: LastComplexRangeOption, Range);
2891 break;
2892 case options::OPT_fno_cx_limited_range:
2893 setComplexRange(D, NewOpt: A->getSpelling(),
2894 NewRange: LangOptions::ComplexRangeKind::CX_Full,
2895 LastOpt&: LastComplexRangeOption, Range);
2896 break;
2897 case options::OPT_fcx_fortran_rules:
2898 setComplexRange(D, NewOpt: A->getSpelling(),
2899 NewRange: LangOptions::ComplexRangeKind::CX_Improved,
2900 LastOpt&: LastComplexRangeOption, Range);
2901 break;
2902 case options::OPT_fno_cx_fortran_rules:
2903 setComplexRange(D, NewOpt: A->getSpelling(),
2904 NewRange: LangOptions::ComplexRangeKind::CX_Full,
2905 LastOpt&: LastComplexRangeOption, Range);
2906 break;
2907 case options::OPT_fcomplex_arithmetic_EQ: {
2908 LangOptions::ComplexRangeKind RangeVal;
2909 StringRef Val = A->getValue();
2910 if (Val == "full")
2911 RangeVal = LangOptions::ComplexRangeKind::CX_Full;
2912 else if (Val == "improved")
2913 RangeVal = LangOptions::ComplexRangeKind::CX_Improved;
2914 else if (Val == "promoted")
2915 RangeVal = LangOptions::ComplexRangeKind::CX_Promoted;
2916 else if (Val == "basic")
2917 RangeVal = LangOptions::ComplexRangeKind::CX_Basic;
2918 else {
2919 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2920 << A->getSpelling() << Val;
2921 break;
2922 }
2923 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val), NewRange: RangeVal,
2924 LastOpt&: LastComplexRangeOption, Range);
2925 break;
2926 }
2927 case options::OPT_ffp_model_EQ: {
2928 // If -ffp-model= is seen, reset to fno-fast-math
2929 HonorINFs = true;
2930 HonorNaNs = true;
2931 ApproxFunc = false;
2932 // Turning *off* -ffast-math restores the toolchain default.
2933 MathErrno = TC.IsMathErrnoDefault();
2934 AssociativeMath = false;
2935 ReciprocalMath = false;
2936 SignedZeros = true;
2937
2938 StringRef Val = A->getValue();
2939 if (OFastEnabled && Val != "aggressive") {
2940 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
2941 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
2942 << Args.MakeArgString(Str: "-ffp-model=" + Val) << "-Ofast";
2943 break;
2944 }
2945 StrictFPModel = false;
2946 if (!FPModel.empty() && FPModel != Val)
2947 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
2948 << Args.MakeArgString(Str: "-ffp-model=" + FPModel)
2949 << Args.MakeArgString(Str: "-ffp-model=" + Val);
2950 if (Val == "fast") {
2951 FPModel = Val;
2952 applyFastMath(false, Args.MakeArgString(Str: A->getSpelling() + Val));
2953 // applyFastMath sets fp-contract="fast"
2954 LastFpContractOverrideOption = "-ffp-model=fast";
2955 } else if (Val == "aggressive") {
2956 FPModel = Val;
2957 applyFastMath(true, Args.MakeArgString(Str: A->getSpelling() + Val));
2958 // applyFastMath sets fp-contract="fast"
2959 LastFpContractOverrideOption = "-ffp-model=aggressive";
2960 } else if (Val == "precise") {
2961 FPModel = Val;
2962 FPContract = "on";
2963 LastFpContractOverrideOption = "-ffp-model=precise";
2964 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val),
2965 NewRange: LangOptions::ComplexRangeKind::CX_Full,
2966 LastOpt&: LastComplexRangeOption, Range);
2967 } else if (Val == "strict") {
2968 StrictFPModel = true;
2969 FPExceptionBehavior = "strict";
2970 FPModel = Val;
2971 FPContract = "off";
2972 LastFpContractOverrideOption = "-ffp-model=strict";
2973 TrappingMath = true;
2974 RoundingFPMath = true;
2975 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val),
2976 NewRange: LangOptions::ComplexRangeKind::CX_Full,
2977 LastOpt&: LastComplexRangeOption, Range);
2978 } else
2979 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2980 << A->getSpelling() << Val;
2981 break;
2982 }
2983
2984 // Options controlling individual features
2985 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2986 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2987 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2988 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2989 case options::OPT_fapprox_func: ApproxFunc = true; break;
2990 case options::OPT_fno_approx_func: ApproxFunc = false; break;
2991 case options::OPT_fmath_errno: MathErrno = true; break;
2992 case options::OPT_fno_math_errno: MathErrno = false; break;
2993 case options::OPT_fassociative_math: AssociativeMath = true; break;
2994 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2995 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2996 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2997 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2998 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2999 case options::OPT_ftrapping_math:
3000 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3001 FPExceptionBehavior != "strict")
3002 // Warn that previous value of option is overridden.
3003 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3004 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3005 FPExceptionBehavior)
3006 << "-ftrapping-math";
3007 TrappingMath = true;
3008 TrappingMathPresent = true;
3009 FPExceptionBehavior = "strict";
3010 break;
3011 case options::OPT_fveclib:
3012 VecLibArg = A;
3013 NoMathErrnoWasImpliedByVecLib =
3014 llvm::is_contained(Range: VecLibImpliesNoMathErrno, Element: A->getValue());
3015 if (NoMathErrnoWasImpliedByVecLib)
3016 MathErrno = false;
3017 break;
3018 case options::OPT_fno_trapping_math:
3019 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3020 FPExceptionBehavior != "ignore")
3021 // Warn that previous value of option is overridden.
3022 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3023 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3024 FPExceptionBehavior)
3025 << "-fno-trapping-math";
3026 TrappingMath = false;
3027 TrappingMathPresent = true;
3028 FPExceptionBehavior = "ignore";
3029 break;
3030
3031 case options::OPT_frounding_math:
3032 RoundingFPMath = true;
3033 break;
3034
3035 case options::OPT_fno_rounding_math:
3036 RoundingFPMath = false;
3037 break;
3038
3039 case options::OPT_fdenormal_fp_math_EQ:
3040 DenormalFPMath = llvm::parseDenormalFPAttribute(Str: A->getValue());
3041 DenormalFP32Math = DenormalFPMath;
3042 if (!DenormalFPMath.isValid()) {
3043 D.Diag(DiagID: diag::err_drv_invalid_value)
3044 << A->getAsString(Args) << A->getValue();
3045 }
3046 break;
3047
3048 case options::OPT_fdenormal_fp_math_f32_EQ:
3049 DenormalFP32Math = llvm::parseDenormalFPAttribute(Str: A->getValue());
3050 if (!DenormalFP32Math.isValid()) {
3051 D.Diag(DiagID: diag::err_drv_invalid_value)
3052 << A->getAsString(Args) << A->getValue();
3053 }
3054 break;
3055
3056 // Validate and pass through -ffp-contract option.
3057 case options::OPT_ffp_contract: {
3058 StringRef Val = A->getValue();
3059 if (Val == "fast" || Val == "on" || Val == "off" ||
3060 Val == "fast-honor-pragmas") {
3061 if (Val != FPContract && LastFpContractOverrideOption != "") {
3062 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3063 << LastFpContractOverrideOption
3064 << Args.MakeArgString(Str: "-ffp-contract=" + Val);
3065 }
3066
3067 FPContract = Val;
3068 LastSeenFfpContractOption = Val;
3069 LastFpContractOverrideOption = "";
3070 } else
3071 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3072 << A->getSpelling() << Val;
3073 break;
3074 }
3075
3076 // Validate and pass through -ffp-exception-behavior option.
3077 case options::OPT_ffp_exception_behavior_EQ: {
3078 StringRef Val = A->getValue();
3079 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3080 FPExceptionBehavior != Val)
3081 // Warn that previous value of option is overridden.
3082 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3083 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3084 FPExceptionBehavior)
3085 << Args.MakeArgString(Str: "-ffp-exception-behavior=" + Val);
3086 TrappingMath = TrappingMathPresent = false;
3087 if (Val == "ignore" || Val == "maytrap")
3088 FPExceptionBehavior = Val;
3089 else if (Val == "strict") {
3090 FPExceptionBehavior = Val;
3091 TrappingMath = TrappingMathPresent = true;
3092 } else
3093 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3094 << A->getSpelling() << Val;
3095 break;
3096 }
3097
3098 // Validate and pass through -ffp-eval-method option.
3099 case options::OPT_ffp_eval_method_EQ: {
3100 StringRef Val = A->getValue();
3101 if (Val == "double" || Val == "extended" || Val == "source")
3102 FPEvalMethod = Val;
3103 else
3104 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3105 << A->getSpelling() << Val;
3106 break;
3107 }
3108
3109 case options::OPT_fexcess_precision_EQ: {
3110 StringRef Val = A->getValue();
3111 const llvm::Triple::ArchType Arch = TC.getArch();
3112 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3113 if (Val == "standard" || Val == "fast")
3114 Float16ExcessPrecision = Val;
3115 // To make it GCC compatible, allow the value of "16" which
3116 // means disable excess precision, the same meaning than clang's
3117 // equivalent value "none".
3118 else if (Val == "16")
3119 Float16ExcessPrecision = "none";
3120 else
3121 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3122 << A->getSpelling() << Val;
3123 } else {
3124 if (!(Val == "standard" || Val == "fast"))
3125 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3126 << A->getSpelling() << Val;
3127 }
3128 BFloat16ExcessPrecision = Float16ExcessPrecision;
3129 break;
3130 }
3131 case options::OPT_ffinite_math_only:
3132 HonorINFs = false;
3133 HonorNaNs = false;
3134 break;
3135 case options::OPT_fno_finite_math_only:
3136 HonorINFs = true;
3137 HonorNaNs = true;
3138 break;
3139
3140 case options::OPT_funsafe_math_optimizations:
3141 AssociativeMath = true;
3142 ReciprocalMath = true;
3143 SignedZeros = false;
3144 ApproxFunc = true;
3145 TrappingMath = false;
3146 FPExceptionBehavior = "";
3147 FPContract = "fast";
3148 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3149 SeenUnsafeMathModeOption = true;
3150 break;
3151 case options::OPT_fno_unsafe_math_optimizations:
3152 AssociativeMath = false;
3153 ReciprocalMath = false;
3154 SignedZeros = true;
3155 ApproxFunc = false;
3156 restoreFPContractState();
3157 break;
3158
3159 case options::OPT_Ofast:
3160 // If -Ofast is the optimization level, then -ffast-math should be enabled
3161 if (!OFastEnabled)
3162 continue;
3163 [[fallthrough]];
3164 case options::OPT_ffast_math:
3165 applyFastMath(true, A->getSpelling());
3166 if (A->getOption().getID() == options::OPT_Ofast)
3167 LastFpContractOverrideOption = "-Ofast";
3168 else
3169 LastFpContractOverrideOption = "-ffast-math";
3170 break;
3171 case options::OPT_fno_fast_math:
3172 HonorINFs = true;
3173 HonorNaNs = true;
3174 // Turning on -ffast-math (with either flag) removes the need for
3175 // MathErrno. However, turning *off* -ffast-math merely restores the
3176 // toolchain default (which may be false).
3177 MathErrno = TC.IsMathErrnoDefault();
3178 AssociativeMath = false;
3179 ReciprocalMath = false;
3180 ApproxFunc = false;
3181 SignedZeros = true;
3182 restoreFPContractState();
3183 if (Range != LangOptions::ComplexRangeKind::CX_Full)
3184 setComplexRange(D, NewOpt: A->getSpelling(),
3185 NewRange: LangOptions::ComplexRangeKind::CX_None,
3186 LastOpt&: LastComplexRangeOption, Range);
3187 else
3188 Range = LangOptions::ComplexRangeKind::CX_None;
3189 LastComplexRangeOption = "";
3190 LastFpContractOverrideOption = "";
3191 break;
3192 } // End switch (A->getOption().getID())
3193
3194 // The StrictFPModel local variable is needed to report warnings
3195 // in the way we intend. If -ffp-model=strict has been used, we
3196 // want to report a warning for the next option encountered that
3197 // takes us out of the settings described by fp-model=strict, but
3198 // we don't want to continue issuing warnings for other conflicting
3199 // options after that.
3200 if (StrictFPModel) {
3201 // If -ffp-model=strict has been specified on command line but
3202 // subsequent options conflict then emit warning diagnostic.
3203 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3204 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3205 FPContract == "off")
3206 // OK: Current Arg doesn't conflict with -ffp-model=strict
3207 ;
3208 else {
3209 StrictFPModel = false;
3210 FPModel = "";
3211 // The warning for -ffp-contract would have been reported by the
3212 // OPT_ffp_contract_EQ handler above. A special check here is needed
3213 // to avoid duplicating the warning.
3214 auto RHS = (A->getNumValues() == 0)
3215 ? A->getSpelling()
3216 : Args.MakeArgString(Str: A->getSpelling() + A->getValue());
3217 if (A->getSpelling() != "-ffp-contract=") {
3218 if (RHS != "-ffp-model=strict")
3219 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3220 << "-ffp-model=strict" << RHS;
3221 }
3222 }
3223 }
3224
3225 // If we handled this option claim it
3226 A->claim();
3227 }
3228
3229 if (!HonorINFs)
3230 CmdArgs.push_back(Elt: "-menable-no-infs");
3231
3232 if (!HonorNaNs)
3233 CmdArgs.push_back(Elt: "-menable-no-nans");
3234
3235 if (ApproxFunc)
3236 CmdArgs.push_back(Elt: "-fapprox-func");
3237
3238 if (MathErrno) {
3239 CmdArgs.push_back(Elt: "-fmath-errno");
3240 if (NoMathErrnoWasImpliedByVecLib)
3241 D.Diag(DiagID: clang::diag::warn_drv_math_errno_enabled_after_veclib)
3242 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3243 << VecLibArg->getAsString(Args);
3244 }
3245
3246 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3247 !TrappingMath)
3248 CmdArgs.push_back(Elt: "-funsafe-math-optimizations");
3249
3250 if (!SignedZeros)
3251 CmdArgs.push_back(Elt: "-fno-signed-zeros");
3252
3253 if (AssociativeMath && !SignedZeros && !TrappingMath)
3254 CmdArgs.push_back(Elt: "-mreassociate");
3255
3256 if (ReciprocalMath)
3257 CmdArgs.push_back(Elt: "-freciprocal-math");
3258
3259 if (TrappingMath) {
3260 // FP Exception Behavior is also set to strict
3261 assert(FPExceptionBehavior == "strict");
3262 }
3263
3264 // The default is IEEE.
3265 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3266 llvm::SmallString<64> DenormFlag;
3267 llvm::raw_svector_ostream ArgStr(DenormFlag);
3268 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3269 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArgStr.str()));
3270 }
3271
3272 // Add f32 specific denormal mode flag if it's different.
3273 if (DenormalFP32Math != DenormalFPMath) {
3274 llvm::SmallString<64> DenormFlag;
3275 llvm::raw_svector_ostream ArgStr(DenormFlag);
3276 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3277 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArgStr.str()));
3278 }
3279
3280 if (!FPContract.empty())
3281 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-contract=" + FPContract));
3282
3283 if (RoundingFPMath)
3284 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-frounding-math"));
3285 else
3286 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fno-rounding-math"));
3287
3288 if (!FPExceptionBehavior.empty())
3289 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3290 FPExceptionBehavior));
3291
3292 if (!FPEvalMethod.empty())
3293 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-eval-method=" + FPEvalMethod));
3294
3295 if (!Float16ExcessPrecision.empty())
3296 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffloat16-excess-precision=" +
3297 Float16ExcessPrecision));
3298 if (!BFloat16ExcessPrecision.empty())
3299 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fbfloat16-excess-precision=" +
3300 BFloat16ExcessPrecision));
3301
3302 StringRef Recip = parseMRecipOption(Diags&: D.getDiags(), Args);
3303 if (!Recip.empty())
3304 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mrecip=" + Recip));
3305
3306 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3307 // individual features enabled by -ffast-math instead of the option itself as
3308 // that's consistent with gcc's behaviour.
3309 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3310 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3311 CmdArgs.push_back(Elt: "-ffast-math");
3312
3313 // Handle __FINITE_MATH_ONLY__ similarly.
3314 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3315 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3316 // -menable-no-nans are set by the user.
3317 bool shouldAddFiniteMathOnly = false;
3318 if (!HonorINFs && !HonorNaNs) {
3319 shouldAddFiniteMathOnly = true;
3320 } else {
3321 bool InfValues = true;
3322 bool NanValues = true;
3323 for (const auto *Arg : Args.filtered(Ids: options::OPT_Xclang)) {
3324 StringRef ArgValue = Arg->getValue();
3325 if (ArgValue == "-menable-no-nans")
3326 NanValues = false;
3327 else if (ArgValue == "-menable-no-infs")
3328 InfValues = false;
3329 }
3330 if (!NanValues && !InfValues)
3331 shouldAddFiniteMathOnly = true;
3332 }
3333 if (shouldAddFiniteMathOnly) {
3334 CmdArgs.push_back(Elt: "-ffinite-math-only");
3335 }
3336 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mfpmath_EQ)) {
3337 CmdArgs.push_back(Elt: "-mfpmath");
3338 CmdArgs.push_back(Elt: A->getValue());
3339 }
3340
3341 // Disable a codegen optimization for floating-point casts.
3342 if (Args.hasFlag(Pos: options::OPT_fno_strict_float_cast_overflow,
3343 Neg: options::OPT_fstrict_float_cast_overflow, Default: false))
3344 CmdArgs.push_back(Elt: "-fno-strict-float-cast-overflow");
3345
3346 if (Range != LangOptions::ComplexRangeKind::CX_None)
3347 ComplexRangeStr = renderComplexRangeOption(Range);
3348 if (!ComplexRangeStr.empty()) {
3349 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ComplexRangeStr));
3350 if (Args.hasArg(Ids: options::OPT_fcomplex_arithmetic_EQ))
3351 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fcomplex-arithmetic=" +
3352 complexRangeKindToStr(Range)));
3353 }
3354 if (Args.hasArg(Ids: options::OPT_fcx_limited_range))
3355 CmdArgs.push_back(Elt: "-fcx-limited-range");
3356 if (Args.hasArg(Ids: options::OPT_fcx_fortran_rules))
3357 CmdArgs.push_back(Elt: "-fcx-fortran-rules");
3358 if (Args.hasArg(Ids: options::OPT_fno_cx_limited_range))
3359 CmdArgs.push_back(Elt: "-fno-cx-limited-range");
3360 if (Args.hasArg(Ids: options::OPT_fno_cx_fortran_rules))
3361 CmdArgs.push_back(Elt: "-fno-cx-fortran-rules");
3362}
3363
3364static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3365 const llvm::Triple &Triple,
3366 const InputInfo &Input) {
3367 // Add default argument set.
3368 if (!Args.hasArg(Ids: options::OPT__analyzer_no_default_checks)) {
3369 CmdArgs.push_back(Elt: "-analyzer-checker=core");
3370 CmdArgs.push_back(Elt: "-analyzer-checker=apiModeling");
3371
3372 if (!Triple.isWindowsMSVCEnvironment()) {
3373 CmdArgs.push_back(Elt: "-analyzer-checker=unix");
3374 } else {
3375 // Enable "unix" checkers that also work on Windows.
3376 CmdArgs.push_back(Elt: "-analyzer-checker=unix.API");
3377 CmdArgs.push_back(Elt: "-analyzer-checker=unix.Malloc");
3378 CmdArgs.push_back(Elt: "-analyzer-checker=unix.MallocSizeof");
3379 CmdArgs.push_back(Elt: "-analyzer-checker=unix.MismatchedDeallocator");
3380 CmdArgs.push_back(Elt: "-analyzer-checker=unix.cstring.BadSizeArg");
3381 CmdArgs.push_back(Elt: "-analyzer-checker=unix.cstring.NullArg");
3382 }
3383
3384 // Disable some unix checkers for PS4/PS5.
3385 if (Triple.isPS()) {
3386 CmdArgs.push_back(Elt: "-analyzer-disable-checker=unix.API");
3387 CmdArgs.push_back(Elt: "-analyzer-disable-checker=unix.Vfork");
3388 }
3389
3390 if (Triple.isOSDarwin()) {
3391 CmdArgs.push_back(Elt: "-analyzer-checker=osx");
3392 CmdArgs.push_back(
3393 Elt: "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3394 }
3395 else if (Triple.isOSFuchsia())
3396 CmdArgs.push_back(Elt: "-analyzer-checker=fuchsia");
3397
3398 CmdArgs.push_back(Elt: "-analyzer-checker=deadcode");
3399
3400 if (types::isCXX(Id: Input.getType()))
3401 CmdArgs.push_back(Elt: "-analyzer-checker=cplusplus");
3402
3403 if (!Triple.isPS()) {
3404 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3405 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.getpw");
3406 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.gets");
3407 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.mktemp");
3408 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.mkstemp");
3409 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.vfork");
3410 }
3411
3412 // Default nullability checks.
3413 CmdArgs.push_back(Elt: "-analyzer-checker=nullability.NullPassedToNonnull");
3414 CmdArgs.push_back(Elt: "-analyzer-checker=nullability.NullReturnedFromNonnull");
3415 }
3416
3417 // Set the output format. The default is plist, for (lame) historical reasons.
3418 CmdArgs.push_back(Elt: "-analyzer-output");
3419 if (Arg *A = Args.getLastArg(Ids: options::OPT__analyzer_output))
3420 CmdArgs.push_back(Elt: A->getValue());
3421 else
3422 CmdArgs.push_back(Elt: "plist");
3423
3424 // Disable the presentation of standard compiler warnings when using
3425 // --analyze. We only want to show static analyzer diagnostics or frontend
3426 // errors.
3427 CmdArgs.push_back(Elt: "-w");
3428
3429 // Add -Xanalyzer arguments when running as analyzer.
3430 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Xanalyzer);
3431}
3432
3433static bool isValidSymbolName(StringRef S) {
3434 if (S.empty())
3435 return false;
3436
3437 if (std::isdigit(S[0]))
3438 return false;
3439
3440 return llvm::all_of(Range&: S, P: [](char C) { return std::isalnum(C) || C == '_'; });
3441}
3442
3443static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3444 const ArgList &Args, ArgStringList &CmdArgs,
3445 bool KernelOrKext) {
3446 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3447
3448 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3449 // doesn't even have a stack!
3450 if (EffectiveTriple.isNVPTX())
3451 return;
3452
3453 // -stack-protector=0 is default.
3454 LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3455 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3456 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3457
3458 if (Arg *A = Args.getLastArg(Ids: options::OPT_fno_stack_protector,
3459 Ids: options::OPT_fstack_protector_all,
3460 Ids: options::OPT_fstack_protector_strong,
3461 Ids: options::OPT_fstack_protector)) {
3462 if (A->getOption().matches(ID: options::OPT_fstack_protector))
3463 StackProtectorLevel =
3464 std::max<>(a: LangOptions::SSPOn, b: DefaultStackProtectorLevel);
3465 else if (A->getOption().matches(ID: options::OPT_fstack_protector_strong))
3466 StackProtectorLevel = LangOptions::SSPStrong;
3467 else if (A->getOption().matches(ID: options::OPT_fstack_protector_all))
3468 StackProtectorLevel = LangOptions::SSPReq;
3469
3470 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3471 D.Diag(DiagID: diag::warn_drv_unsupported_option_for_target)
3472 << A->getSpelling() << EffectiveTriple.getTriple();
3473 StackProtectorLevel = DefaultStackProtectorLevel;
3474 }
3475 } else {
3476 StackProtectorLevel = DefaultStackProtectorLevel;
3477 }
3478
3479 if (StackProtectorLevel) {
3480 CmdArgs.push_back(Elt: "-stack-protector");
3481 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(StackProtectorLevel)));
3482 }
3483
3484 // --param ssp-buffer-size=
3485 for (const Arg *A : Args.filtered(Ids: options::OPT__param)) {
3486 StringRef Str(A->getValue());
3487 if (Str.consume_front(Prefix: "ssp-buffer-size=")) {
3488 if (StackProtectorLevel) {
3489 CmdArgs.push_back(Elt: "-stack-protector-buffer-size");
3490 // FIXME: Verify the argument is a valid integer.
3491 CmdArgs.push_back(Elt: Args.MakeArgString(Str));
3492 }
3493 A->claim();
3494 }
3495 }
3496
3497 const std::string &TripleStr = EffectiveTriple.getTriple();
3498 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_EQ)) {
3499 StringRef Value = A->getValue();
3500 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3501 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3502 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3503 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3504 << A->getAsString(Args) << TripleStr;
3505 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3506 EffectiveTriple.isThumb()) &&
3507 Value != "tls" && Value != "global") {
3508 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3509 << A->getOption().getName() << Value << "tls global";
3510 return;
3511 }
3512 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3513 Value == "tls") {
3514 if (!Args.hasArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3515 D.Diag(DiagID: diag::err_drv_ssp_missing_offset_argument)
3516 << A->getAsString(Args);
3517 return;
3518 }
3519 // Check whether the target subarch supports the hardware TLS register
3520 if (!arm::isHardTPSupported(Triple: EffectiveTriple)) {
3521 D.Diag(DiagID: diag::err_target_unsupported_tp_hard)
3522 << EffectiveTriple.getArchName();
3523 return;
3524 }
3525 // Check whether the user asked for something other than -mtp=cp15
3526 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtp_mode_EQ)) {
3527 StringRef Value = A->getValue();
3528 if (Value != "cp15") {
3529 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
3530 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3531 return;
3532 }
3533 }
3534 CmdArgs.push_back(Elt: "-target-feature");
3535 CmdArgs.push_back(Elt: "+read-tp-tpidruro");
3536 }
3537 if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3538 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3539 << A->getOption().getName() << Value << "sysreg global";
3540 return;
3541 }
3542 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3543 if (Value != "tls" && Value != "global") {
3544 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3545 << A->getOption().getName() << Value << "tls global";
3546 return;
3547 }
3548 if (Value == "tls") {
3549 if (!Args.hasArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3550 D.Diag(DiagID: diag::err_drv_ssp_missing_offset_argument)
3551 << A->getAsString(Args);
3552 return;
3553 }
3554 }
3555 }
3556 A->render(Args, Output&: CmdArgs);
3557 }
3558
3559 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3560 StringRef Value = A->getValue();
3561 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3562 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3563 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3564 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3565 << A->getAsString(Args) << TripleStr;
3566 int Offset;
3567 if (Value.getAsInteger(Radix: 10, Result&: Offset)) {
3568 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3569 return;
3570 }
3571 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3572 (Offset < 0 || Offset > 0xfffff)) {
3573 D.Diag(DiagID: diag::err_drv_invalid_int_value)
3574 << A->getOption().getName() << Value;
3575 return;
3576 }
3577 A->render(Args, Output&: CmdArgs);
3578 }
3579
3580 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_reg_EQ)) {
3581 StringRef Value = A->getValue();
3582 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3583 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3584 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3585 << A->getAsString(Args) << TripleStr;
3586 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3587 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3588 << A->getOption().getName() << Value << "fs gs";
3589 return;
3590 }
3591 if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3592 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3593 return;
3594 }
3595 if (EffectiveTriple.isRISCV() && Value != "tp") {
3596 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3597 << A->getOption().getName() << Value << "tp";
3598 return;
3599 }
3600 if (EffectiveTriple.isPPC64() && Value != "r13") {
3601 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3602 << A->getOption().getName() << Value << "r13";
3603 return;
3604 }
3605 if (EffectiveTriple.isPPC32() && Value != "r2") {
3606 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3607 << A->getOption().getName() << Value << "r2";
3608 return;
3609 }
3610 A->render(Args, Output&: CmdArgs);
3611 }
3612
3613 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_symbol_EQ)) {
3614 StringRef Value = A->getValue();
3615 if (!isValidSymbolName(S: Value)) {
3616 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
3617 << A->getOption().getName() << "legal symbol name";
3618 return;
3619 }
3620 A->render(Args, Output&: CmdArgs);
3621 }
3622}
3623
3624static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3625 ArgStringList &CmdArgs) {
3626 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3627
3628 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3629 !EffectiveTriple.isOSFuchsia())
3630 return;
3631
3632 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3633 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3634 !EffectiveTriple.isRISCV())
3635 return;
3636
3637 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstack_clash_protection,
3638 Neg: options::OPT_fno_stack_clash_protection);
3639}
3640
3641static void RenderTrivialAutoVarInitOptions(const Driver &D,
3642 const ToolChain &TC,
3643 const ArgList &Args,
3644 ArgStringList &CmdArgs) {
3645 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3646 StringRef TrivialAutoVarInit = "";
3647
3648 for (const Arg *A : Args) {
3649 switch (A->getOption().getID()) {
3650 default:
3651 continue;
3652 case options::OPT_ftrivial_auto_var_init: {
3653 A->claim();
3654 StringRef Val = A->getValue();
3655 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3656 TrivialAutoVarInit = Val;
3657 else
3658 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3659 << A->getSpelling() << Val;
3660 break;
3661 }
3662 }
3663 }
3664
3665 if (TrivialAutoVarInit.empty())
3666 switch (DefaultTrivialAutoVarInit) {
3667 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3668 break;
3669 case LangOptions::TrivialAutoVarInitKind::Pattern:
3670 TrivialAutoVarInit = "pattern";
3671 break;
3672 case LangOptions::TrivialAutoVarInitKind::Zero:
3673 TrivialAutoVarInit = "zero";
3674 break;
3675 }
3676
3677 if (!TrivialAutoVarInit.empty()) {
3678 CmdArgs.push_back(
3679 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3680 }
3681
3682 if (Arg *A =
3683 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init_stop_after)) {
3684 if (!Args.hasArg(Ids: options::OPT_ftrivial_auto_var_init) ||
3685 StringRef(
3686 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init)->getValue()) ==
3687 "uninitialized")
3688 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3689 A->claim();
3690 StringRef Val = A->getValue();
3691 if (std::stoi(str: Val.str()) <= 0)
3692 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3693 CmdArgs.push_back(
3694 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init-stop-after=" + Val));
3695 }
3696
3697 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init_max_size)) {
3698 if (!Args.hasArg(Ids: options::OPT_ftrivial_auto_var_init) ||
3699 StringRef(
3700 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init)->getValue()) ==
3701 "uninitialized")
3702 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3703 A->claim();
3704 StringRef Val = A->getValue();
3705 if (std::stoi(str: Val.str()) <= 0)
3706 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3707 CmdArgs.push_back(
3708 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init-max-size=" + Val));
3709 }
3710}
3711
3712static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3713 types::ID InputType) {
3714 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3715 // for denormal flushing handling based on the target.
3716 const unsigned ForwardedArguments[] = {
3717 options::OPT_cl_opt_disable,
3718 options::OPT_cl_strict_aliasing,
3719 options::OPT_cl_single_precision_constant,
3720 options::OPT_cl_finite_math_only,
3721 options::OPT_cl_kernel_arg_info,
3722 options::OPT_cl_unsafe_math_optimizations,
3723 options::OPT_cl_fast_relaxed_math,
3724 options::OPT_cl_mad_enable,
3725 options::OPT_cl_no_signed_zeros,
3726 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3727 options::OPT_cl_uniform_work_group_size
3728 };
3729
3730 if (Arg *A = Args.getLastArg(Ids: options::OPT_cl_std_EQ)) {
3731 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3732 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CLStdStr));
3733 } else if (Arg *A = Args.getLastArg(Ids: options::OPT_cl_ext_EQ)) {
3734 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3735 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CLExtStr));
3736 }
3737
3738 if (Args.hasArg(Ids: options::OPT_cl_finite_math_only)) {
3739 CmdArgs.push_back(Elt: "-menable-no-infs");
3740 CmdArgs.push_back(Elt: "-menable-no-nans");
3741 }
3742
3743 for (const auto &Arg : ForwardedArguments)
3744 if (const auto *A = Args.getLastArg(Ids: Arg))
3745 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getOption().getPrefixedName()));
3746
3747 // Only add the default headers if we are compiling OpenCL sources.
3748 if ((types::isOpenCL(Id: InputType) ||
3749 (Args.hasArg(Ids: options::OPT_cl_std_EQ) && types::isSrcFile(Id: InputType))) &&
3750 !Args.hasArg(Ids: options::OPT_cl_no_stdinc)) {
3751 CmdArgs.push_back(Elt: "-finclude-default-header");
3752 CmdArgs.push_back(Elt: "-fdeclare-opencl-builtins");
3753 }
3754}
3755
3756static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3757 types::ID InputType) {
3758 const unsigned ForwardedArguments[] = {
3759 options::OPT_hlsl_all_resources_bound,
3760 options::OPT_dxil_validator_version,
3761 options::OPT_res_may_alias,
3762 options::OPT_D,
3763 options::OPT_I,
3764 options::OPT_O,
3765 options::OPT_emit_llvm,
3766 options::OPT_emit_obj,
3767 options::OPT_disable_llvm_passes,
3768 options::OPT_fnative_half_type,
3769 options::OPT_fnative_int16_type,
3770 options::OPT_fmatrix_memory_layout_EQ,
3771 options::OPT_hlsl_entrypoint,
3772 options::OPT_fdx_rootsignature_define,
3773 options::OPT_fdx_rootsignature_version,
3774 options::OPT_fhlsl_spv_use_unknown_image_format,
3775 options::OPT_fhlsl_spv_enable_maximal_reconvergence};
3776 if (!types::isHLSL(Id: InputType))
3777 return;
3778 for (const auto &Arg : ForwardedArguments)
3779 if (const auto *A = Args.getLastArg(Ids: Arg))
3780 A->renderAsInput(Args, Output&: CmdArgs);
3781 // Add the default headers if dxc_no_stdinc is not set.
3782 if (!Args.hasArg(Ids: options::OPT_dxc_no_stdinc) &&
3783 !Args.hasArg(Ids: options::OPT_nostdinc))
3784 CmdArgs.push_back(Elt: "-finclude-default-header");
3785}
3786
3787static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
3788 ArgStringList &CmdArgs, types::ID InputType) {
3789 if (!Args.hasArg(Ids: options::OPT_fopenacc))
3790 return;
3791
3792 CmdArgs.push_back(Elt: "-fopenacc");
3793}
3794
3795static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3796 const ArgList &Args, ArgStringList &CmdArgs) {
3797 // -fbuiltin is default unless -mkernel is used.
3798 bool UseBuiltins =
3799 Args.hasFlag(Pos: options::OPT_fbuiltin, Neg: options::OPT_fno_builtin,
3800 Default: !Args.hasArg(Ids: options::OPT_mkernel));
3801 if (!UseBuiltins)
3802 CmdArgs.push_back(Elt: "-fno-builtin");
3803
3804 // -ffreestanding implies -fno-builtin.
3805 if (Args.hasArg(Ids: options::OPT_ffreestanding))
3806 UseBuiltins = false;
3807
3808 // Process the -fno-builtin-* options.
3809 for (const Arg *A : Args.filtered(Ids: options::OPT_fno_builtin_)) {
3810 A->claim();
3811
3812 // If -fno-builtin is specified, then there's no need to pass the option to
3813 // the frontend.
3814 if (UseBuiltins)
3815 A->render(Args, Output&: CmdArgs);
3816 }
3817}
3818
3819bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
3820 if (const char *Str = std::getenv(name: "CLANG_MODULE_CACHE_PATH")) {
3821 Twine Path{Str};
3822 Path.toVector(Out&: Result);
3823 return Path.getSingleStringRef() != "";
3824 }
3825 if (llvm::sys::path::cache_directory(result&: Result)) {
3826 llvm::sys::path::append(path&: Result, a: "clang");
3827 llvm::sys::path::append(path&: Result, a: "ModuleCache");
3828 return true;
3829 }
3830 return false;
3831}
3832
3833llvm::SmallString<256>
3834clang::driver::tools::getCXX20NamedModuleOutputPath(const ArgList &Args,
3835 const char *BaseInput) {
3836 if (Arg *ModuleOutputEQ = Args.getLastArg(Ids: options::OPT_fmodule_output_EQ))
3837 return StringRef(ModuleOutputEQ->getValue());
3838
3839 SmallString<256> OutputPath;
3840 if (Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o);
3841 FinalOutput && Args.hasArg(Ids: options::OPT_c))
3842 OutputPath = FinalOutput->getValue();
3843 else {
3844 llvm::sys::fs::current_path(result&: OutputPath);
3845 llvm::sys::path::append(path&: OutputPath, a: llvm::sys::path::filename(path: BaseInput));
3846 }
3847
3848 const char *Extension = types::getTypeTempSuffix(Id: types::TY_ModuleFile);
3849 llvm::sys::path::replace_extension(path&: OutputPath, extension: Extension);
3850 return OutputPath;
3851}
3852
3853static bool RenderModulesOptions(Compilation &C, const Driver &D,
3854 const ArgList &Args, const InputInfo &Input,
3855 const InputInfo &Output, bool HaveStd20,
3856 ArgStringList &CmdArgs) {
3857 const bool IsCXX = types::isCXX(Id: Input.getType());
3858 const bool HaveStdCXXModules = IsCXX && HaveStd20;
3859 bool HaveModules = HaveStdCXXModules;
3860
3861 // -fmodules enables the use of precompiled modules (off by default).
3862 // Users can pass -fno-cxx-modules to turn off modules support for
3863 // C++/Objective-C++ programs.
3864 const bool AllowedInCXX = Args.hasFlag(Pos: options::OPT_fcxx_modules,
3865 Neg: options::OPT_fno_cxx_modules, Default: true);
3866 bool HaveClangModules = false;
3867 if (Args.hasFlag(Pos: options::OPT_fmodules, Neg: options::OPT_fno_modules, Default: false)) {
3868 if (AllowedInCXX || !IsCXX) {
3869 CmdArgs.push_back(Elt: "-fmodules");
3870 HaveClangModules = true;
3871 }
3872 }
3873
3874 HaveModules |= HaveClangModules;
3875
3876 if (HaveModules && !AllowedInCXX)
3877 CmdArgs.push_back(Elt: "-fno-cxx-modules");
3878
3879 // -fmodule-maps enables implicit reading of module map files. By default,
3880 // this is enabled if we are using Clang's flavor of precompiled modules.
3881 if (Args.hasFlag(Pos: options::OPT_fimplicit_module_maps,
3882 Neg: options::OPT_fno_implicit_module_maps, Default: HaveClangModules))
3883 CmdArgs.push_back(Elt: "-fimplicit-module-maps");
3884
3885 // -fmodules-decluse checks that modules used are declared so (off by default)
3886 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fmodules_decluse,
3887 Neg: options::OPT_fno_modules_decluse);
3888
3889 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3890 // all #included headers are part of modules.
3891 if (Args.hasFlag(Pos: options::OPT_fmodules_strict_decluse,
3892 Neg: options::OPT_fno_modules_strict_decluse, Default: false))
3893 CmdArgs.push_back(Elt: "-fmodules-strict-decluse");
3894
3895 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fmodulemap_allow_subdirectory_search,
3896 Neg: options::OPT_fno_modulemap_allow_subdirectory_search);
3897
3898 // -fno-implicit-modules turns off implicitly compiling modules on demand.
3899 bool ImplicitModules = false;
3900 if (!Args.hasFlag(Pos: options::OPT_fimplicit_modules,
3901 Neg: options::OPT_fno_implicit_modules, Default: HaveClangModules)) {
3902 if (HaveModules)
3903 CmdArgs.push_back(Elt: "-fno-implicit-modules");
3904 } else if (HaveModules) {
3905 ImplicitModules = true;
3906 // -fmodule-cache-path specifies where our implicitly-built module files
3907 // should be written.
3908 SmallString<128> Path;
3909 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmodules_cache_path))
3910 Path = A->getValue();
3911
3912 bool HasPath = true;
3913 if (C.isForDiagnostics()) {
3914 // When generating crash reports, we want to emit the modules along with
3915 // the reproduction sources, so we ignore any provided module path.
3916 Path = Output.getFilename();
3917 llvm::sys::path::replace_extension(path&: Path, extension: ".cache");
3918 llvm::sys::path::append(path&: Path, a: "modules");
3919 } else if (Path.empty()) {
3920 // No module path was provided: use the default.
3921 HasPath = Driver::getDefaultModuleCachePath(Result&: Path);
3922 }
3923
3924 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3925 // That being said, that failure is unlikely and not caching is harmless.
3926 if (HasPath) {
3927 const char Arg[] = "-fmodules-cache-path=";
3928 Path.insert(I: Path.begin(), From: Arg, To: Arg + strlen(s: Arg));
3929 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Path));
3930 }
3931
3932 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fimplicit_modules_lock_timeout_EQ);
3933 }
3934
3935 if (HaveModules) {
3936 if (Args.hasFlag(Pos: options::OPT_fprebuilt_implicit_modules,
3937 Neg: options::OPT_fno_prebuilt_implicit_modules, Default: false))
3938 CmdArgs.push_back(Elt: "-fprebuilt-implicit-modules");
3939 if (Args.hasFlag(Pos: options::OPT_fmodules_validate_input_files_content,
3940 Neg: options::OPT_fno_modules_validate_input_files_content,
3941 Default: false))
3942 CmdArgs.push_back(Elt: "-fvalidate-ast-input-files-content");
3943 }
3944
3945 // -fmodule-name specifies the module that is currently being built (or
3946 // used for header checking by -fmodule-maps).
3947 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodule_name_EQ);
3948
3949 // -fmodule-map-file can be used to specify files containing module
3950 // definitions.
3951 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodule_map_file);
3952
3953 // -fbuiltin-module-map can be used to load the clang
3954 // builtin headers modulemap file.
3955 if (Args.hasArg(Ids: options::OPT_fbuiltin_module_map)) {
3956 SmallString<128> BuiltinModuleMap(D.ResourceDir);
3957 llvm::sys::path::append(path&: BuiltinModuleMap, a: "include");
3958 llvm::sys::path::append(path&: BuiltinModuleMap, a: "module.modulemap");
3959 if (llvm::sys::fs::exists(Path: BuiltinModuleMap))
3960 CmdArgs.push_back(
3961 Elt: Args.MakeArgString(Str: "-fmodule-map-file=" + BuiltinModuleMap));
3962 }
3963
3964 // The -fmodule-file=<name>=<file> form specifies the mapping of module
3965 // names to precompiled module files (the module is loaded only if used).
3966 // The -fmodule-file=<file> form can be used to unconditionally load
3967 // precompiled module files (whether used or not).
3968 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
3969 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodule_file);
3970
3971 // -fprebuilt-module-path specifies where to load the prebuilt module files.
3972 for (const Arg *A : Args.filtered(Ids: options::OPT_fprebuilt_module_path)) {
3973 CmdArgs.push_back(Elt: Args.MakeArgString(
3974 Str: std::string("-fprebuilt-module-path=") + A->getValue()));
3975 A->claim();
3976 }
3977 } else
3978 Args.ClaimAllArgs(Id0: options::OPT_fmodule_file);
3979
3980 // When building modules and generating crashdumps, we need to dump a module
3981 // dependency VFS alongside the output.
3982 if (HaveClangModules && C.isForDiagnostics()) {
3983 SmallString<128> VFSDir(Output.getFilename());
3984 llvm::sys::path::replace_extension(path&: VFSDir, extension: ".cache");
3985 // Add the cache directory as a temp so the crash diagnostics pick it up.
3986 C.addTempFile(Name: Args.MakeArgString(Str: VFSDir));
3987
3988 llvm::sys::path::append(path&: VFSDir, a: "vfs");
3989 CmdArgs.push_back(Elt: "-module-dependency-dir");
3990 CmdArgs.push_back(Elt: Args.MakeArgString(Str: VFSDir));
3991 }
3992
3993 if (HaveClangModules)
3994 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_user_build_path);
3995
3996 // Pass through all -fmodules-ignore-macro arguments.
3997 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodules_ignore_macro);
3998 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_prune_interval);
3999 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_prune_after);
4000
4001 if (HaveClangModules) {
4002 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fbuild_session_timestamp);
4003
4004 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbuild_session_file)) {
4005 if (Args.hasArg(Ids: options::OPT_fbuild_session_timestamp))
4006 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
4007 << A->getAsString(Args) << "-fbuild-session-timestamp";
4008
4009 llvm::sys::fs::file_status Status;
4010 if (llvm::sys::fs::status(path: A->getValue(), result&: Status))
4011 D.Diag(DiagID: diag::err_drv_no_such_file) << A->getValue();
4012 CmdArgs.push_back(Elt: Args.MakeArgString(
4013 Str: "-fbuild-session-timestamp=" +
4014 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
4015 d: Status.getLastModificationTime().time_since_epoch())
4016 .count())));
4017 }
4018
4019 if (Args.getLastArg(
4020 Ids: options::OPT_fmodules_validate_once_per_build_session)) {
4021 if (!Args.getLastArg(Ids: options::OPT_fbuild_session_timestamp,
4022 Ids: options::OPT_fbuild_session_file))
4023 D.Diag(DiagID: diag::err_drv_modules_validate_once_requires_timestamp);
4024
4025 Args.AddLastArg(Output&: CmdArgs,
4026 Ids: options::OPT_fmodules_validate_once_per_build_session);
4027 }
4028
4029 if (Args.hasFlag(Pos: options::OPT_fmodules_validate_system_headers,
4030 Neg: options::OPT_fno_modules_validate_system_headers,
4031 Default: ImplicitModules))
4032 CmdArgs.push_back(Elt: "-fmodules-validate-system-headers");
4033
4034 Args.AddLastArg(Output&: CmdArgs,
4035 Ids: options::OPT_fmodules_disable_diagnostic_validation);
4036 } else {
4037 Args.ClaimAllArgs(Id0: options::OPT_fbuild_session_timestamp);
4038 Args.ClaimAllArgs(Id0: options::OPT_fbuild_session_file);
4039 Args.ClaimAllArgs(Id0: options::OPT_fmodules_validate_once_per_build_session);
4040 Args.ClaimAllArgs(Id0: options::OPT_fmodules_validate_system_headers);
4041 Args.ClaimAllArgs(Id0: options::OPT_fno_modules_validate_system_headers);
4042 Args.ClaimAllArgs(Id0: options::OPT_fmodules_disable_diagnostic_validation);
4043 }
4044
4045 // FIXME: We provisionally don't check ODR violations for decls in the global
4046 // module fragment.
4047 CmdArgs.push_back(Elt: "-fskip-odr-check-in-gmf");
4048
4049 if (Input.getType() == driver::types::TY_CXXModule ||
4050 Input.getType() == driver::types::TY_PP_CXXModule) {
4051 if (!Args.hasArg(Ids: options::OPT_fno_modules_reduced_bmi))
4052 CmdArgs.push_back(Elt: "-fmodules-reduced-bmi");
4053
4054 if (Args.hasArg(Ids: options::OPT_fmodule_output_EQ))
4055 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodule_output_EQ);
4056 else if (!(Args.hasArg(Ids: options::OPT__precompile) ||
4057 Args.hasArg(Ids: options::OPT__precompile_reduced_bmi)) ||
4058 Args.hasArg(Ids: options::OPT_fmodule_output))
4059 // If --precompile is specified, we will always generate a module file if
4060 // we're compiling an importable module unit. This is fine even if the
4061 // compilation process won't reach the point of generating the module file
4062 // (e.g., in the preprocessing mode), since the attached flag
4063 // '-fmodule-output' is useless.
4064 //
4065 // But if '--precompile' is specified, it might be annoying to always
4066 // generate the module file as '--precompile' will generate the module
4067 // file anyway.
4068 CmdArgs.push_back(Elt: Args.MakeArgString(
4069 Str: "-fmodule-output=" +
4070 getCXX20NamedModuleOutputPath(Args, BaseInput: Input.getBaseInput())));
4071 }
4072
4073 if (Args.hasArg(Ids: options::OPT_fmodules_reduced_bmi) &&
4074 Args.hasArg(Ids: options::OPT__precompile) &&
4075 (!Args.hasArg(Ids: options::OPT_o) ||
4076 Args.getLastArg(Ids: options::OPT_o)->getValue() ==
4077 getCXX20NamedModuleOutputPath(Args, BaseInput: Input.getBaseInput()))) {
4078 D.Diag(DiagID: diag::err_drv_reduced_module_output_overrided);
4079 }
4080
4081 // Noop if we see '-fmodules-reduced-bmi' or `-fno-modules-reduced-bmi` with
4082 // other translation units than module units. This is more user friendly to
4083 // allow end uers to enable this feature without asking for help from build
4084 // systems.
4085 Args.ClaimAllArgs(Id0: options::OPT_fmodules_reduced_bmi);
4086 Args.ClaimAllArgs(Id0: options::OPT_fno_modules_reduced_bmi);
4087
4088 // We need to include the case the input file is a module file here.
4089 // Since the default compilation model for C++ module interface unit will
4090 // create temporary module file and compile the temporary module file
4091 // to get the object file. Then the `-fmodule-output` flag will be
4092 // brought to the second compilation process. So we have to claim it for
4093 // the case too.
4094 if (Input.getType() == driver::types::TY_CXXModule ||
4095 Input.getType() == driver::types::TY_PP_CXXModule ||
4096 Input.getType() == driver::types::TY_ModuleFile) {
4097 Args.ClaimAllArgs(Id0: options::OPT_fmodule_output);
4098 Args.ClaimAllArgs(Id0: options::OPT_fmodule_output_EQ);
4099 }
4100
4101 if (Args.hasArg(Ids: options::OPT_fmodules_embed_all_files))
4102 CmdArgs.push_back(Elt: "-fmodules-embed-all-files");
4103
4104 return HaveModules;
4105}
4106
4107static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4108 ArgStringList &CmdArgs) {
4109 // -fsigned-char is default.
4110 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsigned_char,
4111 Ids: options::OPT_fno_signed_char,
4112 Ids: options::OPT_funsigned_char,
4113 Ids: options::OPT_fno_unsigned_char)) {
4114 if (A->getOption().matches(ID: options::OPT_funsigned_char) ||
4115 A->getOption().matches(ID: options::OPT_fno_signed_char)) {
4116 CmdArgs.push_back(Elt: "-fno-signed-char");
4117 }
4118 } else if (!isSignedCharDefault(Triple: T)) {
4119 CmdArgs.push_back(Elt: "-fno-signed-char");
4120 }
4121
4122 // The default depends on the language standard.
4123 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fchar8__t, Ids: options::OPT_fno_char8__t);
4124
4125 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fshort_wchar,
4126 Ids: options::OPT_fno_short_wchar)) {
4127 if (A->getOption().matches(ID: options::OPT_fshort_wchar)) {
4128 CmdArgs.push_back(Elt: "-fwchar-type=short");
4129 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4130 } else {
4131 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4132 CmdArgs.push_back(Elt: "-fwchar-type=int");
4133 if (T.isOSzOS() ||
4134 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4135 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4136 else
4137 CmdArgs.push_back(Elt: "-fsigned-wchar");
4138 }
4139 } else if (T.isOSzOS())
4140 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4141}
4142
4143static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4144 const llvm::Triple &T, const ArgList &Args,
4145 ObjCRuntime &Runtime, bool InferCovariantReturns,
4146 const InputInfo &Input, ArgStringList &CmdArgs) {
4147 const llvm::Triple::ArchType Arch = TC.getArch();
4148
4149 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4150 // is the default. Except for deployment target of 10.5, next runtime is
4151 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4152 if (Runtime.isNonFragile()) {
4153 if (!Args.hasFlag(Pos: options::OPT_fobjc_legacy_dispatch,
4154 Neg: options::OPT_fno_objc_legacy_dispatch,
4155 Default: Runtime.isLegacyDispatchDefaultForArch(Arch))) {
4156 if (TC.UseObjCMixedDispatch())
4157 CmdArgs.push_back(Elt: "-fobjc-dispatch-method=mixed");
4158 else
4159 CmdArgs.push_back(Elt: "-fobjc-dispatch-method=non-legacy");
4160 }
4161 }
4162
4163 // Forward -fobjc-direct-precondition-thunk to cc1
4164 // Defaults to false and needs explict turn on for now
4165 // TODO: switch to default true and needs explict turn off in the future.
4166 // TODO: add support for other runtimes
4167 if (Args.hasFlag(Pos: options::OPT_fobjc_direct_precondition_thunk,
4168 Neg: options::OPT_fno_objc_direct_precondition_thunk, Default: false)) {
4169 if (Runtime.isNeXTFamily()) {
4170 CmdArgs.push_back(Elt: "-fobjc-direct-precondition-thunk");
4171 } else {
4172 D.Diag(DiagID: diag::warn_drv_unsupported_option_for_runtime)
4173 << "-fobjc-direct-precondition-thunk" << Runtime.getAsString();
4174 }
4175 }
4176
4177 if (types::isObjC(Id: Input.getType())) {
4178 // Pass down -fobjc-msgsend-selector-stubs if present.
4179 if (Args.hasFlag(Pos: options::OPT_fobjc_msgsend_selector_stubs,
4180 Neg: options::OPT_fno_objc_msgsend_selector_stubs, Default: false))
4181 CmdArgs.push_back(Elt: "-fobjc-msgsend-selector-stubs");
4182
4183 // Pass down -fobjc-msgsend-class-selector-stubs if present.
4184 if (Args.hasFlag(Pos: options::OPT_fobjc_msgsend_class_selector_stubs,
4185 Neg: options::OPT_fno_objc_msgsend_class_selector_stubs, Default: false))
4186 CmdArgs.push_back(Elt: "-fobjc-msgsend-class-selector-stubs");
4187 }
4188
4189 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4190 // to do Array/Dictionary subscripting by default.
4191 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4192 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4193 CmdArgs.push_back(Elt: "-fobjc-subscripting-legacy-runtime");
4194
4195 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4196 // NOTE: This logic is duplicated in ToolChains.cpp.
4197 if (isObjCAutoRefCount(Args)) {
4198 TC.CheckObjCARC();
4199
4200 CmdArgs.push_back(Elt: "-fobjc-arc");
4201
4202 // FIXME: It seems like this entire block, and several around it should be
4203 // wrapped in isObjC, but for now we just use it here as this is where it
4204 // was being used previously.
4205 if (types::isCXX(Id: Input.getType()) && types::isObjC(Id: Input.getType())) {
4206 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4207 CmdArgs.push_back(Elt: "-fobjc-arc-cxxlib=libc++");
4208 else
4209 CmdArgs.push_back(Elt: "-fobjc-arc-cxxlib=libstdc++");
4210 }
4211
4212 // Allow the user to enable full exceptions code emission.
4213 // We default off for Objective-C, on for Objective-C++.
4214 if (Args.hasFlag(Pos: options::OPT_fobjc_arc_exceptions,
4215 Neg: options::OPT_fno_objc_arc_exceptions,
4216 /*Default=*/types::isCXX(Id: Input.getType())))
4217 CmdArgs.push_back(Elt: "-fobjc-arc-exceptions");
4218 }
4219
4220 // Silence warning for full exception code emission options when explicitly
4221 // set to use no ARC.
4222 if (Args.hasArg(Ids: options::OPT_fno_objc_arc)) {
4223 Args.ClaimAllArgs(Id0: options::OPT_fobjc_arc_exceptions);
4224 Args.ClaimAllArgs(Id0: options::OPT_fno_objc_arc_exceptions);
4225 }
4226
4227 // Allow the user to control whether messages can be converted to runtime
4228 // functions.
4229 if (types::isObjC(Id: Input.getType())) {
4230 auto *Arg = Args.getLastArg(
4231 Ids: options::OPT_fobjc_convert_messages_to_runtime_calls,
4232 Ids: options::OPT_fno_objc_convert_messages_to_runtime_calls);
4233 if (Arg &&
4234 Arg->getOption().matches(
4235 ID: options::OPT_fno_objc_convert_messages_to_runtime_calls))
4236 CmdArgs.push_back(Elt: "-fno-objc-convert-messages-to-runtime-calls");
4237 }
4238
4239 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4240 // rewriter.
4241 if (InferCovariantReturns)
4242 CmdArgs.push_back(Elt: "-fno-objc-infer-related-result-type");
4243
4244 // Pass down -fobjc-weak or -fno-objc-weak if present.
4245 if (types::isObjC(Id: Input.getType())) {
4246 auto WeakArg =
4247 Args.getLastArg(Ids: options::OPT_fobjc_weak, Ids: options::OPT_fno_objc_weak);
4248 if (!WeakArg) {
4249 // nothing to do
4250 } else if (!Runtime.allowsWeak()) {
4251 if (WeakArg->getOption().matches(ID: options::OPT_fobjc_weak))
4252 D.Diag(DiagID: diag::err_objc_weak_unsupported);
4253 } else {
4254 WeakArg->render(Args, Output&: CmdArgs);
4255 }
4256 }
4257
4258 if (Args.hasArg(Ids: options::OPT_fobjc_disable_direct_methods_for_testing))
4259 CmdArgs.push_back(Elt: "-fobjc-disable-direct-methods-for-testing");
4260}
4261
4262static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4263 ArgStringList &CmdArgs) {
4264 bool CaretDefault = true;
4265 bool ColumnDefault = true;
4266
4267 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_diagnostics_classic,
4268 Ids: options::OPT__SLASH_diagnostics_column,
4269 Ids: options::OPT__SLASH_diagnostics_caret)) {
4270 switch (A->getOption().getID()) {
4271 case options::OPT__SLASH_diagnostics_caret:
4272 CaretDefault = true;
4273 ColumnDefault = true;
4274 break;
4275 case options::OPT__SLASH_diagnostics_column:
4276 CaretDefault = false;
4277 ColumnDefault = true;
4278 break;
4279 case options::OPT__SLASH_diagnostics_classic:
4280 CaretDefault = false;
4281 ColumnDefault = false;
4282 break;
4283 }
4284 }
4285
4286 // -fcaret-diagnostics is default.
4287 if (!Args.hasFlag(Pos: options::OPT_fcaret_diagnostics,
4288 Neg: options::OPT_fno_caret_diagnostics, Default: CaretDefault))
4289 CmdArgs.push_back(Elt: "-fno-caret-diagnostics");
4290
4291 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_fixit_info,
4292 Neg: options::OPT_fno_diagnostics_fixit_info);
4293 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_option,
4294 Neg: options::OPT_fno_diagnostics_show_option);
4295
4296 if (const Arg *A =
4297 Args.getLastArg(Ids: options::OPT_fdiagnostics_show_category_EQ)) {
4298 CmdArgs.push_back(Elt: "-fdiagnostics-show-category");
4299 CmdArgs.push_back(Elt: A->getValue());
4300 }
4301
4302 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_hotness,
4303 Neg: options::OPT_fno_diagnostics_show_hotness);
4304
4305 if (const Arg *A =
4306 Args.getLastArg(Ids: options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4307 std::string Opt =
4308 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4309 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
4310 }
4311
4312 if (const Arg *A =
4313 Args.getLastArg(Ids: options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4314 std::string Opt =
4315 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4316 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
4317 }
4318
4319 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fdiagnostics_format_EQ)) {
4320 CmdArgs.push_back(Elt: "-fdiagnostics-format");
4321 CmdArgs.push_back(Elt: A->getValue());
4322 if (StringRef(A->getValue()) == "sarif" ||
4323 StringRef(A->getValue()) == "SARIF")
4324 D.Diag(DiagID: diag::warn_drv_sarif_format_unstable);
4325 }
4326
4327 if (const Arg *A = Args.getLastArg(
4328 Ids: options::OPT_fdiagnostics_show_note_include_stack,
4329 Ids: options::OPT_fno_diagnostics_show_note_include_stack)) {
4330 const Option &O = A->getOption();
4331 if (O.matches(ID: options::OPT_fdiagnostics_show_note_include_stack))
4332 CmdArgs.push_back(Elt: "-fdiagnostics-show-note-include-stack");
4333 else
4334 CmdArgs.push_back(Elt: "-fno-diagnostics-show-note-include-stack");
4335 }
4336
4337 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4338
4339 if (Args.hasArg(Ids: options::OPT_fansi_escape_codes))
4340 CmdArgs.push_back(Elt: "-fansi-escape-codes");
4341
4342 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fshow_source_location,
4343 Neg: options::OPT_fno_show_source_location);
4344
4345 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_line_numbers,
4346 Neg: options::OPT_fno_diagnostics_show_line_numbers);
4347
4348 if (Args.hasArg(Ids: options::OPT_fdiagnostics_absolute_paths))
4349 CmdArgs.push_back(Elt: "-fdiagnostics-absolute-paths");
4350
4351 if (!Args.hasFlag(Pos: options::OPT_fshow_column, Neg: options::OPT_fno_show_column,
4352 Default: ColumnDefault))
4353 CmdArgs.push_back(Elt: "-fno-show-column");
4354
4355 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fspell_checking,
4356 Neg: options::OPT_fno_spell_checking);
4357
4358 Args.addLastArg(Output&: CmdArgs, Ids: options::OPT_warning_suppression_mappings_EQ);
4359}
4360
4361static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4362 const ArgList &Args, ArgStringList &CmdArgs,
4363 unsigned DwarfVersion) {
4364 auto *DwarfFormatArg =
4365 Args.getLastArg(Ids: options::OPT_gdwarf64, Ids: options::OPT_gdwarf32);
4366 if (!DwarfFormatArg)
4367 return;
4368
4369 if (DwarfFormatArg->getOption().matches(ID: options::OPT_gdwarf64)) {
4370 if (DwarfVersion < 3)
4371 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4372 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4373 else if (!T.isArch64Bit())
4374 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4375 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4376 else if (!T.isOSBinFormatELF())
4377 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4378 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4379 }
4380
4381 DwarfFormatArg->render(Args, Output&: CmdArgs);
4382}
4383
4384static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D,
4385 const ArgList &Args) {
4386 bool NeedsSimpleTemplateNames =
4387 Args.hasFlag(Pos: options::OPT_gsimple_template_names,
4388 Neg: options::OPT_gno_simple_template_names,
4389 Default: TC.getDefaultDebugSimpleTemplateNames());
4390 if (!NeedsSimpleTemplateNames)
4391 return false;
4392
4393 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gsimple_template_names))
4394 if (!checkDebugInfoOption(A, Args, D, TC))
4395 return false;
4396
4397 return true;
4398}
4399
4400static void
4401renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4402 const ArgList &Args, types::ID InputType,
4403 ArgStringList &CmdArgs, const InputInfo &Output,
4404 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4405 DwarfFissionKind &DwarfFission) {
4406 bool IRInput = isLLVMIR(Id: InputType);
4407 bool PlainCOrCXX = isDerivedFromC(Id: InputType) && !isCuda(Id: InputType) &&
4408 !isHIP(Id: InputType) && !isObjC(Id: InputType) &&
4409 !isOpenCL(Id: InputType);
4410
4411 if (Args.hasFlag(Pos: options::OPT_fdebug_info_for_profiling,
4412 Neg: options::OPT_fno_debug_info_for_profiling, Default: false) &&
4413 checkDebugInfoOption(
4414 A: Args.getLastArg(Ids: options::OPT_fdebug_info_for_profiling), Args, D, TC))
4415 CmdArgs.push_back(Elt: "-fdebug-info-for-profiling");
4416
4417 // The 'g' groups options involve a somewhat intricate sequence of decisions
4418 // about what to pass from the driver to the frontend, but by the time they
4419 // reach cc1 they've been factored into three well-defined orthogonal choices:
4420 // * what level of debug info to generate
4421 // * what dwarf version to write
4422 // * what debugger tuning to use
4423 // This avoids having to monkey around further in cc1 other than to disable
4424 // codeview if not running in a Windows environment. Perhaps even that
4425 // decision should be made in the driver as well though.
4426 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4427
4428 bool SplitDWARFInlining =
4429 Args.hasFlag(Pos: options::OPT_fsplit_dwarf_inlining,
4430 Neg: options::OPT_fno_split_dwarf_inlining, Default: false);
4431
4432 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4433 // object file generation and no IR generation, -gN should not be needed. So
4434 // allow -gsplit-dwarf with either -gN or IR input.
4435 if (IRInput || Args.hasArg(Ids: options::OPT_g_Group)) {
4436 // FIXME: -gsplit-dwarf on AIX is currently unimplemented.
4437 if (TC.getTriple().isOSAIX() && Args.hasArg(Ids: options::OPT_gsplit_dwarf)) {
4438 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
4439 << Args.getLastArg(Ids: options::OPT_gsplit_dwarf)->getSpelling()
4440 << TC.getTriple().str();
4441 return;
4442 }
4443 Arg *SplitDWARFArg;
4444 DwarfFission = getDebugFissionKind(D, Args, Arg&: SplitDWARFArg);
4445 if (DwarfFission != DwarfFissionKind::None &&
4446 !checkDebugInfoOption(A: SplitDWARFArg, Args, D, TC)) {
4447 DwarfFission = DwarfFissionKind::None;
4448 SplitDWARFInlining = false;
4449 }
4450 }
4451 if (const Arg *A = Args.getLastArg(Ids: options::OPT_g_Group)) {
4452 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4453
4454 // If the last option explicitly specified a debug-info level, use it.
4455 if (checkDebugInfoOption(A, Args, D, TC) &&
4456 A->getOption().matches(ID: options::OPT_gN_Group)) {
4457 DebugInfoKind = debugLevelToInfoKind(A: *A);
4458 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4459 // complicated if you've disabled inline info in the skeleton CUs
4460 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4461 // line-tables-only, so let those compose naturally in that case.
4462 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4463 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4464 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4465 SplitDWARFInlining))
4466 DwarfFission = DwarfFissionKind::None;
4467 }
4468 }
4469
4470 // If a debugger tuning argument appeared, remember it.
4471 bool HasDebuggerTuning = false;
4472 if (const Arg *A =
4473 Args.getLastArg(Ids: options::OPT_gTune_Group, Ids: options::OPT_ggdbN_Group)) {
4474 HasDebuggerTuning = true;
4475 if (checkDebugInfoOption(A, Args, D, TC)) {
4476 if (A->getOption().matches(ID: options::OPT_glldb))
4477 DebuggerTuning = llvm::DebuggerKind::LLDB;
4478 else if (A->getOption().matches(ID: options::OPT_gsce))
4479 DebuggerTuning = llvm::DebuggerKind::SCE;
4480 else if (A->getOption().matches(ID: options::OPT_gdbx))
4481 DebuggerTuning = llvm::DebuggerKind::DBX;
4482 else
4483 DebuggerTuning = llvm::DebuggerKind::GDB;
4484 }
4485 }
4486
4487 // If a -gdwarf argument appeared, remember it.
4488 bool EmitDwarf = false;
4489 if (const Arg *A = getDwarfNArg(Args))
4490 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4491
4492 bool EmitCodeView = false;
4493 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcodeview))
4494 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4495
4496 // If the user asked for debug info but did not explicitly specify -gcodeview
4497 // or -gdwarf, ask the toolchain for the default format.
4498 if (!EmitCodeView && !EmitDwarf &&
4499 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4500 switch (TC.getDefaultDebugFormat()) {
4501 case llvm::codegenoptions::DIF_CodeView:
4502 EmitCodeView = true;
4503 break;
4504 case llvm::codegenoptions::DIF_DWARF:
4505 EmitDwarf = true;
4506 break;
4507 }
4508 }
4509
4510 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4511 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4512 // be lower than what the user wanted.
4513 if (EmitDwarf) {
4514 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4515 // Clamp effective DWARF version to the max supported by the toolchain.
4516 EffectiveDWARFVersion =
4517 std::min(a: RequestedDWARFVersion, b: TC.getMaxDwarfVersion());
4518 } else {
4519 Args.ClaimAllArgs(Id0: options::OPT_fdebug_default_version);
4520 }
4521
4522 // -gline-directives-only supported only for the DWARF debug info.
4523 if (RequestedDWARFVersion == 0 &&
4524 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4525 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4526
4527 // strict DWARF is set to false by default. But for DBX, we need it to be set
4528 // as true by default.
4529 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gstrict_dwarf))
4530 (void)checkDebugInfoOption(A, Args, D, TC);
4531 if (Args.hasFlag(Pos: options::OPT_gstrict_dwarf, Neg: options::OPT_gno_strict_dwarf,
4532 Default: DebuggerTuning == llvm::DebuggerKind::DBX))
4533 CmdArgs.push_back(Elt: "-gstrict-dwarf");
4534
4535 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4536 Args.ClaimAllArgs(Id0: options::OPT_g_flags_Group);
4537
4538 // Column info is included by default for everything except SCE and
4539 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4540 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4541 // practice, however, the Microsoft debuggers don't handle missing end columns
4542 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4543 // it's better not to include any column info.
4544 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcolumn_info))
4545 (void)checkDebugInfoOption(A, Args, D, TC);
4546 if (!Args.hasFlag(Pos: options::OPT_gcolumn_info, Neg: options::OPT_gno_column_info,
4547 Default: !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4548 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4549 DebuggerTuning != llvm::DebuggerKind::DBX)))
4550 CmdArgs.push_back(Elt: "-gno-column-info");
4551
4552 if (!Args.hasFlag(Pos: options::OPT_gcall_site_info,
4553 Neg: options::OPT_gno_call_site_info, Default: true))
4554 CmdArgs.push_back(Elt: "-gno-call-site-info");
4555
4556 // FIXME: Move backend command line options to the module.
4557 if (Args.hasFlag(Pos: options::OPT_gmodules, Neg: options::OPT_gno_modules, Default: false)) {
4558 // If -gline-tables-only or -gline-directives-only is the last option it
4559 // wins.
4560 if (checkDebugInfoOption(A: Args.getLastArg(Ids: options::OPT_gmodules), Args, D,
4561 TC)) {
4562 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4563 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4564 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4565 CmdArgs.push_back(Elt: "-dwarf-ext-refs");
4566 CmdArgs.push_back(Elt: "-fmodule-format=obj");
4567 }
4568 }
4569 }
4570
4571 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4572 CmdArgs.push_back(Elt: "-fsplit-dwarf-inlining");
4573
4574 // After we've dealt with all combinations of things that could
4575 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4576 // figure out if we need to "upgrade" it to standalone debug info.
4577 // We parse these two '-f' options whether or not they will be used,
4578 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4579 bool NeedFullDebug = Args.hasFlag(
4580 Pos: options::OPT_fstandalone_debug, Neg: options::OPT_fno_standalone_debug,
4581 Default: DebuggerTuning == llvm::DebuggerKind::LLDB ||
4582 TC.GetDefaultStandaloneDebug());
4583 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fstandalone_debug))
4584 (void)checkDebugInfoOption(A, Args, D, TC);
4585
4586 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4587 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4588 if (Args.hasFlag(Pos: options::OPT_fno_eliminate_unused_debug_types,
4589 Neg: options::OPT_feliminate_unused_debug_types, Default: false))
4590 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4591 else if (NeedFullDebug)
4592 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4593 }
4594
4595 if (Args.hasFlag(Pos: options::OPT_gembed_source, Neg: options::OPT_gno_embed_source,
4596 Default: false)) {
4597 // Source embedding is a vendor extension to DWARF v5. By now we have
4598 // checked if a DWARF version was stated explicitly, and have otherwise
4599 // fallen back to the target default, so if this is still not at least 5
4600 // we emit an error.
4601 const Arg *A = Args.getLastArg(Ids: options::OPT_gembed_source);
4602 if (RequestedDWARFVersion < 5)
4603 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4604 << A->getAsString(Args) << "-gdwarf-5";
4605 else if (EffectiveDWARFVersion < 5)
4606 // The toolchain has reduced allowed dwarf version, so we can't enable
4607 // -gembed-source.
4608 D.Diag(DiagID: diag::warn_drv_dwarf_version_limited_by_target)
4609 << A->getAsString(Args) << TC.getTripleString() << 5
4610 << EffectiveDWARFVersion;
4611 else if (checkDebugInfoOption(A, Args, D, TC))
4612 CmdArgs.push_back(Elt: "-gembed-source");
4613 }
4614
4615 // Enable Key Instructions by default if we're emitting DWARF, the language is
4616 // plain C or C++, and optimisations are enabled.
4617 Arg *OptLevel = Args.getLastArg(Ids: options::OPT_O_Group);
4618 bool KeyInstructionsOnByDefault =
4619 EmitDwarf && PlainCOrCXX && OptLevel &&
4620 !OptLevel->getOption().matches(ID: options::OPT_O0);
4621 if (Args.hasFlag(Pos: options::OPT_gkey_instructions,
4622 Neg: options::OPT_gno_key_instructions,
4623 Default: KeyInstructionsOnByDefault))
4624 CmdArgs.push_back(Elt: "-gkey-instructions");
4625
4626 if (!Args.hasFlag(Pos: options::OPT_gstructor_decl_linkage_names,
4627 Neg: options::OPT_gno_structor_decl_linkage_names, Default: true))
4628 CmdArgs.push_back(Elt: "-gno-structor-decl-linkage-names");
4629
4630 if (EmitCodeView) {
4631 CmdArgs.push_back(Elt: "-gcodeview");
4632
4633 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_gcodeview_ghash,
4634 Neg: options::OPT_gno_codeview_ghash);
4635
4636 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_gcodeview_command_line,
4637 Neg: options::OPT_gno_codeview_command_line);
4638 }
4639
4640 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_ginline_line_tables,
4641 Neg: options::OPT_gno_inline_line_tables);
4642
4643 // When emitting remarks, we need at least debug lines in the output.
4644 if (willEmitRemarks(Args) &&
4645 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4646 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4647
4648 // Adjust the debug info kind for the given toolchain.
4649 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4650
4651 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4652 // set.
4653 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion: EffectiveDWARFVersion,
4654 DebuggerTuning: T.isOSAIX() && !HasDebuggerTuning
4655 ? llvm::DebuggerKind::Default
4656 : DebuggerTuning);
4657
4658 // -fdebug-macro turns on macro debug info generation.
4659 if (Args.hasFlag(Pos: options::OPT_fdebug_macro, Neg: options::OPT_fno_debug_macro,
4660 Default: false))
4661 if (checkDebugInfoOption(A: Args.getLastArg(Ids: options::OPT_fdebug_macro), Args,
4662 D, TC))
4663 CmdArgs.push_back(Elt: "-debug-info-macro");
4664
4665 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4666 const auto *PubnamesArg =
4667 Args.getLastArg(Ids: options::OPT_ggnu_pubnames, Ids: options::OPT_gno_gnu_pubnames,
4668 Ids: options::OPT_gpubnames, Ids: options::OPT_gno_pubnames);
4669 if (DwarfFission != DwarfFissionKind::None ||
4670 (PubnamesArg && checkDebugInfoOption(A: PubnamesArg, Args, D, TC))) {
4671 const bool OptionSet =
4672 (PubnamesArg &&
4673 (PubnamesArg->getOption().matches(ID: options::OPT_gpubnames) ||
4674 PubnamesArg->getOption().matches(ID: options::OPT_ggnu_pubnames)));
4675 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
4676 (!PubnamesArg ||
4677 (!PubnamesArg->getOption().matches(ID: options::OPT_gno_gnu_pubnames) &&
4678 !PubnamesArg->getOption().matches(ID: options::OPT_gno_pubnames))))
4679 CmdArgs.push_back(Elt: PubnamesArg && PubnamesArg->getOption().matches(
4680 ID: options::OPT_gpubnames)
4681 ? "-gpubnames"
4682 : "-ggnu-pubnames");
4683 }
4684
4685 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4686 if (getDebugSimpleTemplateNames(TC, D, Args)) {
4687 ForwardTemplateParams = true;
4688 CmdArgs.push_back(Elt: "-gsimple-template-names=simple");
4689 }
4690
4691 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
4692 bool UseDebugTemplateAlias =
4693 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
4694 if (const auto *DebugTemplateAlias = Args.getLastArg(
4695 Ids: options::OPT_gtemplate_alias, Ids: options::OPT_gno_template_alias)) {
4696 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
4697 // asks for it we should let them have it (if the target supports it).
4698 if (checkDebugInfoOption(A: DebugTemplateAlias, Args, D, TC)) {
4699 const auto &Opt = DebugTemplateAlias->getOption();
4700 UseDebugTemplateAlias = Opt.matches(ID: options::OPT_gtemplate_alias);
4701 }
4702 }
4703 if (UseDebugTemplateAlias)
4704 CmdArgs.push_back(Elt: "-gtemplate-alias");
4705
4706 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gsrc_hash_EQ)) {
4707 StringRef v = A->getValue();
4708 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-gsrc-hash=" + v));
4709 }
4710
4711 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdebug_ranges_base_address,
4712 Neg: options::OPT_fno_debug_ranges_base_address);
4713
4714 // -gdwarf-aranges turns on the emission of the aranges section in the
4715 // backend.
4716 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gdwarf_aranges);
4717 A && checkDebugInfoOption(A, Args, D, TC)) {
4718 CmdArgs.push_back(Elt: "-mllvm");
4719 CmdArgs.push_back(Elt: "-generate-arange-section");
4720 }
4721
4722 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fforce_dwarf_frame,
4723 Neg: options::OPT_fno_force_dwarf_frame);
4724
4725 bool EnableTypeUnits = false;
4726 if (Args.hasFlag(Pos: options::OPT_fdebug_types_section,
4727 Neg: options::OPT_fno_debug_types_section, Default: false)) {
4728 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4729 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
4730 << Args.getLastArg(Ids: options::OPT_fdebug_types_section)
4731 ->getAsString(Args)
4732 << T.getTriple();
4733 } else if (checkDebugInfoOption(
4734 A: Args.getLastArg(Ids: options::OPT_fdebug_types_section), Args, D,
4735 TC)) {
4736 EnableTypeUnits = true;
4737 CmdArgs.push_back(Elt: "-mllvm");
4738 CmdArgs.push_back(Elt: "-generate-type-units");
4739 }
4740 }
4741
4742 if (const Arg *A =
4743 Args.getLastArg(Ids: options::OPT_gomit_unreferenced_methods,
4744 Ids: options::OPT_gno_omit_unreferenced_methods))
4745 (void)checkDebugInfoOption(A, Args, D, TC);
4746 if (Args.hasFlag(Pos: options::OPT_gomit_unreferenced_methods,
4747 Neg: options::OPT_gno_omit_unreferenced_methods, Default: false) &&
4748 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
4749 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
4750 !EnableTypeUnits) {
4751 CmdArgs.push_back(Elt: "-gomit-unreferenced-methods");
4752 }
4753
4754 // To avoid join/split of directory+filename, the integrated assembler prefers
4755 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4756 // form before DWARF v5.
4757 if (!Args.hasFlag(Pos: options::OPT_fdwarf_directory_asm,
4758 Neg: options::OPT_fno_dwarf_directory_asm,
4759 Default: TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4760 CmdArgs.push_back(Elt: "-fno-dwarf-directory-asm");
4761
4762 // Decide how to render forward declarations of template instantiations.
4763 // SCE wants full descriptions, others just get them in the name.
4764 if (ForwardTemplateParams)
4765 CmdArgs.push_back(Elt: "-debug-forward-template-params");
4766
4767 // Do we need to explicitly import anonymous namespaces into the parent
4768 // scope?
4769 if (DebuggerTuning == llvm::DebuggerKind::SCE)
4770 CmdArgs.push_back(Elt: "-dwarf-explicit-import");
4771
4772 renderDwarfFormat(D, T, Args, CmdArgs, DwarfVersion: EffectiveDWARFVersion);
4773 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4774
4775 // This controls whether or not we perform JustMyCode instrumentation.
4776 if (Args.hasFlag(Pos: options::OPT_fjmc, Neg: options::OPT_fno_jmc, Default: false)) {
4777 if (TC.getTriple().isOSBinFormatELF() ||
4778 TC.getTriple().isWindowsMSVCEnvironment()) {
4779 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
4780 CmdArgs.push_back(Elt: "-fjmc");
4781 else if (D.IsCLMode())
4782 D.Diag(DiagID: clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
4783 << "'/Zi', '/Z7'";
4784 else
4785 D.Diag(DiagID: clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
4786 << "-g";
4787 } else {
4788 D.Diag(DiagID: clang::diag::warn_drv_fjmc_for_elf_only);
4789 }
4790 }
4791
4792 // Add in -fdebug-compilation-dir if necessary.
4793 const char *DebugCompilationDir =
4794 addDebugCompDirArg(Args, CmdArgs, VFS: D.getVFS());
4795
4796 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
4797
4798 // Add the output path to the object file for CodeView debug infos.
4799 if (EmitCodeView && Output.isFilename())
4800 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
4801 OutputFileName: Output.getFilename());
4802}
4803
4804static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
4805 ArgStringList &CmdArgs) {
4806 unsigned RTOptionID = options::OPT__SLASH_MT;
4807
4808 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
4809 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4810 // but defining _DEBUG is sticky.
4811 RTOptionID = options::OPT__SLASH_MTd;
4812
4813 if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_M_Group))
4814 RTOptionID = A->getOption().getID();
4815
4816 if (Arg *A = Args.getLastArg(Ids: options::OPT_fms_runtime_lib_EQ)) {
4817 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4818 .Case(S: "static", Value: options::OPT__SLASH_MT)
4819 .Case(S: "static_dbg", Value: options::OPT__SLASH_MTd)
4820 .Case(S: "dll", Value: options::OPT__SLASH_MD)
4821 .Case(S: "dll_dbg", Value: options::OPT__SLASH_MDd)
4822 .Default(Value: options::OPT__SLASH_MT);
4823 }
4824
4825 StringRef FlagForCRT;
4826 switch (RTOptionID) {
4827 case options::OPT__SLASH_MD:
4828 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
4829 CmdArgs.push_back(Elt: "-D_DEBUG");
4830 CmdArgs.push_back(Elt: "-D_MT");
4831 CmdArgs.push_back(Elt: "-D_DLL");
4832 FlagForCRT = "--dependent-lib=msvcrt";
4833 break;
4834 case options::OPT__SLASH_MDd:
4835 CmdArgs.push_back(Elt: "-D_DEBUG");
4836 CmdArgs.push_back(Elt: "-D_MT");
4837 CmdArgs.push_back(Elt: "-D_DLL");
4838 FlagForCRT = "--dependent-lib=msvcrtd";
4839 break;
4840 case options::OPT__SLASH_MT:
4841 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
4842 CmdArgs.push_back(Elt: "-D_DEBUG");
4843 CmdArgs.push_back(Elt: "-D_MT");
4844 CmdArgs.push_back(Elt: "-flto-visibility-public-std");
4845 FlagForCRT = "--dependent-lib=libcmt";
4846 break;
4847 case options::OPT__SLASH_MTd:
4848 CmdArgs.push_back(Elt: "-D_DEBUG");
4849 CmdArgs.push_back(Elt: "-D_MT");
4850 CmdArgs.push_back(Elt: "-flto-visibility-public-std");
4851 FlagForCRT = "--dependent-lib=libcmtd";
4852 break;
4853 default:
4854 llvm_unreachable("Unexpected option ID.");
4855 }
4856
4857 if (Args.hasArg(Ids: options::OPT_fms_omit_default_lib)) {
4858 CmdArgs.push_back(Elt: "-D_VC_NODEFAULTLIB");
4859 } else {
4860 CmdArgs.push_back(Elt: FlagForCRT.data());
4861
4862 // This provides POSIX compatibility (maps 'open' to '_open'), which most
4863 // users want. The /Za flag to cl.exe turns this off, but it's not
4864 // implemented in clang.
4865 CmdArgs.push_back(Elt: "--dependent-lib=oldnames");
4866 }
4867
4868 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
4869 // even if the file doesn't actually refer to any of the routines because
4870 // the CRT itself has incomplete dependency markings.
4871 if (TC.getTriple().isWindowsArm64EC())
4872 CmdArgs.push_back(Elt: "--dependent-lib=softintrin");
4873}
4874
4875void Clang::ConstructJob(Compilation &C, const JobAction &JA,
4876 const InputInfo &Output, const InputInfoList &Inputs,
4877 const ArgList &Args, const char *LinkingOutput) const {
4878 const auto &TC = getToolChain();
4879 const llvm::Triple &RawTriple = TC.getTriple();
4880 const llvm::Triple &Triple = TC.getEffectiveTriple();
4881 const std::string &TripleStr = Triple.getTriple();
4882
4883 bool KernelOrKext =
4884 Args.hasArg(Ids: options::OPT_mkernel, Ids: options::OPT_fapple_kext);
4885 const Driver &D = TC.getDriver();
4886 ArgStringList CmdArgs;
4887
4888 assert(Inputs.size() >= 1 && "Must have at least one input.");
4889 // CUDA/HIP compilation may have multiple inputs (source file + results of
4890 // device-side compilations). OpenMP device jobs also take the host IR as a
4891 // second input. Module precompilation accepts a list of header files to
4892 // include as part of the module. API extraction accepts a list of header
4893 // files whose API information is emitted in the output. All other jobs are
4894 // expected to have exactly one input. SYCL compilation only expects a
4895 // single input.
4896 bool IsCuda = JA.isOffloading(OKind: Action::OFK_Cuda);
4897 bool IsCudaDevice = JA.isDeviceOffloading(OKind: Action::OFK_Cuda);
4898 bool IsHIP = JA.isOffloading(OKind: Action::OFK_HIP);
4899 bool IsHIPDevice = JA.isDeviceOffloading(OKind: Action::OFK_HIP);
4900 bool IsSYCL = JA.isOffloading(OKind: Action::OFK_SYCL);
4901 bool IsSYCLDevice = JA.isDeviceOffloading(OKind: Action::OFK_SYCL);
4902 bool IsOpenMPDevice = JA.isDeviceOffloading(OKind: Action::OFK_OpenMP);
4903 bool IsExtractAPI = isa<ExtractAPIJobAction>(Val: JA);
4904 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(OKind: Action::OFK_None) ||
4905 JA.isDeviceOffloading(OKind: Action::OFK_Host));
4906 bool IsHostOffloadingAction =
4907 JA.isHostOffloading(OKind: Action::OFK_OpenMP) ||
4908 JA.isHostOffloading(OKind: Action::OFK_SYCL) ||
4909 (JA.isHostOffloading(OKind: C.getActiveOffloadKinds()) &&
4910 Args.hasFlag(Pos: options::OPT_offload_new_driver,
4911 Neg: options::OPT_no_offload_new_driver,
4912 Default: C.getActiveOffloadKinds() != Action::OFK_None));
4913
4914 bool IsRDCMode =
4915 Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false);
4916
4917 auto LTOMode = IsDeviceOffloadAction ? D.getOffloadLTOMode() : D.getLTOMode();
4918 bool IsUsingLTO = LTOMode != LTOK_None;
4919
4920 // Extract API doesn't have a main input file, so invent a fake one as a
4921 // placeholder.
4922 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
4923 "extract-api");
4924
4925 const InputInfo &Input =
4926 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
4927
4928 InputInfoList ExtractAPIInputs;
4929 InputInfoList HostOffloadingInputs;
4930 const InputInfo *CudaDeviceInput = nullptr;
4931 const InputInfo *OpenMPDeviceInput = nullptr;
4932 for (const InputInfo &I : Inputs) {
4933 if (&I == &Input || I.getType() == types::TY_Nothing) {
4934 // This is the primary input or contains nothing.
4935 } else if (IsExtractAPI) {
4936 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
4937 if (I.getType() != ExpectedInputType) {
4938 D.Diag(DiagID: diag::err_drv_extract_api_wrong_kind)
4939 << I.getFilename() << types::getTypeName(Id: I.getType())
4940 << types::getTypeName(Id: ExpectedInputType);
4941 }
4942 ExtractAPIInputs.push_back(Elt: I);
4943 } else if (IsHostOffloadingAction) {
4944 HostOffloadingInputs.push_back(Elt: I);
4945 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
4946 CudaDeviceInput = &I;
4947 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
4948 OpenMPDeviceInput = &I;
4949 } else {
4950 llvm_unreachable("unexpectedly given multiple inputs");
4951 }
4952 }
4953
4954 const llvm::Triple *AuxTriple =
4955 (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
4956 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
4957 bool IsUEFI = RawTriple.isUEFI();
4958 bool IsIAMCU = RawTriple.isOSIAMCU();
4959
4960 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling in
4961 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
4962 // Windows), we need to pass Windows-specific flags to cc1.
4963 if (IsCuda || IsHIP || IsSYCL)
4964 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
4965
4966 // C++ is not supported for IAMCU.
4967 if (IsIAMCU && types::isCXX(Id: Input.getType()))
4968 D.Diag(DiagID: diag::err_drv_clang_unsupported) << "C++ for IAMCU";
4969
4970 // Invoke ourselves in -cc1 mode.
4971 //
4972 // FIXME: Implement custom jobs for internal actions.
4973 CmdArgs.push_back(Elt: "-cc1");
4974
4975 // Add the "effective" target triple.
4976 CmdArgs.push_back(Elt: "-triple");
4977 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TripleStr));
4978
4979 if (const Arg *MJ = Args.getLastArg(Ids: options::OPT_MJ)) {
4980 DumpCompilationDatabase(C, Filename: MJ->getValue(), Target: TripleStr, Output, Input, Args);
4981 Args.ClaimAllArgs(Id0: options::OPT_MJ);
4982 } else if (const Arg *GenCDBFragment =
4983 Args.getLastArg(Ids: options::OPT_gen_cdb_fragment_path)) {
4984 DumpCompilationDatabaseFragmentToDir(Dir: GenCDBFragment->getValue(), C,
4985 Target: TripleStr, Output, Input, Args);
4986 Args.ClaimAllArgs(Id0: options::OPT_gen_cdb_fragment_path);
4987 }
4988
4989 if (IsCuda || IsHIP) {
4990 // We have to pass the triple of the host if compiling for a CUDA/HIP device
4991 // and vice-versa.
4992 std::string NormalizedTriple;
4993 if (JA.isDeviceOffloading(OKind: Action::OFK_Cuda) ||
4994 JA.isDeviceOffloading(OKind: Action::OFK_HIP))
4995 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
4996 ->getTriple()
4997 .normalize();
4998 else {
4999 // Host-side compilation.
5000 NormalizedTriple =
5001 (IsCuda ? C.getOffloadToolChains(Kind: Action::OFK_Cuda).first->second
5002 : C.getOffloadToolChains(Kind: Action::OFK_HIP).first->second)
5003 ->getTriple()
5004 .normalize();
5005 if (IsCuda) {
5006 // We need to figure out which CUDA version we're compiling for, as that
5007 // determines how we load and launch GPU kernels.
5008 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
5009 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
5010 assert(CTC && "Expected valid CUDA Toolchain.");
5011 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
5012 CmdArgs.push_back(Elt: Args.MakeArgString(
5013 Str: Twine("-target-sdk-version=") +
5014 CudaVersionToString(V: CTC->CudaInstallation.version())));
5015 }
5016 }
5017 CmdArgs.push_back(Elt: "-aux-triple");
5018 CmdArgs.push_back(Elt: Args.MakeArgString(Str: NormalizedTriple));
5019
5020 if (JA.isDeviceOffloading(OKind: Action::OFK_HIP) &&
5021 (getToolChain().getTriple().isAMDGPU() ||
5022 (getToolChain().getTriple().isSPIRV() &&
5023 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
5024 // Device side compilation printf
5025 if (Args.getLastArg(Ids: options::OPT_mprintf_kind_EQ)) {
5026 CmdArgs.push_back(Elt: Args.MakeArgString(
5027 Str: "-mprintf-kind=" +
5028 Args.getLastArgValue(Id: options::OPT_mprintf_kind_EQ)));
5029 // Force compiler error on invalid conversion specifiers
5030 CmdArgs.push_back(
5031 Elt: Args.MakeArgString(Str: "-Werror=format-invalid-specifier"));
5032 }
5033 }
5034 }
5035
5036 // Optimization level for CodeGen.
5037 if (const Arg *A = Args.getLastArg(Ids: options::OPT_O_Group)) {
5038 if (A->getOption().matches(ID: options::OPT_O4)) {
5039 CmdArgs.push_back(Elt: "-O3");
5040 D.Diag(DiagID: diag::warn_O4_is_O3);
5041 } else {
5042 A->render(Args, Output&: CmdArgs);
5043 }
5044 }
5045
5046 // Unconditionally claim the printf option now to avoid unused diagnostic.
5047 if (const Arg *PF = Args.getLastArg(Ids: options::OPT_mprintf_kind_EQ))
5048 PF->claim();
5049
5050 if (IsSYCL) {
5051 if (IsSYCLDevice) {
5052 // Host triple is needed when doing SYCL device compilations.
5053 llvm::Triple AuxT = C.getDefaultToolChain().getTriple();
5054 std::string NormalizedTriple = AuxT.normalize();
5055 CmdArgs.push_back(Elt: "-aux-triple");
5056 CmdArgs.push_back(Elt: Args.MakeArgString(Str: NormalizedTriple));
5057
5058 // We want to compile sycl kernels.
5059 CmdArgs.push_back(Elt: "-fsycl-is-device");
5060
5061 // Set O2 optimization level by default
5062 if (!Args.getLastArg(Ids: options::OPT_O_Group))
5063 CmdArgs.push_back(Elt: "-O2");
5064 } else {
5065 // Add any options that are needed specific to SYCL offload while
5066 // performing the host side compilation.
5067
5068 // Let the front-end host compilation flow know about SYCL offload
5069 // compilation.
5070 CmdArgs.push_back(Elt: "-fsycl-is-host");
5071 }
5072
5073 // Set options for both host and device.
5074 Arg *SYCLStdArg = Args.getLastArg(Ids: options::OPT_sycl_std_EQ);
5075 if (SYCLStdArg) {
5076 SYCLStdArg->render(Args, Output&: CmdArgs);
5077 } else {
5078 // Ensure the default version in SYCL mode is 2020.
5079 CmdArgs.push_back(Elt: "-sycl-std=2020");
5080 }
5081 }
5082
5083 if (Args.hasArg(Ids: options::OPT_fclangir))
5084 CmdArgs.push_back(Elt: "-fclangir");
5085
5086 if (IsOpenMPDevice) {
5087 // We have to pass the triple of the host if compiling for an OpenMP device.
5088 std::string NormalizedTriple =
5089 C.getSingleOffloadToolChain<Action::OFK_Host>()
5090 ->getTriple()
5091 .normalize();
5092 CmdArgs.push_back(Elt: "-aux-triple");
5093 CmdArgs.push_back(Elt: Args.MakeArgString(Str: NormalizedTriple));
5094 }
5095
5096 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5097 Triple.getArch() == llvm::Triple::thumb)) {
5098 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5099 unsigned Version = 0;
5100 bool Failure =
5101 Triple.getArchName().substr(Start: Offset).consumeInteger(Radix: 10, Result&: Version);
5102 if (Failure || Version < 7)
5103 D.Diag(DiagID: diag::err_target_unsupported_arch) << Triple.getArchName()
5104 << TripleStr;
5105 }
5106
5107 // Push all default warning arguments that are specific to
5108 // the given target. These come before user provided warning options
5109 // are provided.
5110 TC.addClangWarningOptions(CC1Args&: CmdArgs);
5111
5112 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5113 if (Triple.isSPIR() || Triple.isSPIRV())
5114 CmdArgs.push_back(Elt: "-Wspir-compat");
5115
5116 // Select the appropriate action.
5117 RewriteKind rewriteKind = RK_None;
5118
5119 bool UnifiedLTO = false;
5120 if (IsUsingLTO) {
5121 UnifiedLTO = Args.hasFlag(Pos: options::OPT_funified_lto,
5122 Neg: options::OPT_fno_unified_lto, Default: Triple.isPS());
5123 if (UnifiedLTO)
5124 CmdArgs.push_back(Elt: "-funified-lto");
5125 }
5126
5127 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5128 // it claims when not running an assembler. Otherwise, clang would emit
5129 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5130 // flags while debugging something. That'd be somewhat inconvenient, and it's
5131 // also inconsistent with most other flags -- we don't warn on
5132 // -ffunction-sections not being used in -E mode either for example, even
5133 // though it's not really used either.
5134 if (!isa<AssembleJobAction>(Val: JA)) {
5135 // The args claimed here should match the args used in
5136 // CollectArgsForIntegratedAssembler().
5137 if (TC.useIntegratedAs()) {
5138 Args.ClaimAllArgs(Id0: options::OPT_mrelax_all);
5139 Args.ClaimAllArgs(Id0: options::OPT_mno_relax_all);
5140 Args.ClaimAllArgs(Id0: options::OPT_mincremental_linker_compatible);
5141 Args.ClaimAllArgs(Id0: options::OPT_mno_incremental_linker_compatible);
5142 switch (C.getDefaultToolChain().getArch()) {
5143 case llvm::Triple::arm:
5144 case llvm::Triple::armeb:
5145 case llvm::Triple::thumb:
5146 case llvm::Triple::thumbeb:
5147 Args.ClaimAllArgs(Id0: options::OPT_mimplicit_it_EQ);
5148 break;
5149 default:
5150 break;
5151 }
5152 }
5153 Args.ClaimAllArgs(Id0: options::OPT_Wa_COMMA);
5154 Args.ClaimAllArgs(Id0: options::OPT_Xassembler);
5155 Args.ClaimAllArgs(Id0: options::OPT_femit_dwarf_unwind_EQ);
5156 }
5157
5158 bool IsAMDSPIRVForHIPDevice =
5159 IsHIPDevice && getToolChain().getTriple().isSPIRV() &&
5160 getToolChain().getTriple().getVendor() == llvm::Triple::AMD;
5161
5162 if (isa<AnalyzeJobAction>(Val: JA)) {
5163 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5164 CmdArgs.push_back(Elt: "-analyze");
5165 } else if (isa<PreprocessJobAction>(Val: JA)) {
5166 if (Output.getType() == types::TY_Dependencies)
5167 CmdArgs.push_back(Elt: "-Eonly");
5168 else {
5169 CmdArgs.push_back(Elt: "-E");
5170 if (Args.hasArg(Ids: options::OPT_rewrite_objc) &&
5171 !Args.hasArg(Ids: options::OPT_g_Group))
5172 CmdArgs.push_back(Elt: "-P");
5173 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5174 CmdArgs.push_back(Elt: "-fdirectives-only");
5175 }
5176 } else if (isa<AssembleJobAction>(Val: JA)) {
5177 CmdArgs.push_back(Elt: "-emit-obj");
5178
5179 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5180
5181 // Also ignore explicit -force_cpusubtype_ALL option.
5182 (void)Args.hasArg(Ids: options::OPT_force__cpusubtype__ALL);
5183 } else if (isa<PrecompileJobAction>(Val: JA)) {
5184 if (JA.getType() == types::TY_Nothing)
5185 CmdArgs.push_back(Elt: "-fsyntax-only");
5186 else if (JA.getType() == types::TY_ModuleFile) {
5187 if (Args.hasArg(Ids: options::OPT__precompile_reduced_bmi))
5188 CmdArgs.push_back(Elt: "-emit-reduced-module-interface");
5189 else
5190 CmdArgs.push_back(Elt: "-emit-module-interface");
5191 } else if (JA.getType() == types::TY_HeaderUnit)
5192 CmdArgs.push_back(Elt: "-emit-header-unit");
5193 else if (!Args.hasArg(Ids: options::OPT_ignore_pch))
5194 CmdArgs.push_back(Elt: "-emit-pch");
5195 } else if (isa<VerifyPCHJobAction>(Val: JA)) {
5196 CmdArgs.push_back(Elt: "-verify-pch");
5197 } else if (isa<ExtractAPIJobAction>(Val: JA)) {
5198 assert(JA.getType() == types::TY_API_INFO &&
5199 "Extract API actions must generate a API information.");
5200 CmdArgs.push_back(Elt: "-extract-api");
5201
5202 if (Arg *PrettySGFArg = Args.getLastArg(Ids: options::OPT_emit_pretty_sgf))
5203 PrettySGFArg->render(Args, Output&: CmdArgs);
5204
5205 Arg *SymbolGraphDirArg = Args.getLastArg(Ids: options::OPT_symbol_graph_dir_EQ);
5206
5207 if (Arg *ProductNameArg = Args.getLastArg(Ids: options::OPT_product_name_EQ))
5208 ProductNameArg->render(Args, Output&: CmdArgs);
5209 if (Arg *ExtractAPIIgnoresFileArg =
5210 Args.getLastArg(Ids: options::OPT_extract_api_ignores_EQ))
5211 ExtractAPIIgnoresFileArg->render(Args, Output&: CmdArgs);
5212 if (Arg *EmitExtensionSymbolGraphs =
5213 Args.getLastArg(Ids: options::OPT_emit_extension_symbol_graphs)) {
5214 if (!SymbolGraphDirArg)
5215 D.Diag(DiagID: diag::err_drv_missing_symbol_graph_dir);
5216
5217 EmitExtensionSymbolGraphs->render(Args, Output&: CmdArgs);
5218 }
5219 if (SymbolGraphDirArg)
5220 SymbolGraphDirArg->render(Args, Output&: CmdArgs);
5221 } else {
5222 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5223 "Invalid action for clang tool.");
5224 if (JA.getType() == types::TY_Nothing) {
5225 CmdArgs.push_back(Elt: "-fsyntax-only");
5226 } else if (JA.getType() == types::TY_LLVM_IR ||
5227 JA.getType() == types::TY_LTO_IR) {
5228 CmdArgs.push_back(Elt: "-emit-llvm");
5229 } else if (JA.getType() == types::TY_LLVM_BC ||
5230 JA.getType() == types::TY_LTO_BC) {
5231 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5232 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(Ids: options::OPT_S) &&
5233 Args.hasArg(Ids: options::OPT_emit_llvm)) {
5234 CmdArgs.push_back(Elt: "-emit-llvm");
5235 } else {
5236 CmdArgs.push_back(Elt: "-emit-llvm-bc");
5237 }
5238 } else if (JA.getType() == types::TY_IFS ||
5239 JA.getType() == types::TY_IFS_CPP) {
5240 StringRef ArgStr =
5241 Args.hasArg(Ids: options::OPT_interface_stub_version_EQ)
5242 ? Args.getLastArgValue(Id: options::OPT_interface_stub_version_EQ)
5243 : "ifs-v1";
5244 CmdArgs.push_back(Elt: "-emit-interface-stubs");
5245 CmdArgs.push_back(
5246 Elt: Args.MakeArgString(Str: Twine("-interface-stub-version=") + ArgStr.str()));
5247 } else if (JA.getType() == types::TY_PP_Asm) {
5248 CmdArgs.push_back(Elt: "-S");
5249 } else if (JA.getType() == types::TY_AST) {
5250 if (!Args.hasArg(Ids: options::OPT_ignore_pch))
5251 CmdArgs.push_back(Elt: "-emit-pch");
5252 } else if (JA.getType() == types::TY_ModuleFile) {
5253 CmdArgs.push_back(Elt: "-module-file-info");
5254 } else if (JA.getType() == types::TY_RewrittenObjC) {
5255 CmdArgs.push_back(Elt: "-rewrite-objc");
5256 rewriteKind = RK_NonFragile;
5257 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5258 CmdArgs.push_back(Elt: "-rewrite-objc");
5259 rewriteKind = RK_Fragile;
5260 } else if (JA.getType() == types::TY_CIR) {
5261 CmdArgs.push_back(Elt: "-emit-cir");
5262 } else if (JA.getType() == types::TY_Image && IsAMDSPIRVForHIPDevice) {
5263 CmdArgs.push_back(Elt: "-emit-obj");
5264 } else {
5265 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5266 }
5267
5268 // Preserve use-list order by default when emitting bitcode, so that
5269 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5270 // same result as running passes here. For LTO, we don't need to preserve
5271 // the use-list order, since serialization to bitcode is part of the flow.
5272 if (JA.getType() == types::TY_LLVM_BC)
5273 CmdArgs.push_back(Elt: "-emit-llvm-uselists");
5274
5275 if (IsUsingLTO) {
5276 if (IsDeviceOffloadAction && !JA.isDeviceOffloading(OKind: Action::OFK_OpenMP) &&
5277 !Args.hasFlag(Pos: options::OPT_offload_new_driver,
5278 Neg: options::OPT_no_offload_new_driver,
5279 Default: C.getActiveOffloadKinds() != Action::OFK_None) &&
5280 !Triple.isAMDGPU()) {
5281 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5282 << Args.getLastArg(Ids: options::OPT_foffload_lto,
5283 Ids: options::OPT_foffload_lto_EQ)
5284 ->getAsString(Args)
5285 << Triple.getTriple();
5286 } else if (Triple.isNVPTX() && !IsRDCMode &&
5287 JA.isDeviceOffloading(OKind: Action::OFK_Cuda)) {
5288 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_language_mode)
5289 << Args.getLastArg(Ids: options::OPT_foffload_lto,
5290 Ids: options::OPT_foffload_lto_EQ)
5291 ->getAsString(Args)
5292 << "-fno-gpu-rdc";
5293 } else {
5294 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5295 CmdArgs.push_back(Elt: Args.MakeArgString(
5296 Str: Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5297 // PS4 uses the legacy LTO API, which does not support some of the
5298 // features enabled by -flto-unit.
5299 if (!RawTriple.isPS4() ||
5300 (D.getLTOMode() == LTOK_Full) || !UnifiedLTO)
5301 CmdArgs.push_back(Elt: "-flto-unit");
5302 }
5303 }
5304 }
5305
5306 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dumpdir);
5307
5308 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fthinlto_index_EQ)) {
5309 if (!types::isLLVMIR(Id: Input.getType()))
5310 D.Diag(DiagID: diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5311 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fthinlto_index_EQ);
5312 }
5313
5314 if (Triple.isPPC())
5315 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mregnames,
5316 Neg: options::OPT_mno_regnames);
5317
5318 if (Args.getLastArg(Ids: options::OPT_fthin_link_bitcode_EQ))
5319 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fthin_link_bitcode_EQ);
5320
5321 if (Args.getLastArg(Ids: options::OPT_save_temps_EQ))
5322 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_save_temps_EQ);
5323
5324 auto *MemProfArg = Args.getLastArg(Ids: options::OPT_fmemory_profile,
5325 Ids: options::OPT_fmemory_profile_EQ,
5326 Ids: options::OPT_fno_memory_profile);
5327 if (MemProfArg &&
5328 !MemProfArg->getOption().matches(ID: options::OPT_fno_memory_profile))
5329 MemProfArg->render(Args, Output&: CmdArgs);
5330
5331 if (auto *MemProfUseArg =
5332 Args.getLastArg(Ids: options::OPT_fmemory_profile_use_EQ)) {
5333 if (MemProfArg)
5334 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
5335 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5336 if (auto *PGOInstrArg = Args.getLastArg(Ids: options::OPT_fprofile_generate,
5337 Ids: options::OPT_fprofile_generate_EQ))
5338 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
5339 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5340 MemProfUseArg->render(Args, Output&: CmdArgs);
5341 }
5342
5343 // Embed-bitcode option.
5344 // Only white-listed flags below are allowed to be embedded.
5345 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5346 (isa<BackendJobAction>(Val: JA) || isa<AssembleJobAction>(Val: JA))) {
5347 // Add flags implied by -fembed-bitcode.
5348 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fembed_bitcode_EQ);
5349 // Disable all llvm IR level optimizations.
5350 CmdArgs.push_back(Elt: "-disable-llvm-passes");
5351
5352 // Render target options.
5353 TC.addClangTargetOptions(DriverArgs: Args, CC1Args&: CmdArgs, DeviceOffloadKind: JA.getOffloadingDeviceKind());
5354
5355 // reject options that shouldn't be supported in bitcode
5356 // also reject kernel/kext
5357 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5358 options::OPT_mkernel,
5359 options::OPT_fapple_kext,
5360 options::OPT_ffunction_sections,
5361 options::OPT_fno_function_sections,
5362 options::OPT_fdata_sections,
5363 options::OPT_fno_data_sections,
5364 options::OPT_fbasic_block_sections_EQ,
5365 options::OPT_funique_internal_linkage_names,
5366 options::OPT_fno_unique_internal_linkage_names,
5367 options::OPT_funique_section_names,
5368 options::OPT_fno_unique_section_names,
5369 options::OPT_funique_basic_block_section_names,
5370 options::OPT_fno_unique_basic_block_section_names,
5371 options::OPT_mrestrict_it,
5372 options::OPT_mno_restrict_it,
5373 options::OPT_mstackrealign,
5374 options::OPT_mno_stackrealign,
5375 options::OPT_mstack_alignment,
5376 options::OPT_mcmodel_EQ,
5377 options::OPT_mlong_calls,
5378 options::OPT_mno_long_calls,
5379 options::OPT_ggnu_pubnames,
5380 options::OPT_gdwarf_aranges,
5381 options::OPT_fdebug_types_section,
5382 options::OPT_fno_debug_types_section,
5383 options::OPT_fdwarf_directory_asm,
5384 options::OPT_fno_dwarf_directory_asm,
5385 options::OPT_mrelax_all,
5386 options::OPT_mno_relax_all,
5387 options::OPT_ftrap_function_EQ,
5388 options::OPT_ffixed_r9,
5389 options::OPT_mfix_cortex_a53_835769,
5390 options::OPT_mno_fix_cortex_a53_835769,
5391 options::OPT_ffixed_x18,
5392 options::OPT_mglobal_merge,
5393 options::OPT_mno_global_merge,
5394 options::OPT_mred_zone,
5395 options::OPT_mno_red_zone,
5396 options::OPT_Wa_COMMA,
5397 options::OPT_Xassembler,
5398 options::OPT_mllvm,
5399 options::OPT_mmlir,
5400 };
5401 for (const auto &A : Args)
5402 if (llvm::is_contained(Range: kBitcodeOptionIgnorelist, Element: A->getOption().getID()))
5403 D.Diag(DiagID: diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5404
5405 // Render the CodeGen options that need to be passed.
5406 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_foptimize_sibling_calls,
5407 Neg: options::OPT_fno_optimize_sibling_calls);
5408
5409 RenderFloatingPointOptions(TC, D, OFastEnabled: isOptimizationLevelFast(Args), Args,
5410 CmdArgs, JA);
5411
5412 // Render ABI arguments
5413 switch (TC.getArch()) {
5414 default: break;
5415 case llvm::Triple::arm:
5416 case llvm::Triple::armeb:
5417 case llvm::Triple::thumbeb:
5418 RenderARMABI(D, Triple, Args, CmdArgs);
5419 break;
5420 case llvm::Triple::aarch64:
5421 case llvm::Triple::aarch64_32:
5422 case llvm::Triple::aarch64_be:
5423 RenderAArch64ABI(Triple, Args, CmdArgs);
5424 break;
5425 }
5426
5427 // Input/Output file.
5428 if (Output.getType() == types::TY_Dependencies) {
5429 // Handled with other dependency code.
5430 } else if (Output.isFilename()) {
5431 CmdArgs.push_back(Elt: "-o");
5432 CmdArgs.push_back(Elt: Output.getFilename());
5433 } else {
5434 assert(Output.isNothing() && "Input output.");
5435 }
5436
5437 for (const auto &II : Inputs) {
5438 addDashXForInput(Args, Input: II, CmdArgs);
5439 if (II.isFilename())
5440 CmdArgs.push_back(Elt: II.getFilename());
5441 else
5442 II.getInputArg().renderAsInput(Args, Output&: CmdArgs);
5443 }
5444
5445 C.addCommand(C: std::make_unique<Command>(
5446 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args: D.getClangProgramPath(),
5447 args&: CmdArgs, args: Inputs, args: Output, args: D.getPrependArg()));
5448 return;
5449 }
5450
5451 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5452 CmdArgs.push_back(Elt: "-fembed-bitcode=marker");
5453
5454 // We normally speed up the clang process a bit by skipping destructors at
5455 // exit, but when we're generating diagnostics we can rely on some of the
5456 // cleanup.
5457 if (!C.isForDiagnostics())
5458 CmdArgs.push_back(Elt: "-disable-free");
5459 CmdArgs.push_back(Elt: "-clear-ast-before-backend");
5460
5461#ifdef NDEBUG
5462 const bool IsAssertBuild = false;
5463#else
5464 const bool IsAssertBuild = true;
5465#endif
5466
5467 // Disable the verification pass in no-asserts builds unless otherwise
5468 // specified.
5469 if (Args.hasFlag(Pos: options::OPT_fno_verify_intermediate_code,
5470 Neg: options::OPT_fverify_intermediate_code, Default: !IsAssertBuild)) {
5471 CmdArgs.push_back(Elt: "-disable-llvm-verifier");
5472 }
5473
5474 // Discard value names in no-asserts builds unless otherwise specified.
5475 if (Args.hasFlag(Pos: options::OPT_fdiscard_value_names,
5476 Neg: options::OPT_fno_discard_value_names, Default: !IsAssertBuild)) {
5477 if (Args.hasArg(Ids: options::OPT_fdiscard_value_names) &&
5478 llvm::any_of(Range: Inputs, P: [](const clang::driver::InputInfo &II) {
5479 return types::isLLVMIR(Id: II.getType());
5480 })) {
5481 D.Diag(DiagID: diag::warn_ignoring_fdiscard_for_bitcode);
5482 }
5483 CmdArgs.push_back(Elt: "-discard-value-names");
5484 }
5485
5486 // Set the main file name, so that debug info works even with
5487 // -save-temps.
5488 CmdArgs.push_back(Elt: "-main-file-name");
5489 CmdArgs.push_back(Elt: getBaseInputName(Args, Input));
5490
5491 // Some flags which affect the language (via preprocessor
5492 // defines).
5493 if (Args.hasArg(Ids: options::OPT_static))
5494 CmdArgs.push_back(Elt: "-static-define");
5495
5496 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_static_libclosure);
5497
5498 if (Args.hasArg(Ids: options::OPT_municode))
5499 CmdArgs.push_back(Elt: "-DUNICODE");
5500
5501 if (isa<AnalyzeJobAction>(Val: JA))
5502 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5503
5504 if (isa<AnalyzeJobAction>(Val: JA) ||
5505 (isa<PreprocessJobAction>(Val: JA) && Args.hasArg(Ids: options::OPT__analyze)))
5506 CmdArgs.push_back(Elt: "-setup-static-analyzer");
5507
5508 // Enable compatilibily mode to avoid analyzer-config related errors.
5509 // Since we can't access frontend flags through hasArg, let's manually iterate
5510 // through them.
5511 bool FoundAnalyzerConfig = false;
5512 for (auto *Arg : Args.filtered(Ids: options::OPT_Xclang))
5513 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5514 FoundAnalyzerConfig = true;
5515 break;
5516 }
5517 if (!FoundAnalyzerConfig)
5518 for (auto *Arg : Args.filtered(Ids: options::OPT_Xanalyzer))
5519 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5520 FoundAnalyzerConfig = true;
5521 break;
5522 }
5523 if (FoundAnalyzerConfig)
5524 CmdArgs.push_back(Elt: "-analyzer-config-compatibility-mode=true");
5525
5526 CheckCodeGenerationOptions(D, Args);
5527
5528 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5529 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5530 if (FunctionAlignment) {
5531 CmdArgs.push_back(Elt: "-function-alignment");
5532 CmdArgs.push_back(Elt: Args.MakeArgString(Str: std::to_string(val: FunctionAlignment)));
5533 }
5534
5535 if (const Arg *A =
5536 Args.getLastArg(Ids: options::OPT_fpreferred_function_alignment_EQ)) {
5537 unsigned Value = 0;
5538 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: Value) || Value > 65536)
5539 TC.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
5540 << A->getAsString(Args) << A->getValue();
5541 else if (!llvm::isPowerOf2_32(Value))
5542 TC.getDriver().Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
5543 << A->getAsString(Args) << A->getValue();
5544
5545 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fpreferred-function-alignment=" +
5546 Twine(std::min(a: Value, b: 65536u))));
5547 }
5548
5549 // We support -falign-loops=N where N is a power of 2. GCC supports more
5550 // forms.
5551 if (const Arg *A = Args.getLastArg(Ids: options::OPT_falign_loops_EQ)) {
5552 unsigned Value = 0;
5553 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: Value) || Value > 65536)
5554 TC.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
5555 << A->getAsString(Args) << A->getValue();
5556 else if (Value & (Value - 1))
5557 TC.getDriver().Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
5558 << A->getAsString(Args) << A->getValue();
5559 // Treat =0 as unspecified (use the target preference).
5560 if (Value)
5561 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-falign-loops=" +
5562 Twine(std::min(a: Value, b: 65536u))));
5563 }
5564
5565 if (Triple.isOSzOS()) {
5566 // On z/OS some of the system header feature macros need to
5567 // be defined to enable most cross platform projects to build
5568 // successfully. Ths include the libc++ library. A
5569 // complicating factor is that users can define these
5570 // macros to the same or different values. We need to add
5571 // the definition for these macros to the compilation command
5572 // if the user hasn't already defined them.
5573
5574 auto findMacroDefinition = [&](const std::string &Macro) {
5575 auto MacroDefs = Args.getAllArgValues(Id: options::OPT_D);
5576 return llvm::any_of(Range&: MacroDefs, P: [&](const std::string &M) {
5577 return M == Macro || M.find(str: Macro + '=') != std::string::npos;
5578 });
5579 };
5580
5581 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5582 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5583 CmdArgs.push_back(Elt: "-D_UNIX03_WITHDRAWN");
5584 // _OPEN_DEFAULT is required for XL compat
5585 if (!findMacroDefinition("_OPEN_DEFAULT"))
5586 CmdArgs.push_back(Elt: "-D_OPEN_DEFAULT");
5587 if (D.CCCIsCXX() || types::isCXX(Id: Input.getType())) {
5588 // _XOPEN_SOURCE=600 is required for libcxx.
5589 if (!findMacroDefinition("_XOPEN_SOURCE"))
5590 CmdArgs.push_back(Elt: "-D_XOPEN_SOURCE=600");
5591 }
5592 }
5593
5594 llvm::Reloc::Model RelocationModel;
5595 unsigned PICLevel;
5596 bool IsPIE;
5597 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) = ParsePICArgs(ToolChain: TC, Args);
5598 Arg *LastPICDataRelArg =
5599 Args.getLastArg(Ids: options::OPT_mno_pic_data_is_text_relative,
5600 Ids: options::OPT_mpic_data_is_text_relative);
5601 bool NoPICDataIsTextRelative = false;
5602 if (LastPICDataRelArg) {
5603 if (LastPICDataRelArg->getOption().matches(
5604 ID: options::OPT_mno_pic_data_is_text_relative)) {
5605 NoPICDataIsTextRelative = true;
5606 if (!PICLevel)
5607 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
5608 << "-mno-pic-data-is-text-relative"
5609 << "-fpic/-fpie";
5610 }
5611 if (!Triple.isSystemZ())
5612 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5613 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5614 : "-mpic-data-is-text-relative")
5615 << RawTriple.str();
5616 }
5617
5618 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5619 RelocationModel == llvm::Reloc::ROPI_RWPI;
5620 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5621 RelocationModel == llvm::Reloc::ROPI_RWPI;
5622
5623 if (Args.hasArg(Ids: options::OPT_mcmse) &&
5624 !Args.hasArg(Ids: options::OPT_fallow_unsupported)) {
5625 if (IsROPI)
5626 D.Diag(DiagID: diag::err_cmse_pi_are_incompatible) << IsROPI;
5627 if (IsRWPI)
5628 D.Diag(DiagID: diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5629 }
5630
5631 if (IsROPI && types::isCXX(Id: Input.getType()) &&
5632 !Args.hasArg(Ids: options::OPT_fallow_unsupported))
5633 D.Diag(DiagID: diag::err_drv_ropi_incompatible_with_cxx);
5634
5635 const char *RMName = RelocationModelName(Model: RelocationModel);
5636 if (RMName) {
5637 CmdArgs.push_back(Elt: "-mrelocation-model");
5638 CmdArgs.push_back(Elt: RMName);
5639 }
5640 if (PICLevel > 0) {
5641 CmdArgs.push_back(Elt: "-pic-level");
5642 CmdArgs.push_back(Elt: PICLevel == 1 ? "1" : "2");
5643 if (IsPIE)
5644 CmdArgs.push_back(Elt: "-pic-is-pie");
5645 if (NoPICDataIsTextRelative)
5646 CmdArgs.push_back(Elt: "-mcmodel=medium");
5647 }
5648
5649 if (RelocationModel == llvm::Reloc::ROPI ||
5650 RelocationModel == llvm::Reloc::ROPI_RWPI)
5651 CmdArgs.push_back(Elt: "-fropi");
5652 if (RelocationModel == llvm::Reloc::RWPI ||
5653 RelocationModel == llvm::Reloc::ROPI_RWPI)
5654 CmdArgs.push_back(Elt: "-frwpi");
5655
5656 if (Arg *A = Args.getLastArg(Ids: options::OPT_meabi)) {
5657 CmdArgs.push_back(Elt: "-meabi");
5658 CmdArgs.push_back(Elt: A->getValue());
5659 }
5660
5661 // -fsemantic-interposition is forwarded to CC1: set the
5662 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5663 // make default visibility external linkage definitions dso_preemptable.
5664 //
5665 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5666 // aliases (make default visibility external linkage definitions dso_local).
5667 // This is the CC1 default for ELF to match COFF/Mach-O.
5668 //
5669 // Otherwise use Clang's traditional behavior: like
5670 // -fno-semantic-interposition but local aliases are not used. So references
5671 // can be interposed if not optimized out.
5672 if (Triple.isOSBinFormatELF()) {
5673 Arg *A = Args.getLastArg(Ids: options::OPT_fsemantic_interposition,
5674 Ids: options::OPT_fno_semantic_interposition);
5675 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5676 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5677 bool SupportsLocalAlias =
5678 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5679 if (!A)
5680 CmdArgs.push_back(Elt: "-fhalf-no-semantic-interposition");
5681 else if (A->getOption().matches(ID: options::OPT_fsemantic_interposition))
5682 A->render(Args, Output&: CmdArgs);
5683 else if (!SupportsLocalAlias)
5684 CmdArgs.push_back(Elt: "-fhalf-no-semantic-interposition");
5685 }
5686 }
5687
5688 {
5689 std::string Model;
5690 if (Arg *A = Args.getLastArg(Ids: options::OPT_mthread_model)) {
5691 if (!TC.isThreadModelSupported(Model: A->getValue()))
5692 D.Diag(DiagID: diag::err_drv_invalid_thread_model_for_target)
5693 << A->getValue() << A->getAsString(Args);
5694 Model = A->getValue();
5695 } else
5696 Model = TC.getThreadModel();
5697 if (Model != "posix") {
5698 CmdArgs.push_back(Elt: "-mthread-model");
5699 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Model));
5700 }
5701 }
5702
5703 if (Arg *A = Args.getLastArg(Ids: options::OPT_fveclib)) {
5704 StringRef Name = A->getValue();
5705 if (Name == "SVML") {
5706 if (Triple.getArch() != llvm::Triple::x86 &&
5707 Triple.getArch() != llvm::Triple::x86_64)
5708 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5709 << Name << Triple.getArchName();
5710 } else if (Name == "AMDLIBM") {
5711 if (Triple.getArch() != llvm::Triple::x86 &&
5712 Triple.getArch() != llvm::Triple::x86_64)
5713 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5714 << Name << Triple.getArchName();
5715 } else if (Name == "libmvec") {
5716 if (Triple.getArch() != llvm::Triple::x86 &&
5717 Triple.getArch() != llvm::Triple::x86_64 &&
5718 Triple.getArch() != llvm::Triple::aarch64 &&
5719 Triple.getArch() != llvm::Triple::aarch64_be)
5720 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5721 << Name << Triple.getArchName();
5722 } else if (Name == "SLEEF" || Name == "ArmPL") {
5723 if (Triple.getArch() != llvm::Triple::aarch64 &&
5724 Triple.getArch() != llvm::Triple::aarch64_be && !Triple.isRISCV64())
5725 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5726 << Name << Triple.getArchName();
5727 }
5728 A->render(Args, Output&: CmdArgs);
5729 }
5730
5731 if (Args.hasFlag(Pos: options::OPT_fmerge_all_constants,
5732 Neg: options::OPT_fno_merge_all_constants, Default: false))
5733 CmdArgs.push_back(Elt: "-fmerge-all-constants");
5734
5735 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdelete_null_pointer_checks,
5736 Neg: options::OPT_fno_delete_null_pointer_checks);
5737
5738 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_flifetime_dse,
5739 Neg: options::OPT_fno_lifetime_dse);
5740
5741 // LLVM Code Generator Options.
5742
5743 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ_quadword_atomics)) {
5744 if (!Triple.isOSAIX() || Triple.isPPC32())
5745 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5746 << A->getSpelling() << RawTriple.str();
5747 CmdArgs.push_back(Elt: "-mabi=quadword-atomics");
5748 }
5749
5750 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlong_double_128)) {
5751 // Emit the unsupported option error until the Clang's library integration
5752 // support for 128-bit long double is available for AIX.
5753 if (Triple.isOSAIX())
5754 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5755 << A->getSpelling() << RawTriple.str();
5756 }
5757
5758 if (Arg *A = Args.getLastArg(Ids: options::OPT_Wframe_larger_than_EQ)) {
5759 StringRef V = A->getValue(), V1 = V;
5760 unsigned Size;
5761 if (V1.consumeInteger(Radix: 10, Result&: Size) || !V1.empty())
5762 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
5763 << V << A->getOption().getName();
5764 else
5765 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fwarn-stack-size=" + V));
5766 }
5767
5768 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fjump_tables,
5769 Neg: options::OPT_fno_jump_tables);
5770 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fprofile_sample_accurate,
5771 Neg: options::OPT_fno_profile_sample_accurate);
5772 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fpreserve_as_comments,
5773 Neg: options::OPT_fno_preserve_as_comments);
5774
5775 if (Arg *A = Args.getLastArg(Ids: options::OPT_mregparm_EQ)) {
5776 CmdArgs.push_back(Elt: "-mregparm");
5777 CmdArgs.push_back(Elt: A->getValue());
5778 }
5779
5780 if (Arg *A = Args.getLastArg(Ids: options::OPT_maix_struct_return,
5781 Ids: options::OPT_msvr4_struct_return)) {
5782 if (!TC.getTriple().isPPC32()) {
5783 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5784 << A->getSpelling() << RawTriple.str();
5785 } else if (A->getOption().matches(ID: options::OPT_maix_struct_return)) {
5786 CmdArgs.push_back(Elt: "-maix-struct-return");
5787 } else {
5788 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5789 CmdArgs.push_back(Elt: "-msvr4-struct-return");
5790 }
5791 }
5792
5793 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpcc_struct_return,
5794 Ids: options::OPT_freg_struct_return)) {
5795 if (TC.getArch() != llvm::Triple::x86) {
5796 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5797 << A->getSpelling() << RawTriple.str();
5798 } else if (A->getOption().matches(ID: options::OPT_fpcc_struct_return)) {
5799 CmdArgs.push_back(Elt: "-fpcc-struct-return");
5800 } else {
5801 assert(A->getOption().matches(options::OPT_freg_struct_return));
5802 CmdArgs.push_back(Elt: "-freg-struct-return");
5803 }
5804 }
5805
5806 if (Args.hasFlag(Pos: options::OPT_mrtd, Neg: options::OPT_mno_rtd, Default: false)) {
5807 if (Triple.getArch() == llvm::Triple::m68k)
5808 CmdArgs.push_back(Elt: "-fdefault-calling-conv=rtdcall");
5809 else
5810 CmdArgs.push_back(Elt: "-fdefault-calling-conv=stdcall");
5811 }
5812
5813 if (Args.hasArg(Ids: options::OPT_fenable_matrix)) {
5814 // enable-matrix is needed by both the LangOpts and by LLVM.
5815 CmdArgs.push_back(Elt: "-fenable-matrix");
5816 CmdArgs.push_back(Elt: "-mllvm");
5817 CmdArgs.push_back(Elt: "-enable-matrix");
5818 // Only handle default layout if matrix is enabled
5819 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fmatrix_memory_layout_EQ)) {
5820 StringRef Val = A->getValue();
5821 if (Val == "row-major" || Val == "column-major") {
5822 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fmatrix-memory-layout=" + Val));
5823 CmdArgs.push_back(Elt: "-mllvm");
5824 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-matrix-default-layout=" + Val));
5825
5826 } else {
5827 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
5828 }
5829 }
5830 }
5831
5832 CodeGenOptions::FramePointerKind FPKeepKind =
5833 getFramePointerKind(Args, Triple: RawTriple);
5834 const char *FPKeepKindStr = nullptr;
5835 switch (FPKeepKind) {
5836 case CodeGenOptions::FramePointerKind::None:
5837 FPKeepKindStr = "-mframe-pointer=none";
5838 break;
5839 case CodeGenOptions::FramePointerKind::Reserved:
5840 FPKeepKindStr = "-mframe-pointer=reserved";
5841 break;
5842 case CodeGenOptions::FramePointerKind::NonLeafNoReserve:
5843 FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";
5844 break;
5845 case CodeGenOptions::FramePointerKind::NonLeaf:
5846 FPKeepKindStr = "-mframe-pointer=non-leaf";
5847 break;
5848 case CodeGenOptions::FramePointerKind::All:
5849 FPKeepKindStr = "-mframe-pointer=all";
5850 break;
5851 }
5852 assert(FPKeepKindStr && "unknown FramePointerKind");
5853 CmdArgs.push_back(Elt: FPKeepKindStr);
5854
5855 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fzero_initialized_in_bss,
5856 Neg: options::OPT_fno_zero_initialized_in_bss);
5857
5858 bool OFastEnabled = isOptimizationLevelFast(Args);
5859 if (OFastEnabled)
5860 D.Diag(DiagID: diag::warn_drv_deprecated_arg_ofast);
5861 // If -Ofast is the optimization level, then -fstrict-aliasing should be
5862 // enabled. This alias option is being used to simplify the hasFlag logic.
5863 OptSpecifier StrictAliasingAliasOption =
5864 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
5865 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
5866 // doesn't do any TBAA.
5867 if (!Args.hasFlag(Pos: options::OPT_fstrict_aliasing, PosAlias: StrictAliasingAliasOption,
5868 Neg: options::OPT_fno_strict_aliasing,
5869 Default: !IsWindowsMSVC && !IsUEFI))
5870 CmdArgs.push_back(Elt: "-relaxed-aliasing");
5871 if (Args.hasFlag(Pos: options::OPT_fno_pointer_tbaa, Neg: options::OPT_fpointer_tbaa,
5872 Default: false))
5873 CmdArgs.push_back(Elt: "-no-pointer-tbaa");
5874 if (!Args.hasFlag(Pos: options::OPT_fstruct_path_tbaa,
5875 Neg: options::OPT_fno_struct_path_tbaa, Default: true))
5876 CmdArgs.push_back(Elt: "-no-struct-path-tbaa");
5877 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_enums,
5878 Neg: options::OPT_fno_strict_enums);
5879 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_return,
5880 Neg: options::OPT_fno_strict_return);
5881 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fallow_editor_placeholders,
5882 Neg: options::OPT_fno_allow_editor_placeholders);
5883 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_vtable_pointers,
5884 Neg: options::OPT_fno_strict_vtable_pointers);
5885 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fforce_emit_vtables,
5886 Neg: options::OPT_fno_force_emit_vtables);
5887 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_foptimize_sibling_calls,
5888 Neg: options::OPT_fno_optimize_sibling_calls);
5889 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fescaping_block_tail_calls,
5890 Neg: options::OPT_fno_escaping_block_tail_calls);
5891
5892 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffine_grained_bitfield_accesses,
5893 Ids: options::OPT_fno_fine_grained_bitfield_accesses);
5894
5895 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_relative_cxx_abi_vtables,
5896 Ids: options::OPT_fno_experimental_relative_cxx_abi_vtables);
5897
5898 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_omit_vtable_rtti,
5899 Ids: options::OPT_fno_experimental_omit_vtable_rtti);
5900
5901 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdisable_block_signature_string,
5902 Ids: options::OPT_fno_disable_block_signature_string);
5903
5904 // Handle segmented stacks.
5905 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fsplit_stack,
5906 Neg: options::OPT_fno_split_stack);
5907
5908 // -fprotect-parens=0 is default.
5909 if (Args.hasFlag(Pos: options::OPT_fprotect_parens,
5910 Neg: options::OPT_fno_protect_parens, Default: false))
5911 CmdArgs.push_back(Elt: "-fprotect-parens");
5912
5913 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
5914
5915 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_remote_memory,
5916 Neg: options::OPT_fno_atomic_remote_memory);
5917 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_fine_grained_memory,
5918 Neg: options::OPT_fno_atomic_fine_grained_memory);
5919 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_ignore_denormal_mode,
5920 Neg: options::OPT_fno_atomic_ignore_denormal_mode);
5921
5922 if (Arg *A = Args.getLastArg(Ids: options::OPT_fextend_args_EQ)) {
5923 const llvm::Triple::ArchType Arch = TC.getArch();
5924 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5925 StringRef V = A->getValue();
5926 if (V == "64")
5927 CmdArgs.push_back(Elt: "-fextend-arguments=64");
5928 else if (V != "32")
5929 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
5930 << A->getValue() << A->getOption().getName();
5931 } else
5932 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5933 << A->getOption().getName() << TripleStr;
5934 }
5935
5936 if (Arg *A = Args.getLastArg(Ids: options::OPT_mdouble_EQ)) {
5937 if (TC.getArch() == llvm::Triple::avr)
5938 A->render(Args, Output&: CmdArgs);
5939 else
5940 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5941 << A->getAsString(Args) << TripleStr;
5942 }
5943
5944 if (Arg *A = Args.getLastArg(Ids: options::OPT_LongDouble_Group)) {
5945 if (TC.getTriple().isX86())
5946 A->render(Args, Output&: CmdArgs);
5947 else if (TC.getTriple().isPPC() &&
5948 (A->getOption().getID() != options::OPT_mlong_double_80))
5949 A->render(Args, Output&: CmdArgs);
5950 else
5951 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5952 << A->getAsString(Args) << TripleStr;
5953 }
5954
5955 // Decide whether to use verbose asm. Verbose assembly is the default on
5956 // toolchains which have the integrated assembler on by default.
5957 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
5958 if (!Args.hasFlag(Pos: options::OPT_fverbose_asm, Neg: options::OPT_fno_verbose_asm,
5959 Default: IsIntegratedAssemblerDefault))
5960 CmdArgs.push_back(Elt: "-fno-verbose-asm");
5961
5962 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5963 // use that to indicate the MC default in the backend.
5964 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbinutils_version_EQ)) {
5965 StringRef V = A->getValue();
5966 unsigned Num;
5967 if (V == "none")
5968 A->render(Args, Output&: CmdArgs);
5969 else if (!V.consumeInteger(Radix: 10, Result&: Num) && Num > 0 &&
5970 (V.empty() || (V.consume_front(Prefix: ".") &&
5971 !V.consumeInteger(Radix: 10, Result&: Num) && V.empty())))
5972 A->render(Args, Output&: CmdArgs);
5973 else
5974 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
5975 << A->getValue() << A->getOption().getName();
5976 }
5977
5978 // If toolchain choose to use MCAsmParser for inline asm don't pass the
5979 // option to disable integrated-as explicitly.
5980 if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
5981 CmdArgs.push_back(Elt: "-no-integrated-as");
5982
5983 if (Args.hasArg(Ids: options::OPT_fdebug_pass_structure)) {
5984 CmdArgs.push_back(Elt: "-mdebug-pass");
5985 CmdArgs.push_back(Elt: "Structure");
5986 }
5987 if (Args.hasArg(Ids: options::OPT_fdebug_pass_arguments)) {
5988 CmdArgs.push_back(Elt: "-mdebug-pass");
5989 CmdArgs.push_back(Elt: "Arguments");
5990 }
5991
5992 // Enable -mconstructor-aliases except on darwin, where we have to work around
5993 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
5994 // code, where aliases aren't supported.
5995 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
5996 CmdArgs.push_back(Elt: "-mconstructor-aliases");
5997
5998 // Darwin's kernel doesn't support guard variables; just die if we
5999 // try to use them.
6000 if (KernelOrKext && RawTriple.isOSDarwin())
6001 CmdArgs.push_back(Elt: "-fforbid-guard-variables");
6002
6003 if (Arg *A = Args.getLastArg(Ids: options::OPT_mms_bitfields,
6004 Ids: options::OPT_mno_ms_bitfields)) {
6005 if (A->getOption().matches(ID: options::OPT_mms_bitfields))
6006 CmdArgs.push_back(Elt: "-fms-layout-compatibility=microsoft");
6007 else
6008 CmdArgs.push_back(Elt: "-fms-layout-compatibility=itanium");
6009 }
6010
6011 if (Triple.isOSCygMing()) {
6012 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fauto_import,
6013 Neg: options::OPT_fno_auto_import);
6014 }
6015
6016 if (Args.hasFlag(Pos: options::OPT_fms_volatile, Neg: options::OPT_fno_ms_volatile,
6017 Default: Triple.isX86() && IsWindowsMSVC))
6018 CmdArgs.push_back(Elt: "-fms-volatile");
6019
6020 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
6021 // defaults to -fno-direct-access-external-data. Pass the option if different
6022 // from the default.
6023 if (Arg *A = Args.getLastArg(Ids: options::OPT_fdirect_access_external_data,
6024 Ids: options::OPT_fno_direct_access_external_data)) {
6025 if (A->getOption().matches(ID: options::OPT_fdirect_access_external_data) !=
6026 (PICLevel == 0))
6027 A->render(Args, Output&: CmdArgs);
6028 } else if (PICLevel == 0 && Triple.isLoongArch()) {
6029 // Some targets default to -fno-direct-access-external-data even for
6030 // -fno-pic.
6031 CmdArgs.push_back(Elt: "-fno-direct-access-external-data");
6032 }
6033
6034 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
6035 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fplt, Neg: options::OPT_fno_plt);
6036
6037 // -fhosted is default.
6038 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
6039 // use Freestanding.
6040 bool Freestanding =
6041 Args.hasFlag(Pos: options::OPT_ffreestanding, Neg: options::OPT_fhosted, Default: false) ||
6042 KernelOrKext;
6043 if (Freestanding)
6044 CmdArgs.push_back(Elt: "-ffreestanding");
6045
6046 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_knr_functions);
6047
6048 auto SanitizeArgs = TC.getSanitizerArgs(JobArgs: Args);
6049 Args.AddLastArg(Output&: CmdArgs,
6050 Ids: options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
6051
6052 // This is a coarse approximation of what llvm-gcc actually does, both
6053 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
6054 // complicated ways.
6055 bool IsAsyncUnwindTablesDefault =
6056 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
6057 bool IsSyncUnwindTablesDefault =
6058 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
6059
6060 bool AsyncUnwindTables = Args.hasFlag(
6061 Pos: options::OPT_fasynchronous_unwind_tables,
6062 Neg: options::OPT_fno_asynchronous_unwind_tables,
6063 Default: (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6064 !Freestanding);
6065 bool UnwindTables =
6066 Args.hasFlag(Pos: options::OPT_funwind_tables, Neg: options::OPT_fno_unwind_tables,
6067 Default: IsSyncUnwindTablesDefault && !Freestanding);
6068 if (AsyncUnwindTables)
6069 CmdArgs.push_back(Elt: "-funwind-tables=2");
6070 else if (UnwindTables)
6071 CmdArgs.push_back(Elt: "-funwind-tables=1");
6072
6073 // Sframe unwind tables are independent of the other types. Although also
6074 // defined for aarch64, only x86_64 support is implemented at the moment.
6075 if (Arg *A = Args.getLastArg(Ids: options::OPT_gsframe)) {
6076 if (Triple.isOSBinFormatELF() && Triple.isX86())
6077 CmdArgs.push_back(Elt: "--gsframe");
6078 else
6079 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6080 << A->getOption().getName() << TripleStr;
6081 }
6082
6083 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6084 // `--gpu-use-aux-triple-only` is specified.
6085 if (!Args.getLastArg(Ids: options::OPT_gpu_use_aux_triple_only) &&
6086 (IsCudaDevice || IsHIPDevice || IsSYCLDevice)) {
6087 const ArgList &HostArgs =
6088 C.getArgsForToolChain(TC: nullptr, BoundArch: StringRef(), DeviceOffloadKind: Action::OFK_None);
6089 std::string HostCPU =
6090 getCPUName(D, Args: HostArgs, T: *TC.getAuxTriple(), /*FromAs*/ false);
6091 if (!HostCPU.empty()) {
6092 CmdArgs.push_back(Elt: "-aux-target-cpu");
6093 CmdArgs.push_back(Elt: Args.MakeArgString(Str: HostCPU));
6094 }
6095 getTargetFeatures(D, Triple: *TC.getAuxTriple(), Args: HostArgs, CmdArgs,
6096 /*ForAS*/ false, /*IsAux*/ true);
6097 }
6098
6099 TC.addClangTargetOptions(DriverArgs: Args, CC1Args&: CmdArgs, DeviceOffloadKind: JA.getOffloadingDeviceKind());
6100
6101 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6102
6103 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtls_size_EQ)) {
6104 StringRef Value = A->getValue();
6105 unsigned TLSSize = 0;
6106 Value.getAsInteger(Radix: 10, Result&: TLSSize);
6107 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6108 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6109 << A->getOption().getName() << TripleStr;
6110 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6111 D.Diag(DiagID: diag::err_drv_invalid_int_value)
6112 << A->getOption().getName() << Value;
6113 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mtls_size_EQ);
6114 }
6115
6116 if (isTLSDESCEnabled(TC, Args))
6117 CmdArgs.push_back(Elt: "-enable-tlsdesc");
6118
6119 // Add the target cpu
6120 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ false);
6121 if (!CPU.empty()) {
6122 CmdArgs.push_back(Elt: "-target-cpu");
6123 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
6124 }
6125
6126 RenderTargetOptions(EffectiveTriple: Triple, Args, KernelOrKext, CmdArgs);
6127
6128 // Add clang-cl arguments.
6129 types::ID InputType = Input.getType();
6130 if (D.IsCLMode())
6131 AddClangCLArgs(Args, InputType, CmdArgs);
6132
6133 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6134 llvm::codegenoptions::NoDebugInfo;
6135 DwarfFissionKind DwarfFission = DwarfFissionKind::None;
6136 renderDebugOptions(TC, D, T: RawTriple, Args, InputType, CmdArgs, Output,
6137 DebugInfoKind, DwarfFission);
6138
6139 // Add the split debug info name to the command lines here so we
6140 // can propagate it to the backend.
6141 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6142 (TC.getTriple().isOSBinFormatELF() ||
6143 TC.getTriple().isOSBinFormatWasm() ||
6144 TC.getTriple().isOSBinFormatCOFF()) &&
6145 (isa<AssembleJobAction>(Val: JA) || isa<CompileJobAction>(Val: JA) ||
6146 isa<BackendJobAction>(Val: JA));
6147 if (SplitDWARF) {
6148 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6149 CmdArgs.push_back(Elt: "-split-dwarf-file");
6150 CmdArgs.push_back(Elt: SplitDWARFOut);
6151 if (DwarfFission == DwarfFissionKind::Split) {
6152 CmdArgs.push_back(Elt: "-split-dwarf-output");
6153 CmdArgs.push_back(Elt: SplitDWARFOut);
6154 }
6155 }
6156
6157 // Pass the linker version in use.
6158 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlinker_version_EQ)) {
6159 CmdArgs.push_back(Elt: "-target-linker-version");
6160 CmdArgs.push_back(Elt: A->getValue());
6161 }
6162
6163 // Explicitly error on some things we know we don't support and can't just
6164 // ignore.
6165 if (!Args.hasArg(Ids: options::OPT_fallow_unsupported)) {
6166 Arg *Unsupported;
6167 if (types::isCXX(Id: InputType) && RawTriple.isOSDarwin() &&
6168 TC.getArch() == llvm::Triple::x86) {
6169 if ((Unsupported = Args.getLastArg(Ids: options::OPT_fapple_kext)) ||
6170 (Unsupported = Args.getLastArg(Ids: options::OPT_mkernel)))
6171 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6172 << Unsupported->getOption().getName();
6173 }
6174 // The faltivec option has been superseded by the maltivec option.
6175 if ((Unsupported = Args.getLastArg(Ids: options::OPT_faltivec)))
6176 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_faltivec)
6177 << Unsupported->getOption().getName()
6178 << "please use -maltivec and include altivec.h explicitly";
6179 if ((Unsupported = Args.getLastArg(Ids: options::OPT_fno_altivec)))
6180 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_faltivec)
6181 << Unsupported->getOption().getName() << "please use -mno-altivec";
6182 }
6183
6184 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_v);
6185
6186 if (Args.getLastArg(Ids: options::OPT_H)) {
6187 CmdArgs.push_back(Elt: "-H");
6188 CmdArgs.push_back(Elt: "-sys-header-deps");
6189 }
6190 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fshow_skipped_includes);
6191
6192 if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
6193 CmdArgs.push_back(Elt: "-header-include-file");
6194 CmdArgs.push_back(Elt: !D.CCPrintHeadersFilename.empty()
6195 ? D.CCPrintHeadersFilename.c_str()
6196 : "-");
6197 CmdArgs.push_back(Elt: "-sys-header-deps");
6198 CmdArgs.push_back(Elt: Args.MakeArgString(
6199 Str: "-header-include-format=" +
6200 std::string(headerIncludeFormatKindToString(K: D.CCPrintHeadersFormat))));
6201 CmdArgs.push_back(
6202 Elt: Args.MakeArgString(Str: "-header-include-filtering=" +
6203 std::string(headerIncludeFilteringKindToString(
6204 K: D.CCPrintHeadersFiltering))));
6205 }
6206 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_P);
6207 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_print_ivar_layout);
6208
6209 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6210 CmdArgs.push_back(Elt: "-diagnostic-log-file");
6211 CmdArgs.push_back(Elt: !D.CCLogDiagnosticsFilename.empty()
6212 ? D.CCLogDiagnosticsFilename.c_str()
6213 : "-");
6214 }
6215
6216 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6217 // crashes.
6218 if (D.CCGenDiagnostics)
6219 CmdArgs.push_back(Elt: "-disable-pragma-debug-crash");
6220
6221 // Allow backend to put its diagnostic files in the same place as frontend
6222 // crash diagnostics files.
6223 if (Args.hasArg(Ids: options::OPT_fcrash_diagnostics_dir)) {
6224 StringRef Dir = Args.getLastArgValue(Id: options::OPT_fcrash_diagnostics_dir);
6225 CmdArgs.push_back(Elt: "-mllvm");
6226 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-crash-diagnostics-dir=" + Dir));
6227 }
6228
6229 bool UseSeparateSections = isUseSeparateSections(Triple);
6230
6231 if (Args.hasFlag(Pos: options::OPT_ffunction_sections,
6232 Neg: options::OPT_fno_function_sections, Default: UseSeparateSections)) {
6233 CmdArgs.push_back(Elt: "-ffunction-sections");
6234 }
6235
6236 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbasic_block_address_map,
6237 Ids: options::OPT_fno_basic_block_address_map)) {
6238 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6239 if (A->getOption().matches(ID: options::OPT_fbasic_block_address_map))
6240 A->render(Args, Output&: CmdArgs);
6241 } else {
6242 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6243 << A->getAsString(Args) << TripleStr;
6244 }
6245 }
6246
6247 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbasic_block_sections_EQ)) {
6248 StringRef Val = A->getValue();
6249 if (Val == "labels") {
6250 D.Diag(DiagID: diag::warn_drv_deprecated_arg)
6251 << A->getAsString(Args) << /*hasReplacement=*/true
6252 << "-fbasic-block-address-map";
6253 CmdArgs.push_back(Elt: "-fbasic-block-address-map");
6254 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6255 if (Val != "all" && Val != "none" && !Val.starts_with(Prefix: "list="))
6256 D.Diag(DiagID: diag::err_drv_invalid_value)
6257 << A->getAsString(Args) << A->getValue();
6258 else
6259 A->render(Args, Output&: CmdArgs);
6260 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6261 // "all" is not supported on AArch64 since branch relaxation creates new
6262 // basic blocks for some cross-section branches.
6263 if (Val != "labels" && Val != "none" && !Val.starts_with(Prefix: "list="))
6264 D.Diag(DiagID: diag::err_drv_invalid_value)
6265 << A->getAsString(Args) << A->getValue();
6266 else
6267 A->render(Args, Output&: CmdArgs);
6268 } else if (Triple.isNVPTX()) {
6269 // Do not pass the option to the GPU compilation. We still want it enabled
6270 // for the host-side compilation, so seeing it here is not an error.
6271 } else if (Val != "none") {
6272 // =none is allowed everywhere. It's useful for overriding the option
6273 // and is the same as not specifying the option.
6274 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6275 << A->getAsString(Args) << TripleStr;
6276 }
6277 }
6278
6279 bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
6280 if (Args.hasFlag(Pos: options::OPT_fdata_sections, Neg: options::OPT_fno_data_sections,
6281 Default: UseSeparateSections || HasDefaultDataSections)) {
6282 CmdArgs.push_back(Elt: "-fdata-sections");
6283 }
6284
6285 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_funique_section_names,
6286 Neg: options::OPT_fno_unique_section_names);
6287 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fseparate_named_sections,
6288 Neg: options::OPT_fno_separate_named_sections);
6289 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_funique_internal_linkage_names,
6290 Neg: options::OPT_fno_unique_internal_linkage_names);
6291 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_funique_basic_block_section_names,
6292 Neg: options::OPT_fno_unique_basic_block_section_names);
6293
6294 if (Arg *A = Args.getLastArg(Ids: options::OPT_fsplit_machine_functions,
6295 Ids: options::OPT_fno_split_machine_functions)) {
6296 if (!A->getOption().matches(ID: options::OPT_fno_split_machine_functions)) {
6297 // This codegen pass is only available on x86 and AArch64 ELF targets.
6298 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
6299 A->render(Args, Output&: CmdArgs);
6300 else
6301 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6302 << A->getAsString(Args) << TripleStr;
6303 }
6304 }
6305
6306 if (Arg *A =
6307 Args.getLastArg(Ids: options::OPT_fpartition_static_data_sections,
6308 Ids: options::OPT_fno_partition_static_data_sections)) {
6309 if (!A->getOption().matches(
6310 ID: options::OPT_fno_partition_static_data_sections)) {
6311 // This codegen pass is only available on x86 and AArch64 ELF targets.
6312 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6313 A->render(Args, Output&: CmdArgs);
6314 CmdArgs.push_back(Elt: "-mllvm");
6315 CmdArgs.push_back(Elt: "-memprof-annotate-static-data-prefix");
6316 } else
6317 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6318 << A->getAsString(Args) << TripleStr;
6319 }
6320 }
6321
6322 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_finstrument_functions,
6323 Ids: options::OPT_finstrument_functions_after_inlining,
6324 Ids: options::OPT_finstrument_function_entry_bare);
6325 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconvergent_functions,
6326 Ids: options::OPT_fno_convergent_functions);
6327
6328 // NVPTX doesn't support PGO or coverage
6329 if (!Triple.isNVPTX())
6330 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanArgs&: SanitizeArgs, CmdArgs);
6331
6332 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fclang_abi_compat_EQ);
6333
6334 if (getLastProfileSampleUseArg(Args) &&
6335 Args.hasFlag(Pos: options::OPT_fsample_profile_use_profi,
6336 Neg: options::OPT_fno_sample_profile_use_profi, Default: true)) {
6337 CmdArgs.push_back(Elt: "-mllvm");
6338 CmdArgs.push_back(Elt: "-sample-profile-use-profi");
6339 }
6340
6341 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6342 if (RawTriple.isPS() &&
6343 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs)) {
6344 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6345 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6346 }
6347
6348 // Pass options for controlling the default header search paths.
6349 if (Args.hasArg(Ids: options::OPT_nostdinc)) {
6350 CmdArgs.push_back(Elt: "-nostdsysteminc");
6351 CmdArgs.push_back(Elt: "-nobuiltininc");
6352 } else {
6353 if (Args.hasArg(Ids: options::OPT_nostdlibinc))
6354 CmdArgs.push_back(Elt: "-nostdsysteminc");
6355 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_nostdincxx);
6356 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_nobuiltininc);
6357 }
6358
6359 // Pass the path to compiler resource files.
6360 CmdArgs.push_back(Elt: "-resource-dir");
6361 CmdArgs.push_back(Elt: D.ResourceDir.c_str());
6362
6363 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_working_directory);
6364
6365 // Add preprocessing options like -I, -D, etc. if we are using the
6366 // preprocessor.
6367 //
6368 // FIXME: Support -fpreprocessed
6369 if (types::getPreprocessedType(Id: InputType) != types::TY_INVALID)
6370 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6371
6372 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6373 // that "The compiler can only warn and ignore the option if not recognized".
6374 // When building with ccache, it will pass -D options to clang even on
6375 // preprocessed inputs and configure concludes that -fPIC is not supported.
6376 Args.ClaimAllArgs(Id0: options::OPT_D);
6377
6378 // Warn about ignored options to clang.
6379 for (const Arg *A :
6380 Args.filtered(Ids: options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6381 D.Diag(DiagID: diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6382 A->claim();
6383 }
6384
6385 for (const Arg *A :
6386 Args.filtered(Ids: options::OPT_clang_ignored_legacy_options_Group)) {
6387 D.Diag(DiagID: diag::warn_ignored_clang_option) << A->getAsString(Args);
6388 A->claim();
6389 }
6390
6391 claimNoWarnArgs(Args);
6392
6393 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_R_Group);
6394
6395 for (const Arg *A :
6396 Args.filtered(Ids: options::OPT_W_Group, Ids: options::OPT__SLASH_wd)) {
6397 A->claim();
6398 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6399 unsigned WarningNumber;
6400 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: WarningNumber)) {
6401 D.Diag(DiagID: diag::err_drv_invalid_int_value)
6402 << A->getAsString(Args) << A->getValue();
6403 continue;
6404 }
6405
6406 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6407 CmdArgs.push_back(Elt: Args.MakeArgString(
6408 Str: "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6409 }
6410 continue;
6411 }
6412 A->render(Args, Output&: CmdArgs);
6413 }
6414
6415 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_Wsystem_headers_in_module_EQ);
6416
6417 if (Args.hasFlag(Pos: options::OPT_pedantic, Neg: options::OPT_no_pedantic, Default: false))
6418 CmdArgs.push_back(Elt: "-pedantic");
6419 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pedantic_errors);
6420 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_w);
6421
6422 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_ffixed_point,
6423 Neg: options::OPT_fno_fixed_point);
6424
6425 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_overflow_behavior_types,
6426 Neg: options::OPT_fno_experimental_overflow_behavior_types);
6427
6428 if (Arg *A = Args.getLastArg(Ids: options::OPT_fcxx_abi_EQ))
6429 A->render(Args, Output&: CmdArgs);
6430
6431 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_relative_cxx_abi_vtables,
6432 Ids: options::OPT_fno_experimental_relative_cxx_abi_vtables);
6433
6434 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_omit_vtable_rtti,
6435 Ids: options::OPT_fno_experimental_omit_vtable_rtti);
6436
6437 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffuchsia_api_level_EQ))
6438 A->render(Args, Output&: CmdArgs);
6439
6440 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6441 // (-ansi is equivalent to -std=c89 or -std=c++98).
6442 //
6443 // If a std is supplied, only add -trigraphs if it follows the
6444 // option.
6445 bool ImplyVCPPCVer = false;
6446 bool ImplyVCPPCXXVer = false;
6447 const Arg *Std = Args.getLastArg(Ids: options::OPT_std_EQ, Ids: options::OPT_ansi);
6448 if (Std) {
6449 if (Std->getOption().matches(ID: options::OPT_ansi))
6450 if (types::isCXX(Id: InputType))
6451 CmdArgs.push_back(Elt: "-std=c++98");
6452 else
6453 CmdArgs.push_back(Elt: "-std=c89");
6454 else
6455 Std->render(Args, Output&: CmdArgs);
6456
6457 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6458 if (Arg *A = Args.getLastArg(Ids: options::OPT_std_EQ, Ids: options::OPT_ansi,
6459 Ids: options::OPT_ftrigraphs,
6460 Ids: options::OPT_fno_trigraphs))
6461 if (A != Std)
6462 A->render(Args, Output&: CmdArgs);
6463 } else {
6464 // Honor -std-default.
6465 //
6466 // FIXME: Clang doesn't correctly handle -std= when the input language
6467 // doesn't match. For the time being just ignore this for C++ inputs;
6468 // eventually we want to do all the standard defaulting here instead of
6469 // splitting it between the driver and clang -cc1.
6470 if (!types::isCXX(Id: InputType)) {
6471 if (!Args.hasArg(Ids: options::OPT__SLASH_std)) {
6472 Args.AddAllArgsTranslated(Output&: CmdArgs, Id0: options::OPT_std_default_EQ, Translation: "-std=",
6473 /*Joined=*/true);
6474 } else
6475 ImplyVCPPCVer = true;
6476 }
6477 else if (IsWindowsMSVC)
6478 ImplyVCPPCXXVer = true;
6479
6480 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrigraphs,
6481 Ids: options::OPT_fno_trigraphs);
6482 }
6483
6484 // GCC's behavior for -Wwrite-strings is a bit strange:
6485 // * In C, this "warning flag" changes the types of string literals from
6486 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6487 // for the discarded qualifier.
6488 // * In C++, this is just a normal warning flag.
6489 //
6490 // Implementing this warning correctly in C is hard, so we follow GCC's
6491 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6492 // a non-const char* in C, rather than using this crude hack.
6493 if (!types::isCXX(Id: InputType)) {
6494 // FIXME: This should behave just like a warning flag, and thus should also
6495 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6496 Arg *WriteStrings =
6497 Args.getLastArg(Ids: options::OPT_Wwrite_strings,
6498 Ids: options::OPT_Wno_write_strings, Ids: options::OPT_w);
6499 if (WriteStrings &&
6500 WriteStrings->getOption().matches(ID: options::OPT_Wwrite_strings))
6501 CmdArgs.push_back(Elt: "-fconst-strings");
6502 }
6503
6504 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6505 // during C++ compilation, which it is by default. GCC keeps this define even
6506 // in the presence of '-w', match this behavior bug-for-bug.
6507 if (types::isCXX(Id: InputType) &&
6508 Args.hasFlag(Pos: options::OPT_Wdeprecated, Neg: options::OPT_Wno_deprecated,
6509 Default: true)) {
6510 CmdArgs.push_back(Elt: "-fdeprecated-macro");
6511 }
6512
6513 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6514 if (Arg *Asm = Args.getLastArg(Ids: options::OPT_fasm, Ids: options::OPT_fno_asm)) {
6515 if (Asm->getOption().matches(ID: options::OPT_fasm))
6516 CmdArgs.push_back(Elt: "-fgnu-keywords");
6517 else
6518 CmdArgs.push_back(Elt: "-fno-gnu-keywords");
6519 }
6520
6521 if (!ShouldEnableAutolink(Args, TC, JA))
6522 CmdArgs.push_back(Elt: "-fno-autolink");
6523
6524 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftemplate_depth_EQ);
6525 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foperator_arrow_depth_EQ);
6526 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_depth_EQ);
6527 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_steps_EQ);
6528
6529 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_library);
6530
6531 if (Args.hasArg(Ids: options::OPT_fexperimental_new_constant_interpreter))
6532 CmdArgs.push_back(Elt: "-fexperimental-new-constant-interpreter");
6533
6534 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbracket_depth_EQ)) {
6535 CmdArgs.push_back(Elt: "-fbracket-depth");
6536 CmdArgs.push_back(Elt: A->getValue());
6537 }
6538
6539 if (Arg *A = Args.getLastArg(Ids: options::OPT_Wlarge_by_value_copy_EQ,
6540 Ids: options::OPT_Wlarge_by_value_copy_def)) {
6541 if (A->getNumValues()) {
6542 StringRef bytes = A->getValue();
6543 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-Wlarge-by-value-copy=" + bytes));
6544 } else
6545 CmdArgs.push_back(Elt: "-Wlarge-by-value-copy=64"); // default value
6546 }
6547
6548 if (Args.hasArg(Ids: options::OPT_relocatable_pch))
6549 CmdArgs.push_back(Elt: "-relocatable-pch");
6550
6551 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fcf_runtime_abi_EQ)) {
6552 static const char *kCFABIs[] = {
6553 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6554 };
6555
6556 if (!llvm::is_contained(Range&: kCFABIs, Element: StringRef(A->getValue())))
6557 D.Diag(DiagID: diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6558 else
6559 A->render(Args, Output&: CmdArgs);
6560 }
6561
6562 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_string_class_EQ)) {
6563 CmdArgs.push_back(Elt: "-fconstant-string-class");
6564 CmdArgs.push_back(Elt: A->getValue());
6565 }
6566
6567 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftabstop_EQ)) {
6568 CmdArgs.push_back(Elt: "-ftabstop");
6569 CmdArgs.push_back(Elt: A->getValue());
6570 }
6571
6572 if (Args.hasFlag(Pos: options::OPT_fexperimental_call_graph_section,
6573 Neg: options::OPT_fno_experimental_call_graph_section, Default: false))
6574 CmdArgs.push_back(Elt: "-fexperimental-call-graph-section");
6575
6576 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstack_size_section,
6577 Neg: options::OPT_fno_stack_size_section);
6578
6579 if (Args.hasArg(Ids: options::OPT_fstack_usage)) {
6580 CmdArgs.push_back(Elt: "-stack-usage-file");
6581
6582 if (Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o)) {
6583 SmallString<128> OutputFilename(OutputOpt->getValue());
6584 llvm::sys::path::replace_extension(path&: OutputFilename, extension: "su");
6585 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OutputFilename));
6586 } else
6587 CmdArgs.push_back(
6588 Elt: Args.MakeArgString(Str: Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6589 }
6590
6591 CmdArgs.push_back(Elt: "-ferror-limit");
6592 if (Arg *A = Args.getLastArg(Ids: options::OPT_ferror_limit_EQ))
6593 CmdArgs.push_back(Elt: A->getValue());
6594 else
6595 CmdArgs.push_back(Elt: "19");
6596
6597 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_backtrace_limit_EQ);
6598 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmacro_backtrace_limit_EQ);
6599 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftemplate_backtrace_limit_EQ);
6600 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fspell_checking_limit_EQ);
6601 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fcaret_diagnostics_max_lines_EQ);
6602
6603 // Pass -fmessage-length=.
6604 unsigned MessageLength = 0;
6605 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmessage_length_EQ)) {
6606 StringRef V(A->getValue());
6607 if (V.getAsInteger(Radix: 0, Result&: MessageLength))
6608 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6609 << V << A->getOption().getName();
6610 } else {
6611 // If -fmessage-length=N was not specified, determine whether this is a
6612 // terminal and, if so, implicitly define -fmessage-length appropriately.
6613 MessageLength = llvm::sys::Process::StandardErrColumns();
6614 }
6615 if (MessageLength != 0)
6616 CmdArgs.push_back(
6617 Elt: Args.MakeArgString(Str: "-fmessage-length=" + Twine(MessageLength)));
6618
6619 if (Arg *A = Args.getLastArg(Ids: options::OPT_frandomize_layout_seed_EQ))
6620 CmdArgs.push_back(
6621 Elt: Args.MakeArgString(Str: "-frandomize-layout-seed=" + Twine(A->getValue(N: 0))));
6622
6623 if (Arg *A = Args.getLastArg(Ids: options::OPT_frandomize_layout_seed_file_EQ))
6624 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-frandomize-layout-seed-file=" +
6625 Twine(A->getValue(N: 0))));
6626
6627 // -fvisibility= and -fvisibility-ms-compat are of a piece.
6628 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fvisibility_EQ,
6629 Ids: options::OPT_fvisibility_ms_compat)) {
6630 if (A->getOption().matches(ID: options::OPT_fvisibility_EQ)) {
6631 A->render(Args, Output&: CmdArgs);
6632 } else {
6633 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6634 CmdArgs.push_back(Elt: "-fvisibility=hidden");
6635 CmdArgs.push_back(Elt: "-ftype-visibility=default");
6636 }
6637 } else if (IsOpenMPDevice) {
6638 // When compiling for the OpenMP device we want protected visibility by
6639 // default. This prevents the device from accidentally preempting code on
6640 // the host, makes the system more robust, and improves performance.
6641 CmdArgs.push_back(Elt: "-fvisibility=protected");
6642 }
6643
6644 // PS4/PS5 process these options in addClangTargetOptions.
6645 if (!RawTriple.isPS()) {
6646 if (const Arg *A =
6647 Args.getLastArg(Ids: options::OPT_fvisibility_from_dllstorageclass,
6648 Ids: options::OPT_fno_visibility_from_dllstorageclass)) {
6649 if (A->getOption().matches(
6650 ID: options::OPT_fvisibility_from_dllstorageclass)) {
6651 CmdArgs.push_back(Elt: "-fvisibility-from-dllstorageclass");
6652 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_dllexport_EQ);
6653 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_nodllstorageclass_EQ);
6654 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_externs_dllimport_EQ);
6655 Args.AddLastArg(Output&: CmdArgs,
6656 Ids: options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6657 }
6658 }
6659 }
6660
6661 if (Args.hasFlag(Pos: options::OPT_fvisibility_inlines_hidden,
6662 Neg: options::OPT_fno_visibility_inlines_hidden, Default: false))
6663 CmdArgs.push_back(Elt: "-fvisibility-inlines-hidden");
6664
6665 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_inlines_hidden_static_local_var,
6666 Ids: options::OPT_fno_visibility_inlines_hidden_static_local_var);
6667
6668 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
6669 // -fvisibility-global-new-delete=force-hidden.
6670 if (const Arg *A =
6671 Args.getLastArg(Ids: options::OPT_fvisibility_global_new_delete_hidden)) {
6672 D.Diag(DiagID: diag::warn_drv_deprecated_arg)
6673 << A->getAsString(Args) << /*hasReplacement=*/true
6674 << "-fvisibility-global-new-delete=force-hidden";
6675 }
6676
6677 if (const Arg *A =
6678 Args.getLastArg(Ids: options::OPT_fvisibility_global_new_delete_EQ,
6679 Ids: options::OPT_fvisibility_global_new_delete_hidden)) {
6680 if (A->getOption().matches(ID: options::OPT_fvisibility_global_new_delete_EQ)) {
6681 A->render(Args, Output&: CmdArgs);
6682 } else {
6683 assert(A->getOption().matches(
6684 options::OPT_fvisibility_global_new_delete_hidden));
6685 CmdArgs.push_back(Elt: "-fvisibility-global-new-delete=force-hidden");
6686 }
6687 }
6688
6689 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftlsmodel_EQ);
6690
6691 if (Args.hasFlag(Pos: options::OPT_fnew_infallible,
6692 Neg: options::OPT_fno_new_infallible, Default: false))
6693 CmdArgs.push_back(Elt: "-fnew-infallible");
6694
6695 if (Args.hasFlag(Pos: options::OPT_fno_operator_names,
6696 Neg: options::OPT_foperator_names, Default: false))
6697 CmdArgs.push_back(Elt: "-fno-operator-names");
6698
6699 // Forward -f (flag) options which we can pass directly.
6700 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_femit_all_decls);
6701 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fheinous_gnu_extensions);
6702 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdigraphs, Ids: options::OPT_fno_digraphs);
6703 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fzero_call_used_regs_EQ);
6704 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fraw_string_literals,
6705 Ids: options::OPT_fno_raw_string_literals);
6706
6707 if (Args.hasFlag(Pos: options::OPT_femulated_tls, Neg: options::OPT_fno_emulated_tls,
6708 Default: Triple.hasDefaultEmulatedTLS()))
6709 CmdArgs.push_back(Elt: "-femulated-tls");
6710
6711 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcheck_new,
6712 Neg: options::OPT_fno_check_new);
6713
6714 if (Arg *A = Args.getLastArg(Ids: options::OPT_fzero_call_used_regs_EQ)) {
6715 // FIXME: There's no reason for this to be restricted to X86. The backend
6716 // code needs to be changed to include the appropriate function calls
6717 // automatically.
6718 if (!Triple.isX86() && !Triple.isAArch64())
6719 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6720 << A->getAsString(Args) << TripleStr;
6721 }
6722
6723 // AltiVec-like language extensions aren't relevant for assembling.
6724 if (!isa<PreprocessJobAction>(Val: JA) || Output.getType() != types::TY_PP_Asm)
6725 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fzvector);
6726
6727 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_show_template_tree);
6728 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_elide_type);
6729
6730 // Forward flags for OpenMP. We don't do this if the current action is an
6731 // device offloading action other than OpenMP.
6732 if (Args.hasFlag(Pos: options::OPT_fopenmp, PosAlias: options::OPT_fopenmp_EQ,
6733 Neg: options::OPT_fno_openmp, Default: false) &&
6734 !Args.hasFlag(Pos: options::OPT_foffload_via_llvm,
6735 Neg: options::OPT_fno_offload_via_llvm, Default: false) &&
6736 (JA.isDeviceOffloading(OKind: Action::OFK_None) ||
6737 JA.isDeviceOffloading(OKind: Action::OFK_OpenMP))) {
6738
6739 // Determine if target-fast optimizations should be enabled
6740 bool TargetFastUsed =
6741 Args.hasFlag(Pos: options::OPT_fopenmp_target_fast,
6742 Neg: options::OPT_fno_openmp_target_fast, Default: OFastEnabled);
6743 switch (D.getOpenMPRuntime(Args)) {
6744 case Driver::OMPRT_OMP:
6745 case Driver::OMPRT_IOMP5:
6746 // Clang can generate useful OpenMP code for these two runtime libraries.
6747 CmdArgs.push_back(Elt: "-fopenmp");
6748
6749 // If no option regarding the use of TLS in OpenMP codegeneration is
6750 // given, decide a default based on the target. Otherwise rely on the
6751 // options and pass the right information to the frontend.
6752 if (!Args.hasFlag(Pos: options::OPT_fopenmp_use_tls,
6753 Neg: options::OPT_fnoopenmp_use_tls, /*Default=*/true))
6754 CmdArgs.push_back(Elt: "-fnoopenmp-use-tls");
6755 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fopenmp_simd,
6756 Ids: options::OPT_fno_openmp_simd);
6757 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_enable_irbuilder);
6758 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_version_EQ);
6759 if (!Args.hasFlag(Pos: options::OPT_fopenmp_extensions,
6760 Neg: options::OPT_fno_openmp_extensions, /*Default=*/true))
6761 CmdArgs.push_back(Elt: "-fno-openmp-extensions");
6762 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_cuda_number_of_sm_EQ);
6763 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
6764 Args.AddAllArgs(Output&: CmdArgs,
6765 Id0: options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
6766 if (Args.hasFlag(Pos: options::OPT_fopenmp_optimistic_collapse,
6767 Neg: options::OPT_fno_openmp_optimistic_collapse,
6768 /*Default=*/false))
6769 CmdArgs.push_back(Elt: "-fopenmp-optimistic-collapse");
6770
6771 // When in OpenMP offloading mode with NVPTX target, forward
6772 // cuda-mode flag
6773 if (Args.hasFlag(Pos: options::OPT_fopenmp_cuda_mode,
6774 Neg: options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
6775 CmdArgs.push_back(Elt: "-fopenmp-cuda-mode");
6776
6777 // When in OpenMP offloading mode, enable debugging on the device.
6778 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_target_debug_EQ);
6779 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_debug,
6780 Neg: options::OPT_fno_openmp_target_debug, /*Default=*/false))
6781 CmdArgs.push_back(Elt: "-fopenmp-target-debug");
6782
6783 // When in OpenMP offloading mode, forward assumptions information about
6784 // thread and team counts in the device.
6785 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_teams_oversubscription,
6786 Neg: options::OPT_fno_openmp_assume_teams_oversubscription,
6787 /*Default=*/false))
6788 CmdArgs.push_back(Elt: "-fopenmp-assume-teams-oversubscription");
6789 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_threads_oversubscription,
6790 Neg: options::OPT_fno_openmp_assume_threads_oversubscription,
6791 /*Default=*/false))
6792 CmdArgs.push_back(Elt: "-fopenmp-assume-threads-oversubscription");
6793
6794 // Handle -fopenmp-assume-no-thread-state (implied by target-fast)
6795 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_no_thread_state,
6796 Neg: options::OPT_fno_openmp_assume_no_thread_state,
6797 /*Default=*/TargetFastUsed))
6798 CmdArgs.push_back(Elt: "-fopenmp-assume-no-thread-state");
6799
6800 // Handle -fopenmp-assume-no-nested-parallelism (implied by target-fast)
6801 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_no_nested_parallelism,
6802 Neg: options::OPT_fno_openmp_assume_no_nested_parallelism,
6803 /*Default=*/TargetFastUsed))
6804 CmdArgs.push_back(Elt: "-fopenmp-assume-no-nested-parallelism");
6805
6806 if (Args.hasArg(Ids: options::OPT_fopenmp_offload_mandatory))
6807 CmdArgs.push_back(Elt: "-fopenmp-offload-mandatory");
6808 if (Args.hasArg(Ids: options::OPT_fopenmp_force_usm))
6809 CmdArgs.push_back(Elt: "-fopenmp-force-usm");
6810 break;
6811 default:
6812 // By default, if Clang doesn't know how to generate useful OpenMP code
6813 // for a specific runtime library, we just don't pass the '-fopenmp' flag
6814 // down to the actual compilation.
6815 // FIXME: It would be better to have a mode which *only* omits IR
6816 // generation based on the OpenMP support so that we get consistent
6817 // semantic analysis, etc.
6818 break;
6819 }
6820 } else {
6821 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fopenmp_simd,
6822 Ids: options::OPT_fno_openmp_simd);
6823 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_version_EQ);
6824 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fopenmp_extensions,
6825 Neg: options::OPT_fno_openmp_extensions);
6826 }
6827 // Forward the offload runtime change to code generation, liboffload implies
6828 // new driver. Otherwise, check if we should forward the new driver to change
6829 // offloading code generation.
6830 if (Args.hasFlag(Pos: options::OPT_foffload_via_llvm,
6831 Neg: options::OPT_fno_offload_via_llvm, Default: false)) {
6832 CmdArgs.append(IL: {"--offload-new-driver", "-foffload-via-llvm"});
6833 } else if (Args.hasFlag(Pos: options::OPT_offload_new_driver,
6834 Neg: options::OPT_no_offload_new_driver,
6835 Default: C.getActiveOffloadKinds() != Action::OFK_None)) {
6836 CmdArgs.push_back(Elt: "--offload-new-driver");
6837 }
6838
6839 const XRayArgs &XRay = TC.getXRayArgs(Args);
6840 XRay.addArgs(TC, Args, CmdArgs, InputType);
6841
6842 for (const auto &Filename :
6843 Args.getAllArgValues(Id: options::OPT_fprofile_list_EQ)) {
6844 if (D.getVFS().exists(Path: Filename))
6845 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-list=" + Filename));
6846 else
6847 D.Diag(DiagID: clang::diag::err_drv_no_such_file) << Filename;
6848 }
6849
6850 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpatchable_function_entry_EQ)) {
6851 StringRef S0 = A->getValue(), S = S0;
6852 unsigned Size, Offset = 0;
6853 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
6854 !Triple.isX86() && !Triple.isSystemZ() &&
6855 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
6856 Triple.getArch() == llvm::Triple::ppc64 ||
6857 Triple.getArch() == llvm::Triple::ppc64le)))
6858 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6859 << A->getAsString(Args) << TripleStr;
6860 else if (S.consumeInteger(Radix: 10, Result&: Size) ||
6861 (!S.empty() &&
6862 (!S.consume_front(Prefix: ",") || S.consumeInteger(Radix: 10, Result&: Offset))) ||
6863 (!S.empty() && (!S.consume_front(Prefix: ",") || S.empty())))
6864 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6865 << S0 << A->getOption().getName();
6866 else if (Size < Offset)
6867 D.Diag(DiagID: diag::err_drv_unsupported_fpatchable_function_entry_argument);
6868 else {
6869 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getSpelling() + Twine(Size)));
6870 CmdArgs.push_back(Elt: Args.MakeArgString(
6871 Str: "-fpatchable-function-entry-offset=" + Twine(Offset)));
6872 if (!S.empty())
6873 CmdArgs.push_back(
6874 Elt: Args.MakeArgString(Str: "-fpatchable-function-entry-section=" + S));
6875 }
6876 }
6877
6878 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fms_hotpatch);
6879
6880 if (Args.hasArg(Ids: options::OPT_fms_secure_hotpatch_functions_file))
6881 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fms_secure_hotpatch_functions_file);
6882
6883 for (const auto &A :
6884 Args.getAllArgValues(Id: options::OPT_fms_secure_hotpatch_functions_list))
6885 CmdArgs.push_back(
6886 Elt: Args.MakeArgString(Str: "-fms-secure-hotpatch-functions-list=" + Twine(A)));
6887
6888 if (TC.SupportsProfiling()) {
6889 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pg);
6890
6891 llvm::Triple::ArchType Arch = TC.getArch();
6892 if (Arg *A = Args.getLastArg(Ids: options::OPT_mfentry)) {
6893 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
6894 A->render(Args, Output&: CmdArgs);
6895 else
6896 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6897 << A->getAsString(Args) << TripleStr;
6898 }
6899 if (Arg *A = Args.getLastArg(Ids: options::OPT_mnop_mcount)) {
6900 if (Arch == llvm::Triple::systemz)
6901 A->render(Args, Output&: CmdArgs);
6902 else
6903 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6904 << A->getAsString(Args) << TripleStr;
6905 }
6906 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrecord_mcount)) {
6907 if (Arch == llvm::Triple::systemz)
6908 A->render(Args, Output&: CmdArgs);
6909 else
6910 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6911 << A->getAsString(Args) << TripleStr;
6912 }
6913 }
6914
6915 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_pg)) {
6916 if (TC.getTriple().isOSzOS()) {
6917 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6918 << A->getAsString(Args) << TripleStr;
6919 }
6920 }
6921 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_p)) {
6922 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
6923 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6924 << A->getAsString(Args) << TripleStr;
6925 }
6926 }
6927 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_p, Ids: options::OPT_pg)) {
6928 if (A->getOption().matches(ID: options::OPT_p)) {
6929 A->claim();
6930 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(Ids: options::OPT_pg))
6931 CmdArgs.push_back(Elt: "-pg");
6932 }
6933 }
6934
6935 // Reject AIX-specific link options on other targets.
6936 if (!TC.getTriple().isOSAIX()) {
6937 for (const Arg *A : Args.filtered(Ids: options::OPT_b, Ids: options::OPT_K,
6938 Ids: options::OPT_mxcoff_build_id_EQ)) {
6939 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6940 << A->getSpelling() << TripleStr;
6941 }
6942 }
6943
6944 if (Args.getLastArg(Ids: options::OPT_fapple_kext) ||
6945 (Args.hasArg(Ids: options::OPT_mkernel) && types::isCXX(Id: InputType)))
6946 CmdArgs.push_back(Elt: "-fapple-kext");
6947
6948 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_altivec_src_compat);
6949 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_flax_vector_conversions_EQ);
6950 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fobjc_sender_dependent_dispatch);
6951 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_print_source_range_info);
6952 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_parseable_fixits);
6953 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report);
6954 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report_EQ);
6955 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report_json);
6956 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrapv);
6957 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_malign_double);
6958 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_temp_file);
6959
6960 if (const char *Name = C.getTimeTraceFile(JA: &JA)) {
6961 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ftime-trace=" + Twine(Name)));
6962 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_trace_granularity_EQ);
6963 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_trace_verbose);
6964 }
6965
6966 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftrapv_handler_EQ)) {
6967 CmdArgs.push_back(Elt: "-ftrapv-handler");
6968 CmdArgs.push_back(Elt: A->getValue());
6969 }
6970
6971 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrap_function_EQ);
6972
6973 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
6974 // clang and flang.
6975 renderCommonIntegerOverflowOptions(Args, CmdArgs);
6976
6977 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffinite_loops,
6978 Ids: options::OPT_fno_finite_loops);
6979
6980 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fwritable_strings);
6981 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_funroll_loops,
6982 Ids: options::OPT_fno_unroll_loops);
6983 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_floop_interchange,
6984 Ids: options::OPT_fno_loop_interchange);
6985 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_loop_fusion,
6986 Neg: options::OPT_fno_experimental_loop_fusion);
6987
6988 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fstrict_flex_arrays_EQ);
6989
6990 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pthread);
6991
6992 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mspeculative_load_hardening,
6993 Neg: options::OPT_mno_speculative_load_hardening);
6994
6995 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
6996 RenderSCPOptions(TC, Args, CmdArgs);
6997 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
6998
6999 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fswift_async_fp_EQ);
7000
7001 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mstackrealign,
7002 Neg: options::OPT_mno_stackrealign);
7003
7004 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mstack_alignment)) {
7005 StringRef Value = A->getValue();
7006 int64_t Alignment = 0;
7007 if (Value.getAsInteger(Radix: 10, Result&: Alignment) || Alignment < 0)
7008 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
7009 << Value << A->getOption().getName();
7010 else if (Alignment & (Alignment - 1))
7011 D.Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
7012 << A->getAsString(Args) << Value;
7013 else
7014 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mstack-alignment=" + Value));
7015 }
7016
7017 if (Args.hasArg(Ids: options::OPT_mstack_probe_size)) {
7018 StringRef Size = Args.getLastArgValue(Id: options::OPT_mstack_probe_size);
7019
7020 if (!Size.empty())
7021 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mstack-probe-size=" + Size));
7022 else
7023 CmdArgs.push_back(Elt: "-mstack-probe-size=0");
7024 }
7025
7026 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_mstack_arg_probe,
7027 Neg: options::OPT_mno_stack_arg_probe);
7028
7029 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrestrict_it,
7030 Ids: options::OPT_mno_restrict_it)) {
7031 if (A->getOption().matches(ID: options::OPT_mrestrict_it)) {
7032 CmdArgs.push_back(Elt: "-mllvm");
7033 CmdArgs.push_back(Elt: "-arm-restrict-it");
7034 } else {
7035 CmdArgs.push_back(Elt: "-mllvm");
7036 CmdArgs.push_back(Elt: "-arm-default-it");
7037 }
7038 }
7039
7040 // Forward -cl options to -cc1
7041 RenderOpenCLOptions(Args, CmdArgs, InputType);
7042
7043 // Forward hlsl options to -cc1
7044 RenderHLSLOptions(Args, CmdArgs, InputType);
7045
7046 // Forward OpenACC options to -cc1
7047 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
7048
7049 if (IsHIP) {
7050 if (Args.hasFlag(Pos: options::OPT_fhip_new_launch_api,
7051 Neg: options::OPT_fno_hip_new_launch_api, Default: true))
7052 CmdArgs.push_back(Elt: "-fhip-new-launch-api");
7053 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgpu_allow_device_init,
7054 Neg: options::OPT_fno_gpu_allow_device_init);
7055 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_hipstdpar);
7056 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_hipstdpar_interpose_alloc);
7057 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fhip_kernel_arg_name,
7058 Neg: options::OPT_fno_hip_kernel_arg_name);
7059 }
7060
7061 if (IsCuda || IsHIP) {
7062 if (IsRDCMode)
7063 CmdArgs.push_back(Elt: "-fgpu-rdc");
7064 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgpu_defer_diag,
7065 Neg: options::OPT_fno_gpu_defer_diag);
7066 if (Args.hasFlag(Pos: options::OPT_fgpu_exclude_wrong_side_overloads,
7067 Neg: options::OPT_fno_gpu_exclude_wrong_side_overloads,
7068 Default: false)) {
7069 CmdArgs.push_back(Elt: "-fgpu-exclude-wrong-side-overloads");
7070 CmdArgs.push_back(Elt: "-fgpu-defer-diag");
7071 }
7072 }
7073
7074 // Forward --no-offloadlib to -cc1.
7075 if (!Args.hasFlag(Pos: options::OPT_offloadlib, Neg: options::OPT_no_offloadlib, Default: true))
7076 CmdArgs.push_back(Elt: "--no-offloadlib");
7077
7078 if (Arg *A = Args.getLastArg(Ids: options::OPT_fcf_protection_EQ)) {
7079 CmdArgs.push_back(
7080 Elt: Args.MakeArgString(Str: Twine("-fcf-protection=") + A->getValue()));
7081
7082 if (Arg *SA = Args.getLastArg(Ids: options::OPT_mcf_branch_label_scheme_EQ))
7083 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-mcf-branch-label-scheme=") +
7084 SA->getValue()));
7085 } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
7086 // Emit IBT endbr64 instructions by default
7087 CmdArgs.push_back(Elt: "-fcf-protection=branch");
7088 // jump-table can generate indirect jumps, which are not permitted
7089 CmdArgs.push_back(Elt: "-fno-jump-tables");
7090 }
7091
7092 if (Arg *A = Args.getLastArg(Ids: options::OPT_mfunction_return_EQ))
7093 CmdArgs.push_back(
7094 Elt: Args.MakeArgString(Str: Twine("-mfunction-return=") + A->getValue()));
7095
7096 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mindirect_branch_cs_prefix);
7097
7098 // Forward -f options with positive and negative forms; we translate these by
7099 // hand. Do not propagate PGO options to the GPU-side compilations as the
7100 // profile info is for the host-side compilation only.
7101 if (!(IsCudaDevice || IsHIPDevice)) {
7102 if (Arg *A = getLastProfileSampleUseArg(Args)) {
7103 auto *PGOArg = Args.getLastArg(
7104 Ids: options::OPT_fprofile_generate, Ids: options::OPT_fprofile_generate_EQ,
7105 Ids: options::OPT_fcs_profile_generate,
7106 Ids: options::OPT_fcs_profile_generate_EQ, Ids: options::OPT_fprofile_use,
7107 Ids: options::OPT_fprofile_use_EQ);
7108 if (PGOArg)
7109 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
7110 << "SampleUse with PGO options";
7111
7112 StringRef fname = A->getValue();
7113 if (!llvm::sys::fs::exists(Path: fname))
7114 D.Diag(DiagID: diag::err_drv_no_such_file) << fname;
7115 else
7116 A->render(Args, Output&: CmdArgs);
7117 }
7118 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fprofile_remapping_file_EQ);
7119
7120 if (Args.hasFlag(Pos: options::OPT_fpseudo_probe_for_profiling,
7121 Neg: options::OPT_fno_pseudo_probe_for_profiling, Default: false)) {
7122 CmdArgs.push_back(Elt: "-fpseudo-probe-for-profiling");
7123 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7124 // off.
7125 if (Args.hasFlag(Pos: options::OPT_funique_internal_linkage_names,
7126 Neg: options::OPT_fno_unique_internal_linkage_names, Default: true))
7127 CmdArgs.push_back(Elt: "-funique-internal-linkage-names");
7128 }
7129 }
7130 RenderBuiltinOptions(TC, T: RawTriple, Args, CmdArgs);
7131
7132 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_sane_operator_new,
7133 Neg: options::OPT_fno_assume_sane_operator_new);
7134
7135 if (Args.hasFlag(Pos: options::OPT_fapinotes, Neg: options::OPT_fno_apinotes, Default: false))
7136 CmdArgs.push_back(Elt: "-fapinotes");
7137 if (Args.hasFlag(Pos: options::OPT_fapinotes_modules,
7138 Neg: options::OPT_fno_apinotes_modules, Default: false))
7139 CmdArgs.push_back(Elt: "-fapinotes-modules");
7140 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fapinotes_swift_version);
7141
7142 if (Args.hasFlag(Pos: options::OPT_fswift_version_independent_apinotes,
7143 Neg: options::OPT_fno_swift_version_independent_apinotes, Default: false))
7144 CmdArgs.push_back(Elt: "-fswift-version-independent-apinotes");
7145
7146 // -fblocks=0 is default.
7147 if (Args.hasFlag(Pos: options::OPT_fblocks, Neg: options::OPT_fno_blocks,
7148 Default: TC.IsBlocksDefault()) ||
7149 (Args.hasArg(Ids: options::OPT_fgnu_runtime) &&
7150 Args.hasArg(Ids: options::OPT_fobjc_nonfragile_abi) &&
7151 !Args.hasArg(Ids: options::OPT_fno_blocks))) {
7152 CmdArgs.push_back(Elt: "-fblocks");
7153
7154 if (!Args.hasArg(Ids: options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7155 CmdArgs.push_back(Elt: "-fblocks-runtime-optional");
7156 }
7157
7158 // -fencode-extended-block-signature=1 is default.
7159 if (TC.IsEncodeExtendedBlockSignatureDefault())
7160 CmdArgs.push_back(Elt: "-fencode-extended-block-signature");
7161
7162 if (Args.hasFlag(Pos: options::OPT_fcoro_aligned_allocation,
7163 Neg: options::OPT_fno_coro_aligned_allocation, Default: false) &&
7164 types::isCXX(Id: InputType))
7165 CmdArgs.push_back(Elt: "-fcoro-aligned-allocation");
7166
7167 if (Args.hasFlag(Pos: options::OPT_fdefer_ts, Neg: options::OPT_fno_defer_ts,
7168 /*Default=*/false))
7169 CmdArgs.push_back(Elt: "-fdefer-ts");
7170
7171 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdouble_square_bracket_attributes,
7172 Ids: options::OPT_fno_double_square_bracket_attributes);
7173
7174 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_faccess_control,
7175 Neg: options::OPT_fno_access_control);
7176 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_felide_constructors,
7177 Neg: options::OPT_fno_elide_constructors);
7178
7179 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7180
7181 if (KernelOrKext || (types::isCXX(Id: InputType) &&
7182 (RTTIMode == ToolChain::RM_Disabled)))
7183 CmdArgs.push_back(Elt: "-fno-rtti");
7184
7185 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7186 if (Args.hasFlag(Pos: options::OPT_fshort_enums, Neg: options::OPT_fno_short_enums,
7187 Default: TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7188 CmdArgs.push_back(Elt: "-fshort-enums");
7189
7190 RenderCharacterOptions(Args, T: AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7191
7192 // -fuse-cxa-atexit is default.
7193 if (!Args.hasFlag(
7194 Pos: options::OPT_fuse_cxa_atexit, Neg: options::OPT_fno_use_cxa_atexit,
7195 Default: !RawTriple.isOSAIX() &&
7196 (!RawTriple.isOSWindows() ||
7197 RawTriple.isWindowsCygwinEnvironment()) &&
7198 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7199 RawTriple.hasEnvironment())) ||
7200 KernelOrKext)
7201 CmdArgs.push_back(Elt: "-fno-use-cxa-atexit");
7202
7203 if (Args.hasFlag(Pos: options::OPT_fregister_global_dtors_with_atexit,
7204 Neg: options::OPT_fno_register_global_dtors_with_atexit,
7205 Default: RawTriple.isOSDarwin() && !KernelOrKext))
7206 CmdArgs.push_back(Elt: "-fregister-global-dtors-with-atexit");
7207
7208 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fuse_line_directives,
7209 Neg: options::OPT_fno_use_line_directives);
7210
7211 // -fno-minimize-whitespace is default.
7212 if (Args.hasFlag(Pos: options::OPT_fminimize_whitespace,
7213 Neg: options::OPT_fno_minimize_whitespace, Default: false)) {
7214 types::ID InputType = Inputs[0].getType();
7215 if (!isDerivedFromC(Id: InputType))
7216 D.Diag(DiagID: diag::err_drv_opt_unsupported_input_type)
7217 << "-fminimize-whitespace" << types::getTypeName(Id: InputType);
7218 CmdArgs.push_back(Elt: "-fminimize-whitespace");
7219 }
7220
7221 // -fno-keep-system-includes is default.
7222 if (Args.hasFlag(Pos: options::OPT_fkeep_system_includes,
7223 Neg: options::OPT_fno_keep_system_includes, Default: false)) {
7224 types::ID InputType = Inputs[0].getType();
7225 if (!isDerivedFromC(Id: InputType))
7226 D.Diag(DiagID: diag::err_drv_opt_unsupported_input_type)
7227 << "-fkeep-system-includes" << types::getTypeName(Id: InputType);
7228 CmdArgs.push_back(Elt: "-fkeep-system-includes");
7229 }
7230
7231 // -fms-extensions=0 is default.
7232 if (Args.hasFlag(Pos: options::OPT_fms_extensions, Neg: options::OPT_fno_ms_extensions,
7233 Default: IsWindowsMSVC || IsUEFI))
7234 CmdArgs.push_back(Elt: "-fms-extensions");
7235
7236 // -fms-compatibility=0 is default.
7237 bool IsMSVCCompat = Args.hasFlag(
7238 Pos: options::OPT_fms_compatibility, Neg: options::OPT_fno_ms_compatibility,
7239 Default: (IsWindowsMSVC && Args.hasFlag(Pos: options::OPT_fms_extensions,
7240 Neg: options::OPT_fno_ms_extensions, Default: true)));
7241 if (IsMSVCCompat) {
7242 CmdArgs.push_back(Elt: "-fms-compatibility");
7243 if (!types::isCXX(Id: Input.getType()) &&
7244 Args.hasArg(Ids: options::OPT_fms_define_stdc))
7245 CmdArgs.push_back(Elt: "-fms-define-stdc");
7246 }
7247
7248 // -fms-anonymous-structs is disabled by default.
7249 // Determine whether to enable Microsoft named anonymous struct/union support.
7250 // This implements "last flag wins" semantics for -fms-anonymous-structs,
7251 // where the feature can be:
7252 // - Explicitly enabled via -fms-anonymous-structs.
7253 // - Explicitly disabled via fno-ms-anonymous-structs
7254 // - Implicitly enabled via -fms-extensions or -fms-compatibility
7255 // - Implicitly disabled via -fno-ms-extensions or -fno-ms-compatibility
7256 //
7257 // When multiple relevent options are present, the last option on the command
7258 // line takes precedence. This allows users to selectively override implicit
7259 // enablement. Examples:
7260 // -fms-extensions -fno-ms-anonymous-structs -> disabled (explicit override)
7261 // -fno-ms-anonymous-structs -fms-extensions -> enabled (last flag wins)
7262 auto MSAnonymousStructsOptionToUseOrNull =
7263 [](const ArgList &Args) -> const char * {
7264 const char *Option = nullptr;
7265 constexpr const char *Enable = "-fms-anonymous-structs";
7266 constexpr const char *Disable = "-fno-ms-anonymous-structs";
7267
7268 // Iterate through all arguments in order to implement "last flag wins".
7269 for (const Arg *A : Args) {
7270 switch (A->getOption().getID()) {
7271 case options::OPT_fms_anonymous_structs:
7272 A->claim();
7273 Option = Enable;
7274 break;
7275 case options::OPT_fno_ms_anonymous_structs:
7276 A->claim();
7277 Option = Disable;
7278 break;
7279 // Each of -fms-extensions and -fms-compatibility implicitly enables the
7280 // feature.
7281 case options::OPT_fms_extensions:
7282 case options::OPT_fms_compatibility:
7283 Option = Enable;
7284 break;
7285 // Each of -fno-ms-extensions and -fno-ms-compatibility implicitly
7286 // disables the feature.
7287 case options::OPT_fno_ms_extensions:
7288 case options::OPT_fno_ms_compatibility:
7289 Option = Disable;
7290 break;
7291 default:
7292 break;
7293 }
7294 }
7295 return Option;
7296 };
7297
7298 // Only pass a flag to CC1 if a relevant option was seen
7299 if (auto MSAnonOpt = MSAnonymousStructsOptionToUseOrNull(Args))
7300 CmdArgs.push_back(Elt: MSAnonOpt);
7301
7302 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7303 Args.hasArg(Ids: options::OPT_fms_runtime_lib_EQ))
7304 ProcessVSRuntimeLibrary(TC: getToolChain(), Args, CmdArgs);
7305
7306 // Handle -fgcc-version, if present.
7307 VersionTuple GNUCVer;
7308 if (Arg *A = Args.getLastArg(Ids: options::OPT_fgnuc_version_EQ)) {
7309 // Check that the version has 1 to 3 components and the minor and patch
7310 // versions fit in two decimal digits.
7311 StringRef Val = A->getValue();
7312 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7313 bool Invalid = GNUCVer.tryParse(string: Val);
7314 unsigned Minor = GNUCVer.getMinor().value_or(u: 0);
7315 unsigned Patch = GNUCVer.getSubminor().value_or(u: 0);
7316 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7317 D.Diag(DiagID: diag::err_drv_invalid_value)
7318 << A->getAsString(Args) << A->getValue();
7319 }
7320 } else if (!IsMSVCCompat) {
7321 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7322 GNUCVer = VersionTuple(4, 2, 1);
7323 }
7324 if (!GNUCVer.empty()) {
7325 CmdArgs.push_back(
7326 Elt: Args.MakeArgString(Str: "-fgnuc-version=" + GNUCVer.getAsString()));
7327 }
7328
7329 VersionTuple MSVT = TC.computeMSVCVersion(D: &D, Args);
7330 if (!MSVT.empty())
7331 CmdArgs.push_back(
7332 Elt: Args.MakeArgString(Str: "-fms-compatibility-version=" + MSVT.getAsString()));
7333
7334 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7335 if (ImplyVCPPCVer) {
7336 StringRef LanguageStandard;
7337 if (const Arg *StdArg = Args.getLastArg(Ids: options::OPT__SLASH_std)) {
7338 Std = StdArg;
7339 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7340 .Case(S: "c11", Value: "-std=c11")
7341 .Case(S: "c17", Value: "-std=c17")
7342 // If you add cases below for spellings that are
7343 // not in LangStandards.def, update
7344 // TransferableCommand::tryParseStdArg() in
7345 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7346 // to match.
7347 // TODO: add c23 when MSVC supports it.
7348 .Case(S: "clatest", Value: "-std=c23")
7349 .Default(Value: "");
7350 if (LanguageStandard.empty())
7351 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
7352 << StdArg->getAsString(Args);
7353 }
7354 CmdArgs.push_back(Elt: LanguageStandard.data());
7355 }
7356 if (ImplyVCPPCXXVer) {
7357 StringRef LanguageStandard;
7358 if (const Arg *StdArg = Args.getLastArg(Ids: options::OPT__SLASH_std)) {
7359 Std = StdArg;
7360 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7361 .Case(S: "c++14", Value: "-std=c++14")
7362 .Case(S: "c++17", Value: "-std=c++17")
7363 .Case(S: "c++20", Value: "-std=c++20")
7364 // If you add cases below for spellings that are
7365 // not in LangStandards.def, update
7366 // TransferableCommand::tryParseStdArg() in
7367 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7368 // to match.
7369 // TODO add c++23 and c++26 when MSVC supports it.
7370 .Case(S: "c++23preview", Value: "-std=c++23")
7371 .Case(S: "c++latest", Value: "-std=c++26")
7372 .Default(Value: "");
7373 if (LanguageStandard.empty())
7374 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
7375 << StdArg->getAsString(Args);
7376 }
7377
7378 if (LanguageStandard.empty()) {
7379 if (IsMSVC2015Compatible)
7380 LanguageStandard = "-std=c++14";
7381 else
7382 LanguageStandard = "-std=c++11";
7383 }
7384
7385 CmdArgs.push_back(Elt: LanguageStandard.data());
7386 }
7387
7388 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fborland_extensions,
7389 Neg: options::OPT_fno_borland_extensions);
7390
7391 // -fno-declspec is default, except for PS4/PS5.
7392 if (Args.hasFlag(Pos: options::OPT_fdeclspec, Neg: options::OPT_fno_declspec,
7393 Default: RawTriple.isPS()))
7394 CmdArgs.push_back(Elt: "-fdeclspec");
7395 else if (Args.hasArg(Ids: options::OPT_fno_declspec))
7396 CmdArgs.push_back(Elt: "-fno-declspec"); // Explicitly disabling __declspec.
7397
7398 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7399 // than 19.
7400 if (!Args.hasFlag(Pos: options::OPT_fthreadsafe_statics,
7401 Neg: options::OPT_fno_threadsafe_statics,
7402 Default: !types::isOpenCL(Id: InputType) &&
7403 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7404 CmdArgs.push_back(Elt: "-fno-threadsafe-statics");
7405
7406 if (!Args.hasFlag(Pos: options::OPT_fms_tls_guards, Neg: options::OPT_fno_ms_tls_guards,
7407 Default: true))
7408 CmdArgs.push_back(Elt: "-fno-ms-tls-guards");
7409
7410 // Add -fno-assumptions, if it was specified.
7411 if (!Args.hasFlag(Pos: options::OPT_fassumptions, Neg: options::OPT_fno_assumptions,
7412 Default: true))
7413 CmdArgs.push_back(Elt: "-fno-assumptions");
7414
7415 // -fgnu-keywords default varies depending on language; only pass if
7416 // specified.
7417 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fgnu_keywords,
7418 Ids: options::OPT_fno_gnu_keywords);
7419
7420 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgnu89_inline,
7421 Neg: options::OPT_fno_gnu89_inline);
7422
7423 const Arg *InlineArg = Args.getLastArg(Ids: options::OPT_finline_functions,
7424 Ids: options::OPT_finline_hint_functions,
7425 Ids: options::OPT_fno_inline_functions);
7426 if (Arg *A = Args.getLastArg(Ids: options::OPT_finline, Ids: options::OPT_fno_inline)) {
7427 if (A->getOption().matches(ID: options::OPT_fno_inline))
7428 A->render(Args, Output&: CmdArgs);
7429 } else if (InlineArg) {
7430 InlineArg->render(Args, Output&: CmdArgs);
7431 }
7432
7433 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_finline_max_stacksize_EQ);
7434
7435 // FIXME: Find a better way to determine whether we are in C++20.
7436 bool HaveCxx20 =
7437 Std &&
7438 (Std->containsValue(Value: "c++2a") || Std->containsValue(Value: "gnu++2a") ||
7439 Std->containsValue(Value: "c++20") || Std->containsValue(Value: "gnu++20") ||
7440 Std->containsValue(Value: "c++2b") || Std->containsValue(Value: "gnu++2b") ||
7441 Std->containsValue(Value: "c++23") || Std->containsValue(Value: "gnu++23") ||
7442 Std->containsValue(Value: "c++23preview") || Std->containsValue(Value: "c++2c") ||
7443 Std->containsValue(Value: "gnu++2c") || Std->containsValue(Value: "c++26") ||
7444 Std->containsValue(Value: "gnu++26") || Std->containsValue(Value: "c++latest") ||
7445 Std->containsValue(Value: "gnu++latest"));
7446 bool HaveModules =
7447 RenderModulesOptions(C, D, Args, Input, Output, HaveStd20: HaveCxx20, CmdArgs);
7448
7449 // -fdelayed-template-parsing is default when targeting MSVC.
7450 // Many old Windows SDK versions require this to parse.
7451 //
7452 // According to
7453 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7454 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7455 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7456 // not enable -fdelayed-template-parsing by default after C++20.
7457 //
7458 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7459 // able to disable this by default at some point.
7460 if (Args.hasFlag(Pos: options::OPT_fdelayed_template_parsing,
7461 Neg: options::OPT_fno_delayed_template_parsing,
7462 Default: IsWindowsMSVC && !HaveCxx20)) {
7463 if (HaveCxx20)
7464 D.Diag(DiagID: clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7465
7466 CmdArgs.push_back(Elt: "-fdelayed-template-parsing");
7467 }
7468
7469 if (Args.hasFlag(Pos: options::OPT_fpch_validate_input_files_content,
7470 Neg: options::OPT_fno_pch_validate_input_files_content, Default: false))
7471 CmdArgs.push_back(Elt: "-fvalidate-ast-input-files-content");
7472 if (Args.hasFlag(Pos: options::OPT_fpch_instantiate_templates,
7473 Neg: options::OPT_fno_pch_instantiate_templates, Default: false))
7474 CmdArgs.push_back(Elt: "-fpch-instantiate-templates");
7475 if (Args.hasFlag(Pos: options::OPT_fpch_codegen, Neg: options::OPT_fno_pch_codegen,
7476 Default: false))
7477 CmdArgs.push_back(Elt: "-fmodules-codegen");
7478 if (Args.hasFlag(Pos: options::OPT_fpch_debuginfo, Neg: options::OPT_fno_pch_debuginfo,
7479 Default: false))
7480 CmdArgs.push_back(Elt: "-fmodules-debuginfo");
7481
7482 ObjCRuntime Runtime = AddObjCRuntimeArgs(args: Args, inputs: Inputs, cmdArgs&: CmdArgs, rewrite: rewriteKind);
7483 RenderObjCOptions(TC, D, T: RawTriple, Args, Runtime, InferCovariantReturns: rewriteKind != RK_None,
7484 Input, CmdArgs);
7485
7486 if (types::isObjC(Id: Input.getType()) &&
7487 Args.hasFlag(Pos: options::OPT_fobjc_encode_cxx_class_template_spec,
7488 Neg: options::OPT_fno_objc_encode_cxx_class_template_spec,
7489 Default: !Runtime.isNeXTFamily()))
7490 CmdArgs.push_back(Elt: "-fobjc-encode-cxx-class-template-spec");
7491
7492 if (Args.hasFlag(Pos: options::OPT_fapplication_extension,
7493 Neg: options::OPT_fno_application_extension, Default: false))
7494 CmdArgs.push_back(Elt: "-fapplication-extension");
7495
7496 // Handle GCC-style exception args.
7497 bool EH = false;
7498 if (!C.getDriver().IsCLMode())
7499 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, objcRuntime: Runtime, CmdArgs);
7500
7501 // Handle exception personalities
7502 Arg *A = Args.getLastArg(
7503 Ids: options::OPT_fsjlj_exceptions, Ids: options::OPT_fseh_exceptions,
7504 Ids: options::OPT_fdwarf_exceptions, Ids: options::OPT_fwasm_exceptions);
7505 if (A) {
7506 const Option &Opt = A->getOption();
7507 if (Opt.matches(ID: options::OPT_fsjlj_exceptions))
7508 CmdArgs.push_back(Elt: "-exception-model=sjlj");
7509 if (Opt.matches(ID: options::OPT_fseh_exceptions))
7510 CmdArgs.push_back(Elt: "-exception-model=seh");
7511 if (Opt.matches(ID: options::OPT_fdwarf_exceptions))
7512 CmdArgs.push_back(Elt: "-exception-model=dwarf");
7513 if (Opt.matches(ID: options::OPT_fwasm_exceptions))
7514 CmdArgs.push_back(Elt: "-exception-model=wasm");
7515 } else {
7516 switch (TC.GetExceptionModel(Args)) {
7517 default:
7518 break;
7519 case llvm::ExceptionHandling::DwarfCFI:
7520 CmdArgs.push_back(Elt: "-exception-model=dwarf");
7521 break;
7522 case llvm::ExceptionHandling::SjLj:
7523 CmdArgs.push_back(Elt: "-exception-model=sjlj");
7524 break;
7525 case llvm::ExceptionHandling::WinEH:
7526 CmdArgs.push_back(Elt: "-exception-model=seh");
7527 break;
7528 }
7529 }
7530
7531 // Unwind v2 (epilog) information for x64 Windows.
7532 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_winx64_eh_unwindv2);
7533
7534 // C++ "sane" operator new.
7535 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_sane_operator_new,
7536 Neg: options::OPT_fno_assume_sane_operator_new);
7537
7538 // -fassume-unique-vtables is on by default.
7539 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_unique_vtables,
7540 Neg: options::OPT_fno_assume_unique_vtables);
7541
7542 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
7543 // by default.
7544 Args.addLastArg(Output&: CmdArgs, Ids: options::OPT_fsized_deallocation,
7545 Ids: options::OPT_fno_sized_deallocation);
7546
7547 // -faligned-allocation is on by default in C++17 onwards and otherwise off
7548 // by default.
7549 if (Arg *A = Args.getLastArg(Ids: options::OPT_faligned_allocation,
7550 Ids: options::OPT_fno_aligned_allocation,
7551 Ids: options::OPT_faligned_new_EQ)) {
7552 if (A->getOption().matches(ID: options::OPT_fno_aligned_allocation))
7553 CmdArgs.push_back(Elt: "-fno-aligned-allocation");
7554 else
7555 CmdArgs.push_back(Elt: "-faligned-allocation");
7556 }
7557
7558 // The default new alignment can be specified using a dedicated option or via
7559 // a GCC-compatible option that also turns on aligned allocation.
7560 if (Arg *A = Args.getLastArg(Ids: options::OPT_fnew_alignment_EQ,
7561 Ids: options::OPT_faligned_new_EQ))
7562 CmdArgs.push_back(
7563 Elt: Args.MakeArgString(Str: Twine("-fnew-alignment=") + A->getValue()));
7564
7565 // -fconstant-cfstrings is default, and may be subject to argument translation
7566 // on Darwin.
7567 if (!Args.hasFlag(Pos: options::OPT_fconstant_cfstrings,
7568 Neg: options::OPT_fno_constant_cfstrings, Default: true) ||
7569 !Args.hasFlag(Pos: options::OPT_mconstant_cfstrings,
7570 Neg: options::OPT_mno_constant_cfstrings, Default: true))
7571 CmdArgs.push_back(Elt: "-fno-constant-cfstrings");
7572
7573 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fpascal_strings,
7574 Neg: options::OPT_fno_pascal_strings);
7575
7576 // Honor -fpack-struct= and -fpack-struct, if given. Note that
7577 // -fno-pack-struct doesn't apply to -fpack-struct=.
7578 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpack_struct_EQ)) {
7579 std::string PackStructStr = "-fpack-struct=";
7580 PackStructStr += A->getValue();
7581 CmdArgs.push_back(Elt: Args.MakeArgString(Str: PackStructStr));
7582 } else if (Args.hasFlag(Pos: options::OPT_fpack_struct,
7583 Neg: options::OPT_fno_pack_struct, Default: false)) {
7584 CmdArgs.push_back(Elt: "-fpack-struct=1");
7585 }
7586
7587 // Handle -fmax-type-align=N and -fno-type-align
7588 bool SkipMaxTypeAlign = Args.hasArg(Ids: options::OPT_fno_max_type_align);
7589 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmax_type_align_EQ)) {
7590 if (!SkipMaxTypeAlign) {
7591 std::string MaxTypeAlignStr = "-fmax-type-align=";
7592 MaxTypeAlignStr += A->getValue();
7593 CmdArgs.push_back(Elt: Args.MakeArgString(Str: MaxTypeAlignStr));
7594 }
7595 } else if (RawTriple.isOSDarwin()) {
7596 if (!SkipMaxTypeAlign) {
7597 std::string MaxTypeAlignStr = "-fmax-type-align=16";
7598 CmdArgs.push_back(Elt: Args.MakeArgString(Str: MaxTypeAlignStr));
7599 }
7600 }
7601
7602 if (!Args.hasFlag(Pos: options::OPT_Qy, Neg: options::OPT_Qn, Default: true))
7603 CmdArgs.push_back(Elt: "-Qn");
7604
7605 // -fno-common is the default, set -fcommon only when that flag is set.
7606 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcommon, Neg: options::OPT_fno_common);
7607
7608 // -fsigned-bitfields is default, and clang doesn't yet support
7609 // -funsigned-bitfields.
7610 if (!Args.hasFlag(Pos: options::OPT_fsigned_bitfields,
7611 Neg: options::OPT_funsigned_bitfields, Default: true))
7612 D.Diag(DiagID: diag::warn_drv_clang_unsupported)
7613 << Args.getLastArg(Ids: options::OPT_funsigned_bitfields)->getAsString(Args);
7614
7615 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
7616 if (!Args.hasFlag(Pos: options::OPT_ffor_scope, Neg: options::OPT_fno_for_scope, Default: true))
7617 D.Diag(DiagID: diag::err_drv_clang_unsupported)
7618 << Args.getLastArg(Ids: options::OPT_fno_for_scope)->getAsString(Args);
7619
7620 // -finput_charset=UTF-8 is default. Reject others
7621 if (Arg *inputCharset = Args.getLastArg(Ids: options::OPT_finput_charset_EQ)) {
7622 StringRef value = inputCharset->getValue();
7623 if (!value.equals_insensitive(RHS: "utf-8"))
7624 D.Diag(DiagID: diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
7625 << value;
7626 }
7627
7628 // -fexec_charset=UTF-8 is default. Reject others
7629 if (Arg *execCharset = Args.getLastArg(Ids: options::OPT_fexec_charset_EQ)) {
7630 StringRef value = execCharset->getValue();
7631 if (!value.equals_insensitive(RHS: "utf-8"))
7632 D.Diag(DiagID: diag::err_drv_invalid_value) << execCharset->getAsString(Args)
7633 << value;
7634 }
7635
7636 RenderDiagnosticsOptions(D, Args, CmdArgs);
7637
7638 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fasm_blocks,
7639 Neg: options::OPT_fno_asm_blocks);
7640
7641 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fgnu_inline_asm,
7642 Neg: options::OPT_fno_gnu_inline_asm);
7643
7644 handleVectorizeLoopsArgs(Args, CmdArgs);
7645 handleVectorizeSLPArgs(Args, CmdArgs);
7646
7647 StringRef VecWidth = parseMPreferVectorWidthOption(Diags&: D.getDiags(), Args);
7648 if (!VecWidth.empty())
7649 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mprefer-vector-width=" + VecWidth));
7650
7651 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fshow_overloads_EQ);
7652 Args.AddLastArg(Output&: CmdArgs,
7653 Ids: options::OPT_fsanitize_undefined_strip_path_components_EQ);
7654
7655 // -fdollars-in-identifiers default varies depending on platform and
7656 // language; only pass if specified.
7657 if (Arg *A = Args.getLastArg(Ids: options::OPT_fdollars_in_identifiers,
7658 Ids: options::OPT_fno_dollars_in_identifiers)) {
7659 if (A->getOption().matches(ID: options::OPT_fdollars_in_identifiers))
7660 CmdArgs.push_back(Elt: "-fdollars-in-identifiers");
7661 else
7662 CmdArgs.push_back(Elt: "-fno-dollars-in-identifiers");
7663 }
7664
7665 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fapple_pragma_pack,
7666 Neg: options::OPT_fno_apple_pragma_pack);
7667
7668 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
7669 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
7670 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
7671
7672 bool RewriteImports = Args.hasFlag(Pos: options::OPT_frewrite_imports,
7673 Neg: options::OPT_fno_rewrite_imports, Default: false);
7674 if (RewriteImports)
7675 CmdArgs.push_back(Elt: "-frewrite-imports");
7676
7677 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdirectives_only,
7678 Neg: options::OPT_fno_directives_only);
7679
7680 // Enable rewrite includes if the user's asked for it or if we're generating
7681 // diagnostics.
7682 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
7683 // nice to enable this when doing a crashdump for modules as well.
7684 if (Args.hasFlag(Pos: options::OPT_frewrite_includes,
7685 Neg: options::OPT_fno_rewrite_includes, Default: false) ||
7686 (C.isForDiagnostics() && !HaveModules))
7687 CmdArgs.push_back(Elt: "-frewrite-includes");
7688
7689 if (Args.hasFlag(Pos: options::OPT_fzos_extensions,
7690 Neg: options::OPT_fno_zos_extensions, Default: false))
7691 CmdArgs.push_back(Elt: "-fzos-extensions");
7692 else if (Args.hasArg(Ids: options::OPT_fno_zos_extensions))
7693 CmdArgs.push_back(Elt: "-fno-zos-extensions");
7694
7695 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
7696 if (Arg *A = Args.getLastArg(Ids: options::OPT_traditional,
7697 Ids: options::OPT_traditional_cpp)) {
7698 if (isa<PreprocessJobAction>(Val: JA))
7699 CmdArgs.push_back(Elt: "-traditional-cpp");
7700 else
7701 D.Diag(DiagID: diag::err_drv_clang_unsupported) << A->getAsString(Args);
7702 }
7703
7704 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dM);
7705 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dD);
7706 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dI);
7707
7708 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmax_tokens_EQ);
7709
7710 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_extract_summaries);
7711 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT__ssaf_tu_summary_file);
7712
7713 // Handle serialized diagnostics.
7714 if (Arg *A = Args.getLastArg(Ids: options::OPT__serialize_diags)) {
7715 CmdArgs.push_back(Elt: "-serialize-diagnostic-file");
7716 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getValue()));
7717 }
7718
7719 if (Args.hasArg(Ids: options::OPT_fretain_comments_from_system_headers))
7720 CmdArgs.push_back(Elt: "-fretain-comments-from-system-headers");
7721
7722 if (Arg *A = Args.getLastArg(Ids: options::OPT_fextend_variable_liveness_EQ)) {
7723 A->render(Args, Output&: CmdArgs);
7724 } else if (Arg *A = Args.getLastArg(Ids: options::OPT_O_Group);
7725 A && A->containsValue(Value: "g")) {
7726 // Set -fextend-variable-liveness=all by default at -Og.
7727 CmdArgs.push_back(Elt: "-fextend-variable-liveness=all");
7728 }
7729
7730 // Forward -fcomment-block-commands to -cc1.
7731 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fcomment_block_commands);
7732 // Forward -fparse-all-comments to -cc1.
7733 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fparse_all_comments);
7734
7735 // Turn -fplugin=name.so into -load name.so
7736 for (const Arg *A : Args.filtered(Ids: options::OPT_fplugin_EQ)) {
7737 CmdArgs.push_back(Elt: "-load");
7738 CmdArgs.push_back(Elt: A->getValue());
7739 A->claim();
7740 }
7741
7742 // Turn -fplugin-arg-pluginname-key=value into
7743 // -plugin-arg-pluginname key=value
7744 // GCC has an actual plugin_argument struct with key/value pairs that it
7745 // passes to its plugins, but we don't, so just pass it on as-is.
7746 //
7747 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
7748 // argument key are allowed to contain dashes. GCC therefore only
7749 // allows dashes in the key. We do the same.
7750 for (const Arg *A : Args.filtered(Ids: options::OPT_fplugin_arg)) {
7751 auto ArgValue = StringRef(A->getValue());
7752 auto FirstDashIndex = ArgValue.find(C: '-');
7753 StringRef PluginName = ArgValue.substr(Start: 0, N: FirstDashIndex);
7754 StringRef Arg = ArgValue.substr(Start: FirstDashIndex + 1);
7755
7756 A->claim();
7757 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
7758 if (PluginName.empty()) {
7759 D.Diag(DiagID: diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
7760 } else {
7761 D.Diag(DiagID: diag::warn_drv_missing_plugin_arg)
7762 << PluginName << A->getAsString(Args);
7763 }
7764 continue;
7765 }
7766
7767 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-plugin-arg-") + PluginName));
7768 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Arg));
7769 }
7770
7771 // Forward -fpass-plugin=name.so to -cc1.
7772 for (const Arg *A : Args.filtered(Ids: options::OPT_fpass_plugin_EQ)) {
7773 CmdArgs.push_back(
7774 Elt: Args.MakeArgString(Str: Twine("-fpass-plugin=") + A->getValue()));
7775 A->claim();
7776 }
7777
7778 // Forward --vfsoverlay to -cc1.
7779 for (const Arg *A : Args.filtered(Ids: options::OPT_vfsoverlay)) {
7780 CmdArgs.push_back(Elt: "--vfsoverlay");
7781 CmdArgs.push_back(Elt: A->getValue());
7782 A->claim();
7783 }
7784
7785 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fsafe_buffer_usage_suggestions,
7786 Neg: options::OPT_fno_safe_buffer_usage_suggestions);
7787
7788 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_late_parse_attributes,
7789 Neg: options::OPT_fno_experimental_late_parse_attributes);
7790
7791 if (Args.hasFlag(Pos: options::OPT_funique_source_file_names,
7792 Neg: options::OPT_fno_unique_source_file_names, Default: false)) {
7793 if (Arg *A = Args.getLastArg(Ids: options::OPT_unique_source_file_identifier_EQ))
7794 A->render(Args, Output&: CmdArgs);
7795 else
7796 CmdArgs.push_back(Elt: Args.MakeArgString(
7797 Str: Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
7798 }
7799
7800 if (Args.hasFlag(
7801 Pos: options::OPT_fexperimental_allow_pointer_field_protection_attr,
7802 Neg: options::OPT_fno_experimental_allow_pointer_field_protection_attr,
7803 Default: false) ||
7804 Args.hasFlag(Pos: options::OPT_fexperimental_pointer_field_protection_abi,
7805 Neg: options::OPT_fno_experimental_pointer_field_protection_abi,
7806 Default: false))
7807 CmdArgs.push_back(Elt: "-fexperimental-allow-pointer-field-protection-attr");
7808
7809 if (!IsCudaDevice) {
7810 Args.addOptInFlag(
7811 Output&: CmdArgs, Pos: options::OPT_fexperimental_pointer_field_protection_abi,
7812 Neg: options::OPT_fno_experimental_pointer_field_protection_abi);
7813 Args.addOptInFlag(
7814 Output&: CmdArgs, Pos: options::OPT_fexperimental_pointer_field_protection_tagged,
7815 Neg: options::OPT_fno_experimental_pointer_field_protection_tagged);
7816 }
7817
7818 // Setup statistics file output.
7819 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
7820 if (!StatsFile.empty()) {
7821 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-stats-file=") + StatsFile));
7822 if (D.CCPrintInternalStats)
7823 CmdArgs.push_back(Elt: "-stats-file-append");
7824 }
7825
7826 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
7827 // parser.
7828 for (auto Arg : Args.filtered(Ids: options::OPT_Xclang)) {
7829 Arg->claim();
7830 // -finclude-default-header flag is for preprocessor,
7831 // do not pass it to other cc1 commands when save-temps is enabled
7832 if (C.getDriver().isSaveTempsEnabled() &&
7833 !isa<PreprocessJobAction>(Val: JA)) {
7834 if (StringRef(Arg->getValue()) == "-finclude-default-header")
7835 continue;
7836 }
7837 CmdArgs.push_back(Elt: Arg->getValue());
7838 }
7839 for (const Arg *A : Args.filtered(Ids: options::OPT_mllvm)) {
7840 A->claim();
7841
7842 // We translate this by hand to the -cc1 argument, since nightly test uses
7843 // it and developers have been trained to spell it with -mllvm. Both
7844 // spellings are now deprecated and should be removed.
7845 if (StringRef(A->getValue(N: 0)) == "-disable-llvm-optzns") {
7846 CmdArgs.push_back(Elt: "-disable-llvm-optzns");
7847 } else {
7848 A->render(Args, Output&: CmdArgs);
7849 }
7850 }
7851
7852 // This needs to run after -Xclang argument forwarding to pick up the target
7853 // features enabled through -Xclang -target-feature flags.
7854 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
7855
7856 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_falloc_token_max_EQ);
7857
7858#if CLANG_ENABLE_CIR
7859 // Forward -mmlir arguments to to the MLIR option parser.
7860 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
7861 A->claim();
7862 A->render(Args, CmdArgs);
7863 }
7864#endif // CLANG_ENABLE_CIR
7865
7866 // With -save-temps, we want to save the unoptimized bitcode output from the
7867 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
7868 // by the frontend.
7869 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
7870 // has slightly different breakdown between stages.
7871 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
7872 // pristine IR generated by the frontend. Ideally, a new compile action should
7873 // be added so both IR can be captured.
7874 if ((C.getDriver().isSaveTempsEnabled() ||
7875 JA.isHostOffloading(OKind: Action::OFK_OpenMP)) &&
7876 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
7877 isa<CompileJobAction>(Val: JA))
7878 CmdArgs.push_back(Elt: "-disable-llvm-passes");
7879
7880 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_undef);
7881
7882 const char *Exec = D.getClangProgramPath();
7883
7884 // Optionally embed the -cc1 level arguments into the debug info or a
7885 // section, for build analysis.
7886 // Also record command line arguments into the debug info if
7887 // -grecord-gcc-switches options is set on.
7888 // By default, -gno-record-gcc-switches is set on and no recording.
7889 auto GRecordSwitches = false;
7890 auto FRecordSwitches = false;
7891 if (shouldRecordCommandLine(TC, Args, FRecordCommandLine&: FRecordSwitches, GRecordCommandLine&: GRecordSwitches)) {
7892 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
7893 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
7894 CmdArgs.push_back(Elt: "-dwarf-debug-flags");
7895 CmdArgs.push_back(Elt: FlagsArgString);
7896 }
7897 if (FRecordSwitches) {
7898 CmdArgs.push_back(Elt: "-record-command-line");
7899 CmdArgs.push_back(Elt: FlagsArgString);
7900 }
7901 }
7902
7903 // Host-side offloading compilation receives all device-side outputs. Include
7904 // them in the host compilation depending on the target. If the host inputs
7905 // are not empty we use the new-driver scheme, otherwise use the old scheme.
7906 if ((IsCuda || IsHIP) && CudaDeviceInput) {
7907 CmdArgs.push_back(Elt: "-fcuda-include-gpubinary");
7908 CmdArgs.push_back(Elt: CudaDeviceInput->getFilename());
7909 } else if (!HostOffloadingInputs.empty()) {
7910 if ((IsCuda || IsHIP) && !IsRDCMode) {
7911 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
7912 CmdArgs.push_back(Elt: "-fcuda-include-gpubinary");
7913 CmdArgs.push_back(Elt: HostOffloadingInputs.front().getFilename());
7914 } else {
7915 for (const InputInfo Input : HostOffloadingInputs)
7916 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fembed-offload-object=" +
7917 TC.getInputFilename(Input)));
7918 }
7919 }
7920
7921 if (IsCuda) {
7922 if (Args.hasFlag(Pos: options::OPT_fcuda_short_ptr,
7923 Neg: options::OPT_fno_cuda_short_ptr, Default: false))
7924 CmdArgs.push_back(Elt: "-fcuda-short-ptr");
7925 }
7926
7927 if (IsCuda || IsHIP) {
7928 // Determine the original source input.
7929 const Action *SourceAction = &JA;
7930 while (SourceAction->getKind() != Action::InputClass) {
7931 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7932 SourceAction = SourceAction->getInputs()[0];
7933 }
7934 auto CUID = cast<InputAction>(Val: SourceAction)->getId();
7935 if (!CUID.empty())
7936 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-cuid=") + Twine(CUID)));
7937
7938 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
7939 // be overriden by -fno-gpu-approx-transcendentals.
7940 bool UseApproxTranscendentals = Args.hasFlag(
7941 Pos: options::OPT_ffast_math, Neg: options::OPT_fno_fast_math, Default: false);
7942 if (Args.hasFlag(Pos: options::OPT_fgpu_approx_transcendentals,
7943 Neg: options::OPT_fno_gpu_approx_transcendentals,
7944 Default: UseApproxTranscendentals))
7945 CmdArgs.push_back(Elt: "-fgpu-approx-transcendentals");
7946 } else {
7947 Args.claimAllArgs(Ids: options::OPT_fgpu_approx_transcendentals,
7948 Ids: options::OPT_fno_gpu_approx_transcendentals);
7949 }
7950
7951 if (IsHIP) {
7952 CmdArgs.push_back(Elt: "-fcuda-allow-variadic-functions");
7953 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fgpu_default_stream_EQ);
7954 }
7955
7956 Args.AddAllArgs(Output&: CmdArgs,
7957 Id0: options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
7958
7959 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foffload_uniform_block,
7960 Ids: options::OPT_fno_offload_uniform_block);
7961
7962 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foffload_implicit_host_device_templates,
7963 Ids: options::OPT_fno_offload_implicit_host_device_templates);
7964
7965 if (IsCudaDevice || IsHIPDevice) {
7966 StringRef InlineThresh =
7967 Args.getLastArgValue(Id: options::OPT_fgpu_inline_threshold_EQ);
7968 if (!InlineThresh.empty()) {
7969 std::string ArgStr =
7970 std::string("-inline-threshold=") + InlineThresh.str();
7971 CmdArgs.append(IL: {"-mllvm", Args.MakeArgStringRef(Str: ArgStr)});
7972 }
7973 }
7974
7975 if (IsHIPDevice)
7976 Args.addOptOutFlag(Output&: CmdArgs,
7977 Pos: options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
7978 Neg: options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
7979
7980 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
7981 // to specify the result of the compile phase on the host, so the meaningful
7982 // device declarations can be identified. Also, -fopenmp-is-target-device is
7983 // passed along to tell the frontend that it is generating code for a device,
7984 // so that only the relevant declarations are emitted.
7985 if (IsOpenMPDevice) {
7986 CmdArgs.push_back(Elt: "-fopenmp-is-target-device");
7987 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
7988 if (Args.hasArg(Ids: options::OPT_foffload_via_llvm))
7989 CmdArgs.push_back(Elt: "-fcuda-is-device");
7990
7991 if (OpenMPDeviceInput) {
7992 CmdArgs.push_back(Elt: "-fopenmp-host-ir-file-path");
7993 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OpenMPDeviceInput->getFilename()));
7994 }
7995 }
7996
7997 if (Triple.isAMDGPU()) {
7998 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
7999
8000 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_munsafe_fp_atomics,
8001 Neg: options::OPT_mno_unsafe_fp_atomics);
8002 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_mamdgpu_ieee,
8003 Neg: options::OPT_mno_amdgpu_ieee);
8004 }
8005
8006 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
8007
8008 if (Args.hasFlag(Pos: options::OPT_fdevirtualize_speculatively,
8009 Neg: options::OPT_fno_devirtualize_speculatively,
8010 /*Default value*/ Default: false))
8011 CmdArgs.push_back(Elt: "-fdevirtualize-speculatively");
8012
8013 bool VirtualFunctionElimination =
8014 Args.hasFlag(Pos: options::OPT_fvirtual_function_elimination,
8015 Neg: options::OPT_fno_virtual_function_elimination, Default: false);
8016 if (VirtualFunctionElimination) {
8017 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
8018 // in the future).
8019 if (LTOMode != LTOK_Full)
8020 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
8021 << "-fvirtual-function-elimination"
8022 << "-flto=full";
8023
8024 CmdArgs.push_back(Elt: "-fvirtual-function-elimination");
8025 }
8026
8027 // VFE requires whole-program-vtables, and enables it by default.
8028 bool WholeProgramVTables = Args.hasFlag(
8029 Pos: options::OPT_fwhole_program_vtables,
8030 Neg: options::OPT_fno_whole_program_vtables, Default: VirtualFunctionElimination);
8031 if (VirtualFunctionElimination && !WholeProgramVTables) {
8032 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
8033 << "-fno-whole-program-vtables"
8034 << "-fvirtual-function-elimination";
8035 }
8036
8037 if (WholeProgramVTables) {
8038 // PS4 uses the legacy LTO API, which does not support this feature in
8039 // ThinLTO mode.
8040 bool IsPS4 = getToolChain().getTriple().isPS4();
8041
8042 // Check if we passed LTO options but they were suppressed because this is a
8043 // device offloading action, or we passed device offload LTO options which
8044 // were suppressed because this is not the device offload action.
8045 // Check if we are using PS4 in regular LTO mode.
8046 // Otherwise, issue an error.
8047
8048 auto OtherLTOMode =
8049 IsDeviceOffloadAction ? D.getLTOMode() : D.getOffloadLTOMode();
8050 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
8051
8052 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
8053 (IsPS4 && !UnifiedLTO && (D.getLTOMode() != LTOK_Full)))
8054 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
8055 << "-fwhole-program-vtables"
8056 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
8057
8058 // Propagate -fwhole-program-vtables if this is an LTO compile.
8059 if (IsUsingLTO)
8060 CmdArgs.push_back(Elt: "-fwhole-program-vtables");
8061 }
8062
8063 bool DefaultsSplitLTOUnit =
8064 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
8065 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
8066 (!Triple.isPS4() && UnifiedLTO);
8067 bool SplitLTOUnit =
8068 Args.hasFlag(Pos: options::OPT_fsplit_lto_unit,
8069 Neg: options::OPT_fno_split_lto_unit, Default: DefaultsSplitLTOUnit);
8070 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
8071 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
8072 << "-fsanitize=cfi";
8073 if (SplitLTOUnit)
8074 CmdArgs.push_back(Elt: "-fsplit-lto-unit");
8075
8076 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffat_lto_objects,
8077 Ids: options::OPT_fno_fat_lto_objects)) {
8078 if (IsUsingLTO && A->getOption().matches(ID: options::OPT_ffat_lto_objects)) {
8079 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
8080 if (!Triple.isOSBinFormatELF() && !Triple.isOSBinFormatCOFF()) {
8081 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
8082 << A->getAsString(Args) << TC.getTripleString();
8083 }
8084 CmdArgs.push_back(Elt: Args.MakeArgString(
8085 Str: Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
8086 CmdArgs.push_back(Elt: "-flto-unit");
8087 CmdArgs.push_back(Elt: "-ffat-lto-objects");
8088 A->render(Args, Output&: CmdArgs);
8089 }
8090 }
8091
8092 renderGlobalISelOptions(D, Args, CmdArgs, Triple);
8093
8094 if (Arg *A = Args.getLastArg(Ids: options::OPT_fforce_enable_int128,
8095 Ids: options::OPT_fno_force_enable_int128)) {
8096 if (A->getOption().matches(ID: options::OPT_fforce_enable_int128))
8097 CmdArgs.push_back(Elt: "-fforce-enable-int128");
8098 }
8099
8100 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_static_consts,
8101 Neg: options::OPT_fno_keep_static_consts);
8102 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_persistent_storage_variables,
8103 Neg: options::OPT_fno_keep_persistent_storage_variables);
8104 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcomplete_member_pointers,
8105 Neg: options::OPT_fno_complete_member_pointers);
8106 if (Arg *A = Args.getLastArg(Ids: options::OPT_cxx_static_destructors_EQ))
8107 A->render(Args, Output&: CmdArgs);
8108
8109 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
8110
8111 addOutlineAtomicsArgs(D, TC: getToolChain(), Args, CmdArgs, Triple);
8112
8113 if (Triple.isAArch64() &&
8114 (Args.hasArg(Ids: options::OPT_mno_fmv) ||
8115 (Triple.isAndroid() && Triple.isAndroidVersionLT(Major: 23)) ||
8116 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
8117 // Disable Function Multiversioning on AArch64 target.
8118 CmdArgs.push_back(Elt: "-target-feature");
8119 CmdArgs.push_back(Elt: "-fmv");
8120 }
8121
8122 if (Args.hasFlag(Pos: options::OPT_faddrsig, Neg: options::OPT_fno_addrsig,
8123 Default: (TC.getTriple().isOSBinFormatELF() ||
8124 TC.getTriple().isOSBinFormatCOFF()) &&
8125 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
8126 !TC.getTriple().isOSNetBSD() &&
8127 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
8128 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
8129 CmdArgs.push_back(Elt: "-faddrsig");
8130
8131 const bool HasDefaultDwarf2CFIASM =
8132 (Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
8133 (EH || UnwindTables || AsyncUnwindTables ||
8134 DebugInfoKind != llvm::codegenoptions::NoDebugInfo);
8135 if (Args.hasFlag(Pos: options::OPT_fdwarf2_cfi_asm,
8136 Neg: options::OPT_fno_dwarf2_cfi_asm, Default: HasDefaultDwarf2CFIASM))
8137 CmdArgs.push_back(Elt: "-fdwarf2-cfi-asm");
8138
8139 if (Arg *A = Args.getLastArg(Ids: options::OPT_fsymbol_partition_EQ)) {
8140 std::string Str = A->getAsString(Args);
8141 if (!TC.getTriple().isOSBinFormatELF())
8142 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
8143 << Str << TC.getTripleString();
8144 CmdArgs.push_back(Elt: Args.MakeArgString(Str));
8145 }
8146
8147 // Add the "-o out -x type src.c" flags last. This is done primarily to make
8148 // the -cc1 command easier to edit when reproducing compiler crashes.
8149 if (Output.getType() == types::TY_Dependencies) {
8150 // Handled with other dependency code.
8151 } else if (Output.isFilename()) {
8152 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
8153 Output.getType() == clang::driver::types::TY_IFS) {
8154 SmallString<128> OutputFilename(Output.getFilename());
8155 llvm::sys::path::replace_extension(path&: OutputFilename, extension: "ifs");
8156 CmdArgs.push_back(Elt: "-o");
8157 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OutputFilename));
8158 } else {
8159 CmdArgs.push_back(Elt: "-o");
8160 CmdArgs.push_back(Elt: Output.getFilename());
8161 }
8162 } else {
8163 assert(Output.isNothing() && "Invalid output.");
8164 }
8165
8166 addDashXForInput(Args, Input, CmdArgs);
8167
8168 ArrayRef<InputInfo> FrontendInputs = Input;
8169 if (IsExtractAPI)
8170 FrontendInputs = ExtractAPIInputs;
8171 else if (Input.isNothing())
8172 FrontendInputs = {};
8173
8174 for (const InputInfo &Input : FrontendInputs) {
8175 if (Input.isFilename())
8176 CmdArgs.push_back(Elt: Input.getFilename());
8177 else
8178 Input.getInputArg().renderAsInput(Args, Output&: CmdArgs);
8179 }
8180
8181 if (D.CC1Main && !D.CCGenDiagnostics) {
8182 // Invoke the CC1 directly in this process
8183 C.addCommand(C: std::make_unique<CC1Command>(
8184 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8185 args: Output, args: D.getPrependArg()));
8186 } else {
8187 C.addCommand(C: std::make_unique<Command>(
8188 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8189 args: Output, args: D.getPrependArg()));
8190 }
8191
8192 // Make the compile command echo its inputs for /showFilenames.
8193 if (Output.getType() == types::TY_Object &&
8194 Args.hasFlag(Pos: options::OPT__SLASH_showFilenames,
8195 Neg: options::OPT__SLASH_showFilenames_, Default: false)) {
8196 C.getJobs().getJobs().back()->PrintInputFilenames = true;
8197 }
8198
8199 if (Arg *A = Args.getLastArg(Ids: options::OPT_pg))
8200 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8201 !Args.hasArg(Ids: options::OPT_mfentry))
8202 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8203 << A->getAsString(Args);
8204
8205 // Claim some arguments which clang supports automatically.
8206
8207 // -fpch-preprocess is used with gcc to add a special marker in the output to
8208 // include the PCH file.
8209 Args.ClaimAllArgs(Id0: options::OPT_fpch_preprocess);
8210
8211 // Claim some arguments which clang doesn't support, but we don't
8212 // care to warn the user about.
8213 Args.ClaimAllArgs(Id0: options::OPT_clang_ignored_f_Group);
8214 Args.ClaimAllArgs(Id0: options::OPT_clang_ignored_m_Group);
8215
8216 // Disable warnings for clang -E -emit-llvm foo.c
8217 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
8218}
8219
8220Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8221 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8222 // as it is for other tools. Some operations on a Tool actually test
8223 // whether that tool is Clang based on the Tool's Name as a string.
8224 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8225
8226Clang::~Clang() {}
8227
8228/// Add options related to the Objective-C runtime/ABI.
8229///
8230/// Returns true if the runtime is non-fragile.
8231ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8232 const InputInfoList &inputs,
8233 ArgStringList &cmdArgs,
8234 RewriteKind rewriteKind) const {
8235 // Look for the controlling runtime option.
8236 Arg *runtimeArg =
8237 args.getLastArg(Ids: options::OPT_fnext_runtime, Ids: options::OPT_fgnu_runtime,
8238 Ids: options::OPT_fobjc_runtime_EQ);
8239
8240 // Just forward -fobjc-runtime= to the frontend. This supercedes
8241 // options about fragility.
8242 if (runtimeArg &&
8243 runtimeArg->getOption().matches(ID: options::OPT_fobjc_runtime_EQ)) {
8244 ObjCRuntime runtime;
8245 StringRef value = runtimeArg->getValue();
8246 if (runtime.tryParse(input: value)) {
8247 getToolChain().getDriver().Diag(DiagID: diag::err_drv_unknown_objc_runtime)
8248 << value;
8249 }
8250 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8251 (runtime.getVersion() >= VersionTuple(2, 0)))
8252 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8253 !getToolChain().getTriple().isOSBinFormatCOFF()) {
8254 getToolChain().getDriver().Diag(
8255 DiagID: diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8256 << runtime.getVersion().getMajor();
8257 }
8258
8259 runtimeArg->render(Args: args, Output&: cmdArgs);
8260 return runtime;
8261 }
8262
8263 // Otherwise, we'll need the ABI "version". Version numbers are
8264 // slightly confusing for historical reasons:
8265 // 1 - Traditional "fragile" ABI
8266 // 2 - Non-fragile ABI, version 1
8267 // 3 - Non-fragile ABI, version 2
8268 unsigned objcABIVersion = 1;
8269 // If -fobjc-abi-version= is present, use that to set the version.
8270 if (Arg *abiArg = args.getLastArg(Ids: options::OPT_fobjc_abi_version_EQ)) {
8271 StringRef value = abiArg->getValue();
8272 if (value == "1")
8273 objcABIVersion = 1;
8274 else if (value == "2")
8275 objcABIVersion = 2;
8276 else if (value == "3")
8277 objcABIVersion = 3;
8278 else
8279 getToolChain().getDriver().Diag(DiagID: diag::err_drv_clang_unsupported) << value;
8280 } else {
8281 // Otherwise, determine if we are using the non-fragile ABI.
8282 bool nonFragileABIIsDefault =
8283 (rewriteKind == RK_NonFragile ||
8284 (rewriteKind == RK_None &&
8285 getToolChain().IsObjCNonFragileABIDefault()));
8286 if (args.hasFlag(Pos: options::OPT_fobjc_nonfragile_abi,
8287 Neg: options::OPT_fno_objc_nonfragile_abi,
8288 Default: nonFragileABIIsDefault)) {
8289// Determine the non-fragile ABI version to use.
8290#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8291 unsigned nonFragileABIVersion = 1;
8292#else
8293 unsigned nonFragileABIVersion = 2;
8294#endif
8295
8296 if (Arg *abiArg =
8297 args.getLastArg(Ids: options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8298 StringRef value = abiArg->getValue();
8299 if (value == "1")
8300 nonFragileABIVersion = 1;
8301 else if (value == "2")
8302 nonFragileABIVersion = 2;
8303 else
8304 getToolChain().getDriver().Diag(DiagID: diag::err_drv_clang_unsupported)
8305 << value;
8306 }
8307
8308 objcABIVersion = 1 + nonFragileABIVersion;
8309 } else {
8310 objcABIVersion = 1;
8311 }
8312 }
8313
8314 // We don't actually care about the ABI version other than whether
8315 // it's non-fragile.
8316 bool isNonFragile = objcABIVersion != 1;
8317
8318 // If we have no runtime argument, ask the toolchain for its default runtime.
8319 // However, the rewriter only really supports the Mac runtime, so assume that.
8320 ObjCRuntime runtime;
8321 if (!runtimeArg) {
8322 switch (rewriteKind) {
8323 case RK_None:
8324 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8325 break;
8326 case RK_Fragile:
8327 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8328 break;
8329 case RK_NonFragile:
8330 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8331 break;
8332 }
8333
8334 // -fnext-runtime
8335 } else if (runtimeArg->getOption().matches(ID: options::OPT_fnext_runtime)) {
8336 // On Darwin, make this use the default behavior for the toolchain.
8337 if (getToolChain().getTriple().isOSDarwin()) {
8338 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8339
8340 // Otherwise, build for a generic macosx port.
8341 } else {
8342 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8343 }
8344
8345 // -fgnu-runtime
8346 } else {
8347 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8348 // Legacy behaviour is to target the gnustep runtime if we are in
8349 // non-fragile mode or the GCC runtime in fragile mode.
8350 if (isNonFragile)
8351 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8352 else
8353 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8354 }
8355
8356 if (llvm::any_of(Range: inputs, P: [](const InputInfo &input) {
8357 return types::isObjC(Id: input.getType());
8358 }))
8359 cmdArgs.push_back(
8360 Elt: args.MakeArgString(Str: "-fobjc-runtime=" + runtime.getAsString()));
8361 return runtime;
8362}
8363
8364static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8365 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8366 I += HaveDash;
8367 return !HaveDash;
8368}
8369
8370namespace {
8371struct EHFlags {
8372 bool Synch = false;
8373 bool Asynch = false;
8374 bool NoUnwindC = false;
8375};
8376} // end anonymous namespace
8377
8378/// /EH controls whether to run destructor cleanups when exceptions are
8379/// thrown. There are three modifiers:
8380/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8381/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8382/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8383/// - c: Assume that extern "C" functions are implicitly nounwind.
8384/// The default is /EHs-c-, meaning cleanups are disabled.
8385static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8386 bool isWindowsMSVC) {
8387 EHFlags EH;
8388
8389 std::vector<std::string> EHArgs =
8390 Args.getAllArgValues(Id: options::OPT__SLASH_EH);
8391 for (const auto &EHVal : EHArgs) {
8392 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8393 switch (EHVal[I]) {
8394 case 'a':
8395 EH.Asynch = maybeConsumeDash(EH: EHVal, I);
8396 if (EH.Asynch) {
8397 // Async exceptions are Windows MSVC only.
8398 if (!isWindowsMSVC) {
8399 EH.Asynch = false;
8400 D.Diag(DiagID: clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8401 continue;
8402 }
8403 EH.Synch = false;
8404 }
8405 continue;
8406 case 'c':
8407 EH.NoUnwindC = maybeConsumeDash(EH: EHVal, I);
8408 continue;
8409 case 's':
8410 EH.Synch = maybeConsumeDash(EH: EHVal, I);
8411 if (EH.Synch)
8412 EH.Asynch = false;
8413 continue;
8414 default:
8415 break;
8416 }
8417 D.Diag(DiagID: clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8418 break;
8419 }
8420 }
8421 // The /GX, /GX- flags are only processed if there are not /EH flags.
8422 // The default is that /GX is not specified.
8423 if (EHArgs.empty() &&
8424 Args.hasFlag(Pos: options::OPT__SLASH_GX, Neg: options::OPT__SLASH_GX_,
8425 /*Default=*/false)) {
8426 EH.Synch = true;
8427 EH.NoUnwindC = true;
8428 }
8429
8430 if (Args.hasArg(Ids: options::OPT__SLASH_kernel)) {
8431 EH.Synch = false;
8432 EH.NoUnwindC = false;
8433 EH.Asynch = false;
8434 }
8435
8436 return EH;
8437}
8438
8439void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8440 ArgStringList &CmdArgs) const {
8441 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8442
8443 ProcessVSRuntimeLibrary(TC: getToolChain(), Args, CmdArgs);
8444
8445 if (Arg *ShowIncludes =
8446 Args.getLastArg(Ids: options::OPT__SLASH_showIncludes,
8447 Ids: options::OPT__SLASH_showIncludes_user)) {
8448 CmdArgs.push_back(Elt: "--show-includes");
8449 if (ShowIncludes->getOption().matches(ID: options::OPT__SLASH_showIncludes))
8450 CmdArgs.push_back(Elt: "-sys-header-deps");
8451 }
8452
8453 // This controls whether or not we emit RTTI data for polymorphic types.
8454 if (Args.hasFlag(Pos: options::OPT__SLASH_GR_, Neg: options::OPT__SLASH_GR,
8455 /*Default=*/false))
8456 CmdArgs.push_back(Elt: "-fno-rtti-data");
8457
8458 // This controls whether or not we emit stack-protector instrumentation.
8459 // In MSVC, Buffer Security Check (/GS) is on by default.
8460 if (!isNVPTX && Args.hasFlag(Pos: options::OPT__SLASH_GS, Neg: options::OPT__SLASH_GS_,
8461 /*Default=*/true)) {
8462 CmdArgs.push_back(Elt: "-stack-protector");
8463 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(LangOptions::SSPStrong)));
8464 }
8465
8466 const Driver &D = getToolChain().getDriver();
8467
8468 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
8469 EHFlags EH = parseClangCLEHFlags(D, Args, isWindowsMSVC: IsWindowsMSVC);
8470 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
8471 if (types::isCXX(Id: InputType))
8472 CmdArgs.push_back(Elt: "-fcxx-exceptions");
8473 CmdArgs.push_back(Elt: "-fexceptions");
8474 if (EH.Asynch)
8475 CmdArgs.push_back(Elt: "-fasync-exceptions");
8476 }
8477 if (types::isCXX(Id: InputType) && EH.Synch && EH.NoUnwindC)
8478 CmdArgs.push_back(Elt: "-fexternc-nounwind");
8479
8480 // /EP should expand to -E -P.
8481 if (Args.hasArg(Ids: options::OPT__SLASH_EP)) {
8482 CmdArgs.push_back(Elt: "-E");
8483 CmdArgs.push_back(Elt: "-P");
8484 }
8485
8486 if (Args.hasFlag(Pos: options::OPT__SLASH_Zc_dllexportInlines_,
8487 Neg: options::OPT__SLASH_Zc_dllexportInlines,
8488 Default: false)) {
8489 CmdArgs.push_back(Elt: "-fno-dllexport-inlines");
8490 }
8491
8492 if (Args.hasFlag(Pos: options::OPT__SLASH_Zc_wchar_t_,
8493 Neg: options::OPT__SLASH_Zc_wchar_t, Default: false)) {
8494 CmdArgs.push_back(Elt: "-fno-wchar");
8495 }
8496
8497 if (Args.hasArg(Ids: options::OPT__SLASH_kernel)) {
8498 llvm::Triple::ArchType Arch = getToolChain().getArch();
8499 std::vector<std::string> Values =
8500 Args.getAllArgValues(Id: options::OPT__SLASH_arch);
8501 if (!Values.empty()) {
8502 llvm::SmallSet<std::string, 4> SupportedArches;
8503 if (Arch == llvm::Triple::x86)
8504 SupportedArches.insert(V: "IA32");
8505
8506 for (auto &V : Values)
8507 if (!SupportedArches.contains(V))
8508 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
8509 << std::string("/arch:").append(str: V) << "/kernel";
8510 }
8511
8512 CmdArgs.push_back(Elt: "-fno-rtti");
8513 if (Args.hasFlag(Pos: options::OPT__SLASH_GR, Neg: options::OPT__SLASH_GR_, Default: false))
8514 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "/GR"
8515 << "/kernel";
8516 }
8517
8518 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_vlen,
8519 Ids: options::OPT__SLASH_vlen_EQ_256,
8520 Ids: options::OPT__SLASH_vlen_EQ_512)) {
8521 llvm::Triple::ArchType AT = getToolChain().getArch();
8522 StringRef Default = AT == llvm::Triple::x86 ? "IA32" : "SSE2";
8523 StringRef Arch = Args.getLastArgValue(Id: options::OPT__SLASH_arch, Default);
8524 llvm::SmallSet<StringRef, 4> Arch512 = {"AVX512F", "AVX512", "AVX10.1",
8525 "AVX10.2"};
8526
8527 if (A->getOption().matches(ID: options::OPT__SLASH_vlen_EQ_512)) {
8528 if (Arch512.contains(V: Arch))
8529 CmdArgs.push_back(Elt: "-mprefer-vector-width=512");
8530 else
8531 D.Diag(DiagID: diag::warn_drv_argument_not_allowed_with)
8532 << "/vlen=512" << std::string("/arch:").append(svt: Arch);
8533 } else if (A->getOption().matches(ID: options::OPT__SLASH_vlen_EQ_256)) {
8534 if (Arch512.contains(V: Arch))
8535 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
8536 else if (Arch != "AVX" && Arch != "AVX2")
8537 D.Diag(DiagID: diag::warn_drv_argument_not_allowed_with)
8538 << "/vlen=256" << std::string("/arch:").append(svt: Arch);
8539 } else {
8540 if (Arch == "AVX10.1" || Arch == "AVX10.2")
8541 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
8542 }
8543 } else {
8544 StringRef Arch = Args.getLastArgValue(Id: options::OPT__SLASH_arch);
8545 if (Arch == "AVX10.1" || Arch == "AVX10.2")
8546 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
8547 }
8548
8549 Arg *MostGeneralArg = Args.getLastArg(Ids: options::OPT__SLASH_vmg);
8550 Arg *BestCaseArg = Args.getLastArg(Ids: options::OPT__SLASH_vmb);
8551 if (MostGeneralArg && BestCaseArg)
8552 D.Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with)
8553 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
8554
8555 if (MostGeneralArg) {
8556 Arg *SingleArg = Args.getLastArg(Ids: options::OPT__SLASH_vms);
8557 Arg *MultipleArg = Args.getLastArg(Ids: options::OPT__SLASH_vmm);
8558 Arg *VirtualArg = Args.getLastArg(Ids: options::OPT__SLASH_vmv);
8559
8560 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
8561 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
8562 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
8563 D.Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with)
8564 << FirstConflict->getAsString(Args)
8565 << SecondConflict->getAsString(Args);
8566
8567 if (SingleArg)
8568 CmdArgs.push_back(Elt: "-fms-memptr-rep=single");
8569 else if (MultipleArg)
8570 CmdArgs.push_back(Elt: "-fms-memptr-rep=multiple");
8571 else
8572 CmdArgs.push_back(Elt: "-fms-memptr-rep=virtual");
8573 }
8574
8575 if (Args.hasArg(Ids: options::OPT_regcall4))
8576 CmdArgs.push_back(Elt: "-regcall4");
8577
8578 // Parse the default calling convention options.
8579 if (Arg *CCArg =
8580 Args.getLastArg(Ids: options::OPT__SLASH_Gd, Ids: options::OPT__SLASH_Gr,
8581 Ids: options::OPT__SLASH_Gz, Ids: options::OPT__SLASH_Gv,
8582 Ids: options::OPT__SLASH_Gregcall)) {
8583 unsigned DCCOptId = CCArg->getOption().getID();
8584 const char *DCCFlag = nullptr;
8585 bool ArchSupported = !isNVPTX;
8586 llvm::Triple::ArchType Arch = getToolChain().getArch();
8587 switch (DCCOptId) {
8588 case options::OPT__SLASH_Gd:
8589 DCCFlag = "-fdefault-calling-conv=cdecl";
8590 break;
8591 case options::OPT__SLASH_Gr:
8592 ArchSupported = Arch == llvm::Triple::x86;
8593 DCCFlag = "-fdefault-calling-conv=fastcall";
8594 break;
8595 case options::OPT__SLASH_Gz:
8596 ArchSupported = Arch == llvm::Triple::x86;
8597 DCCFlag = "-fdefault-calling-conv=stdcall";
8598 break;
8599 case options::OPT__SLASH_Gv:
8600 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8601 DCCFlag = "-fdefault-calling-conv=vectorcall";
8602 break;
8603 case options::OPT__SLASH_Gregcall:
8604 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8605 DCCFlag = "-fdefault-calling-conv=regcall";
8606 break;
8607 }
8608
8609 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
8610 if (ArchSupported && DCCFlag)
8611 CmdArgs.push_back(Elt: DCCFlag);
8612 }
8613
8614 if (Args.hasArg(Ids: options::OPT__SLASH_Gregcall4))
8615 CmdArgs.push_back(Elt: "-regcall4");
8616
8617 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_vtordisp_mode_EQ);
8618
8619 if (!Args.hasArg(Ids: options::OPT_fdiagnostics_format_EQ)) {
8620 CmdArgs.push_back(Elt: "-fdiagnostics-format");
8621 CmdArgs.push_back(Elt: "msvc");
8622 }
8623
8624 if (Args.hasArg(Ids: options::OPT__SLASH_kernel))
8625 CmdArgs.push_back(Elt: "-fms-kernel");
8626
8627 // Unwind v2 (epilog) information for x64 Windows.
8628 if (Args.hasArg(Ids: options::OPT__SLASH_d2epilogunwindrequirev2))
8629 CmdArgs.push_back(Elt: "-fwinx64-eh-unwindv2=required");
8630 else if (Args.hasArg(Ids: options::OPT__SLASH_d2epilogunwind))
8631 CmdArgs.push_back(Elt: "-fwinx64-eh-unwindv2=best-effort");
8632
8633 // Handle the various /guard options. We don't immediately push back clang
8634 // args since there are /d2 args that can modify the behavior of /guard:cf.
8635 bool HasCFGuard = false;
8636 bool HasCFGuardNoChecks = false;
8637 for (const Arg *A : Args.filtered(Ids: options::OPT__SLASH_guard)) {
8638 StringRef GuardArgs = A->getValue();
8639 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
8640 // "ehcont-".
8641 if (GuardArgs.equals_insensitive(RHS: "cf")) {
8642 // Emit CFG instrumentation and the table of address-taken functions.
8643 HasCFGuard = true;
8644 HasCFGuardNoChecks = false;
8645 } else if (GuardArgs.equals_insensitive(RHS: "cf,nochecks")) {
8646 // Emit only the table of address-taken functions.
8647 HasCFGuard = false;
8648 HasCFGuardNoChecks = true;
8649 } else if (GuardArgs.equals_insensitive(RHS: "ehcont")) {
8650 // Emit EH continuation table.
8651 CmdArgs.push_back(Elt: "-ehcontguard");
8652 } else if (GuardArgs.equals_insensitive(RHS: "cf-") ||
8653 GuardArgs.equals_insensitive(RHS: "ehcont-")) {
8654 // Do nothing, but we might want to emit a security warning in future.
8655 } else {
8656 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
8657 }
8658 A->claim();
8659 }
8660
8661 // /d2guardnochecks downgrades /guard:cf to /guard:cf,nochecks (table only).
8662 // If CFG is not enabled, it is a no-op.
8663 if (Args.hasArg(Ids: options::OPT__SLASH_d2guardnochecks)) {
8664 if (HasCFGuard) {
8665 HasCFGuard = false;
8666 HasCFGuardNoChecks = true;
8667 }
8668 }
8669
8670 if (HasCFGuard)
8671 CmdArgs.push_back(Elt: "-cfguard");
8672 else if (HasCFGuardNoChecks)
8673 CmdArgs.push_back(Elt: "-cfguard-no-checks");
8674
8675 for (const auto &FuncOverride :
8676 Args.getAllArgValues(Id: options::OPT__SLASH_funcoverride)) {
8677 CmdArgs.push_back(Elt: Args.MakeArgString(
8678 Str: Twine("-loader-replaceable-function=") + FuncOverride));
8679 }
8680}
8681
8682const char *Clang::getBaseInputName(const ArgList &Args,
8683 const InputInfo &Input) {
8684 return Args.MakeArgString(Str: llvm::sys::path::filename(path: Input.getBaseInput()));
8685}
8686
8687const char *Clang::getBaseInputStem(const ArgList &Args,
8688 const InputInfoList &Inputs) {
8689 const char *Str = getBaseInputName(Args, Input: Inputs[0]);
8690
8691 if (const char *End = strrchr(s: Str, c: '.'))
8692 return Args.MakeArgString(Str: std::string(Str, End));
8693
8694 return Str;
8695}
8696
8697const char *Clang::getDependencyFileName(const ArgList &Args,
8698 const InputInfoList &Inputs) {
8699 // FIXME: Think about this more.
8700
8701 if (Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o)) {
8702 SmallString<128> OutputFilename(OutputOpt->getValue());
8703 llvm::sys::path::replace_extension(path&: OutputFilename, extension: llvm::Twine('d'));
8704 return Args.MakeArgString(Str: OutputFilename);
8705 }
8706
8707 return Args.MakeArgString(Str: Twine(getBaseInputStem(Args, Inputs)) + ".d");
8708}
8709
8710// Begin ClangAs
8711
8712void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
8713 ArgStringList &CmdArgs) const {
8714 StringRef CPUName;
8715 StringRef ABIName;
8716 const llvm::Triple &Triple = getToolChain().getTriple();
8717 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
8718
8719 CmdArgs.push_back(Elt: "-target-abi");
8720 CmdArgs.push_back(Elt: ABIName.data());
8721}
8722
8723void ClangAs::AddX86TargetArgs(const ArgList &Args,
8724 ArgStringList &CmdArgs) const {
8725 addX86AlignBranchArgs(D: getToolChain().getDriver(), Args, CmdArgs,
8726 /*IsLTO=*/false);
8727
8728 if (Arg *A = Args.getLastArg(Ids: options::OPT_masm_EQ)) {
8729 StringRef Value = A->getValue();
8730 if (Value == "intel" || Value == "att") {
8731 CmdArgs.push_back(Elt: "-mllvm");
8732 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
8733 } else {
8734 getToolChain().getDriver().Diag(DiagID: diag::err_drv_unsupported_option_argument)
8735 << A->getSpelling() << Value;
8736 }
8737 }
8738}
8739
8740void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
8741 ArgStringList &CmdArgs) const {
8742 CmdArgs.push_back(Elt: "-target-abi");
8743 CmdArgs.push_back(Elt: loongarch::getLoongArchABI(D: getToolChain().getDriver(), Args,
8744 Triple: getToolChain().getTriple())
8745 .data());
8746}
8747
8748void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
8749 ArgStringList &CmdArgs) const {
8750 const llvm::Triple &Triple = getToolChain().getTriple();
8751 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
8752
8753 CmdArgs.push_back(Elt: "-target-abi");
8754 CmdArgs.push_back(Elt: ABIName.data());
8755
8756 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
8757 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
8758 CmdArgs.push_back(Elt: "-mllvm");
8759 CmdArgs.push_back(Elt: "-riscv-add-build-attributes");
8760 }
8761}
8762
8763void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
8764 const InputInfo &Output, const InputInfoList &Inputs,
8765 const ArgList &Args,
8766 const char *LinkingOutput) const {
8767 ArgStringList CmdArgs;
8768
8769 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
8770 const InputInfo &Input = Inputs[0];
8771
8772 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
8773 const std::string &TripleStr = Triple.getTriple();
8774 const auto &D = getToolChain().getDriver();
8775
8776 // Don't warn about "clang -w -c foo.s"
8777 Args.ClaimAllArgs(Id0: options::OPT_w);
8778 // and "clang -emit-llvm -c foo.s"
8779 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
8780
8781 claimNoWarnArgs(Args);
8782
8783 // Invoke ourselves in -cc1as mode.
8784 //
8785 // FIXME: Implement custom jobs for internal actions.
8786 CmdArgs.push_back(Elt: "-cc1as");
8787
8788 // Add the "effective" target triple.
8789 CmdArgs.push_back(Elt: "-triple");
8790 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TripleStr));
8791
8792 getToolChain().addClangCC1ASTargetOptions(Args, CC1ASArgs&: CmdArgs);
8793
8794 // Set the output mode, we currently only expect to be used as a real
8795 // assembler.
8796 CmdArgs.push_back(Elt: "-filetype");
8797 CmdArgs.push_back(Elt: "obj");
8798
8799 // Set the main file name, so that debug info works even with
8800 // -save-temps or preprocessed assembly.
8801 CmdArgs.push_back(Elt: "-main-file-name");
8802 CmdArgs.push_back(Elt: Clang::getBaseInputName(Args, Input));
8803
8804 // Add the target cpu
8805 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ true);
8806 if (!CPU.empty()) {
8807 CmdArgs.push_back(Elt: "-target-cpu");
8808 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
8809 }
8810
8811 // Add the target features
8812 getTargetFeatures(D, Triple, Args, CmdArgs, ForAS: true);
8813
8814 // Ignore explicit -force_cpusubtype_ALL option.
8815 (void)Args.hasArg(Ids: options::OPT_force__cpusubtype__ALL);
8816
8817 // Pass along any -I options so we get proper .include search paths.
8818 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_I_Group);
8819
8820 // Pass along any --embed-dir or similar options so we get proper embed paths.
8821 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_embed_dir_EQ);
8822
8823 // Determine the original source input.
8824 auto FindSource = [](const Action *S) -> const Action * {
8825 while (S->getKind() != Action::InputClass) {
8826 assert(!S->getInputs().empty() && "unexpected root action!");
8827 S = S->getInputs()[0];
8828 }
8829 return S;
8830 };
8831 const Action *SourceAction = FindSource(&JA);
8832
8833 // Forward -g and handle debug info related flags, assuming we are dealing
8834 // with an actual assembly file.
8835 bool WantDebug = false;
8836 Args.ClaimAllArgs(Id0: options::OPT_g_Group);
8837 if (Arg *A = Args.getLastArg(Ids: options::OPT_g_Group))
8838 WantDebug = !A->getOption().matches(ID: options::OPT_g0) &&
8839 !A->getOption().matches(ID: options::OPT_ggdb0);
8840
8841 // If a -gdwarf argument appeared, remember it.
8842 bool EmitDwarf = false;
8843 if (const Arg *A = getDwarfNArg(Args))
8844 EmitDwarf = checkDebugInfoOption(A, Args, D, TC: getToolChain());
8845
8846 bool EmitCodeView = false;
8847 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcodeview))
8848 EmitCodeView = checkDebugInfoOption(A, Args, D, TC: getToolChain());
8849
8850 // If the user asked for debug info but did not explicitly specify -gcodeview
8851 // or -gdwarf, ask the toolchain for the default format.
8852 if (!EmitCodeView && !EmitDwarf && WantDebug) {
8853 switch (getToolChain().getDefaultDebugFormat()) {
8854 case llvm::codegenoptions::DIF_CodeView:
8855 EmitCodeView = true;
8856 break;
8857 case llvm::codegenoptions::DIF_DWARF:
8858 EmitDwarf = true;
8859 break;
8860 }
8861 }
8862
8863 // If the arguments don't imply DWARF, don't emit any debug info here.
8864 if (!EmitDwarf)
8865 WantDebug = false;
8866
8867 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
8868 llvm::codegenoptions::NoDebugInfo;
8869
8870 // Add the -fdebug-compilation-dir flag if needed.
8871 const char *DebugCompilationDir =
8872 addDebugCompDirArg(Args, CmdArgs, VFS: C.getDriver().getVFS());
8873
8874 if (SourceAction->getType() == types::TY_Asm ||
8875 SourceAction->getType() == types::TY_PP_Asm) {
8876 // You might think that it would be ok to set DebugInfoKind outside of
8877 // the guard for source type, however there is a test which asserts
8878 // that some assembler invocation receives no -debug-info-kind,
8879 // and it's not clear whether that test is just overly restrictive.
8880 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
8881 : llvm::codegenoptions::NoDebugInfo);
8882
8883 addDebugPrefixMapArg(D: getToolChain().getDriver(), TC: getToolChain(), Args,
8884 CmdArgs);
8885
8886 // Set the AT_producer to the clang version when using the integrated
8887 // assembler on assembly source files.
8888 CmdArgs.push_back(Elt: "-dwarf-debug-producer");
8889 CmdArgs.push_back(Elt: Args.MakeArgString(Str: getClangFullVersion()));
8890
8891 // And pass along -I options
8892 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_I);
8893 }
8894 const unsigned DwarfVersion = getDwarfVersion(TC: getToolChain(), Args);
8895 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
8896 DebuggerTuning: llvm::DebuggerKind::Default);
8897 renderDwarfFormat(D, T: Triple, Args, CmdArgs, DwarfVersion);
8898 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC: getToolChain());
8899
8900 // Handle -fPIC et al -- the relocation-model affects the assembler
8901 // for some targets.
8902 llvm::Reloc::Model RelocationModel;
8903 unsigned PICLevel;
8904 bool IsPIE;
8905 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
8906 ParsePICArgs(ToolChain: getToolChain(), Args);
8907
8908 const char *RMName = RelocationModelName(Model: RelocationModel);
8909 if (RMName) {
8910 CmdArgs.push_back(Elt: "-mrelocation-model");
8911 CmdArgs.push_back(Elt: RMName);
8912 }
8913
8914 // Optionally embed the -cc1as level arguments into the debug info, for build
8915 // analysis.
8916 if (getToolChain().UseDwarfDebugFlags()) {
8917 ArgStringList OriginalArgs;
8918 for (const auto &Arg : Args)
8919 Arg->render(Args, Output&: OriginalArgs);
8920
8921 SmallString<256> Flags;
8922 const char *Exec = getToolChain().getDriver().getClangProgramPath();
8923 escapeSpacesAndBackslashes(Arg: Exec, Res&: Flags);
8924 for (const char *OriginalArg : OriginalArgs) {
8925 SmallString<128> EscapedArg;
8926 escapeSpacesAndBackslashes(Arg: OriginalArg, Res&: EscapedArg);
8927 Flags += " ";
8928 Flags += EscapedArg;
8929 }
8930 CmdArgs.push_back(Elt: "-dwarf-debug-flags");
8931 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Flags));
8932 }
8933
8934 // FIXME: Add -static support, once we have it.
8935
8936 // Add target specific flags.
8937 switch (getToolChain().getArch()) {
8938 default:
8939 break;
8940
8941 case llvm::Triple::mips:
8942 case llvm::Triple::mipsel:
8943 case llvm::Triple::mips64:
8944 case llvm::Triple::mips64el:
8945 AddMIPSTargetArgs(Args, CmdArgs);
8946 break;
8947
8948 case llvm::Triple::x86:
8949 case llvm::Triple::x86_64:
8950 AddX86TargetArgs(Args, CmdArgs);
8951 break;
8952
8953 case llvm::Triple::arm:
8954 case llvm::Triple::armeb:
8955 case llvm::Triple::thumb:
8956 case llvm::Triple::thumbeb:
8957 // This isn't in AddARMTargetArgs because we want to do this for assembly
8958 // only, not C/C++.
8959 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
8960 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
8961 CmdArgs.push_back(Elt: "-mllvm");
8962 CmdArgs.push_back(Elt: "-arm-add-build-attributes");
8963 }
8964 break;
8965
8966 case llvm::Triple::aarch64:
8967 case llvm::Triple::aarch64_32:
8968 case llvm::Triple::aarch64_be:
8969 if (Args.hasArg(Ids: options::OPT_mmark_bti_property)) {
8970 CmdArgs.push_back(Elt: "-mllvm");
8971 CmdArgs.push_back(Elt: "-aarch64-mark-bti-property");
8972 }
8973 break;
8974
8975 case llvm::Triple::loongarch32:
8976 case llvm::Triple::loongarch64:
8977 AddLoongArchTargetArgs(Args, CmdArgs);
8978 break;
8979
8980 case llvm::Triple::riscv32:
8981 case llvm::Triple::riscv64:
8982 case llvm::Triple::riscv32be:
8983 case llvm::Triple::riscv64be:
8984 AddRISCVTargetArgs(Args, CmdArgs);
8985 break;
8986
8987 case llvm::Triple::hexagon:
8988 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
8989 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
8990 CmdArgs.push_back(Elt: "-mllvm");
8991 CmdArgs.push_back(Elt: "-hexagon-add-build-attributes");
8992 }
8993 break;
8994 }
8995
8996 // Consume all the warning flags. Usually this would be handled more
8997 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
8998 // doesn't handle that so rather than warning about unused flags that are
8999 // actually used, we'll lie by omission instead.
9000 // FIXME: Stop lying and consume only the appropriate driver flags
9001 Args.ClaimAllArgs(Id0: options::OPT_W_Group);
9002
9003 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
9004 D: getToolChain().getDriver());
9005
9006 // Forward -Xclangas arguments to -cc1as
9007 for (auto Arg : Args.filtered(Ids: options::OPT_Xclangas)) {
9008 Arg->claim();
9009 CmdArgs.push_back(Elt: Arg->getValue());
9010 }
9011
9012 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_mllvm);
9013
9014 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
9015 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
9016 OutputFileName: Output.getFilename());
9017
9018 // Fixup any previous commands that use -object-file-name because when we
9019 // generated them, the final .obj name wasn't yet known.
9020 for (Command &J : C.getJobs()) {
9021 if (SourceAction != FindSource(&J.getSource()))
9022 continue;
9023 auto &JArgs = J.getArguments();
9024 for (unsigned I = 0; I < JArgs.size(); ++I) {
9025 if (StringRef(JArgs[I]).starts_with(Prefix: "-object-file-name=") &&
9026 Output.isFilename()) {
9027 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
9028 addDebugObjectName(Args, CmdArgs&: NewArgs, DebugCompilationDir,
9029 OutputFileName: Output.getFilename());
9030 NewArgs.append(in_start: JArgs.begin() + I + 1, in_end: JArgs.end());
9031 J.replaceArguments(List: NewArgs);
9032 break;
9033 }
9034 }
9035 }
9036
9037 assert(Output.isFilename() && "Unexpected lipo output.");
9038 CmdArgs.push_back(Elt: "-o");
9039 CmdArgs.push_back(Elt: Output.getFilename());
9040
9041 const llvm::Triple &T = getToolChain().getTriple();
9042 Arg *A;
9043 if (getDebugFissionKind(D, Args, Arg&: A) == DwarfFissionKind::Split &&
9044 T.isOSBinFormatELF()) {
9045 CmdArgs.push_back(Elt: "-split-dwarf-output");
9046 CmdArgs.push_back(Elt: SplitDebugName(JA, Args, Input, Output));
9047 }
9048
9049 if (Triple.isAMDGPU())
9050 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
9051
9052 assert(Input.isFilename() && "Invalid input.");
9053 CmdArgs.push_back(Elt: Input.getFilename());
9054
9055 const char *Exec = getToolChain().getDriver().getClangProgramPath();
9056 if (D.CC1Main && !D.CCGenDiagnostics) {
9057 // Invoke cc1as directly in this process.
9058 C.addCommand(C: std::make_unique<CC1Command>(
9059 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
9060 args: Output, args: D.getPrependArg()));
9061 } else {
9062 C.addCommand(C: std::make_unique<Command>(
9063 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
9064 args: Output, args: D.getPrependArg()));
9065 }
9066}
9067
9068// Begin OffloadBundler
9069void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
9070 const InputInfo &Output,
9071 const InputInfoList &Inputs,
9072 const llvm::opt::ArgList &TCArgs,
9073 const char *LinkingOutput) const {
9074 // The version with only one output is expected to refer to a bundling job.
9075 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
9076
9077 // The bundling command looks like this:
9078 // clang-offload-bundler -type=bc
9079 // -targets=host-triple,openmp-triple1,openmp-triple2
9080 // -output=output_file
9081 // -input=unbundle_file_host
9082 // -input=unbundle_file_tgt1
9083 // -input=unbundle_file_tgt2
9084
9085 ArgStringList CmdArgs;
9086
9087 // Get the type.
9088 CmdArgs.push_back(Elt: TCArgs.MakeArgString(
9089 Str: Twine("-type=") + types::getTypeTempSuffix(Id: Output.getType())));
9090
9091 assert(JA.getInputs().size() == Inputs.size() &&
9092 "Not have inputs for all dependence actions??");
9093
9094 // Get the targets.
9095 SmallString<128> Triples;
9096 Triples += "-targets=";
9097 for (unsigned I = 0; I < Inputs.size(); ++I) {
9098 if (I)
9099 Triples += ',';
9100
9101 // Find ToolChain for this input.
9102 Action::OffloadKind CurKind = Action::OFK_Host;
9103 const ToolChain *CurTC = &getToolChain();
9104 const Action *CurDep = JA.getInputs()[I];
9105
9106 if (const auto *OA = dyn_cast<OffloadAction>(Val: CurDep)) {
9107 CurTC = nullptr;
9108 OA->doOnEachDependence(Work: [&](Action *A, const ToolChain *TC, const char *) {
9109 assert(CurTC == nullptr && "Expected one dependence!");
9110 CurKind = A->getOffloadingDeviceKind();
9111 CurTC = TC;
9112 });
9113 }
9114 Triples += Action::GetOffloadKindName(Kind: CurKind);
9115 Triples += '-';
9116 Triples +=
9117 CurTC->getTriple().normalize(Form: llvm::Triple::CanonicalForm::FOUR_IDENT);
9118 if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&
9119 !StringRef(CurDep->getOffloadingArch()).empty()) {
9120 Triples += '-';
9121 Triples += CurDep->getOffloadingArch();
9122 }
9123
9124 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
9125 // with each toolchain.
9126 StringRef GPUArchName;
9127 if (CurKind == Action::OFK_OpenMP) {
9128 // Extract GPUArch from -march argument in TC argument list.
9129 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
9130 auto ArchStr = StringRef(TCArgs.getArgString(Index: ArgIndex));
9131 auto Arch = ArchStr.starts_with_insensitive(Prefix: "-march=");
9132 if (Arch) {
9133 GPUArchName = ArchStr.substr(Start: 7);
9134 Triples += "-";
9135 break;
9136 }
9137 }
9138 Triples += GPUArchName.str();
9139 }
9140 }
9141 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: Triples));
9142
9143 // Get bundled file command.
9144 CmdArgs.push_back(
9145 Elt: TCArgs.MakeArgString(Str: Twine("-output=") + Output.getFilename()));
9146
9147 // Get unbundled files command.
9148 for (unsigned I = 0; I < Inputs.size(); ++I) {
9149 SmallString<128> UB;
9150 UB += "-input=";
9151
9152 // Find ToolChain for this input.
9153 const ToolChain *CurTC = &getToolChain();
9154 if (const auto *OA = dyn_cast<OffloadAction>(Val: JA.getInputs()[I])) {
9155 CurTC = nullptr;
9156 OA->doOnEachDependence(Work: [&](Action *, const ToolChain *TC, const char *) {
9157 assert(CurTC == nullptr && "Expected one dependence!");
9158 CurTC = TC;
9159 });
9160 UB += C.addTempFile(
9161 Name: C.getArgs().MakeArgString(Str: CurTC->getInputFilename(Input: Inputs[I])));
9162 } else {
9163 UB += CurTC->getInputFilename(Input: Inputs[I]);
9164 }
9165 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: UB));
9166 }
9167 addOffloadCompressArgs(TCArgs, CmdArgs);
9168 // All the inputs are encoded as commands.
9169 C.addCommand(C: std::make_unique<Command>(
9170 args: JA, args: *this, args: ResponseFileSupport::None(),
9171 args: TCArgs.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9172 args&: CmdArgs, args: ArrayRef<InputInfo>(), args: Output));
9173}
9174
9175void OffloadBundler::ConstructJobMultipleOutputs(
9176 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
9177 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
9178 const char *LinkingOutput) const {
9179 // The version with multiple outputs is expected to refer to a unbundling job.
9180 auto &UA = cast<OffloadUnbundlingJobAction>(Val: JA);
9181
9182 // The unbundling command looks like this:
9183 // clang-offload-bundler -type=bc
9184 // -targets=host-triple,openmp-triple1,openmp-triple2
9185 // -input=input_file
9186 // -output=unbundle_file_host
9187 // -output=unbundle_file_tgt1
9188 // -output=unbundle_file_tgt2
9189 // -unbundle
9190
9191 ArgStringList CmdArgs;
9192
9193 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
9194 InputInfo Input = Inputs.front();
9195
9196 // Get the type.
9197 CmdArgs.push_back(Elt: TCArgs.MakeArgString(
9198 Str: Twine("-type=") + types::getTypeTempSuffix(Id: Input.getType())));
9199
9200 // Get the targets.
9201 SmallString<128> Triples;
9202 Triples += "-targets=";
9203 auto DepInfo = UA.getDependentActionsInfo();
9204 for (unsigned I = 0; I < DepInfo.size(); ++I) {
9205 if (I)
9206 Triples += ',';
9207
9208 auto &Dep = DepInfo[I];
9209 Triples += Action::GetOffloadKindName(Kind: Dep.DependentOffloadKind);
9210 Triples += '-';
9211 Triples += Dep.DependentToolChain->getTriple().normalize(
9212 Form: llvm::Triple::CanonicalForm::FOUR_IDENT);
9213 if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
9214 Dep.DependentOffloadKind == Action::OFK_Cuda) &&
9215 !Dep.DependentBoundArch.empty()) {
9216 Triples += '-';
9217 Triples += Dep.DependentBoundArch;
9218 }
9219 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
9220 // with each toolchain.
9221 StringRef GPUArchName;
9222 if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {
9223 // Extract GPUArch from -march argument in TC argument list.
9224 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
9225 StringRef ArchStr = StringRef(TCArgs.getArgString(Index: ArgIndex));
9226 auto Arch = ArchStr.starts_with_insensitive(Prefix: "-march=");
9227 if (Arch) {
9228 GPUArchName = ArchStr.substr(Start: 7);
9229 Triples += "-";
9230 break;
9231 }
9232 }
9233 Triples += GPUArchName.str();
9234 }
9235 }
9236
9237 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: Triples));
9238
9239 // Get bundled file command.
9240 CmdArgs.push_back(
9241 Elt: TCArgs.MakeArgString(Str: Twine("-input=") + Input.getFilename()));
9242
9243 // Get unbundled files command.
9244 for (unsigned I = 0; I < Outputs.size(); ++I) {
9245 SmallString<128> UB;
9246 UB += "-output=";
9247 UB += DepInfo[I].DependentToolChain->getInputFilename(Input: Outputs[I]);
9248 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: UB));
9249 }
9250 CmdArgs.push_back(Elt: "-unbundle");
9251 CmdArgs.push_back(Elt: "-allow-missing-bundles");
9252 if (TCArgs.hasArg(Ids: options::OPT_v))
9253 CmdArgs.push_back(Elt: "-verbose");
9254
9255 // All the inputs are encoded as commands.
9256 C.addCommand(C: std::make_unique<Command>(
9257 args: JA, args: *this, args: ResponseFileSupport::None(),
9258 args: TCArgs.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9259 args&: CmdArgs, args: ArrayRef<InputInfo>(), args: Outputs));
9260}
9261
9262void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
9263 const InputInfo &Output,
9264 const InputInfoList &Inputs,
9265 const llvm::opt::ArgList &Args,
9266 const char *LinkingOutput) const {
9267 ArgStringList CmdArgs;
9268
9269 // Add the output file name.
9270 assert(Output.isFilename() && "Invalid output.");
9271 CmdArgs.push_back(Elt: "-o");
9272 CmdArgs.push_back(Elt: Output.getFilename());
9273
9274 // Create the inputs to bundle the needed metadata.
9275 for (const InputInfo &Input : Inputs) {
9276 const Action *OffloadAction = Input.getAction();
9277 const ToolChain *TC = OffloadAction->getOffloadingToolChain();
9278 const ArgList &TCArgs =
9279 C.getArgsForToolChain(TC, BoundArch: OffloadAction->getOffloadingArch(),
9280 DeviceOffloadKind: OffloadAction->getOffloadingDeviceKind());
9281 StringRef File = C.getArgs().MakeArgString(Str: TC->getInputFilename(Input));
9282 StringRef Arch = OffloadAction->getOffloadingArch()
9283 ? OffloadAction->getOffloadingArch()
9284 : TCArgs.getLastArgValue(Id: options::OPT_march_EQ);
9285 StringRef Kind =
9286 Action::GetOffloadKindName(Kind: OffloadAction->getOffloadingDeviceKind());
9287
9288 ArgStringList Features;
9289 SmallVector<StringRef> FeatureArgs;
9290 getTargetFeatures(D: TC->getDriver(), Triple: TC->getTriple(), Args: TCArgs, CmdArgs&: Features,
9291 ForAS: false);
9292 llvm::copy_if(Range&: Features, Out: std::back_inserter(x&: FeatureArgs),
9293 P: [](StringRef Arg) { return !Arg.starts_with(Prefix: "-target"); });
9294
9295 // TODO: We need to pass in the full target-id and handle it properly in the
9296 // linker wrapper.
9297 SmallVector<std::string> Parts{
9298 "file=" + File.str(),
9299 "triple=" + TC->getTripleString(),
9300 "arch=" + (Arch.empty() ? "generic" : Arch.str()),
9301 "kind=" + Kind.str(),
9302 };
9303
9304 if (TC->getDriver().isUsingOffloadLTO())
9305 for (StringRef Feature : FeatureArgs)
9306 Parts.emplace_back(Args: "feature=" + Feature.str());
9307
9308 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--image=" + llvm::join(R&: Parts, Separator: ",")));
9309 }
9310
9311 C.addCommand(C: std::make_unique<Command>(
9312 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(),
9313 args: Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9314 args&: CmdArgs, args: Inputs, args: Output));
9315}
9316
9317void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
9318 const InputInfo &Output,
9319 const InputInfoList &Inputs,
9320 const ArgList &Args,
9321 const char *LinkingOutput) const {
9322 using namespace options;
9323
9324 // A list of permitted options that will be forwarded to the embedded device
9325 // compilation job.
9326 const llvm::DenseSet<unsigned> CompilerOptions{
9327 OPT_v,
9328 OPT_cuda_path_EQ,
9329 OPT_rocm_path_EQ,
9330 OPT_hip_path_EQ,
9331 OPT_O_Group,
9332 OPT_g_Group,
9333 OPT_g_flags_Group,
9334 OPT_R_value_Group,
9335 OPT_R_Group,
9336 OPT_Xcuda_ptxas,
9337 OPT_ftime_report,
9338 OPT_ftime_trace,
9339 OPT_ftime_trace_EQ,
9340 OPT_ftime_trace_granularity_EQ,
9341 OPT_ftime_trace_verbose,
9342 OPT_opt_record_file,
9343 OPT_opt_record_format,
9344 OPT_opt_record_passes,
9345 OPT_fsave_optimization_record,
9346 OPT_fsave_optimization_record_EQ,
9347 OPT_fno_save_optimization_record,
9348 OPT_foptimization_record_file_EQ,
9349 OPT_foptimization_record_passes_EQ,
9350 OPT_save_temps,
9351 OPT_save_temps_EQ,
9352 OPT_mcode_object_version_EQ,
9353 OPT_load,
9354 OPT_no_canonical_prefixes,
9355 OPT_fno_lto,
9356 OPT_flto,
9357 OPT_flto_partitions_EQ,
9358 OPT_flto_EQ,
9359 OPT_hipspv_pass_plugin_EQ,
9360 OPT_use_spirv_backend};
9361 const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9362 auto ShouldForwardForToolChain = [&](Arg *A, const ToolChain &TC) {
9363 // Don't forward -mllvm to toolchains that don't support LLVM.
9364 return TC.HasNativeLLVMSupport() || A->getOption().getID() != OPT_mllvm;
9365 };
9366 auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A,
9367 const ToolChain &TC) {
9368 // CMake hack to avoid printing verbose informatoin for HIP non-RDC mode.
9369 if (A->getOption().matches(ID: OPT_v) && JA.getType() == types::TY_HIP_FATBIN)
9370 return false;
9371 return (Set.contains(V: A->getOption().getID()) ||
9372 (A->getOption().getGroup().isValid() &&
9373 Set.contains(V: A->getOption().getGroup().getID()))) &&
9374 ShouldForwardForToolChain(A, TC);
9375 };
9376
9377 ArgStringList CmdArgs;
9378 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,
9379 Action::OFK_HIP, Action::OFK_SYCL}) {
9380 auto TCRange = C.getOffloadToolChains(Kind);
9381 for (auto &I : llvm::make_range(p: TCRange)) {
9382 const ToolChain *TC = I.second;
9383
9384 // We do not use a bound architecture here so options passed only to a
9385 // specific architecture via -Xarch_<cpu> will not be forwarded.
9386 ArgStringList CompilerArgs;
9387 ArgStringList LinkerArgs;
9388 const DerivedArgList &ToolChainArgs =
9389 C.getArgsForToolChain(TC, /*BoundArch=*/"", DeviceOffloadKind: Kind);
9390 for (Arg *A : ToolChainArgs) {
9391 if (A->getOption().matches(ID: OPT_Zlinker_input))
9392 LinkerArgs.emplace_back(Args: A->getValue());
9393 else if (ShouldForward(CompilerOptions, A, *TC))
9394 A->render(Args, Output&: CompilerArgs);
9395 else if (ShouldForward(LinkerOptions, A, *TC))
9396 A->render(Args, Output&: LinkerArgs);
9397 }
9398
9399 // If the user explicitly requested it via `--offload-arch` we should
9400 // extract it from any static libraries if present.
9401 for (StringRef Arg : ToolChainArgs.getAllArgValues(Id: OPT_offload_arch_EQ))
9402 CmdArgs.emplace_back(Args: Args.MakeArgString(Str: "--should-extract=" + Arg));
9403
9404 // If this is OpenMP the device linker will need `-lompdevice`.
9405 if (Kind == Action::OFK_OpenMP && !Args.hasArg(Ids: OPT_no_offloadlib) &&
9406 (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9407 LinkerArgs.emplace_back(Args: "-lompdevice");
9408
9409 // For SPIR-V, pass some extra flags to `spirv-link`, the out-of-tree
9410 // SPIR-V linker. `spirv-link` isn't called in LTO mode so restrict these
9411 // flags to normal compilation.
9412 // SPIR-V for AMD doesn't use spirv-link and therefore doesn't need these
9413 // flags.
9414 if (TC->getTriple().isSPIRV() &&
9415 TC->getTriple().getVendor() != llvm::Triple::VendorType::AMD &&
9416 !C.getDriver().isUsingLTO() && !C.getDriver().isUsingOffloadLTO()) {
9417 // For SPIR-V some functions will be defined by the runtime so allow
9418 // unresolved symbols in `spirv-link`.
9419 LinkerArgs.emplace_back(Args: "--allow-partial-linkage");
9420 // Don't optimize out exported symbols.
9421 LinkerArgs.emplace_back(Args: "--create-library");
9422 }
9423
9424 // Forward all of these to the appropriate toolchain.
9425 for (StringRef Arg : CompilerArgs)
9426 CmdArgs.push_back(Elt: Args.MakeArgString(
9427 Str: "--device-compiler=" + TC->getTripleString() + "=" + Arg));
9428 for (StringRef Arg : LinkerArgs)
9429 CmdArgs.push_back(Elt: Args.MakeArgString(
9430 Str: "--device-linker=" + TC->getTripleString() + "=" + Arg));
9431
9432 // Forward the LTO mode relying on the Driver's parsing.
9433 if (C.getDriver().getOffloadLTOMode() == LTOK_Full)
9434 CmdArgs.push_back(Elt: Args.MakeArgString(
9435 Str: "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
9436 else if (C.getDriver().getOffloadLTOMode() == LTOK_Thin) {
9437 CmdArgs.push_back(Elt: Args.MakeArgString(
9438 Str: "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
9439 if (TC->getTriple().isAMDGPU()) {
9440 CmdArgs.push_back(
9441 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9442 "=-plugin-opt=-force-import-all"));
9443 CmdArgs.push_back(
9444 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9445 "=-plugin-opt=-avail-extern-to-local"));
9446 CmdArgs.push_back(Elt: Args.MakeArgString(
9447 Str: "--device-linker=" + TC->getTripleString() +
9448 "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));
9449 if (Kind == Action::OFK_OpenMP) {
9450 CmdArgs.push_back(
9451 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9452 "=-plugin-opt=-amdgpu-internalize-symbols"));
9453 }
9454 }
9455 }
9456 }
9457 }
9458
9459 if (const llvm::Triple *AuxTriple = getToolChain().getAuxTriple())
9460 CmdArgs.push_back(
9461 Elt: Args.MakeArgString(Str: "--host-triple=" + AuxTriple->getTriple()));
9462 else
9463 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--host-triple=" +
9464 getToolChain().getTripleString()));
9465
9466 // CMake hack, suppress passing verbose arguments for the special-case HIP
9467 // non-RDC mode compilation. This confuses default CMake implicit linker
9468 // argument parsing when the language is set to HIP and the system linker is
9469 // also `ld.lld`.
9470 if (Args.hasArg(Ids: options::OPT_v) && JA.getType() != types::TY_HIP_FATBIN)
9471 CmdArgs.push_back(Elt: "--wrapper-verbose");
9472 if (Arg *A = Args.getLastArg(Ids: options::OPT_cuda_path_EQ))
9473 CmdArgs.push_back(
9474 Elt: Args.MakeArgString(Str: Twine("--cuda-path=") + A->getValue()));
9475
9476 // Construct the link job so we can wrap around it.
9477 Linker->ConstructJob(C, JA, Output, Inputs, TCArgs: Args, LinkingOutput);
9478 const auto &LinkCommand = C.getJobs().getJobs().back();
9479
9480 // Forward -Xoffload-{compiler,linker}<-triple> arguments to the linker
9481 // wrapper.
9482 for (Arg *A :
9483 Args.filtered(Ids: options::OPT_Xoffload_compiler, Ids: OPT_Xoffload_linker)) {
9484 StringRef Val = A->getValue(N: 0);
9485 bool IsLinkJob = A->getOption().getID() == OPT_Xoffload_linker;
9486 auto WrapperOption =
9487 IsLinkJob ? Twine("--device-linker=") : Twine("--device-compiler=");
9488 if (Val.empty())
9489 CmdArgs.push_back(Elt: Args.MakeArgString(Str: WrapperOption + A->getValue(N: 1)));
9490 else
9491 CmdArgs.push_back(Elt: Args.MakeArgString(
9492 Str: WrapperOption +
9493 ToolChain::getOpenMPTriple(TripleStr: Val.drop_front()).getTriple() + "=" +
9494 A->getValue(N: 1)));
9495 }
9496 Args.ClaimAllArgs(Id0: options::OPT_Xoffload_compiler);
9497 Args.ClaimAllArgs(Id0: options::OPT_Xoffload_linker);
9498
9499 // Embed bitcode instead of an object in JIT mode.
9500 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_jit,
9501 Neg: options::OPT_fno_openmp_target_jit, Default: false))
9502 CmdArgs.push_back(Elt: "--embed-bitcode");
9503
9504 // Save temporary files created by the linker wrapper.
9505 if (Args.hasArg(Ids: options::OPT_save_temps_EQ) ||
9506 Args.hasArg(Ids: options::OPT_save_temps))
9507 CmdArgs.push_back(Elt: "--save-temps");
9508
9509 // Pass in the C library for GPUs if present and not disabled.
9510 if (Args.hasFlag(Pos: options::OPT_offloadlib, Neg: OPT_no_offloadlib, Default: true) &&
9511 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_r,
9512 Ids: options::OPT_nodefaultlibs, Ids: options::OPT_nolibc,
9513 Ids: options::OPT_nogpulibc)) {
9514 forAllAssociatedToolChains(C, JA, RegularToolChain: getToolChain(), Work: [&](const ToolChain &TC) {
9515 // The device C library is only available for NVPTX and AMDGPU targets
9516 // and we only link it by default for OpenMP currently.
9517 if ((!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU()) ||
9518 !JA.isHostOffloading(OKind: Action::OFK_OpenMP))
9519 return;
9520 bool HasLibC = TC.getStdlibIncludePath().has_value();
9521 if (HasLibC) {
9522 CmdArgs.push_back(Elt: Args.MakeArgString(
9523 Str: "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
9524 CmdArgs.push_back(Elt: Args.MakeArgString(
9525 Str: "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
9526 }
9527 auto HasCompilerRT = getToolChain().getVFS().exists(
9528 Path: TC.getCompilerRT(Args, Component: "builtins", Type: ToolChain::FT_Static,
9529 /*IsFortran=*/false));
9530 if (HasCompilerRT)
9531 CmdArgs.push_back(
9532 Elt: Args.MakeArgString(Str: "--device-linker=" + TC.getTripleString() + "=" +
9533 "-lclang_rt.builtins"));
9534
9535 bool HasFlangRT = getToolChain().getVFS().exists(
9536 Path: TC.getCompilerRT(Args, Component: "runtime", Type: ToolChain::FT_Static,
9537 /*IsFortran=*/true));
9538 if (HasFlangRT && C.getDriver().IsFlangMode())
9539 CmdArgs.push_back(
9540 Elt: Args.MakeArgString(Str: "--device-linker=" + TC.getTripleString() + "=" +
9541 "-lflang_rt.runtime"));
9542 });
9543 }
9544
9545 // Add the linker arguments to be forwarded by the wrapper.
9546 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("--linker-path=") +
9547 LinkCommand->getExecutable()));
9548
9549 // We use action type to differentiate two use cases of the linker wrapper.
9550 // TY_Image for normal linker wrapper work.
9551 // TY_HIP_FATBIN for HIP fno-gpu-rdc emitting a fat binary without wrapping.
9552 assert(JA.getType() == types::TY_HIP_FATBIN ||
9553 JA.getType() == types::TY_Image);
9554 if (JA.getType() == types::TY_HIP_FATBIN) {
9555 CmdArgs.push_back(Elt: "--emit-fatbin-only");
9556 CmdArgs.append(IL: {"-o", Output.getFilename()});
9557 for (auto Input : Inputs)
9558 CmdArgs.push_back(Elt: Input.getFilename());
9559 } else
9560 for (const char *LinkArg : LinkCommand->getArguments())
9561 CmdArgs.push_back(Elt: LinkArg);
9562
9563 addOffloadCompressArgs(TCArgs: Args, CmdArgs);
9564
9565 if (Arg *A = Args.getLastArg(Ids: options::OPT_offload_jobs_EQ)) {
9566 StringRef Val = A->getValue();
9567
9568 if (Val.equals_insensitive(RHS: "jobserver"))
9569 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--wrapper-jobs=jobserver"));
9570 else {
9571 int NumThreads;
9572 if (Val.getAsInteger(Radix: 10, Result&: NumThreads) || NumThreads <= 0) {
9573 C.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
9574 << A->getAsString(Args) << Val;
9575 } else {
9576 CmdArgs.push_back(
9577 Elt: Args.MakeArgString(Str: "--wrapper-jobs=" + Twine(NumThreads)));
9578 }
9579 }
9580 }
9581
9582 // Propagate -no-canonical-prefixes.
9583 if (Args.hasArg(Ids: options::OPT_no_canonical_prefixes))
9584 CmdArgs.push_back(Elt: "--no-canonical-prefixes");
9585
9586 const char *Exec =
9587 Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: "clang-linker-wrapper"));
9588
9589 // Replace the executable and arguments of the link job with the
9590 // wrapper.
9591 LinkCommand->replaceExecutable(Exe: Exec);
9592 LinkCommand->replaceArguments(List: CmdArgs);
9593}
9594