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/Path.h"
53#include "llvm/Support/Process.h"
54#include "llvm/Support/YAMLParser.h"
55#include "llvm/TargetParser/AArch64TargetParser.h"
56#include "llvm/TargetParser/ARMTargetParserCommon.h"
57#include "llvm/TargetParser/Host.h"
58#include "llvm/TargetParser/LoongArchTargetParser.h"
59#include "llvm/TargetParser/PPCTargetParser.h"
60#include "llvm/TargetParser/RISCVISAInfo.h"
61#include "llvm/TargetParser/RISCVTargetParser.h"
62#include <cctype>
63
64using namespace clang::driver;
65using namespace clang::driver::tools;
66using namespace clang;
67using namespace llvm::opt;
68
69static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
70 if (Arg *A = Args.getLastArg(Ids: options::OPT_C, Ids: options::OPT_CC,
71 Ids: options::OPT_fminimize_whitespace,
72 Ids: options::OPT_fno_minimize_whitespace,
73 Ids: options::OPT_fkeep_system_includes,
74 Ids: options::OPT_fno_keep_system_includes)) {
75 if (!Args.hasArg(Ids: options::OPT_E) && !Args.hasArg(Ids: options::OPT__SLASH_P) &&
76 !Args.hasArg(Ids: options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
77 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
78 << A->getBaseArg().getAsString(Args)
79 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
80 }
81 }
82}
83
84static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
85 // In gcc, only ARM checks this, but it seems reasonable to check universally.
86 if (Args.hasArg(Ids: options::OPT_static))
87 if (const Arg *A =
88 Args.getLastArg(Ids: options::OPT_dynamic, Ids: options::OPT_mdynamic_no_pic))
89 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
90 << "-static";
91}
92
93/// Apply \a Work on the current tool chain \a RegularToolChain and any other
94/// offloading tool chain that is associated with the current action \a JA.
95static void
96forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
97 const ToolChain &RegularToolChain,
98 llvm::function_ref<void(const ToolChain &)> Work) {
99 // Apply Work on the current/regular tool chain.
100 Work(RegularToolChain);
101
102 // Apply Work on all the offloading tool chains associated with the current
103 // action.
104 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,
105 Action::OFK_HIP, Action::OFK_SYCL}) {
106 if (JA.isHostOffloading(OKind: Kind)) {
107 auto TCs = C.getOffloadToolChains(Kind);
108 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
109 Work(*II->second);
110 } else if (JA.isDeviceOffloading(OKind: Kind))
111 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
112 }
113}
114
115static bool
116shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
117 const llvm::Triple &Triple) {
118 // We use the zero-cost exception tables for Objective-C if the non-fragile
119 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
120 // later.
121 if (runtime.isNonFragile())
122 return true;
123
124 if (!Triple.isMacOSX())
125 return false;
126
127 return (!Triple.isMacOSXVersionLT(Major: 10, Minor: 5) &&
128 (Triple.getArch() == llvm::Triple::x86_64 ||
129 Triple.getArch() == llvm::Triple::arm));
130}
131
132/// Adds exception related arguments to the driver command arguments. There's a
133/// main flag, -fexceptions and also language specific flags to enable/disable
134/// C++ and Objective-C exceptions. This makes it possible to for example
135/// disable C++ exceptions but enable Objective-C exceptions.
136static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
137 const ToolChain &TC, bool KernelOrKext,
138 const ObjCRuntime &objcRuntime,
139 ArgStringList &CmdArgs) {
140 const llvm::Triple &Triple = TC.getTriple();
141
142 if (KernelOrKext) {
143 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
144 // arguments now to avoid warnings about unused arguments.
145 Args.ClaimAllArgs(Id0: options::OPT_fexceptions);
146 Args.ClaimAllArgs(Id0: options::OPT_fno_exceptions);
147 Args.ClaimAllArgs(Id0: options::OPT_fobjc_exceptions);
148 Args.ClaimAllArgs(Id0: options::OPT_fno_objc_exceptions);
149 Args.ClaimAllArgs(Id0: options::OPT_fcxx_exceptions);
150 Args.ClaimAllArgs(Id0: options::OPT_fno_cxx_exceptions);
151 Args.ClaimAllArgs(Id0: options::OPT_fasync_exceptions);
152 Args.ClaimAllArgs(Id0: options::OPT_fno_async_exceptions);
153 return false;
154 }
155
156 // See if the user explicitly enabled exceptions.
157 bool EH = Args.hasFlag(Pos: options::OPT_fexceptions, Neg: options::OPT_fno_exceptions,
158 Default: false);
159
160 // Async exceptions are Windows MSVC only.
161 if (Triple.isWindowsMSVCEnvironment()) {
162 bool EHa = Args.hasFlag(Pos: options::OPT_fasync_exceptions,
163 Neg: options::OPT_fno_async_exceptions, Default: false);
164 if (EHa) {
165 CmdArgs.push_back(Elt: "-fasync-exceptions");
166 EH = true;
167 }
168 }
169
170 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
171 // is not necessarily sensible, but follows GCC.
172 if (types::isObjC(Id: InputType) &&
173 Args.hasFlag(Pos: options::OPT_fobjc_exceptions,
174 Neg: options::OPT_fno_objc_exceptions, Default: true)) {
175 CmdArgs.push_back(Elt: "-fobjc-exceptions");
176
177 EH |= shouldUseExceptionTablesForObjCExceptions(runtime: objcRuntime, Triple);
178 }
179
180 if (types::isCXX(Id: InputType)) {
181 // Disable C++ EH by default on XCore and PS4/PS5.
182 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
183 !Triple.isPS() && !Triple.isDriverKit();
184 Arg *ExceptionArg = Args.getLastArg(
185 Ids: options::OPT_fcxx_exceptions, Ids: options::OPT_fno_cxx_exceptions,
186 Ids: options::OPT_fexceptions, Ids: options::OPT_fno_exceptions);
187 if (ExceptionArg)
188 CXXExceptionsEnabled =
189 ExceptionArg->getOption().matches(ID: options::OPT_fcxx_exceptions) ||
190 ExceptionArg->getOption().matches(ID: options::OPT_fexceptions);
191
192 if (CXXExceptionsEnabled) {
193 CmdArgs.push_back(Elt: "-fcxx-exceptions");
194
195 EH = true;
196 }
197 }
198
199 // OPT_fignore_exceptions means exception could still be thrown,
200 // but no clean up or catch would happen in current module.
201 // So we do not set EH to false.
202 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fignore_exceptions);
203
204 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fassume_nothrow_exception_dtor,
205 Neg: options::OPT_fno_assume_nothrow_exception_dtor);
206
207 if (EH)
208 CmdArgs.push_back(Elt: "-fexceptions");
209 return EH;
210}
211
212static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
213 const JobAction &JA) {
214 bool Default = true;
215 if (TC.getTriple().isOSDarwin()) {
216 // The native darwin assembler doesn't support the linker_option directives,
217 // so we disable them if we think the .s file will be passed to it.
218 Default = TC.useIntegratedAs();
219 }
220 // The linker_option directives are intended for host compilation.
221 if (JA.isDeviceOffloading(OKind: Action::OFK_Cuda) ||
222 JA.isDeviceOffloading(OKind: Action::OFK_HIP))
223 Default = false;
224 return Args.hasFlag(Pos: options::OPT_fautolink, Neg: options::OPT_fno_autolink,
225 Default);
226}
227
228/// Add a CC1 option to specify the debug compilation directory.
229static const char *addDebugCompDirArg(const ArgList &Args,
230 ArgStringList &CmdArgs,
231 const llvm::vfs::FileSystem &VFS) {
232 std::string DebugCompDir;
233 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffile_compilation_dir_EQ,
234 Ids: options::OPT_fdebug_compilation_dir_EQ))
235 DebugCompDir = A->getValue();
236
237 if (DebugCompDir.empty()) {
238 if (llvm::ErrorOr<std::string> CWD = VFS.getCurrentWorkingDirectory())
239 DebugCompDir = std::move(*CWD);
240 else
241 return nullptr;
242 }
243 CmdArgs.push_back(
244 Elt: Args.MakeArgString(Str: "-fdebug-compilation-dir=" + DebugCompDir));
245 StringRef Path(CmdArgs.back());
246 return Path.substr(Start: Path.find(C: '=') + 1).data();
247}
248
249static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
250 const char *DebugCompilationDir,
251 const char *OutputFileName) {
252 // No need to generate a value for -object-file-name if it was provided.
253 for (auto *Arg : Args.filtered(Ids: options::OPT_Xclang))
254 if (StringRef(Arg->getValue()).starts_with(Prefix: "-object-file-name"))
255 return;
256
257 if (Args.hasArg(Ids: options::OPT_object_file_name_EQ))
258 return;
259
260 SmallString<128> ObjFileNameForDebug(OutputFileName);
261 if (ObjFileNameForDebug != "-" &&
262 !llvm::sys::path::is_absolute(path: ObjFileNameForDebug) &&
263 (!DebugCompilationDir ||
264 llvm::sys::path::is_absolute(path: DebugCompilationDir))) {
265 // Make the path absolute in the debug infos like MSVC does.
266 llvm::sys::fs::make_absolute(path&: ObjFileNameForDebug);
267 }
268 // If the object file name is a relative path, then always use Windows
269 // backslash style as -object-file-name is used for embedding object file path
270 // in codeview and it can only be generated when targeting on Windows.
271 // Otherwise, just use native absolute path.
272 llvm::sys::path::Style Style =
273 llvm::sys::path::is_absolute(path: ObjFileNameForDebug)
274 ? llvm::sys::path::Style::native
275 : llvm::sys::path::Style::windows_backslash;
276 llvm::sys::path::remove_dots(path&: ObjFileNameForDebug, /*remove_dot_dot=*/true,
277 style: Style);
278 CmdArgs.push_back(
279 Elt: Args.MakeArgString(Str: Twine("-object-file-name=") + ObjFileNameForDebug));
280}
281
282/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
283static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
284 const ArgList &Args, ArgStringList &CmdArgs) {
285 auto AddOneArg = [&](StringRef Map, StringRef Name) {
286 if (!Map.contains(C: '='))
287 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option) << Map << Name;
288 else
289 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fdebug-prefix-map=" + Map));
290 };
291
292 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
293 Ids: options::OPT_fdebug_prefix_map_EQ)) {
294 AddOneArg(A->getValue(), A->getOption().getName());
295 A->claim();
296 }
297 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
298 if (GlobalRemapEntry.empty())
299 return;
300 AddOneArg(GlobalRemapEntry, "environment");
301}
302
303/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
304static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
305 ArgStringList &CmdArgs) {
306 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
307 Ids: options::OPT_fmacro_prefix_map_EQ)) {
308 StringRef Map = A->getValue();
309 if (!Map.contains(C: '='))
310 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
311 << Map << A->getOption().getName();
312 else
313 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fmacro-prefix-map=" + Map));
314 A->claim();
315 }
316}
317
318/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
319static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
320 ArgStringList &CmdArgs) {
321 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
322 Ids: options::OPT_fcoverage_prefix_map_EQ)) {
323 StringRef Map = A->getValue();
324 if (!Map.contains(C: '='))
325 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
326 << Map << A->getOption().getName();
327 else
328 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fcoverage-prefix-map=" + Map));
329 A->claim();
330 }
331}
332
333/// Add -x lang to \p CmdArgs for \p Input.
334static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
335 ArgStringList &CmdArgs) {
336 // When using -verify-pch, we don't want to provide the type
337 // 'precompiled-header' if it was inferred from the file extension
338 if (Args.hasArg(Ids: options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
339 return;
340
341 CmdArgs.push_back(Elt: "-x");
342 if (Args.hasArg(Ids: options::OPT_rewrite_objc))
343 CmdArgs.push_back(Elt: types::getTypeName(Id: types::TY_ObjCXX));
344 else {
345 // Map the driver type to the frontend type. This is mostly an identity
346 // mapping, except that the distinction between module interface units
347 // and other source files does not exist at the frontend layer.
348 const char *ClangType;
349 switch (Input.getType()) {
350 case types::TY_CXXModule:
351 ClangType = "c++";
352 break;
353 case types::TY_PP_CXXModule:
354 ClangType = "c++-cpp-output";
355 break;
356 default:
357 ClangType = types::getTypeName(Id: Input.getType());
358 break;
359 }
360 CmdArgs.push_back(Elt: ClangType);
361 }
362}
363
364static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
365 const JobAction &JA, const InputInfo &Output,
366 const ArgList &Args, SanitizerArgs &SanArgs,
367 ArgStringList &CmdArgs) {
368 const Driver &D = TC.getDriver();
369 const llvm::Triple &T = TC.getTriple();
370 auto *PGOGenerateArg = Args.getLastArg(Ids: options::OPT_fprofile_generate,
371 Ids: options::OPT_fprofile_generate_EQ,
372 Ids: options::OPT_fno_profile_generate);
373 if (PGOGenerateArg &&
374 PGOGenerateArg->getOption().matches(ID: options::OPT_fno_profile_generate))
375 PGOGenerateArg = nullptr;
376
377 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
378
379 auto *ProfileGenerateArg = Args.getLastArg(
380 Ids: options::OPT_fprofile_instr_generate,
381 Ids: options::OPT_fprofile_instr_generate_EQ,
382 Ids: options::OPT_fno_profile_instr_generate);
383 if (ProfileGenerateArg &&
384 ProfileGenerateArg->getOption().matches(
385 ID: options::OPT_fno_profile_instr_generate))
386 ProfileGenerateArg = nullptr;
387
388 if (PGOGenerateArg && ProfileGenerateArg)
389 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
390 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
391
392 auto *ProfileUseArg = getLastProfileUseArg(Args);
393
394 if (PGOGenerateArg && ProfileUseArg)
395 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
396 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
397
398 if (ProfileGenerateArg && ProfileUseArg)
399 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
400 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
401
402 if (CSPGOGenerateArg && PGOGenerateArg) {
403 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
404 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
405 PGOGenerateArg = nullptr;
406 }
407
408 if (TC.getTriple().isOSAIX()) {
409 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
410 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
411 << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
412 }
413
414 if (ProfileGenerateArg) {
415 if (ProfileGenerateArg->getOption().matches(
416 ID: options::OPT_fprofile_instr_generate_EQ))
417 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-path=") +
418 ProfileGenerateArg->getValue()));
419 // The default is to use Clang Instrumentation.
420 CmdArgs.push_back(Elt: "-fprofile-instrument=clang");
421 if (TC.getTriple().isWindowsMSVCEnvironment() &&
422 Args.hasFlag(Pos: options::OPT_frtlib_defaultlib,
423 Neg: options::OPT_fno_rtlib_defaultlib, Default: true)) {
424 // Add dependent lib for clang_rt.profile
425 CmdArgs.push_back(Elt: Args.MakeArgString(
426 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "profile")));
427 }
428 }
429
430 if (auto *ColdFuncCoverageArg = Args.getLastArg(
431 Ids: options::OPT_fprofile_generate_cold_function_coverage,
432 Ids: options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
433 SmallString<128> Path(
434 ColdFuncCoverageArg->getOption().matches(
435 ID: options::OPT_fprofile_generate_cold_function_coverage_EQ)
436 ? ColdFuncCoverageArg->getValue()
437 : "");
438 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
439 // FIXME: Idealy the file path should be passed through
440 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
441 // shared with other profile use path(see PGOOptions), we need to refactor
442 // PGOOptions to make it work.
443 CmdArgs.push_back(Elt: "-mllvm");
444 CmdArgs.push_back(Elt: Args.MakeArgString(
445 Str: Twine("--instrument-cold-function-only-path=") + Path));
446 CmdArgs.push_back(Elt: "-mllvm");
447 CmdArgs.push_back(Elt: "--pgo-instrument-cold-function-only");
448 CmdArgs.push_back(Elt: "-mllvm");
449 CmdArgs.push_back(Elt: "--pgo-function-entry-coverage");
450 CmdArgs.push_back(Elt: "-fprofile-instrument=sample-coldcov");
451 }
452
453 if (auto *A = Args.getLastArg(Ids: options::OPT_ftemporal_profile)) {
454 if (!PGOGenerateArg && !CSPGOGenerateArg)
455 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
456 << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
457 CmdArgs.push_back(Elt: "-mllvm");
458 CmdArgs.push_back(Elt: "--pgo-temporal-instrumentation");
459 }
460
461 Arg *PGOGenArg = nullptr;
462 if (PGOGenerateArg) {
463 assert(!CSPGOGenerateArg);
464 PGOGenArg = PGOGenerateArg;
465 CmdArgs.push_back(Elt: "-fprofile-instrument=llvm");
466 }
467 if (CSPGOGenerateArg) {
468 assert(!PGOGenerateArg);
469 PGOGenArg = CSPGOGenerateArg;
470 CmdArgs.push_back(Elt: "-fprofile-instrument=csllvm");
471 }
472 if (PGOGenArg) {
473 if (TC.getTriple().isWindowsMSVCEnvironment() &&
474 Args.hasFlag(Pos: options::OPT_frtlib_defaultlib,
475 Neg: options::OPT_fno_rtlib_defaultlib, Default: true)) {
476 // Add dependent lib for clang_rt.profile
477 CmdArgs.push_back(Elt: Args.MakeArgString(
478 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "profile")));
479 }
480 if (PGOGenArg->getOption().matches(
481 ID: PGOGenerateArg ? options::OPT_fprofile_generate_EQ
482 : options::OPT_fcs_profile_generate_EQ)) {
483 SmallString<128> Path(PGOGenArg->getValue());
484 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
485 CmdArgs.push_back(
486 Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-path=") + Path));
487 }
488 }
489
490 if (ProfileUseArg) {
491 SmallString<128> UsePathBuf;
492 StringRef UsePath;
493 if (ProfileUseArg->getOption().matches(ID: options::OPT_fprofile_instr_use_EQ))
494 UsePath = ProfileUseArg->getValue();
495 else if ((ProfileUseArg->getOption().matches(
496 ID: options::OPT_fprofile_use_EQ) ||
497 ProfileUseArg->getOption().matches(
498 ID: options::OPT_fprofile_instr_use))) {
499 UsePathBuf =
500 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue();
501 if (UsePathBuf.empty() || llvm::sys::fs::is_directory(Path: UsePathBuf))
502 llvm::sys::path::append(path&: UsePathBuf, a: "default.profdata");
503 UsePath = UsePathBuf;
504 }
505 auto ReaderOrErr =
506 llvm::IndexedInstrProfReader::create(Path: UsePath, FS&: D.getVFS());
507 if (auto E = ReaderOrErr.takeError()) {
508 auto DiagID = D.getDiags().getCustomDiagID(
509 L: DiagnosticsEngine::Error, FormatString: "Error in reading profile %0: %1");
510 llvm::handleAllErrors(E: std::move(E), Handlers: [&](const llvm::ErrorInfoBase &EI) {
511 D.Diag(DiagID) << UsePath.str() << EI.message();
512 });
513 } else {
514 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
515 std::move(ReaderOrErr.get());
516 StringRef UseKind;
517 // Currently memprof profiles are only added at the IR level. Mark the
518 // profile type as IR in that case as well and the subsequent matching
519 // needs to detect which is available (might be one or both).
520 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
521 if (PGOReader->hasCSIRLevelProfile())
522 UseKind = "csllvm";
523 else
524 UseKind = "llvm";
525 } else
526 UseKind = "clang";
527
528 CmdArgs.push_back(
529 Elt: Args.MakeArgString(Str: "-fprofile-instrument-use=" + UseKind));
530 CmdArgs.push_back(
531 Elt: Args.MakeArgString(Str: "-fprofile-instrument-use-path=" + UsePath));
532 }
533 }
534
535 bool EmitCovNotes = Args.hasFlag(Pos: options::OPT_ftest_coverage,
536 Neg: options::OPT_fno_test_coverage, Default: false) ||
537 Args.hasArg(Ids: options::OPT_coverage);
538 bool EmitCovData = TC.needsGCovInstrumentation(Args);
539
540 if (Args.hasFlag(Pos: options::OPT_fcoverage_mapping,
541 Neg: options::OPT_fno_coverage_mapping, Default: false)) {
542 if (!ProfileGenerateArg)
543 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
544 << "-fcoverage-mapping"
545 << "-fprofile-instr-generate";
546
547 CmdArgs.push_back(Elt: "-fcoverage-mapping");
548 }
549
550 if (Args.hasFlag(Pos: options::OPT_fmcdc_coverage, Neg: options::OPT_fno_mcdc_coverage,
551 Default: false)) {
552 if (!Args.hasFlag(Pos: options::OPT_fcoverage_mapping,
553 Neg: options::OPT_fno_coverage_mapping, Default: false))
554 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
555 << "-fcoverage-mcdc"
556 << "-fcoverage-mapping";
557
558 CmdArgs.push_back(Elt: "-fcoverage-mcdc");
559 }
560
561 StringRef CoverageCompDir;
562 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffile_compilation_dir_EQ,
563 Ids: options::OPT_fcoverage_compilation_dir_EQ))
564 CoverageCompDir = A->getValue();
565 if (CoverageCompDir.empty()) {
566 if (auto CWD = D.getVFS().getCurrentWorkingDirectory())
567 CmdArgs.push_back(
568 Elt: Args.MakeArgString(Str: Twine("-fcoverage-compilation-dir=") + *CWD));
569 } else
570 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fcoverage-compilation-dir=") +
571 CoverageCompDir));
572
573 if (Args.hasArg(Ids: options::OPT_fprofile_exclude_files_EQ)) {
574 auto *Arg = Args.getLastArg(Ids: options::OPT_fprofile_exclude_files_EQ);
575 if (!Args.hasArg(Ids: options::OPT_coverage))
576 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
577 << "-fprofile-exclude-files="
578 << "--coverage";
579
580 StringRef v = Arg->getValue();
581 CmdArgs.push_back(
582 Elt: Args.MakeArgString(Str: Twine("-fprofile-exclude-files=" + v)));
583 }
584
585 if (Args.hasArg(Ids: options::OPT_fprofile_filter_files_EQ)) {
586 auto *Arg = Args.getLastArg(Ids: options::OPT_fprofile_filter_files_EQ);
587 if (!Args.hasArg(Ids: options::OPT_coverage))
588 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
589 << "-fprofile-filter-files="
590 << "--coverage";
591
592 StringRef v = Arg->getValue();
593 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fprofile-filter-files=" + v)));
594 }
595
596 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_update_EQ)) {
597 StringRef Val = A->getValue();
598 if (Val == "atomic" || Val == "prefer-atomic")
599 CmdArgs.push_back(Elt: "-fprofile-update=atomic");
600 else if (Val != "single")
601 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
602 << A->getSpelling() << Val;
603 }
604 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_continuous)) {
605 if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
606 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
607 << A->getSpelling()
608 << "-fprofile-generate, -fprofile-instr-generate, or "
609 "-fcs-profile-generate";
610 else {
611 CmdArgs.push_back(Elt: "-fprofile-continuous");
612 // Platforms that require a bias variable:
613 if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
614 CmdArgs.push_back(Elt: "-mllvm");
615 CmdArgs.push_back(Elt: "-runtime-counter-relocation");
616 }
617 // -fprofile-instr-generate does not decide the profile file name in the
618 // FE, and so it does not define the filename symbol
619 // (__llvm_profile_filename). Instead, the runtime uses the name
620 // "default.profraw" for the profile file. When continuous mode is ON, we
621 // will create the filename symbol so that we can insert the "%c"
622 // modifier.
623 if (ProfileGenerateArg &&
624 (ProfileGenerateArg->getOption().matches(
625 ID: options::OPT_fprofile_instr_generate) ||
626 (ProfileGenerateArg->getOption().matches(
627 ID: options::OPT_fprofile_instr_generate_EQ) &&
628 strlen(s: ProfileGenerateArg->getValue()) == 0)))
629 CmdArgs.push_back(Elt: "-fprofile-instrument-path=default.profraw");
630 }
631 }
632
633 int FunctionGroups = 1;
634 int SelectedFunctionGroup = 0;
635 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_function_groups)) {
636 StringRef Val = A->getValue();
637 if (Val.getAsInteger(Radix: 0, Result&: FunctionGroups) || FunctionGroups < 1)
638 D.Diag(DiagID: diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
639 }
640 if (const auto *A =
641 Args.getLastArg(Ids: options::OPT_fprofile_selected_function_group)) {
642 StringRef Val = A->getValue();
643 if (Val.getAsInteger(Radix: 0, Result&: SelectedFunctionGroup) ||
644 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
645 D.Diag(DiagID: diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
646 }
647 if (FunctionGroups != 1)
648 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-function-groups=" +
649 Twine(FunctionGroups)));
650 if (SelectedFunctionGroup != 0)
651 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-selected-function-group=" +
652 Twine(SelectedFunctionGroup)));
653
654 // Leave -fprofile-dir= an unused argument unless .gcda emission is
655 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
656 // the flag used. There is no -fno-profile-dir, so the user has no
657 // targeted way to suppress the warning.
658 Arg *FProfileDir = nullptr;
659 if (Args.hasArg(Ids: options::OPT_fprofile_arcs) ||
660 Args.hasArg(Ids: options::OPT_coverage))
661 FProfileDir = Args.getLastArg(Ids: options::OPT_fprofile_dir);
662
663 // Put the .gcno and .gcda files (if needed) next to the primary output file,
664 // or fall back to a file in the current directory for `clang -c --coverage
665 // d/a.c` in the absence of -o.
666 if (EmitCovNotes || EmitCovData) {
667 SmallString<128> CoverageFilename;
668 if (Arg *DumpDir = Args.getLastArgNoClaim(Ids: options::OPT_dumpdir)) {
669 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
670 // path separator.
671 CoverageFilename = DumpDir->getValue();
672 CoverageFilename += llvm::sys::path::filename(path: Output.getBaseInput());
673 } else if (Arg *FinalOutput =
674 C.getArgs().getLastArg(Ids: options::OPT__SLASH_Fo)) {
675 CoverageFilename = FinalOutput->getValue();
676 } else if (Arg *FinalOutput = C.getArgs().getLastArg(Ids: options::OPT_o)) {
677 CoverageFilename = FinalOutput->getValue();
678 } else {
679 CoverageFilename = llvm::sys::path::filename(path: Output.getBaseInput());
680 }
681 if (llvm::sys::path::is_relative(path: CoverageFilename))
682 (void)D.getVFS().makeAbsolute(Path&: CoverageFilename);
683 llvm::sys::path::replace_extension(path&: CoverageFilename, extension: "gcno");
684 if (EmitCovNotes) {
685 CmdArgs.push_back(
686 Elt: Args.MakeArgString(Str: "-coverage-notes-file=" + CoverageFilename));
687 }
688
689 if (EmitCovData) {
690 if (FProfileDir) {
691 SmallString<128> Gcno = std::move(CoverageFilename);
692 CoverageFilename = FProfileDir->getValue();
693 llvm::sys::path::append(path&: CoverageFilename, a: Gcno);
694 }
695 llvm::sys::path::replace_extension(path&: CoverageFilename, extension: "gcda");
696 CmdArgs.push_back(
697 Elt: Args.MakeArgString(Str: "-coverage-data-file=" + CoverageFilename));
698 }
699 }
700}
701
702static void
703RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
704 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
705 unsigned DwarfVersion,
706 llvm::DebuggerKind DebuggerTuning) {
707 addDebugInfoKind(CmdArgs, DebugInfoKind);
708 if (DwarfVersion > 0)
709 CmdArgs.push_back(
710 Elt: Args.MakeArgString(Str: "-dwarf-version=" + Twine(DwarfVersion)));
711 switch (DebuggerTuning) {
712 case llvm::DebuggerKind::GDB:
713 CmdArgs.push_back(Elt: "-debugger-tuning=gdb");
714 break;
715 case llvm::DebuggerKind::LLDB:
716 CmdArgs.push_back(Elt: "-debugger-tuning=lldb");
717 break;
718 case llvm::DebuggerKind::SCE:
719 CmdArgs.push_back(Elt: "-debugger-tuning=sce");
720 break;
721 case llvm::DebuggerKind::DBX:
722 CmdArgs.push_back(Elt: "-debugger-tuning=dbx");
723 break;
724 default:
725 break;
726 }
727}
728
729static void RenderDebugInfoCompressionArgs(const ArgList &Args,
730 ArgStringList &CmdArgs,
731 const Driver &D,
732 const ToolChain &TC) {
733 const Arg *A = Args.getLastArg(Ids: options::OPT_gz_EQ);
734 if (!A)
735 return;
736 if (checkDebugInfoOption(A, Args, D, TC)) {
737 StringRef Value = A->getValue();
738 if (Value == "none") {
739 CmdArgs.push_back(Elt: "--compress-debug-sections=none");
740 } else if (Value == "zlib") {
741 if (llvm::compression::zlib::isAvailable()) {
742 CmdArgs.push_back(
743 Elt: Args.MakeArgString(Str: "--compress-debug-sections=" + Twine(Value)));
744 } else {
745 D.Diag(DiagID: diag::warn_debug_compression_unavailable) << "zlib";
746 }
747 } else if (Value == "zstd") {
748 if (llvm::compression::zstd::isAvailable()) {
749 CmdArgs.push_back(
750 Elt: Args.MakeArgString(Str: "--compress-debug-sections=" + Twine(Value)));
751 } else {
752 D.Diag(DiagID: diag::warn_debug_compression_unavailable) << "zstd";
753 }
754 } else {
755 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
756 << A->getSpelling() << Value;
757 }
758 }
759}
760
761static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
762 const ArgList &Args,
763 ArgStringList &CmdArgs,
764 bool IsCC1As = false) {
765 // If no version was requested by the user, use the default value from the
766 // back end. This is consistent with the value returned from
767 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
768 // requiring the corresponding llvm to have the AMDGPU target enabled,
769 // provided the user (e.g. front end tests) can use the default.
770 if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
771 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
772 CmdArgs.insert(I: CmdArgs.begin() + 1,
773 Elt: Args.MakeArgString(Str: Twine("--amdhsa-code-object-version=") +
774 Twine(CodeObjVer)));
775 CmdArgs.insert(I: CmdArgs.begin() + 1, Elt: "-mllvm");
776 // -cc1as does not accept -mcode-object-version option.
777 if (!IsCC1As)
778 CmdArgs.insert(I: CmdArgs.begin() + 1,
779 Elt: Args.MakeArgString(Str: Twine("-mcode-object-version=") +
780 Twine(CodeObjVer)));
781 }
782}
783
784static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
785 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
786 D.getVFS().getBufferForFile(Name: Path);
787 if (!MemBuf)
788 return false;
789 llvm::file_magic Magic = llvm::identify_magic(magic: (*MemBuf)->getBuffer());
790 if (Magic == llvm::file_magic::unknown)
791 return false;
792 // Return true for both raw Clang AST files and object files which may
793 // contain a __clangast section.
794 if (Magic == llvm::file_magic::clang_ast)
795 return true;
796 Expected<std::unique_ptr<llvm::object::ObjectFile>> Obj =
797 llvm::object::ObjectFile::createObjectFile(Object: **MemBuf, Type: Magic);
798 return !Obj.takeError();
799}
800
801static bool gchProbe(const Driver &D, StringRef Path) {
802 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
803 if (!Status)
804 return false;
805
806 if (Status->isDirectory()) {
807 std::error_code EC;
808 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Dir: Path, EC), DE;
809 !EC && DI != DE; DI = DI.increment(EC)) {
810 if (maybeHasClangPchSignature(D, Path: DI->path()))
811 return true;
812 }
813 D.Diag(DiagID: diag::warn_drv_pch_ignoring_gch_dir) << Path;
814 return false;
815 }
816
817 if (maybeHasClangPchSignature(D, Path))
818 return true;
819 D.Diag(DiagID: diag::warn_drv_pch_ignoring_gch_file) << Path;
820 return false;
821}
822
823void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
824 const Driver &D, const ArgList &Args,
825 ArgStringList &CmdArgs,
826 const InputInfo &Output,
827 const InputInfoList &Inputs) const {
828 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
829
830 CheckPreprocessingOptions(D, Args);
831
832 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_C);
833 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_CC);
834
835 // Handle dependency file generation.
836 Arg *ArgM = Args.getLastArg(Ids: options::OPT_MM);
837 if (!ArgM)
838 ArgM = Args.getLastArg(Ids: options::OPT_M);
839 Arg *ArgMD = Args.getLastArg(Ids: options::OPT_MMD);
840 if (!ArgMD)
841 ArgMD = Args.getLastArg(Ids: options::OPT_MD);
842
843 // -M and -MM imply -w.
844 if (ArgM)
845 CmdArgs.push_back(Elt: "-w");
846 else
847 ArgM = ArgMD;
848
849 if (ArgM) {
850 if (!JA.isDeviceOffloading(OKind: Action::OFK_HIP)) {
851 // Determine the output location.
852 const char *DepFile;
853 if (Arg *MF = Args.getLastArg(Ids: options::OPT_MF)) {
854 DepFile = MF->getValue();
855 C.addFailureResultFile(Name: DepFile, JA: &JA);
856 } else if (Output.getType() == types::TY_Dependencies) {
857 DepFile = Output.getFilename();
858 } else if (!ArgMD) {
859 DepFile = "-";
860 } else {
861 DepFile = getDependencyFileName(Args, Inputs);
862 C.addFailureResultFile(Name: DepFile, JA: &JA);
863 }
864 CmdArgs.push_back(Elt: "-dependency-file");
865 CmdArgs.push_back(Elt: DepFile);
866 }
867 // Cmake generates dependency files using all compilation options specified
868 // by users. Claim those not used for dependency files.
869 if (JA.isOffloading(OKind: Action::OFK_HIP)) {
870 Args.ClaimAllArgs(Id0: options::OPT_offload_compress);
871 Args.ClaimAllArgs(Id0: options::OPT_no_offload_compress);
872 Args.ClaimAllArgs(Id0: options::OPT_offload_jobs_EQ);
873 }
874
875 bool HasTarget = false;
876 for (const Arg *A : Args.filtered(Ids: options::OPT_MT, Ids: options::OPT_MQ)) {
877 HasTarget = true;
878 A->claim();
879 if (A->getOption().matches(ID: options::OPT_MT)) {
880 A->render(Args, Output&: CmdArgs);
881 } else {
882 CmdArgs.push_back(Elt: "-MT");
883 SmallString<128> Quoted;
884 quoteMakeTarget(Target: A->getValue(), Res&: Quoted);
885 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Quoted));
886 }
887 }
888
889 // Add a default target if one wasn't specified.
890 if (!HasTarget) {
891 const char *DepTarget;
892
893 // If user provided -o, that is the dependency target, except
894 // when we are only generating a dependency file.
895 Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o, Ids: options::OPT__SLASH_Fo);
896 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
897 DepTarget = OutputOpt->getValue();
898 } else {
899 // Otherwise derive from the base input.
900 //
901 // FIXME: This should use the computed output file location.
902 SmallString<128> P(Inputs[0].getBaseInput());
903 llvm::sys::path::replace_extension(path&: P, extension: "o");
904 DepTarget = Args.MakeArgString(Str: llvm::sys::path::filename(path: P));
905 }
906
907 CmdArgs.push_back(Elt: "-MT");
908 SmallString<128> Quoted;
909 quoteMakeTarget(Target: DepTarget, Res&: Quoted);
910 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Quoted));
911 }
912
913 if (ArgM->getOption().matches(ID: options::OPT_M) ||
914 ArgM->getOption().matches(ID: options::OPT_MD))
915 CmdArgs.push_back(Elt: "-sys-header-deps");
916 if ((isa<PrecompileJobAction>(Val: JA) &&
917 !Args.hasArg(Ids: options::OPT_fno_module_file_deps)) ||
918 Args.hasArg(Ids: options::OPT_fmodule_file_deps))
919 CmdArgs.push_back(Elt: "-module-file-deps");
920 }
921
922 if (Args.hasArg(Ids: options::OPT_MG)) {
923 if (!ArgM || ArgM->getOption().matches(ID: options::OPT_MD) ||
924 ArgM->getOption().matches(ID: options::OPT_MMD))
925 D.Diag(DiagID: diag::err_drv_mg_requires_m_or_mm);
926 CmdArgs.push_back(Elt: "-MG");
927 }
928
929 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_MP);
930 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_MV);
931
932 // Add offload include arguments specific for CUDA/HIP/SYCL. This must happen
933 // before we -I or -include anything else, because we must pick up the
934 // CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL installation,
935 // rather than from e.g. /usr/local/include.
936 if (JA.isOffloading(OKind: Action::OFK_Cuda))
937 getToolChain().AddCudaIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
938 if (JA.isOffloading(OKind: Action::OFK_HIP))
939 getToolChain().AddHIPIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
940 if (JA.isOffloading(OKind: Action::OFK_SYCL))
941 getToolChain().addSYCLIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
942
943 // If we are offloading to a target via OpenMP we need to include the
944 // openmp_wrappers folder which contains alternative system headers.
945 if (JA.isDeviceOffloading(OKind: Action::OFK_OpenMP) &&
946 !Args.hasArg(Ids: options::OPT_nostdinc) &&
947 Args.hasFlag(Pos: options::OPT_offload_inc, Neg: options::OPT_no_offload_inc,
948 Default: true) &&
949 getToolChain().getTriple().isGPU()) {
950 if (!Args.hasArg(Ids: options::OPT_nobuiltininc)) {
951 // Add openmp_wrappers/* to our system include path. This lets us wrap
952 // standard library headers.
953 SmallString<128> P(D.ResourceDir);
954 llvm::sys::path::append(path&: P, a: "include");
955 llvm::sys::path::append(path&: P, a: "openmp_wrappers");
956 CmdArgs.push_back(Elt: "-internal-isystem");
957 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
958 }
959
960 CmdArgs.push_back(Elt: "-include");
961 CmdArgs.push_back(Elt: "__clang_openmp_device_functions.h");
962 }
963
964 if (Args.hasArg(Ids: options::OPT_foffload_via_llvm)) {
965 // Add llvm_wrappers/* to our system include path. This lets us wrap
966 // standard library headers and other headers.
967 SmallString<128> P(D.ResourceDir);
968 llvm::sys::path::append(path&: P, a: "include", b: "llvm_offload_wrappers");
969 CmdArgs.append(IL: {"-internal-isystem", Args.MakeArgString(Str: P), "-include"});
970 if (JA.isDeviceOffloading(OKind: Action::OFK_OpenMP))
971 CmdArgs.push_back(Elt: "__llvm_offload_device.h");
972 else
973 CmdArgs.push_back(Elt: "__llvm_offload_host.h");
974 }
975
976 // Add -i* options, and automatically translate to
977 // -include-pch/-include-pth for transparent PCH support. It's
978 // wonky, but we include looking for .gch so we can support seamless
979 // replacement into a build system already set up to be generating
980 // .gch files.
981
982 if (getToolChain().getDriver().IsCLMode()) {
983 const Arg *YcArg = Args.getLastArg(Ids: options::OPT__SLASH_Yc);
984 const Arg *YuArg = Args.getLastArg(Ids: options::OPT__SLASH_Yu);
985 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
986 JA.getKind() <= Action::AssembleJobClass) {
987 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-building-pch-with-obj"));
988 // -fpch-instantiate-templates is the default when creating
989 // precomp using /Yc
990 if (Args.hasFlag(Pos: options::OPT_fpch_instantiate_templates,
991 Neg: options::OPT_fno_pch_instantiate_templates, Default: true))
992 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fpch-instantiate-templates"));
993 }
994 if (YcArg || YuArg) {
995 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
996 if (!isa<PrecompileJobAction>(Val: JA)) {
997 CmdArgs.push_back(Elt: "-include-pch");
998 CmdArgs.push_back(Elt: Args.MakeArgString(Str: D.GetClPchPath(
999 C, BaseName: !ThroughHeader.empty()
1000 ? ThroughHeader
1001 : llvm::sys::path::filename(path: Inputs[0].getBaseInput()))));
1002 }
1003
1004 if (ThroughHeader.empty()) {
1005 CmdArgs.push_back(Elt: Args.MakeArgString(
1006 Str: Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1007 } else {
1008 CmdArgs.push_back(
1009 Elt: Args.MakeArgString(Str: Twine("-pch-through-header=") + ThroughHeader));
1010 }
1011 }
1012 }
1013
1014 bool RenderedImplicitInclude = false;
1015 for (const Arg *A : Args.filtered(Ids: options::OPT_clang_i_Group)) {
1016 if (A->getOption().matches(ID: options::OPT_include) &&
1017 D.getProbePrecompiled()) {
1018 // Handling of gcc-style gch precompiled headers.
1019 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1020 RenderedImplicitInclude = true;
1021
1022 bool FoundPCH = false;
1023 SmallString<128> P(A->getValue());
1024 // We want the files to have a name like foo.h.pch. Add a dummy extension
1025 // so that replace_extension does the right thing.
1026 P += ".dummy";
1027 llvm::sys::path::replace_extension(path&: P, extension: "pch");
1028 if (D.getVFS().exists(Path: P))
1029 FoundPCH = true;
1030
1031 if (!FoundPCH) {
1032 // For GCC compat, probe for a file or directory ending in .gch instead.
1033 llvm::sys::path::replace_extension(path&: P, extension: "gch");
1034 FoundPCH = gchProbe(D, Path: P.str());
1035 }
1036
1037 if (FoundPCH) {
1038 if (IsFirstImplicitInclude) {
1039 A->claim();
1040 CmdArgs.push_back(Elt: "-include-pch");
1041 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1042 continue;
1043 } else {
1044 // Ignore the PCH if not first on command line and emit warning.
1045 D.Diag(DiagID: diag::warn_drv_pch_not_first_include) << P
1046 << A->getAsString(Args);
1047 }
1048 }
1049 } else if (A->getOption().matches(ID: options::OPT_isystem_after)) {
1050 // Handling of paths which must come late. These entries are handled by
1051 // the toolchain itself after the resource dir is inserted in the right
1052 // search order.
1053 // Do not claim the argument so that the use of the argument does not
1054 // silently go unnoticed on toolchains which do not honour the option.
1055 continue;
1056 } else if (A->getOption().matches(ID: options::OPT_stdlibxx_isystem)) {
1057 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1058 continue;
1059 } else if (A->getOption().matches(ID: options::OPT_ibuiltininc)) {
1060 // This is used only by the driver. No need to pass to cc1.
1061 continue;
1062 }
1063
1064 // Not translated, render as usual.
1065 A->claim();
1066 A->render(Args, Output&: CmdArgs);
1067 }
1068
1069 if (C.isOffloadingHostKind(Kind: Action::OFK_Cuda) ||
1070 JA.isDeviceOffloading(OKind: Action::OFK_Cuda)) {
1071 // Collect all enabled NVPTX architectures.
1072 std::set<unsigned> ArchIDs;
1073 for (auto &I : llvm::make_range(p: C.getOffloadToolChains(Kind: Action::OFK_Cuda))) {
1074 const ToolChain *TC = I.second;
1075 for (StringRef Arch :
1076 D.getOffloadArchs(C, Args: C.getArgs(), Kind: Action::OFK_Cuda, TC: *TC)) {
1077 OffloadArch OA = StringToOffloadArch(S: Arch);
1078 if (IsNVIDIAOffloadArch(A: OA))
1079 ArchIDs.insert(x: CudaArchToID(Arch: OA));
1080 }
1081 }
1082
1083 if (!ArchIDs.empty()) {
1084 SmallString<128> List;
1085 llvm::raw_svector_ostream OS(List);
1086 llvm::interleave(c: ArchIDs, os&: OS, separator: ",");
1087 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-D__CUDA_ARCH_LIST__=" + List));
1088 }
1089 }
1090
1091 Args.addAllArgs(Output&: CmdArgs,
1092 Ids: {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1093 options::OPT_F, options::OPT_embed_dir_EQ});
1094
1095 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1096
1097 // FIXME: There is a very unfortunate problem here, some troubled
1098 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1099 // really support that we would have to parse and then translate
1100 // those options. :(
1101 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Wp_COMMA,
1102 Id1: options::OPT_Xpreprocessor);
1103
1104 // -I- is a deprecated GCC feature, reject it.
1105 if (Arg *A = Args.getLastArg(Ids: options::OPT_I_))
1106 D.Diag(DiagID: diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1107
1108 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1109 // -isysroot to the CC1 invocation.
1110 StringRef sysroot = C.getSysRoot();
1111 if (sysroot != "") {
1112 if (!Args.hasArg(Ids: options::OPT_isysroot)) {
1113 CmdArgs.push_back(Elt: "-isysroot");
1114 CmdArgs.push_back(Elt: C.getArgs().MakeArgString(Str: sysroot));
1115 }
1116 }
1117
1118 // Parse additional include paths from environment variables.
1119 // FIXME: We should probably sink the logic for handling these from the
1120 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1121 // CPATH - included following the user specified includes (but prior to
1122 // builtin and standard includes).
1123 addDirectoryList(Args, CmdArgs, ArgName: "-I", EnvVar: "CPATH");
1124 // C_INCLUDE_PATH - system includes enabled when compiling C.
1125 addDirectoryList(Args, CmdArgs, ArgName: "-c-isystem", EnvVar: "C_INCLUDE_PATH");
1126 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1127 addDirectoryList(Args, CmdArgs, ArgName: "-cxx-isystem", EnvVar: "CPLUS_INCLUDE_PATH");
1128 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1129 addDirectoryList(Args, CmdArgs, ArgName: "-objc-isystem", EnvVar: "OBJC_INCLUDE_PATH");
1130 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1131 addDirectoryList(Args, CmdArgs, ArgName: "-objcxx-isystem", EnvVar: "OBJCPLUS_INCLUDE_PATH");
1132
1133 // While adding the include arguments, we also attempt to retrieve the
1134 // arguments of related offloading toolchains or arguments that are specific
1135 // of an offloading programming model.
1136
1137 // Add C++ include arguments, if needed.
1138 if (types::isCXX(Id: Inputs[0].getType())) {
1139 bool HasStdlibxxIsystem = Args.hasArg(Ids: options::OPT_stdlibxx_isystem);
1140 forAllAssociatedToolChains(
1141 C, JA, RegularToolChain: getToolChain(),
1142 Work: [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1143 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(DriverArgs: Args, CC1Args&: CmdArgs)
1144 : TC.AddClangCXXStdlibIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1145 });
1146 }
1147
1148 // If we are compiling for a GPU target we want to override the system headers
1149 // with ones created by the 'libc' project if present.
1150 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1151 // OffloadKind as an argument.
1152 if (!Args.hasArg(Ids: options::OPT_nostdinc) &&
1153 Args.hasFlag(Pos: options::OPT_offload_inc, Neg: options::OPT_no_offload_inc,
1154 Default: true) &&
1155 !Args.hasArg(Ids: options::OPT_nobuiltininc) &&
1156 (C.getActiveOffloadKinds() == Action::OFK_OpenMP)) {
1157 // TODO: CUDA / HIP include their own headers for some common functions
1158 // implemented here. We'll need to clean those up so they do not conflict.
1159 SmallString<128> P(D.ResourceDir);
1160 llvm::sys::path::append(path&: P, a: "include");
1161 llvm::sys::path::append(path&: P, a: "llvm_libc_wrappers");
1162 CmdArgs.push_back(Elt: "-internal-isystem");
1163 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1164 }
1165
1166 // Add system include arguments for all targets but IAMCU.
1167 if (!IsIAMCU)
1168 forAllAssociatedToolChains(C, JA, RegularToolChain: getToolChain(),
1169 Work: [&Args, &CmdArgs](const ToolChain &TC) {
1170 TC.AddClangSystemIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1171 });
1172 else {
1173 // For IAMCU add special include arguments.
1174 getToolChain().AddIAMCUIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1175 }
1176
1177 addMacroPrefixMapArg(D, Args, CmdArgs);
1178 addCoveragePrefixMapArg(D, Args, CmdArgs);
1179
1180 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffile_reproducible,
1181 Ids: options::OPT_fno_file_reproducible);
1182
1183 if (const char *Epoch = std::getenv(name: "SOURCE_DATE_EPOCH")) {
1184 CmdArgs.push_back(Elt: "-source-date-epoch");
1185 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Epoch));
1186 }
1187
1188 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdefine_target_os_macros,
1189 Neg: options::OPT_fno_define_target_os_macros);
1190}
1191
1192// FIXME: Move to target hook.
1193static bool isSignedCharDefault(const llvm::Triple &Triple) {
1194 switch (Triple.getArch()) {
1195 default:
1196 return true;
1197
1198 case llvm::Triple::aarch64:
1199 case llvm::Triple::aarch64_32:
1200 case llvm::Triple::aarch64_be:
1201 case llvm::Triple::arm:
1202 case llvm::Triple::armeb:
1203 case llvm::Triple::thumb:
1204 case llvm::Triple::thumbeb:
1205 if (Triple.isOSDarwin() || Triple.isOSWindows())
1206 return true;
1207 return false;
1208
1209 case llvm::Triple::ppc:
1210 case llvm::Triple::ppc64:
1211 if (Triple.isOSDarwin())
1212 return true;
1213 return false;
1214
1215 case llvm::Triple::csky:
1216 case llvm::Triple::hexagon:
1217 case llvm::Triple::msp430:
1218 case llvm::Triple::ppcle:
1219 case llvm::Triple::ppc64le:
1220 case llvm::Triple::riscv32:
1221 case llvm::Triple::riscv64:
1222 case llvm::Triple::riscv32be:
1223 case llvm::Triple::riscv64be:
1224 case llvm::Triple::systemz:
1225 case llvm::Triple::xcore:
1226 case llvm::Triple::xtensa:
1227 return false;
1228 }
1229}
1230
1231static bool hasMultipleInvocations(const llvm::Triple &Triple,
1232 const ArgList &Args) {
1233 // Supported only on Darwin where we invoke the compiler multiple times
1234 // followed by an invocation to lipo.
1235 if (!Triple.isOSDarwin())
1236 return false;
1237 // If more than one "-arch <arch>" is specified, we're targeting multiple
1238 // architectures resulting in a fat binary.
1239 return Args.getAllArgValues(Id: options::OPT_arch).size() > 1;
1240}
1241
1242static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1243 const llvm::Triple &Triple) {
1244 // When enabling remarks, we need to error if:
1245 // * The remark file is specified but we're targeting multiple architectures,
1246 // which means more than one remark file is being generated.
1247 bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1248 bool hasExplicitOutputFile =
1249 Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ);
1250 if (hasMultipleInvocations && hasExplicitOutputFile) {
1251 D.Diag(DiagID: diag::err_drv_invalid_output_with_multiple_archs)
1252 << "-foptimization-record-file";
1253 return false;
1254 }
1255 return true;
1256}
1257
1258static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1259 const llvm::Triple &Triple,
1260 const InputInfo &Input,
1261 const InputInfo &Output, const JobAction &JA) {
1262 StringRef Format = "yaml";
1263 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsave_optimization_record_EQ))
1264 Format = A->getValue();
1265
1266 CmdArgs.push_back(Elt: "-opt-record-file");
1267
1268 const Arg *A = Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ);
1269 if (A) {
1270 CmdArgs.push_back(Elt: A->getValue());
1271 } else {
1272 bool hasMultipleArchs =
1273 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1274 Args.getAllArgValues(Id: options::OPT_arch).size() > 1;
1275
1276 SmallString<128> F;
1277
1278 if (Args.hasArg(Ids: options::OPT_c) || Args.hasArg(Ids: options::OPT_S)) {
1279 if (Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o))
1280 F = FinalOutput->getValue();
1281 } else {
1282 if (Format != "yaml" && // For YAML, keep the original behavior.
1283 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1284 Output.isFilename())
1285 F = Output.getFilename();
1286 }
1287
1288 if (F.empty()) {
1289 // Use the input filename.
1290 F = llvm::sys::path::stem(path: Input.getBaseInput());
1291
1292 // If we're compiling for an offload architecture (i.e. a CUDA device),
1293 // we need to make the file name for the device compilation different
1294 // from the host compilation.
1295 if (!JA.isDeviceOffloading(OKind: Action::OFK_None) &&
1296 !JA.isDeviceOffloading(OKind: Action::OFK_Host)) {
1297 llvm::sys::path::replace_extension(path&: F, extension: "");
1298 F += Action::GetOffloadingFileNamePrefix(Kind: JA.getOffloadingDeviceKind(),
1299 NormalizedTriple: Triple.normalize());
1300 F += "-";
1301 F += JA.getOffloadingArch();
1302 }
1303 }
1304
1305 // If we're having more than one "-arch", we should name the files
1306 // differently so that every cc1 invocation writes to a different file.
1307 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1308 // name from the triple.
1309 if (hasMultipleArchs) {
1310 // First, remember the extension.
1311 SmallString<64> OldExtension = llvm::sys::path::extension(path: F);
1312 // then, remove it.
1313 llvm::sys::path::replace_extension(path&: F, extension: "");
1314 // attach -<arch> to it.
1315 F += "-";
1316 F += Triple.getArchName();
1317 // put back the extension.
1318 llvm::sys::path::replace_extension(path&: F, extension: OldExtension);
1319 }
1320
1321 SmallString<32> Extension;
1322 Extension += "opt.";
1323 Extension += Format;
1324
1325 llvm::sys::path::replace_extension(path&: F, extension: Extension);
1326 CmdArgs.push_back(Elt: Args.MakeArgString(Str: F));
1327 }
1328
1329 if (const Arg *A =
1330 Args.getLastArg(Ids: options::OPT_foptimization_record_passes_EQ)) {
1331 CmdArgs.push_back(Elt: "-opt-record-passes");
1332 CmdArgs.push_back(Elt: A->getValue());
1333 }
1334
1335 if (!Format.empty()) {
1336 CmdArgs.push_back(Elt: "-opt-record-format");
1337 CmdArgs.push_back(Elt: Format.data());
1338 }
1339}
1340
1341void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1342 if (!Args.hasFlag(Pos: options::OPT_faapcs_bitfield_width,
1343 Neg: options::OPT_fno_aapcs_bitfield_width, Default: true))
1344 CmdArgs.push_back(Elt: "-fno-aapcs-bitfield-width");
1345
1346 if (Args.getLastArg(Ids: options::OPT_ForceAAPCSBitfieldLoad))
1347 CmdArgs.push_back(Elt: "-faapcs-bitfield-load");
1348}
1349
1350namespace {
1351void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1352 const ArgList &Args, ArgStringList &CmdArgs) {
1353 // Select the ABI to use.
1354 // FIXME: Support -meabi.
1355 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1356 const char *ABIName = nullptr;
1357 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ))
1358 ABIName = A->getValue();
1359 else
1360 ABIName = llvm::ARM::computeDefaultTargetABI(TT: Triple).data();
1361
1362 CmdArgs.push_back(Elt: "-target-abi");
1363 CmdArgs.push_back(Elt: ABIName);
1364}
1365
1366void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1367 auto StrictAlignIter =
1368 llvm::find_if(Range: llvm::reverse(C&: CmdArgs), P: [](StringRef Arg) {
1369 return Arg == "+strict-align" || Arg == "-strict-align";
1370 });
1371 if (StrictAlignIter != CmdArgs.rend() &&
1372 StringRef(*StrictAlignIter) == "+strict-align")
1373 CmdArgs.push_back(Elt: "-Wunaligned-access");
1374}
1375}
1376
1377static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1378 ArgStringList &CmdArgs, bool isAArch64) {
1379 const llvm::Triple &Triple = TC.getEffectiveTriple();
1380 const Arg *A = isAArch64
1381 ? Args.getLastArg(Ids: options::OPT_msign_return_address_EQ,
1382 Ids: options::OPT_mbranch_protection_EQ)
1383 : Args.getLastArg(Ids: options::OPT_mbranch_protection_EQ);
1384 if (!A) {
1385 if (Triple.isOSOpenBSD() && isAArch64) {
1386 CmdArgs.push_back(Elt: "-msign-return-address=non-leaf");
1387 CmdArgs.push_back(Elt: "-msign-return-address-key=a_key");
1388 CmdArgs.push_back(Elt: "-mbranch-target-enforce");
1389 }
1390 return;
1391 }
1392
1393 const Driver &D = TC.getDriver();
1394 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1395 D.Diag(DiagID: diag::warn_incompatible_branch_protection_option)
1396 << Triple.getArchName();
1397
1398 StringRef Scope, Key;
1399 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1400
1401 if (A->getOption().matches(ID: options::OPT_msign_return_address_EQ)) {
1402 Scope = A->getValue();
1403 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1404 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1405 << A->getSpelling() << Scope;
1406 Key = "a_key";
1407 IndirectBranches = Triple.isOSOpenBSD() && isAArch64;
1408 BranchProtectionPAuthLR = false;
1409 GuardedControlStack = false;
1410 } else {
1411 StringRef DiagMsg;
1412 llvm::ARM::ParsedBranchProtection PBP;
1413 bool EnablePAuthLR = false;
1414
1415 // To know if we need to enable PAuth-LR As part of the standard branch
1416 // protection option, it needs to be determined if the feature has been
1417 // activated in the `march` argument. This information is stored within the
1418 // CmdArgs variable and can be found using a search.
1419 if (isAArch64) {
1420 auto isPAuthLR = [](const char *member) {
1421 llvm::AArch64::ExtensionInfo pauthlr_extension =
1422 llvm::AArch64::getExtensionByID(ExtID: llvm::AArch64::AEK_PAUTHLR);
1423 return pauthlr_extension.PosTargetFeature == member;
1424 };
1425
1426 if (llvm::any_of(Range&: CmdArgs, P: isPAuthLR))
1427 EnablePAuthLR = true;
1428 }
1429 if (!llvm::ARM::parseBranchProtection(Spec: A->getValue(), PBP, Err&: DiagMsg,
1430 EnablePAuthLR))
1431 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1432 << A->getSpelling() << DiagMsg;
1433 if (!isAArch64 && PBP.Key == "b_key")
1434 D.Diag(DiagID: diag::warn_unsupported_branch_protection)
1435 << "b-key" << A->getAsString(Args);
1436 Scope = PBP.Scope;
1437 Key = PBP.Key;
1438 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1439 IndirectBranches = PBP.BranchTargetEnforcement;
1440 GuardedControlStack = PBP.GuardedControlStack;
1441 }
1442
1443 Arg *PtrauthReturnsArg = Args.getLastArg(Ids: options::OPT_fptrauth_returns,
1444 Ids: options::OPT_fno_ptrauth_returns);
1445 bool HasPtrauthReturns =
1446 PtrauthReturnsArg &&
1447 PtrauthReturnsArg->getOption().matches(ID: options::OPT_fptrauth_returns);
1448 // GCS is currently untested with ptrauth-returns, but enabling this could be
1449 // allowed in future after testing with a suitable system.
1450 if (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack) {
1451 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1452 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
1453 << A->getAsString(Args) << Triple.getTriple();
1454 else if (HasPtrauthReturns)
1455 D.Diag(DiagID: diag::err_drv_incompatible_options)
1456 << A->getAsString(Args) << "-fptrauth-returns";
1457 }
1458
1459 CmdArgs.push_back(
1460 Elt: Args.MakeArgString(Str: Twine("-msign-return-address=") + Scope));
1461 if (Scope != "none")
1462 CmdArgs.push_back(
1463 Elt: Args.MakeArgString(Str: Twine("-msign-return-address-key=") + Key));
1464 if (BranchProtectionPAuthLR)
1465 CmdArgs.push_back(
1466 Elt: Args.MakeArgString(Str: Twine("-mbranch-protection-pauth-lr")));
1467 if (IndirectBranches)
1468 CmdArgs.push_back(Elt: "-mbranch-target-enforce");
1469
1470 if (GuardedControlStack)
1471 CmdArgs.push_back(Elt: "-mguarded-control-stack");
1472}
1473
1474void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1475 ArgStringList &CmdArgs, bool KernelOrKext) const {
1476 RenderARMABI(D: getToolChain().getDriver(), Triple, Args, CmdArgs);
1477
1478 // Determine floating point ABI from the options & target defaults.
1479 arm::FloatABI ABI = arm::getARMFloatABI(TC: getToolChain(), Args);
1480 if (ABI == arm::FloatABI::Soft) {
1481 // Floating point operations and argument passing are soft.
1482 // FIXME: This changes CPP defines, we need -target-soft-float.
1483 CmdArgs.push_back(Elt: "-msoft-float");
1484 CmdArgs.push_back(Elt: "-mfloat-abi");
1485 CmdArgs.push_back(Elt: "soft");
1486 } else if (ABI == arm::FloatABI::SoftFP) {
1487 // Floating point operations are hard, but argument passing is soft.
1488 CmdArgs.push_back(Elt: "-mfloat-abi");
1489 CmdArgs.push_back(Elt: "soft");
1490 } else {
1491 // Floating point operations and argument passing are hard.
1492 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1493 CmdArgs.push_back(Elt: "-mfloat-abi");
1494 CmdArgs.push_back(Elt: "hard");
1495 }
1496
1497 // Forward the -mglobal-merge option for explicit control over the pass.
1498 if (Arg *A = Args.getLastArg(Ids: options::OPT_mglobal_merge,
1499 Ids: options::OPT_mno_global_merge)) {
1500 CmdArgs.push_back(Elt: "-mllvm");
1501 if (A->getOption().matches(ID: options::OPT_mno_global_merge))
1502 CmdArgs.push_back(Elt: "-arm-global-merge=false");
1503 else
1504 CmdArgs.push_back(Elt: "-arm-global-merge=true");
1505 }
1506
1507 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
1508 Neg: options::OPT_mno_implicit_float, Default: true))
1509 CmdArgs.push_back(Elt: "-no-implicit-float");
1510
1511 if (Args.getLastArg(Ids: options::OPT_mcmse))
1512 CmdArgs.push_back(Elt: "-mcmse");
1513
1514 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1515
1516 // Enable/disable return address signing and indirect branch targets.
1517 CollectARMPACBTIOptions(TC: getToolChain(), Args, CmdArgs, isAArch64: false /*isAArch64*/);
1518
1519 AddUnalignedAccessWarning(CmdArgs);
1520}
1521
1522void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1523 const ArgList &Args, bool KernelOrKext,
1524 ArgStringList &CmdArgs) const {
1525 const ToolChain &TC = getToolChain();
1526
1527 // Add the target features
1528 getTargetFeatures(D: TC.getDriver(), Triple: EffectiveTriple, Args, CmdArgs, ForAS: false);
1529
1530 // Add target specific flags.
1531 switch (TC.getArch()) {
1532 default:
1533 break;
1534
1535 case llvm::Triple::arm:
1536 case llvm::Triple::armeb:
1537 case llvm::Triple::thumb:
1538 case llvm::Triple::thumbeb:
1539 // Use the effective triple, which takes into account the deployment target.
1540 AddARMTargetArgs(Triple: EffectiveTriple, Args, CmdArgs, KernelOrKext);
1541 break;
1542
1543 case llvm::Triple::aarch64:
1544 case llvm::Triple::aarch64_32:
1545 case llvm::Triple::aarch64_be:
1546 AddAArch64TargetArgs(Args, CmdArgs);
1547 break;
1548
1549 case llvm::Triple::loongarch32:
1550 case llvm::Triple::loongarch64:
1551 AddLoongArchTargetArgs(Args, CmdArgs);
1552 break;
1553
1554 case llvm::Triple::mips:
1555 case llvm::Triple::mipsel:
1556 case llvm::Triple::mips64:
1557 case llvm::Triple::mips64el:
1558 AddMIPSTargetArgs(Args, CmdArgs);
1559 break;
1560
1561 case llvm::Triple::ppc:
1562 case llvm::Triple::ppcle:
1563 case llvm::Triple::ppc64:
1564 case llvm::Triple::ppc64le:
1565 AddPPCTargetArgs(Args, CmdArgs);
1566 break;
1567
1568 case llvm::Triple::riscv32:
1569 case llvm::Triple::riscv64:
1570 case llvm::Triple::riscv32be:
1571 case llvm::Triple::riscv64be:
1572 AddRISCVTargetArgs(Args, CmdArgs);
1573 break;
1574
1575 case llvm::Triple::sparc:
1576 case llvm::Triple::sparcel:
1577 case llvm::Triple::sparcv9:
1578 AddSparcTargetArgs(Args, CmdArgs);
1579 break;
1580
1581 case llvm::Triple::systemz:
1582 AddSystemZTargetArgs(Args, CmdArgs);
1583 break;
1584
1585 case llvm::Triple::x86:
1586 case llvm::Triple::x86_64:
1587 AddX86TargetArgs(Args, CmdArgs);
1588 break;
1589
1590 case llvm::Triple::lanai:
1591 AddLanaiTargetArgs(Args, CmdArgs);
1592 break;
1593
1594 case llvm::Triple::hexagon:
1595 AddHexagonTargetArgs(Args, CmdArgs);
1596 break;
1597
1598 case llvm::Triple::wasm32:
1599 case llvm::Triple::wasm64:
1600 AddWebAssemblyTargetArgs(Args, CmdArgs);
1601 break;
1602
1603 case llvm::Triple::ve:
1604 AddVETargetArgs(Args, CmdArgs);
1605 break;
1606 }
1607}
1608
1609namespace {
1610void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1611 ArgStringList &CmdArgs) {
1612 const char *ABIName = nullptr;
1613 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ))
1614 ABIName = A->getValue();
1615 else if (Triple.isOSDarwin())
1616 ABIName = "darwinpcs";
1617 // TODO: we probably want to have some target hook here.
1618 else if (Triple.isOSLinux() &&
1619 Triple.getEnvironment() == llvm::Triple::PAuthTest)
1620 ABIName = "pauthtest";
1621 else
1622 ABIName = "aapcs";
1623
1624 CmdArgs.push_back(Elt: "-target-abi");
1625 CmdArgs.push_back(Elt: ABIName);
1626}
1627}
1628
1629void Clang::AddAArch64TargetArgs(const ArgList &Args,
1630 ArgStringList &CmdArgs) const {
1631 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1632
1633 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true) ||
1634 Args.hasArg(Ids: options::OPT_mkernel) ||
1635 Args.hasArg(Ids: options::OPT_fapple_kext))
1636 CmdArgs.push_back(Elt: "-disable-red-zone");
1637
1638 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
1639 Neg: options::OPT_mno_implicit_float, Default: true))
1640 CmdArgs.push_back(Elt: "-no-implicit-float");
1641
1642 RenderAArch64ABI(Triple, Args, CmdArgs);
1643
1644 // Forward the -mglobal-merge option for explicit control over the pass.
1645 if (Arg *A = Args.getLastArg(Ids: options::OPT_mglobal_merge,
1646 Ids: options::OPT_mno_global_merge)) {
1647 CmdArgs.push_back(Elt: "-mllvm");
1648 if (A->getOption().matches(ID: options::OPT_mno_global_merge))
1649 CmdArgs.push_back(Elt: "-aarch64-enable-global-merge=false");
1650 else
1651 CmdArgs.push_back(Elt: "-aarch64-enable-global-merge=true");
1652 }
1653
1654 // Handle -msve_vector_bits=<bits>
1655 auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,
1656 StringRef VScaleMax) {
1657 StringRef Val = A->getValue();
1658 const Driver &D = getToolChain().getDriver();
1659 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1660 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1661 Val == "1024+" || Val == "2048+") {
1662 unsigned Bits = 0;
1663 if (!Val.consume_back(Suffix: "+")) {
1664 bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits);
1665 (void)Invalid;
1666 assert(!Invalid && "Failed to parse value");
1667 CmdArgs.push_back(
1668 Elt: Args.MakeArgString(Str: VScaleMax + llvm::Twine(Bits / 128)));
1669 }
1670
1671 bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits);
1672 (void)Invalid;
1673 assert(!Invalid && "Failed to parse value");
1674
1675 CmdArgs.push_back(
1676 Elt: Args.MakeArgString(Str: VScaleMin + llvm::Twine(Bits / 128)));
1677 } else if (Val == "scalable") {
1678 // Silently drop requests for vector-length agnostic code as it's implied.
1679 } else {
1680 // Handle the unsupported values passed to msve-vector-bits.
1681 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1682 << A->getSpelling() << Val;
1683 }
1684 };
1685 if (Arg *A = Args.getLastArg(Ids: options::OPT_msve_vector_bits_EQ))
1686 HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");
1687 if (Arg *A = Args.getLastArg(Ids: options::OPT_msve_streaming_vector_bits_EQ))
1688 HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");
1689
1690 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1691
1692 if (auto TuneCPU = aarch64::getAArch64TargetTuneCPU(Args, Triple)) {
1693 CmdArgs.push_back(Elt: "-tune-cpu");
1694 CmdArgs.push_back(Elt: Args.MakeArgString(Str: *TuneCPU));
1695 }
1696
1697 AddUnalignedAccessWarning(CmdArgs);
1698
1699 if (Triple.isOSDarwin() ||
1700 (Triple.isOSLinux() &&
1701 Triple.getEnvironment() == llvm::Triple::PAuthTest)) {
1702 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_intrinsics,
1703 Neg: options::OPT_fno_ptrauth_intrinsics);
1704 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_calls,
1705 Neg: options::OPT_fno_ptrauth_calls);
1706 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_returns,
1707 Neg: options::OPT_fno_ptrauth_returns);
1708 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_auth_traps,
1709 Neg: options::OPT_fno_ptrauth_auth_traps);
1710 Args.addOptInFlag(
1711 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtable_pointer_address_discrimination,
1712 Neg: options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1713 Args.addOptInFlag(
1714 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtable_pointer_type_discrimination,
1715 Neg: options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1716 Args.addOptInFlag(
1717 Output&: CmdArgs, Pos: options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1718 Neg: options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1719 Args.addOptInFlag(
1720 Output&: CmdArgs, Pos: options::OPT_fptrauth_function_pointer_type_discrimination,
1721 Neg: options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1722 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_indirect_gotos,
1723 Neg: options::OPT_fno_ptrauth_indirect_gotos);
1724 }
1725 if (Triple.isOSLinux() &&
1726 Triple.getEnvironment() == llvm::Triple::PAuthTest) {
1727 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_init_fini,
1728 Neg: options::OPT_fno_ptrauth_init_fini);
1729 Args.addOptInFlag(
1730 Output&: CmdArgs, Pos: options::OPT_fptrauth_init_fini_address_discrimination,
1731 Neg: options::OPT_fno_ptrauth_init_fini_address_discrimination);
1732 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_elf_got,
1733 Neg: options::OPT_fno_ptrauth_elf_got);
1734 }
1735 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_faarch64_jump_table_hardening,
1736 Neg: options::OPT_fno_aarch64_jump_table_hardening);
1737
1738 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_isa,
1739 Neg: options::OPT_fno_ptrauth_objc_isa);
1740 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_interface_sel,
1741 Neg: options::OPT_fno_ptrauth_objc_interface_sel);
1742 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_class_ro,
1743 Neg: options::OPT_fno_ptrauth_objc_class_ro);
1744
1745 // Enable/disable return address signing and indirect branch targets.
1746 CollectARMPACBTIOptions(TC: getToolChain(), Args, CmdArgs, isAArch64: true /*isAArch64*/);
1747}
1748
1749void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1750 ArgStringList &CmdArgs) const {
1751 const llvm::Triple &Triple = getToolChain().getTriple();
1752
1753 CmdArgs.push_back(Elt: "-target-abi");
1754 CmdArgs.push_back(
1755 Elt: loongarch::getLoongArchABI(D: getToolChain().getDriver(), Args, Triple)
1756 .data());
1757
1758 // Handle -mtune.
1759 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
1760 std::string TuneCPU = A->getValue();
1761 TuneCPU = loongarch::postProcessTargetCPUString(CPU: TuneCPU, Triple);
1762 CmdArgs.push_back(Elt: "-tune-cpu");
1763 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
1764 }
1765
1766 if (Arg *A = Args.getLastArg(Ids: options::OPT_mannotate_tablejump,
1767 Ids: options::OPT_mno_annotate_tablejump)) {
1768 if (A->getOption().matches(ID: options::OPT_mannotate_tablejump)) {
1769 CmdArgs.push_back(Elt: "-mllvm");
1770 CmdArgs.push_back(Elt: "-loongarch-annotate-tablejump");
1771 }
1772 }
1773}
1774
1775void Clang::AddMIPSTargetArgs(const ArgList &Args,
1776 ArgStringList &CmdArgs) const {
1777 const Driver &D = getToolChain().getDriver();
1778 StringRef CPUName;
1779 StringRef ABIName;
1780 const llvm::Triple &Triple = getToolChain().getTriple();
1781 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1782
1783 CmdArgs.push_back(Elt: "-target-abi");
1784 CmdArgs.push_back(Elt: ABIName.data());
1785
1786 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1787 if (ABI == mips::FloatABI::Soft) {
1788 // Floating point operations and argument passing are soft.
1789 CmdArgs.push_back(Elt: "-msoft-float");
1790 CmdArgs.push_back(Elt: "-mfloat-abi");
1791 CmdArgs.push_back(Elt: "soft");
1792 } else {
1793 // Floating point operations and argument passing are hard.
1794 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1795 CmdArgs.push_back(Elt: "-mfloat-abi");
1796 CmdArgs.push_back(Elt: "hard");
1797 }
1798
1799 if (Arg *A = Args.getLastArg(Ids: options::OPT_mldc1_sdc1,
1800 Ids: options::OPT_mno_ldc1_sdc1)) {
1801 if (A->getOption().matches(ID: options::OPT_mno_ldc1_sdc1)) {
1802 CmdArgs.push_back(Elt: "-mllvm");
1803 CmdArgs.push_back(Elt: "-mno-ldc1-sdc1");
1804 }
1805 }
1806
1807 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcheck_zero_division,
1808 Ids: options::OPT_mno_check_zero_division)) {
1809 if (A->getOption().matches(ID: options::OPT_mno_check_zero_division)) {
1810 CmdArgs.push_back(Elt: "-mllvm");
1811 CmdArgs.push_back(Elt: "-mno-check-zero-division");
1812 }
1813 }
1814
1815 if (Args.getLastArg(Ids: options::OPT_mfix4300)) {
1816 CmdArgs.push_back(Elt: "-mllvm");
1817 CmdArgs.push_back(Elt: "-mfix4300");
1818 }
1819
1820 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
1821 StringRef v = A->getValue();
1822 CmdArgs.push_back(Elt: "-mllvm");
1823 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mips-ssection-threshold=" + v));
1824 A->claim();
1825 }
1826
1827 Arg *GPOpt = Args.getLastArg(Ids: options::OPT_mgpopt, Ids: options::OPT_mno_gpopt);
1828 Arg *ABICalls =
1829 Args.getLastArg(Ids: options::OPT_mabicalls, Ids: options::OPT_mno_abicalls);
1830
1831 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1832 // -mgpopt is the default for static, -fno-pic environments but these two
1833 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1834 // the only case where -mllvm -mgpopt is passed.
1835 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1836 // passed explicitly when compiling something with -mabicalls
1837 // (implictly) in affect. Currently the warning is in the backend.
1838 //
1839 // When the ABI in use is N64, we also need to determine the PIC mode that
1840 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1841 bool NoABICalls =
1842 ABICalls && ABICalls->getOption().matches(ID: options::OPT_mno_abicalls);
1843
1844 llvm::Reloc::Model RelocationModel;
1845 unsigned PICLevel;
1846 bool IsPIE;
1847 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
1848 ParsePICArgs(ToolChain: getToolChain(), Args);
1849
1850 NoABICalls = NoABICalls ||
1851 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1852
1853 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(ID: options::OPT_mgpopt);
1854 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1855 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1856 CmdArgs.push_back(Elt: "-mllvm");
1857 CmdArgs.push_back(Elt: "-mgpopt");
1858
1859 Arg *LocalSData = Args.getLastArg(Ids: options::OPT_mlocal_sdata,
1860 Ids: options::OPT_mno_local_sdata);
1861 Arg *ExternSData = Args.getLastArg(Ids: options::OPT_mextern_sdata,
1862 Ids: options::OPT_mno_extern_sdata);
1863 Arg *EmbeddedData = Args.getLastArg(Ids: options::OPT_membedded_data,
1864 Ids: options::OPT_mno_embedded_data);
1865 if (LocalSData) {
1866 CmdArgs.push_back(Elt: "-mllvm");
1867 if (LocalSData->getOption().matches(ID: options::OPT_mlocal_sdata)) {
1868 CmdArgs.push_back(Elt: "-mlocal-sdata=1");
1869 } else {
1870 CmdArgs.push_back(Elt: "-mlocal-sdata=0");
1871 }
1872 LocalSData->claim();
1873 }
1874
1875 if (ExternSData) {
1876 CmdArgs.push_back(Elt: "-mllvm");
1877 if (ExternSData->getOption().matches(ID: options::OPT_mextern_sdata)) {
1878 CmdArgs.push_back(Elt: "-mextern-sdata=1");
1879 } else {
1880 CmdArgs.push_back(Elt: "-mextern-sdata=0");
1881 }
1882 ExternSData->claim();
1883 }
1884
1885 if (EmbeddedData) {
1886 CmdArgs.push_back(Elt: "-mllvm");
1887 if (EmbeddedData->getOption().matches(ID: options::OPT_membedded_data)) {
1888 CmdArgs.push_back(Elt: "-membedded-data=1");
1889 } else {
1890 CmdArgs.push_back(Elt: "-membedded-data=0");
1891 }
1892 EmbeddedData->claim();
1893 }
1894
1895 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1896 D.Diag(DiagID: diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1897
1898 if (GPOpt)
1899 GPOpt->claim();
1900
1901 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcompact_branches_EQ)) {
1902 StringRef Val = StringRef(A->getValue());
1903 if (mips::hasCompactBranches(CPU&: CPUName)) {
1904 if (Val == "never" || Val == "always" || Val == "optimal") {
1905 CmdArgs.push_back(Elt: "-mllvm");
1906 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mips-compact-branches=" + Val));
1907 } else
1908 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1909 << A->getSpelling() << Val;
1910 } else
1911 D.Diag(DiagID: diag::warn_target_unsupported_compact_branches) << CPUName;
1912 }
1913
1914 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrelax_pic_calls,
1915 Ids: options::OPT_mno_relax_pic_calls)) {
1916 if (A->getOption().matches(ID: options::OPT_mno_relax_pic_calls)) {
1917 CmdArgs.push_back(Elt: "-mllvm");
1918 CmdArgs.push_back(Elt: "-mips-jalr-reloc=0");
1919 }
1920 }
1921}
1922
1923void Clang::AddPPCTargetArgs(const ArgList &Args,
1924 ArgStringList &CmdArgs) const {
1925 const Driver &D = getToolChain().getDriver();
1926 const llvm::Triple &T = getToolChain().getTriple();
1927 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
1928 CmdArgs.push_back(Elt: "-tune-cpu");
1929 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, CPUName: A->getValue());
1930 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU.str()));
1931 }
1932
1933 // Select the ABI to use.
1934 const char *ABIName = nullptr;
1935 if (T.isOSBinFormatELF()) {
1936 switch (getToolChain().getArch()) {
1937 case llvm::Triple::ppc64: {
1938 if (T.isPPC64ELFv2ABI())
1939 ABIName = "elfv2";
1940 else
1941 ABIName = "elfv1";
1942 break;
1943 }
1944 case llvm::Triple::ppc64le:
1945 ABIName = "elfv2";
1946 break;
1947 default:
1948 break;
1949 }
1950 }
1951
1952 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
1953 bool VecExtabi = false;
1954 for (const Arg *A : Args.filtered(Ids: options::OPT_mabi_EQ)) {
1955 StringRef V = A->getValue();
1956 if (V == "ieeelongdouble") {
1957 IEEELongDouble = true;
1958 A->claim();
1959 } else if (V == "ibmlongdouble") {
1960 IEEELongDouble = false;
1961 A->claim();
1962 } else if (V == "vec-default") {
1963 VecExtabi = false;
1964 A->claim();
1965 } else if (V == "vec-extabi") {
1966 VecExtabi = true;
1967 A->claim();
1968 } else if (V == "elfv1") {
1969 ABIName = "elfv1";
1970 A->claim();
1971 } else if (V == "elfv2") {
1972 ABIName = "elfv2";
1973 A->claim();
1974 } else if (V != "altivec")
1975 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1976 // the option if given as we don't have backend support for any targets
1977 // that don't use the altivec abi.
1978 ABIName = A->getValue();
1979 }
1980 if (IEEELongDouble)
1981 CmdArgs.push_back(Elt: "-mabi=ieeelongdouble");
1982 if (VecExtabi) {
1983 if (!T.isOSAIX())
1984 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
1985 << "-mabi=vec-extabi" << T.str();
1986 CmdArgs.push_back(Elt: "-mabi=vec-extabi");
1987 }
1988
1989 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true))
1990 CmdArgs.push_back(Elt: "-disable-red-zone");
1991
1992 ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
1993 if (FloatABI == ppc::FloatABI::Soft) {
1994 // Floating point operations and argument passing are soft.
1995 CmdArgs.push_back(Elt: "-msoft-float");
1996 CmdArgs.push_back(Elt: "-mfloat-abi");
1997 CmdArgs.push_back(Elt: "soft");
1998 } else {
1999 // Floating point operations and argument passing are hard.
2000 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
2001 CmdArgs.push_back(Elt: "-mfloat-abi");
2002 CmdArgs.push_back(Elt: "hard");
2003 }
2004
2005 if (ABIName) {
2006 CmdArgs.push_back(Elt: "-target-abi");
2007 CmdArgs.push_back(Elt: ABIName);
2008 }
2009}
2010
2011void Clang::AddRISCVTargetArgs(const ArgList &Args,
2012 ArgStringList &CmdArgs) const {
2013 const llvm::Triple &Triple = getToolChain().getTriple();
2014 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2015
2016 CmdArgs.push_back(Elt: "-target-abi");
2017 CmdArgs.push_back(Elt: ABIName.data());
2018
2019 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
2020 CmdArgs.push_back(Elt: "-msmall-data-limit");
2021 CmdArgs.push_back(Elt: A->getValue());
2022 }
2023
2024 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
2025 Neg: options::OPT_mno_implicit_float, Default: true))
2026 CmdArgs.push_back(Elt: "-no-implicit-float");
2027
2028 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2029 CmdArgs.push_back(Elt: "-tune-cpu");
2030 if (strcmp(s1: A->getValue(), s2: "native") == 0)
2031 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::getHostCPUName()));
2032 else
2033 CmdArgs.push_back(Elt: A->getValue());
2034 }
2035
2036 // Handle -mrvv-vector-bits=<bits>
2037 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrvv_vector_bits_EQ)) {
2038 StringRef Val = A->getValue();
2039 const Driver &D = getToolChain().getDriver();
2040
2041 // Get minimum VLen from march.
2042 unsigned MinVLen = 0;
2043 std::string Arch = riscv::getRISCVArch(Args, Triple);
2044 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2045 Arch, /*EnableExperimentalExtensions*/ EnableExperimentalExtension: true);
2046 // Ignore parsing error.
2047 if (!errorToBool(Err: ISAInfo.takeError()))
2048 MinVLen = (*ISAInfo)->getMinVLen();
2049
2050 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2051 // as integer as long as we have a MinVLen.
2052 unsigned Bits = 0;
2053 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2054 Bits = MinVLen;
2055 } else if (!Val.getAsInteger(Radix: 10, Result&: Bits)) {
2056 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2057 // at least MinVLen.
2058 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2059 Bits > 65536 || !llvm::isPowerOf2_32(Value: Bits))
2060 Bits = 0;
2061 }
2062
2063 // If we got a valid value try to use it.
2064 if (Bits != 0) {
2065 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2066 CmdArgs.push_back(
2067 Elt: Args.MakeArgString(Str: "-mvscale-max=" + llvm::Twine(VScaleMin)));
2068 CmdArgs.push_back(
2069 Elt: Args.MakeArgString(Str: "-mvscale-min=" + llvm::Twine(VScaleMin)));
2070 } else if (Val != "scalable") {
2071 // Handle the unsupported values passed to mrvv-vector-bits.
2072 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2073 << A->getSpelling() << Val;
2074 }
2075 }
2076}
2077
2078void Clang::AddSparcTargetArgs(const ArgList &Args,
2079 ArgStringList &CmdArgs) const {
2080 sparc::FloatABI FloatABI =
2081 sparc::getSparcFloatABI(D: getToolChain().getDriver(), Args);
2082
2083 if (FloatABI == sparc::FloatABI::Soft) {
2084 // Floating point operations and argument passing are soft.
2085 CmdArgs.push_back(Elt: "-msoft-float");
2086 CmdArgs.push_back(Elt: "-mfloat-abi");
2087 CmdArgs.push_back(Elt: "soft");
2088 } else {
2089 // Floating point operations and argument passing are hard.
2090 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2091 CmdArgs.push_back(Elt: "-mfloat-abi");
2092 CmdArgs.push_back(Elt: "hard");
2093 }
2094
2095 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2096 StringRef Name = A->getValue();
2097 std::string TuneCPU;
2098 if (Name == "native")
2099 TuneCPU = std::string(llvm::sys::getHostCPUName());
2100 else
2101 TuneCPU = std::string(Name);
2102
2103 CmdArgs.push_back(Elt: "-tune-cpu");
2104 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
2105 }
2106}
2107
2108void Clang::AddSystemZTargetArgs(const ArgList &Args,
2109 ArgStringList &CmdArgs) const {
2110 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2111 CmdArgs.push_back(Elt: "-tune-cpu");
2112 if (strcmp(s1: A->getValue(), s2: "native") == 0)
2113 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::getHostCPUName()));
2114 else
2115 CmdArgs.push_back(Elt: A->getValue());
2116 }
2117
2118 bool HasBackchain =
2119 Args.hasFlag(Pos: options::OPT_mbackchain, Neg: options::OPT_mno_backchain, Default: false);
2120 bool HasPackedStack = Args.hasFlag(Pos: options::OPT_mpacked_stack,
2121 Neg: options::OPT_mno_packed_stack, Default: false);
2122 systemz::FloatABI FloatABI =
2123 systemz::getSystemZFloatABI(D: getToolChain().getDriver(), Args);
2124 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2125 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2126 const Driver &D = getToolChain().getDriver();
2127 D.Diag(DiagID: diag::err_drv_unsupported_opt)
2128 << "-mpacked-stack -mbackchain -mhard-float";
2129 }
2130 if (HasBackchain)
2131 CmdArgs.push_back(Elt: "-mbackchain");
2132 if (HasPackedStack)
2133 CmdArgs.push_back(Elt: "-mpacked-stack");
2134 if (HasSoftFloat) {
2135 // Floating point operations and argument passing are soft.
2136 CmdArgs.push_back(Elt: "-msoft-float");
2137 CmdArgs.push_back(Elt: "-mfloat-abi");
2138 CmdArgs.push_back(Elt: "soft");
2139 }
2140}
2141
2142void Clang::AddX86TargetArgs(const ArgList &Args,
2143 ArgStringList &CmdArgs) const {
2144 const Driver &D = getToolChain().getDriver();
2145 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2146
2147 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true) ||
2148 Args.hasArg(Ids: options::OPT_mkernel) ||
2149 Args.hasArg(Ids: options::OPT_fapple_kext))
2150 CmdArgs.push_back(Elt: "-disable-red-zone");
2151
2152 if (!Args.hasFlag(Pos: options::OPT_mtls_direct_seg_refs,
2153 Neg: options::OPT_mno_tls_direct_seg_refs, Default: true))
2154 CmdArgs.push_back(Elt: "-mno-tls-direct-seg-refs");
2155
2156 // Default to avoid implicit floating-point for kernel/kext code, but allow
2157 // that to be overridden with -mno-soft-float.
2158 bool NoImplicitFloat = (Args.hasArg(Ids: options::OPT_mkernel) ||
2159 Args.hasArg(Ids: options::OPT_fapple_kext));
2160 if (Arg *A = Args.getLastArg(
2161 Ids: options::OPT_msoft_float, Ids: options::OPT_mno_soft_float,
2162 Ids: options::OPT_mimplicit_float, Ids: options::OPT_mno_implicit_float)) {
2163 const Option &O = A->getOption();
2164 NoImplicitFloat = (O.matches(ID: options::OPT_mno_implicit_float) ||
2165 O.matches(ID: options::OPT_msoft_float));
2166 }
2167 if (NoImplicitFloat)
2168 CmdArgs.push_back(Elt: "-no-implicit-float");
2169
2170 if (Arg *A = Args.getLastArg(Ids: options::OPT_masm_EQ)) {
2171 StringRef Value = A->getValue();
2172 if (Value == "intel" || Value == "att") {
2173 CmdArgs.push_back(Elt: "-mllvm");
2174 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
2175 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-inline-asm=" + Value));
2176 } else {
2177 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2178 << A->getSpelling() << Value;
2179 }
2180 } else if (D.IsCLMode()) {
2181 CmdArgs.push_back(Elt: "-mllvm");
2182 CmdArgs.push_back(Elt: "-x86-asm-syntax=intel");
2183 }
2184
2185 if (Arg *A = Args.getLastArg(Ids: options::OPT_mskip_rax_setup,
2186 Ids: options::OPT_mno_skip_rax_setup))
2187 if (A->getOption().matches(ID: options::OPT_mskip_rax_setup))
2188 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mskip-rax-setup"));
2189
2190 // Set flags to support MCU ABI.
2191 if (Args.hasFlag(Pos: options::OPT_miamcu, Neg: options::OPT_mno_iamcu, Default: false)) {
2192 CmdArgs.push_back(Elt: "-mfloat-abi");
2193 CmdArgs.push_back(Elt: "soft");
2194 CmdArgs.push_back(Elt: "-mstack-alignment=4");
2195 }
2196
2197 // Handle -mtune.
2198
2199 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2200 std::string TuneCPU;
2201 if (!Args.hasArg(Ids: options::OPT_march_EQ) && !getToolChain().getTriple().isPS())
2202 TuneCPU = "generic";
2203
2204 // Override based on -mtune.
2205 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2206 StringRef Name = A->getValue();
2207
2208 if (Name == "native") {
2209 Name = llvm::sys::getHostCPUName();
2210 if (!Name.empty())
2211 TuneCPU = std::string(Name);
2212 } else
2213 TuneCPU = std::string(Name);
2214 }
2215
2216 if (!TuneCPU.empty()) {
2217 CmdArgs.push_back(Elt: "-tune-cpu");
2218 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
2219 }
2220}
2221
2222void Clang::AddHexagonTargetArgs(const ArgList &Args,
2223 ArgStringList &CmdArgs) const {
2224 CmdArgs.push_back(Elt: "-mqdsp6-compat");
2225 CmdArgs.push_back(Elt: "-Wreturn-type");
2226
2227 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2228 CmdArgs.push_back(Elt: "-mllvm");
2229 CmdArgs.push_back(
2230 Elt: Args.MakeArgString(Str: "-hexagon-small-data-threshold=" + Twine(*G)));
2231 }
2232
2233 if (!Args.hasArg(Ids: options::OPT_fno_short_enums))
2234 CmdArgs.push_back(Elt: "-fshort-enums");
2235 if (Args.getLastArg(Ids: options::OPT_mieee_rnd_near)) {
2236 CmdArgs.push_back(Elt: "-mllvm");
2237 CmdArgs.push_back(Elt: "-enable-hexagon-ieee-rnd-near");
2238 }
2239 CmdArgs.push_back(Elt: "-mllvm");
2240 CmdArgs.push_back(Elt: "-machine-sink-split=0");
2241}
2242
2243void Clang::AddLanaiTargetArgs(const ArgList &Args,
2244 ArgStringList &CmdArgs) const {
2245 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ)) {
2246 StringRef CPUName = A->getValue();
2247
2248 CmdArgs.push_back(Elt: "-target-cpu");
2249 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPUName));
2250 }
2251 if (Arg *A = Args.getLastArg(Ids: options::OPT_mregparm_EQ)) {
2252 StringRef Value = A->getValue();
2253 // Only support mregparm=4 to support old usage. Report error for all other
2254 // cases.
2255 int Mregparm;
2256 if (Value.getAsInteger(Radix: 10, Result&: Mregparm)) {
2257 if (Mregparm != 4) {
2258 getToolChain().getDriver().Diag(
2259 DiagID: diag::err_drv_unsupported_option_argument)
2260 << A->getSpelling() << Value;
2261 }
2262 }
2263 }
2264}
2265
2266void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2267 ArgStringList &CmdArgs) const {
2268 // Default to "hidden" visibility.
2269 if (!Args.hasArg(Ids: options::OPT_fvisibility_EQ,
2270 Ids: options::OPT_fvisibility_ms_compat))
2271 CmdArgs.push_back(Elt: "-fvisibility=hidden");
2272}
2273
2274void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2275 // Floating point operations and argument passing are hard.
2276 CmdArgs.push_back(Elt: "-mfloat-abi");
2277 CmdArgs.push_back(Elt: "hard");
2278}
2279
2280void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2281 StringRef Target, const InputInfo &Output,
2282 const InputInfo &Input, const ArgList &Args) const {
2283 // If this is a dry run, do not create the compilation database file.
2284 if (C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH))
2285 return;
2286
2287 using llvm::yaml::escape;
2288 const Driver &D = getToolChain().getDriver();
2289
2290 if (!CompilationDatabase) {
2291 std::error_code EC;
2292 auto File = std::make_unique<llvm::raw_fd_ostream>(
2293 args&: Filename, args&: EC,
2294 args: llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2295 if (EC) {
2296 D.Diag(DiagID: clang::diag::err_drv_compilationdatabase) << Filename
2297 << EC.message();
2298 return;
2299 }
2300 CompilationDatabase = std::move(File);
2301 }
2302 auto &CDB = *CompilationDatabase;
2303 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2304 if (!CWD)
2305 CWD = ".";
2306 CDB << "{ \"directory\": \"" << escape(Input: *CWD) << "\"";
2307 CDB << ", \"file\": \"" << escape(Input: Input.getFilename()) << "\"";
2308 if (Output.isFilename())
2309 CDB << ", \"output\": \"" << escape(Input: Output.getFilename()) << "\"";
2310 CDB << ", \"arguments\": [\"" << escape(Input: D.ClangExecutable) << "\"";
2311 SmallString<128> Buf;
2312 Buf = "-x";
2313 Buf += types::getTypeName(Id: Input.getType());
2314 CDB << ", \"" << escape(Input: Buf) << "\"";
2315 if (!D.SysRoot.empty() && !Args.hasArg(Ids: options::OPT__sysroot_EQ)) {
2316 Buf = "--sysroot=";
2317 Buf += D.SysRoot;
2318 CDB << ", \"" << escape(Input: Buf) << "\"";
2319 }
2320 CDB << ", \"" << escape(Input: Input.getFilename()) << "\"";
2321 if (Output.isFilename())
2322 CDB << ", \"-o\", \"" << escape(Input: Output.getFilename()) << "\"";
2323 for (auto &A: Args) {
2324 auto &O = A->getOption();
2325 // Skip language selection, which is positional.
2326 if (O.getID() == options::OPT_x)
2327 continue;
2328 // Skip writing dependency output and the compilation database itself.
2329 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2330 continue;
2331 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2332 continue;
2333 // Skip inputs.
2334 if (O.getKind() == Option::InputClass)
2335 continue;
2336 // Skip output.
2337 if (O.getID() == options::OPT_o)
2338 continue;
2339 // All other arguments are quoted and appended.
2340 ArgStringList ASL;
2341 A->render(Args, Output&: ASL);
2342 for (auto &it: ASL)
2343 CDB << ", \"" << escape(Input: it) << "\"";
2344 }
2345 Buf = "--target=";
2346 Buf += Target;
2347 CDB << ", \"" << escape(Input: Buf) << "\"]},\n";
2348}
2349
2350void Clang::DumpCompilationDatabaseFragmentToDir(
2351 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2352 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2353 // If this is a dry run, do not create the compilation database file.
2354 if (C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH))
2355 return;
2356
2357 if (CompilationDatabase)
2358 DumpCompilationDatabase(C, Filename: "", Target, Output, Input, Args);
2359
2360 SmallString<256> Path = Dir;
2361 const auto &Driver = C.getDriver();
2362 Driver.getVFS().makeAbsolute(Path);
2363 auto Err = llvm::sys::fs::create_directory(path: Path, /*IgnoreExisting=*/true);
2364 if (Err) {
2365 Driver.Diag(DiagID: diag::err_drv_compilationdatabase) << Dir << Err.message();
2366 return;
2367 }
2368
2369 llvm::sys::path::append(
2370 path&: Path,
2371 a: Twine(llvm::sys::path::filename(path: Input.getFilename())) + ".%%%%.json");
2372 int FD;
2373 SmallString<256> TempPath;
2374 Err = llvm::sys::fs::createUniqueFile(Model: Path, ResultFD&: FD, ResultPath&: TempPath,
2375 Flags: llvm::sys::fs::OF_Text);
2376 if (Err) {
2377 Driver.Diag(DiagID: diag::err_drv_compilationdatabase) << Path << Err.message();
2378 return;
2379 }
2380 CompilationDatabase =
2381 std::make_unique<llvm::raw_fd_ostream>(args&: FD, /*shouldClose=*/args: true);
2382 DumpCompilationDatabase(C, Filename: "", Target, Output, Input, Args);
2383}
2384
2385static bool CheckARMImplicitITArg(StringRef Value) {
2386 return Value == "always" || Value == "never" || Value == "arm" ||
2387 Value == "thumb";
2388}
2389
2390static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2391 StringRef Value) {
2392 CmdArgs.push_back(Elt: "-mllvm");
2393 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-arm-implicit-it=" + Value));
2394}
2395
2396static void CollectArgsForIntegratedAssembler(Compilation &C,
2397 const ArgList &Args,
2398 ArgStringList &CmdArgs,
2399 const Driver &D) {
2400 // Default to -mno-relax-all.
2401 //
2402 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2403 // cannot be done by assembler branch relaxation as it needs a free temporary
2404 // register. Because of this, branch relaxation is handled by a MachineIR pass
2405 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2406 // MachineIR branch relaxation inaccurate and it will miss cases where an
2407 // indirect branch is necessary.
2408 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mrelax_all,
2409 Neg: options::OPT_mno_relax_all);
2410
2411 // Only default to -mincremental-linker-compatible if we think we are
2412 // targeting the MSVC linker.
2413 bool DefaultIncrementalLinkerCompatible =
2414 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2415 if (Args.hasFlag(Pos: options::OPT_mincremental_linker_compatible,
2416 Neg: options::OPT_mno_incremental_linker_compatible,
2417 Default: DefaultIncrementalLinkerCompatible))
2418 CmdArgs.push_back(Elt: "-mincremental-linker-compatible");
2419
2420 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_femit_dwarf_unwind_EQ);
2421
2422 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_femit_compact_unwind_non_canonical,
2423 Neg: options::OPT_fno_emit_compact_unwind_non_canonical);
2424
2425 // If you add more args here, also add them to the block below that
2426 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2427
2428 // When passing -I arguments to the assembler we sometimes need to
2429 // unconditionally take the next argument. For example, when parsing
2430 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2431 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2432 // arg after parsing the '-I' arg.
2433 bool TakeNextArg = false;
2434
2435 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2436 bool IsELF = Triple.isOSBinFormatELF();
2437 bool Crel = false, ExperimentalCrel = false;
2438 bool SFrame = false, ExperimentalSFrame = false;
2439 bool ImplicitMapSyms = false;
2440 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2441 bool UseNoExecStack = false;
2442 bool Msa = false;
2443 const char *MipsTargetFeature = nullptr;
2444 llvm::SmallVector<const char *> SparcTargetFeatures;
2445 StringRef ImplicitIt;
2446 for (const Arg *A :
2447 Args.filtered(Ids: options::OPT_Wa_COMMA, Ids: options::OPT_Xassembler,
2448 Ids: options::OPT_mimplicit_it_EQ)) {
2449 A->claim();
2450
2451 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2452 switch (C.getDefaultToolChain().getArch()) {
2453 case llvm::Triple::arm:
2454 case llvm::Triple::armeb:
2455 case llvm::Triple::thumb:
2456 case llvm::Triple::thumbeb:
2457 // Only store the value; the last value set takes effect.
2458 ImplicitIt = A->getValue();
2459 if (!CheckARMImplicitITArg(Value: ImplicitIt))
2460 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2461 << A->getSpelling() << ImplicitIt;
2462 continue;
2463 default:
2464 break;
2465 }
2466 }
2467
2468 for (StringRef Value : A->getValues()) {
2469 if (TakeNextArg) {
2470 CmdArgs.push_back(Elt: Value.data());
2471 TakeNextArg = false;
2472 continue;
2473 }
2474
2475 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2476 Value == "-mbig-obj")
2477 continue; // LLVM handles bigobj automatically
2478
2479 auto Equal = Value.split(Separator: '=');
2480 auto checkArg = [&](bool ValidTarget,
2481 std::initializer_list<const char *> Set) {
2482 if (!ValidTarget) {
2483 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2484 << (Twine("-Wa,") + Equal.first + "=").str()
2485 << Triple.getTriple();
2486 } else if (!llvm::is_contained(Set, Element: Equal.second)) {
2487 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2488 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2489 }
2490 };
2491 switch (C.getDefaultToolChain().getArch()) {
2492 default:
2493 break;
2494 case llvm::Triple::x86:
2495 case llvm::Triple::x86_64:
2496 if (Equal.first == "-mrelax-relocations" ||
2497 Equal.first == "--mrelax-relocations") {
2498 UseRelaxRelocations = Equal.second == "yes";
2499 checkArg(IsELF, {"yes", "no"});
2500 continue;
2501 }
2502 if (Value == "-msse2avx") {
2503 CmdArgs.push_back(Elt: "-msse2avx");
2504 continue;
2505 }
2506 break;
2507 case llvm::Triple::wasm32:
2508 case llvm::Triple::wasm64:
2509 if (Value == "--no-type-check") {
2510 CmdArgs.push_back(Elt: "-mno-type-check");
2511 continue;
2512 }
2513 break;
2514 case llvm::Triple::thumb:
2515 case llvm::Triple::thumbeb:
2516 case llvm::Triple::arm:
2517 case llvm::Triple::armeb:
2518 if (Equal.first == "-mimplicit-it") {
2519 // Only store the value; the last value set takes effect.
2520 ImplicitIt = Equal.second;
2521 checkArg(true, {"always", "never", "arm", "thumb"});
2522 continue;
2523 }
2524 if (Value == "-mthumb")
2525 // -mthumb has already been processed in ComputeLLVMTriple()
2526 // recognize but skip over here.
2527 continue;
2528 break;
2529 case llvm::Triple::aarch64:
2530 case llvm::Triple::aarch64_be:
2531 case llvm::Triple::aarch64_32:
2532 if (Equal.first == "-mmapsyms") {
2533 ImplicitMapSyms = Equal.second == "implicit";
2534 checkArg(IsELF, {"default", "implicit"});
2535 continue;
2536 }
2537 break;
2538 case llvm::Triple::mips:
2539 case llvm::Triple::mipsel:
2540 case llvm::Triple::mips64:
2541 case llvm::Triple::mips64el:
2542 if (Value == "--trap") {
2543 CmdArgs.push_back(Elt: "-target-feature");
2544 CmdArgs.push_back(Elt: "+use-tcc-in-div");
2545 continue;
2546 }
2547 if (Value == "--break") {
2548 CmdArgs.push_back(Elt: "-target-feature");
2549 CmdArgs.push_back(Elt: "-use-tcc-in-div");
2550 continue;
2551 }
2552 if (Value.starts_with(Prefix: "-msoft-float")) {
2553 CmdArgs.push_back(Elt: "-target-feature");
2554 CmdArgs.push_back(Elt: "+soft-float");
2555 continue;
2556 }
2557 if (Value.starts_with(Prefix: "-mhard-float")) {
2558 CmdArgs.push_back(Elt: "-target-feature");
2559 CmdArgs.push_back(Elt: "-soft-float");
2560 continue;
2561 }
2562 if (Value == "-mmsa") {
2563 Msa = true;
2564 continue;
2565 }
2566 if (Value == "-mno-msa") {
2567 Msa = false;
2568 continue;
2569 }
2570 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2571 .Case(S: "-mips1", Value: "+mips1")
2572 .Case(S: "-mips2", Value: "+mips2")
2573 .Case(S: "-mips3", Value: "+mips3")
2574 .Case(S: "-mips4", Value: "+mips4")
2575 .Case(S: "-mips5", Value: "+mips5")
2576 .Case(S: "-mips32", Value: "+mips32")
2577 .Case(S: "-mips32r2", Value: "+mips32r2")
2578 .Case(S: "-mips32r3", Value: "+mips32r3")
2579 .Case(S: "-mips32r5", Value: "+mips32r5")
2580 .Case(S: "-mips32r6", Value: "+mips32r6")
2581 .Case(S: "-mips64", Value: "+mips64")
2582 .Case(S: "-mips64r2", Value: "+mips64r2")
2583 .Case(S: "-mips64r3", Value: "+mips64r3")
2584 .Case(S: "-mips64r5", Value: "+mips64r5")
2585 .Case(S: "-mips64r6", Value: "+mips64r6")
2586 .Default(Value: nullptr);
2587 if (MipsTargetFeature)
2588 continue;
2589 break;
2590
2591 case llvm::Triple::sparc:
2592 case llvm::Triple::sparcel:
2593 case llvm::Triple::sparcv9:
2594 if (Value == "--undeclared-regs") {
2595 // LLVM already allows undeclared use of G registers, so this option
2596 // becomes a no-op. This solely exists for GNU compatibility.
2597 // TODO implement --no-undeclared-regs
2598 continue;
2599 }
2600 SparcTargetFeatures =
2601 llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2602 .Case(S: "-Av8", Value: {"-v8plus"})
2603 .Case(S: "-Av8plus", Value: {"+v8plus", "+v9"})
2604 .Case(S: "-Av8plusa", Value: {"+v8plus", "+v9", "+vis"})
2605 .Case(S: "-Av8plusb", Value: {"+v8plus", "+v9", "+vis", "+vis2"})
2606 .Case(S: "-Av8plusd", Value: {"+v8plus", "+v9", "+vis", "+vis2", "+vis3"})
2607 .Case(S: "-Av9", Value: {"+v9"})
2608 .Case(S: "-Av9a", Value: {"+v9", "+vis"})
2609 .Case(S: "-Av9b", Value: {"+v9", "+vis", "+vis2"})
2610 .Case(S: "-Av9d", Value: {"+v9", "+vis", "+vis2", "+vis3"})
2611 .Default(Value: {});
2612 if (!SparcTargetFeatures.empty())
2613 continue;
2614 break;
2615 }
2616
2617 if (Value == "-force_cpusubtype_ALL") {
2618 // Do nothing, this is the default and we don't support anything else.
2619 } else if (Value == "-L") {
2620 CmdArgs.push_back(Elt: "-msave-temp-labels");
2621 } else if (Value == "--fatal-warnings") {
2622 CmdArgs.push_back(Elt: "-massembler-fatal-warnings");
2623 } else if (Value == "--no-warn" || Value == "-W") {
2624 CmdArgs.push_back(Elt: "-massembler-no-warn");
2625 } else if (Value == "--noexecstack") {
2626 UseNoExecStack = true;
2627 } else if (Value.starts_with(Prefix: "-compress-debug-sections") ||
2628 Value.starts_with(Prefix: "--compress-debug-sections") ||
2629 Value == "-nocompress-debug-sections" ||
2630 Value == "--nocompress-debug-sections") {
2631 CmdArgs.push_back(Elt: Value.data());
2632 } else if (Value == "--crel") {
2633 Crel = true;
2634 } else if (Value == "--no-crel") {
2635 Crel = false;
2636 } else if (Value == "--allow-experimental-crel") {
2637 ExperimentalCrel = true;
2638 } else if (Value.starts_with(Prefix: "-I")) {
2639 CmdArgs.push_back(Elt: Value.data());
2640 // We need to consume the next argument if the current arg is a plain
2641 // -I. The next arg will be the include directory.
2642 if (Value == "-I")
2643 TakeNextArg = true;
2644 } else if (Value.starts_with(Prefix: "-gdwarf-")) {
2645 // "-gdwarf-N" options are not cc1as options.
2646 unsigned DwarfVersion = DwarfVersionNum(ArgValue: Value);
2647 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2648 CmdArgs.push_back(Elt: Value.data());
2649 } else {
2650 RenderDebugEnablingArgs(Args, CmdArgs,
2651 DebugInfoKind: llvm::codegenoptions::DebugInfoConstructor,
2652 DwarfVersion, DebuggerTuning: llvm::DebuggerKind::Default);
2653 }
2654 } else if (Value == "--gsframe") {
2655 SFrame = true;
2656 } else if (Value == "--allow-experimental-sframe") {
2657 ExperimentalSFrame = true;
2658 } else if (Value.starts_with(Prefix: "-mcpu") || Value.starts_with(Prefix: "-mfpu") ||
2659 Value.starts_with(Prefix: "-mhwdiv") || Value.starts_with(Prefix: "-march")) {
2660 // Do nothing, we'll validate it later.
2661 } else if (Value == "-defsym" || Value == "--defsym") {
2662 if (A->getNumValues() != 2) {
2663 D.Diag(DiagID: diag::err_drv_defsym_invalid_format) << Value;
2664 break;
2665 }
2666 const char *S = A->getValue(N: 1);
2667 auto Pair = StringRef(S).split(Separator: '=');
2668 auto Sym = Pair.first;
2669 auto SVal = Pair.second;
2670
2671 if (Sym.empty() || SVal.empty()) {
2672 D.Diag(DiagID: diag::err_drv_defsym_invalid_format) << S;
2673 break;
2674 }
2675 int64_t IVal;
2676 if (SVal.getAsInteger(Radix: 0, Result&: IVal)) {
2677 D.Diag(DiagID: diag::err_drv_defsym_invalid_symval) << SVal;
2678 break;
2679 }
2680 CmdArgs.push_back(Elt: "--defsym");
2681 TakeNextArg = true;
2682 } else if (Value == "-fdebug-compilation-dir") {
2683 CmdArgs.push_back(Elt: "-fdebug-compilation-dir");
2684 TakeNextArg = true;
2685 } else if (Value.consume_front(Prefix: "-fdebug-compilation-dir=")) {
2686 // The flag is a -Wa / -Xassembler argument and Options doesn't
2687 // parse the argument, so this isn't automatically aliased to
2688 // -fdebug-compilation-dir (without '=') here.
2689 CmdArgs.push_back(Elt: "-fdebug-compilation-dir");
2690 CmdArgs.push_back(Elt: Value.data());
2691 } else if (Value == "--version") {
2692 D.PrintVersion(C, OS&: llvm::outs());
2693 } else {
2694 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2695 << A->getSpelling() << Value;
2696 }
2697 }
2698 }
2699 if (ImplicitIt.size())
2700 AddARMImplicitITArgs(Args, CmdArgs, Value: ImplicitIt);
2701 if (Crel) {
2702 if (!ExperimentalCrel)
2703 D.Diag(DiagID: diag::err_drv_experimental_crel);
2704 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2705 CmdArgs.push_back(Elt: "--crel");
2706 } else {
2707 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2708 << "-Wa,--crel" << D.getTargetTriple();
2709 }
2710 }
2711 if (SFrame) {
2712 if (Triple.isOSBinFormatELF() && Triple.isX86()) {
2713 if (!ExperimentalSFrame)
2714 D.Diag(DiagID: diag::err_drv_experimental_sframe);
2715 else
2716 CmdArgs.push_back(Elt: "--gsframe");
2717 } else {
2718 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2719 << "-Wa,--gsframe" << D.getTargetTriple();
2720 }
2721 }
2722 if (ImplicitMapSyms)
2723 CmdArgs.push_back(Elt: "-mmapsyms=implicit");
2724 if (Msa)
2725 CmdArgs.push_back(Elt: "-mmsa");
2726 if (!UseRelaxRelocations)
2727 CmdArgs.push_back(Elt: "-mrelax-relocations=no");
2728 if (UseNoExecStack)
2729 CmdArgs.push_back(Elt: "-mnoexecstack");
2730 if (MipsTargetFeature != nullptr) {
2731 CmdArgs.push_back(Elt: "-target-feature");
2732 CmdArgs.push_back(Elt: MipsTargetFeature);
2733 }
2734
2735 for (const char *Feature : SparcTargetFeatures) {
2736 CmdArgs.push_back(Elt: "-target-feature");
2737 CmdArgs.push_back(Elt: Feature);
2738 }
2739
2740 // forward -fembed-bitcode to assmebler
2741 if (C.getDriver().embedBitcodeEnabled() ||
2742 C.getDriver().embedBitcodeMarkerOnly())
2743 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fembed_bitcode_EQ);
2744
2745 if (const char *AsSecureLogFile = getenv(name: "AS_SECURE_LOG_FILE")) {
2746 CmdArgs.push_back(Elt: "-as-secure-log-file");
2747 CmdArgs.push_back(Elt: Args.MakeArgString(Str: AsSecureLogFile));
2748 }
2749}
2750
2751static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2752 bool OFastEnabled, const ArgList &Args,
2753 ArgStringList &CmdArgs,
2754 const JobAction &JA) {
2755 // List of veclibs which when used with -fveclib imply -fno-math-errno.
2756 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2757 llvm::StringLiteral("SLEEF")};
2758 bool NoMathErrnoWasImpliedByVecLib = false;
2759 const Arg *VecLibArg = nullptr;
2760 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
2761 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
2762
2763 // Handle various floating point optimization flags, mapping them to the
2764 // appropriate LLVM code generation flags. This is complicated by several
2765 // "umbrella" flags, so we do this by stepping through the flags incrementally
2766 // adjusting what we think is enabled/disabled, then at the end setting the
2767 // LLVM flags based on the final state.
2768 bool HonorINFs = true;
2769 bool HonorNaNs = true;
2770 bool ApproxFunc = false;
2771 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2772 bool MathErrno = TC.IsMathErrnoDefault();
2773 bool AssociativeMath = false;
2774 bool ReciprocalMath = false;
2775 bool SignedZeros = true;
2776 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2777 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2778 // overriden by ffp-exception-behavior?
2779 bool RoundingFPMath = false;
2780 // -ffp-model values: strict, fast, precise
2781 StringRef FPModel = "";
2782 // -ffp-exception-behavior options: strict, maytrap, ignore
2783 StringRef FPExceptionBehavior = "";
2784 // -ffp-eval-method options: double, extended, source
2785 StringRef FPEvalMethod = "";
2786 llvm::DenormalMode DenormalFPMath =
2787 TC.getDefaultDenormalModeForType(DriverArgs: Args, JA);
2788 llvm::DenormalMode DenormalFP32Math =
2789 TC.getDefaultDenormalModeForType(DriverArgs: Args, JA, FPType: &llvm::APFloat::IEEEsingle());
2790
2791 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2792 // If one wasn't given by the user, don't pass it here.
2793 StringRef FPContract;
2794 StringRef LastSeenFfpContractOption;
2795 StringRef LastFpContractOverrideOption;
2796 bool SeenUnsafeMathModeOption = false;
2797 if (!JA.isDeviceOffloading(OKind: Action::OFK_Cuda) &&
2798 !JA.isOffloading(OKind: Action::OFK_HIP))
2799 FPContract = "on";
2800 bool StrictFPModel = false;
2801 StringRef Float16ExcessPrecision = "";
2802 StringRef BFloat16ExcessPrecision = "";
2803 LangOptions::ComplexRangeKind Range = LangOptions::ComplexRangeKind::CX_None;
2804 std::string ComplexRangeStr;
2805 StringRef LastComplexRangeOption;
2806
2807 // Lambda to set fast-math options. This is also used by -ffp-model=fast
2808 auto applyFastMath = [&](bool Aggressive, StringRef CallerOption) {
2809 if (Aggressive) {
2810 HonorINFs = false;
2811 HonorNaNs = false;
2812 setComplexRange(D, NewOpt: CallerOption, NewRange: LangOptions::ComplexRangeKind::CX_Basic,
2813 LastOpt&: LastComplexRangeOption, Range);
2814 } else {
2815 HonorINFs = true;
2816 HonorNaNs = true;
2817 setComplexRange(D, NewOpt: CallerOption,
2818 NewRange: LangOptions::ComplexRangeKind::CX_Promoted,
2819 LastOpt&: LastComplexRangeOption, Range);
2820 }
2821 MathErrno = false;
2822 AssociativeMath = true;
2823 ReciprocalMath = true;
2824 ApproxFunc = true;
2825 SignedZeros = false;
2826 TrappingMath = false;
2827 RoundingFPMath = false;
2828 FPExceptionBehavior = "";
2829 FPContract = "fast";
2830 SeenUnsafeMathModeOption = true;
2831 };
2832
2833 // Lambda to consolidate common handling for fp-contract
2834 auto restoreFPContractState = [&]() {
2835 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2836 // For other targets, if the state has been changed by one of the
2837 // unsafe-math umbrella options a subsequent -fno-fast-math or
2838 // -fno-unsafe-math-optimizations option reverts to the last value seen for
2839 // the -ffp-contract option or "on" if we have not seen the -ffp-contract
2840 // option. If we have not seen an unsafe-math option or -ffp-contract,
2841 // we leave the FPContract state unchanged.
2842 if (!JA.isDeviceOffloading(OKind: Action::OFK_Cuda) &&
2843 !JA.isOffloading(OKind: Action::OFK_HIP)) {
2844 if (LastSeenFfpContractOption != "")
2845 FPContract = LastSeenFfpContractOption;
2846 else if (SeenUnsafeMathModeOption)
2847 FPContract = "on";
2848 }
2849 // In this case, we're reverting to the last explicit fp-contract option
2850 // or the platform default
2851 LastFpContractOverrideOption = "";
2852 };
2853
2854 if (const Arg *A = Args.getLastArg(Ids: options::OPT_flimited_precision_EQ)) {
2855 CmdArgs.push_back(Elt: "-mlimit-float-precision");
2856 CmdArgs.push_back(Elt: A->getValue());
2857 }
2858
2859 for (const Arg *A : Args) {
2860 llvm::scope_exit CheckMathErrnoForVecLib(
2861 [&, MathErrnoBeforeArg = MathErrno] {
2862 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
2863 ArgThatEnabledMathErrnoAfterVecLib = A;
2864 });
2865
2866 switch (A->getOption().getID()) {
2867 // If this isn't an FP option skip the claim below
2868 default: continue;
2869
2870 case options::OPT_fcx_limited_range:
2871 setComplexRange(D, NewOpt: A->getSpelling(),
2872 NewRange: LangOptions::ComplexRangeKind::CX_Basic,
2873 LastOpt&: LastComplexRangeOption, Range);
2874 break;
2875 case options::OPT_fno_cx_limited_range:
2876 setComplexRange(D, NewOpt: A->getSpelling(),
2877 NewRange: LangOptions::ComplexRangeKind::CX_Full,
2878 LastOpt&: LastComplexRangeOption, Range);
2879 break;
2880 case options::OPT_fcx_fortran_rules:
2881 setComplexRange(D, NewOpt: A->getSpelling(),
2882 NewRange: LangOptions::ComplexRangeKind::CX_Improved,
2883 LastOpt&: LastComplexRangeOption, Range);
2884 break;
2885 case options::OPT_fno_cx_fortran_rules:
2886 setComplexRange(D, NewOpt: A->getSpelling(),
2887 NewRange: LangOptions::ComplexRangeKind::CX_Full,
2888 LastOpt&: LastComplexRangeOption, Range);
2889 break;
2890 case options::OPT_fcomplex_arithmetic_EQ: {
2891 LangOptions::ComplexRangeKind RangeVal;
2892 StringRef Val = A->getValue();
2893 if (Val == "full")
2894 RangeVal = LangOptions::ComplexRangeKind::CX_Full;
2895 else if (Val == "improved")
2896 RangeVal = LangOptions::ComplexRangeKind::CX_Improved;
2897 else if (Val == "promoted")
2898 RangeVal = LangOptions::ComplexRangeKind::CX_Promoted;
2899 else if (Val == "basic")
2900 RangeVal = LangOptions::ComplexRangeKind::CX_Basic;
2901 else {
2902 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2903 << A->getSpelling() << Val;
2904 break;
2905 }
2906 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val), NewRange: RangeVal,
2907 LastOpt&: LastComplexRangeOption, Range);
2908 break;
2909 }
2910 case options::OPT_ffp_model_EQ: {
2911 // If -ffp-model= is seen, reset to fno-fast-math
2912 HonorINFs = true;
2913 HonorNaNs = true;
2914 ApproxFunc = false;
2915 // Turning *off* -ffast-math restores the toolchain default.
2916 MathErrno = TC.IsMathErrnoDefault();
2917 AssociativeMath = false;
2918 ReciprocalMath = false;
2919 SignedZeros = true;
2920
2921 StringRef Val = A->getValue();
2922 if (OFastEnabled && Val != "aggressive") {
2923 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
2924 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
2925 << Args.MakeArgString(Str: "-ffp-model=" + Val) << "-Ofast";
2926 break;
2927 }
2928 StrictFPModel = false;
2929 if (!FPModel.empty() && FPModel != Val)
2930 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
2931 << Args.MakeArgString(Str: "-ffp-model=" + FPModel)
2932 << Args.MakeArgString(Str: "-ffp-model=" + Val);
2933 if (Val == "fast") {
2934 FPModel = Val;
2935 applyFastMath(false, Args.MakeArgString(Str: A->getSpelling() + Val));
2936 // applyFastMath sets fp-contract="fast"
2937 LastFpContractOverrideOption = "-ffp-model=fast";
2938 } else if (Val == "aggressive") {
2939 FPModel = Val;
2940 applyFastMath(true, Args.MakeArgString(Str: A->getSpelling() + Val));
2941 // applyFastMath sets fp-contract="fast"
2942 LastFpContractOverrideOption = "-ffp-model=aggressive";
2943 } else if (Val == "precise") {
2944 FPModel = Val;
2945 FPContract = "on";
2946 LastFpContractOverrideOption = "-ffp-model=precise";
2947 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val),
2948 NewRange: LangOptions::ComplexRangeKind::CX_Full,
2949 LastOpt&: LastComplexRangeOption, Range);
2950 } else if (Val == "strict") {
2951 StrictFPModel = true;
2952 FPExceptionBehavior = "strict";
2953 FPModel = Val;
2954 FPContract = "off";
2955 LastFpContractOverrideOption = "-ffp-model=strict";
2956 TrappingMath = true;
2957 RoundingFPMath = true;
2958 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val),
2959 NewRange: LangOptions::ComplexRangeKind::CX_Full,
2960 LastOpt&: LastComplexRangeOption, Range);
2961 } else
2962 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2963 << A->getSpelling() << Val;
2964 break;
2965 }
2966
2967 // Options controlling individual features
2968 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2969 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2970 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2971 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2972 case options::OPT_fapprox_func: ApproxFunc = true; break;
2973 case options::OPT_fno_approx_func: ApproxFunc = false; break;
2974 case options::OPT_fmath_errno: MathErrno = true; break;
2975 case options::OPT_fno_math_errno: MathErrno = false; break;
2976 case options::OPT_fassociative_math: AssociativeMath = true; break;
2977 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2978 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2979 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2980 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2981 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2982 case options::OPT_ftrapping_math:
2983 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2984 FPExceptionBehavior != "strict")
2985 // Warn that previous value of option is overridden.
2986 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
2987 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
2988 FPExceptionBehavior)
2989 << "-ftrapping-math";
2990 TrappingMath = true;
2991 TrappingMathPresent = true;
2992 FPExceptionBehavior = "strict";
2993 break;
2994 case options::OPT_fveclib:
2995 VecLibArg = A;
2996 NoMathErrnoWasImpliedByVecLib =
2997 llvm::is_contained(Range: VecLibImpliesNoMathErrno, Element: A->getValue());
2998 if (NoMathErrnoWasImpliedByVecLib)
2999 MathErrno = false;
3000 break;
3001 case options::OPT_fno_trapping_math:
3002 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3003 FPExceptionBehavior != "ignore")
3004 // Warn that previous value of option is overridden.
3005 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3006 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3007 FPExceptionBehavior)
3008 << "-fno-trapping-math";
3009 TrappingMath = false;
3010 TrappingMathPresent = true;
3011 FPExceptionBehavior = "ignore";
3012 break;
3013
3014 case options::OPT_frounding_math:
3015 RoundingFPMath = true;
3016 break;
3017
3018 case options::OPT_fno_rounding_math:
3019 RoundingFPMath = false;
3020 break;
3021
3022 case options::OPT_fdenormal_fp_math_EQ:
3023 DenormalFPMath = llvm::parseDenormalFPAttribute(Str: A->getValue());
3024 DenormalFP32Math = DenormalFPMath;
3025 if (!DenormalFPMath.isValid()) {
3026 D.Diag(DiagID: diag::err_drv_invalid_value)
3027 << A->getAsString(Args) << A->getValue();
3028 }
3029 break;
3030
3031 case options::OPT_fdenormal_fp_math_f32_EQ:
3032 DenormalFP32Math = llvm::parseDenormalFPAttribute(Str: A->getValue());
3033 if (!DenormalFP32Math.isValid()) {
3034 D.Diag(DiagID: diag::err_drv_invalid_value)
3035 << A->getAsString(Args) << A->getValue();
3036 }
3037 break;
3038
3039 // Validate and pass through -ffp-contract option.
3040 case options::OPT_ffp_contract: {
3041 StringRef Val = A->getValue();
3042 if (Val == "fast" || Val == "on" || Val == "off" ||
3043 Val == "fast-honor-pragmas") {
3044 if (Val != FPContract && LastFpContractOverrideOption != "") {
3045 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3046 << LastFpContractOverrideOption
3047 << Args.MakeArgString(Str: "-ffp-contract=" + Val);
3048 }
3049
3050 FPContract = Val;
3051 LastSeenFfpContractOption = Val;
3052 LastFpContractOverrideOption = "";
3053 } else
3054 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3055 << A->getSpelling() << Val;
3056 break;
3057 }
3058
3059 // Validate and pass through -ffp-exception-behavior option.
3060 case options::OPT_ffp_exception_behavior_EQ: {
3061 StringRef Val = A->getValue();
3062 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3063 FPExceptionBehavior != Val)
3064 // Warn that previous value of option is overridden.
3065 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3066 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3067 FPExceptionBehavior)
3068 << Args.MakeArgString(Str: "-ffp-exception-behavior=" + Val);
3069 TrappingMath = TrappingMathPresent = false;
3070 if (Val == "ignore" || Val == "maytrap")
3071 FPExceptionBehavior = Val;
3072 else if (Val == "strict") {
3073 FPExceptionBehavior = Val;
3074 TrappingMath = TrappingMathPresent = true;
3075 } else
3076 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3077 << A->getSpelling() << Val;
3078 break;
3079 }
3080
3081 // Validate and pass through -ffp-eval-method option.
3082 case options::OPT_ffp_eval_method_EQ: {
3083 StringRef Val = A->getValue();
3084 if (Val == "double" || Val == "extended" || Val == "source")
3085 FPEvalMethod = Val;
3086 else
3087 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3088 << A->getSpelling() << Val;
3089 break;
3090 }
3091
3092 case options::OPT_fexcess_precision_EQ: {
3093 StringRef Val = A->getValue();
3094 const llvm::Triple::ArchType Arch = TC.getArch();
3095 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3096 if (Val == "standard" || Val == "fast")
3097 Float16ExcessPrecision = Val;
3098 // To make it GCC compatible, allow the value of "16" which
3099 // means disable excess precision, the same meaning than clang's
3100 // equivalent value "none".
3101 else if (Val == "16")
3102 Float16ExcessPrecision = "none";
3103 else
3104 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3105 << A->getSpelling() << Val;
3106 } else {
3107 if (!(Val == "standard" || Val == "fast"))
3108 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3109 << A->getSpelling() << Val;
3110 }
3111 BFloat16ExcessPrecision = Float16ExcessPrecision;
3112 break;
3113 }
3114 case options::OPT_ffinite_math_only:
3115 HonorINFs = false;
3116 HonorNaNs = false;
3117 break;
3118 case options::OPT_fno_finite_math_only:
3119 HonorINFs = true;
3120 HonorNaNs = true;
3121 break;
3122
3123 case options::OPT_funsafe_math_optimizations:
3124 AssociativeMath = true;
3125 ReciprocalMath = true;
3126 SignedZeros = false;
3127 ApproxFunc = true;
3128 TrappingMath = false;
3129 FPExceptionBehavior = "";
3130 FPContract = "fast";
3131 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3132 SeenUnsafeMathModeOption = true;
3133 break;
3134 case options::OPT_fno_unsafe_math_optimizations:
3135 AssociativeMath = false;
3136 ReciprocalMath = false;
3137 SignedZeros = true;
3138 ApproxFunc = false;
3139 restoreFPContractState();
3140 break;
3141
3142 case options::OPT_Ofast:
3143 // If -Ofast is the optimization level, then -ffast-math should be enabled
3144 if (!OFastEnabled)
3145 continue;
3146 [[fallthrough]];
3147 case options::OPT_ffast_math:
3148 applyFastMath(true, A->getSpelling());
3149 if (A->getOption().getID() == options::OPT_Ofast)
3150 LastFpContractOverrideOption = "-Ofast";
3151 else
3152 LastFpContractOverrideOption = "-ffast-math";
3153 break;
3154 case options::OPT_fno_fast_math:
3155 HonorINFs = true;
3156 HonorNaNs = true;
3157 // Turning on -ffast-math (with either flag) removes the need for
3158 // MathErrno. However, turning *off* -ffast-math merely restores the
3159 // toolchain default (which may be false).
3160 MathErrno = TC.IsMathErrnoDefault();
3161 AssociativeMath = false;
3162 ReciprocalMath = false;
3163 ApproxFunc = false;
3164 SignedZeros = true;
3165 restoreFPContractState();
3166 if (Range != LangOptions::ComplexRangeKind::CX_Full)
3167 setComplexRange(D, NewOpt: A->getSpelling(),
3168 NewRange: LangOptions::ComplexRangeKind::CX_None,
3169 LastOpt&: LastComplexRangeOption, Range);
3170 else
3171 Range = LangOptions::ComplexRangeKind::CX_None;
3172 LastComplexRangeOption = "";
3173 LastFpContractOverrideOption = "";
3174 break;
3175 } // End switch (A->getOption().getID())
3176
3177 // The StrictFPModel local variable is needed to report warnings
3178 // in the way we intend. If -ffp-model=strict has been used, we
3179 // want to report a warning for the next option encountered that
3180 // takes us out of the settings described by fp-model=strict, but
3181 // we don't want to continue issuing warnings for other conflicting
3182 // options after that.
3183 if (StrictFPModel) {
3184 // If -ffp-model=strict has been specified on command line but
3185 // subsequent options conflict then emit warning diagnostic.
3186 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3187 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3188 FPContract == "off")
3189 // OK: Current Arg doesn't conflict with -ffp-model=strict
3190 ;
3191 else {
3192 StrictFPModel = false;
3193 FPModel = "";
3194 // The warning for -ffp-contract would have been reported by the
3195 // OPT_ffp_contract_EQ handler above. A special check here is needed
3196 // to avoid duplicating the warning.
3197 auto RHS = (A->getNumValues() == 0)
3198 ? A->getSpelling()
3199 : Args.MakeArgString(Str: A->getSpelling() + A->getValue());
3200 if (A->getSpelling() != "-ffp-contract=") {
3201 if (RHS != "-ffp-model=strict")
3202 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3203 << "-ffp-model=strict" << RHS;
3204 }
3205 }
3206 }
3207
3208 // If we handled this option claim it
3209 A->claim();
3210 }
3211
3212 if (!HonorINFs)
3213 CmdArgs.push_back(Elt: "-menable-no-infs");
3214
3215 if (!HonorNaNs)
3216 CmdArgs.push_back(Elt: "-menable-no-nans");
3217
3218 if (ApproxFunc)
3219 CmdArgs.push_back(Elt: "-fapprox-func");
3220
3221 if (MathErrno) {
3222 CmdArgs.push_back(Elt: "-fmath-errno");
3223 if (NoMathErrnoWasImpliedByVecLib)
3224 D.Diag(DiagID: clang::diag::warn_drv_math_errno_enabled_after_veclib)
3225 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3226 << VecLibArg->getAsString(Args);
3227 }
3228
3229 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3230 !TrappingMath)
3231 CmdArgs.push_back(Elt: "-funsafe-math-optimizations");
3232
3233 if (!SignedZeros)
3234 CmdArgs.push_back(Elt: "-fno-signed-zeros");
3235
3236 if (AssociativeMath && !SignedZeros && !TrappingMath)
3237 CmdArgs.push_back(Elt: "-mreassociate");
3238
3239 if (ReciprocalMath)
3240 CmdArgs.push_back(Elt: "-freciprocal-math");
3241
3242 if (TrappingMath) {
3243 // FP Exception Behavior is also set to strict
3244 assert(FPExceptionBehavior == "strict");
3245 }
3246
3247 // The default is IEEE.
3248 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3249 llvm::SmallString<64> DenormFlag;
3250 llvm::raw_svector_ostream ArgStr(DenormFlag);
3251 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3252 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArgStr.str()));
3253 }
3254
3255 // Add f32 specific denormal mode flag if it's different.
3256 if (DenormalFP32Math != DenormalFPMath) {
3257 llvm::SmallString<64> DenormFlag;
3258 llvm::raw_svector_ostream ArgStr(DenormFlag);
3259 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3260 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArgStr.str()));
3261 }
3262
3263 if (!FPContract.empty())
3264 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-contract=" + FPContract));
3265
3266 if (RoundingFPMath)
3267 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-frounding-math"));
3268 else
3269 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fno-rounding-math"));
3270
3271 if (!FPExceptionBehavior.empty())
3272 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3273 FPExceptionBehavior));
3274
3275 if (!FPEvalMethod.empty())
3276 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-eval-method=" + FPEvalMethod));
3277
3278 if (!Float16ExcessPrecision.empty())
3279 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffloat16-excess-precision=" +
3280 Float16ExcessPrecision));
3281 if (!BFloat16ExcessPrecision.empty())
3282 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fbfloat16-excess-precision=" +
3283 BFloat16ExcessPrecision));
3284
3285 StringRef Recip = parseMRecipOption(Diags&: D.getDiags(), Args);
3286 if (!Recip.empty())
3287 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mrecip=" + Recip));
3288
3289 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3290 // individual features enabled by -ffast-math instead of the option itself as
3291 // that's consistent with gcc's behaviour.
3292 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3293 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3294 CmdArgs.push_back(Elt: "-ffast-math");
3295
3296 // Handle __FINITE_MATH_ONLY__ similarly.
3297 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3298 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3299 // -menable-no-nans are set by the user.
3300 bool shouldAddFiniteMathOnly = false;
3301 if (!HonorINFs && !HonorNaNs) {
3302 shouldAddFiniteMathOnly = true;
3303 } else {
3304 bool InfValues = true;
3305 bool NanValues = true;
3306 for (const auto *Arg : Args.filtered(Ids: options::OPT_Xclang)) {
3307 StringRef ArgValue = Arg->getValue();
3308 if (ArgValue == "-menable-no-nans")
3309 NanValues = false;
3310 else if (ArgValue == "-menable-no-infs")
3311 InfValues = false;
3312 }
3313 if (!NanValues && !InfValues)
3314 shouldAddFiniteMathOnly = true;
3315 }
3316 if (shouldAddFiniteMathOnly) {
3317 CmdArgs.push_back(Elt: "-ffinite-math-only");
3318 }
3319 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mfpmath_EQ)) {
3320 CmdArgs.push_back(Elt: "-mfpmath");
3321 CmdArgs.push_back(Elt: A->getValue());
3322 }
3323
3324 // Disable a codegen optimization for floating-point casts.
3325 if (Args.hasFlag(Pos: options::OPT_fno_strict_float_cast_overflow,
3326 Neg: options::OPT_fstrict_float_cast_overflow, Default: false))
3327 CmdArgs.push_back(Elt: "-fno-strict-float-cast-overflow");
3328
3329 if (Range != LangOptions::ComplexRangeKind::CX_None)
3330 ComplexRangeStr = renderComplexRangeOption(Range);
3331 if (!ComplexRangeStr.empty()) {
3332 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ComplexRangeStr));
3333 if (Args.hasArg(Ids: options::OPT_fcomplex_arithmetic_EQ))
3334 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fcomplex-arithmetic=" +
3335 complexRangeKindToStr(Range)));
3336 }
3337 if (Args.hasArg(Ids: options::OPT_fcx_limited_range))
3338 CmdArgs.push_back(Elt: "-fcx-limited-range");
3339 if (Args.hasArg(Ids: options::OPT_fcx_fortran_rules))
3340 CmdArgs.push_back(Elt: "-fcx-fortran-rules");
3341 if (Args.hasArg(Ids: options::OPT_fno_cx_limited_range))
3342 CmdArgs.push_back(Elt: "-fno-cx-limited-range");
3343 if (Args.hasArg(Ids: options::OPT_fno_cx_fortran_rules))
3344 CmdArgs.push_back(Elt: "-fno-cx-fortran-rules");
3345}
3346
3347static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3348 const llvm::Triple &Triple,
3349 const InputInfo &Input) {
3350 // Add default argument set.
3351 if (!Args.hasArg(Ids: options::OPT__analyzer_no_default_checks)) {
3352 CmdArgs.push_back(Elt: "-analyzer-checker=core");
3353 CmdArgs.push_back(Elt: "-analyzer-checker=apiModeling");
3354
3355 if (!Triple.isWindowsMSVCEnvironment()) {
3356 CmdArgs.push_back(Elt: "-analyzer-checker=unix");
3357 } else {
3358 // Enable "unix" checkers that also work on Windows.
3359 CmdArgs.push_back(Elt: "-analyzer-checker=unix.API");
3360 CmdArgs.push_back(Elt: "-analyzer-checker=unix.Malloc");
3361 CmdArgs.push_back(Elt: "-analyzer-checker=unix.MallocSizeof");
3362 CmdArgs.push_back(Elt: "-analyzer-checker=unix.MismatchedDeallocator");
3363 CmdArgs.push_back(Elt: "-analyzer-checker=unix.cstring.BadSizeArg");
3364 CmdArgs.push_back(Elt: "-analyzer-checker=unix.cstring.NullArg");
3365 }
3366
3367 // Disable some unix checkers for PS4/PS5.
3368 if (Triple.isPS()) {
3369 CmdArgs.push_back(Elt: "-analyzer-disable-checker=unix.API");
3370 CmdArgs.push_back(Elt: "-analyzer-disable-checker=unix.Vfork");
3371 }
3372
3373 if (Triple.isOSDarwin()) {
3374 CmdArgs.push_back(Elt: "-analyzer-checker=osx");
3375 CmdArgs.push_back(
3376 Elt: "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3377 }
3378 else if (Triple.isOSFuchsia())
3379 CmdArgs.push_back(Elt: "-analyzer-checker=fuchsia");
3380
3381 CmdArgs.push_back(Elt: "-analyzer-checker=deadcode");
3382
3383 if (types::isCXX(Id: Input.getType()))
3384 CmdArgs.push_back(Elt: "-analyzer-checker=cplusplus");
3385
3386 if (!Triple.isPS()) {
3387 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3388 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.getpw");
3389 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.gets");
3390 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.mktemp");
3391 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.mkstemp");
3392 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.vfork");
3393 }
3394
3395 // Default nullability checks.
3396 CmdArgs.push_back(Elt: "-analyzer-checker=nullability.NullPassedToNonnull");
3397 CmdArgs.push_back(Elt: "-analyzer-checker=nullability.NullReturnedFromNonnull");
3398 }
3399
3400 // Set the output format. The default is plist, for (lame) historical reasons.
3401 CmdArgs.push_back(Elt: "-analyzer-output");
3402 if (Arg *A = Args.getLastArg(Ids: options::OPT__analyzer_output))
3403 CmdArgs.push_back(Elt: A->getValue());
3404 else
3405 CmdArgs.push_back(Elt: "plist");
3406
3407 // Disable the presentation of standard compiler warnings when using
3408 // --analyze. We only want to show static analyzer diagnostics or frontend
3409 // errors.
3410 CmdArgs.push_back(Elt: "-w");
3411
3412 // Add -Xanalyzer arguments when running as analyzer.
3413 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Xanalyzer);
3414}
3415
3416static bool isValidSymbolName(StringRef S) {
3417 if (S.empty())
3418 return false;
3419
3420 if (std::isdigit(S[0]))
3421 return false;
3422
3423 return llvm::all_of(Range&: S, P: [](char C) { return std::isalnum(C) || C == '_'; });
3424}
3425
3426static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3427 const ArgList &Args, ArgStringList &CmdArgs,
3428 bool KernelOrKext) {
3429 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3430
3431 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3432 // doesn't even have a stack!
3433 if (EffectiveTriple.isNVPTX())
3434 return;
3435
3436 // -stack-protector=0 is default.
3437 LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3438 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3439 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3440
3441 if (Arg *A = Args.getLastArg(Ids: options::OPT_fno_stack_protector,
3442 Ids: options::OPT_fstack_protector_all,
3443 Ids: options::OPT_fstack_protector_strong,
3444 Ids: options::OPT_fstack_protector)) {
3445 if (A->getOption().matches(ID: options::OPT_fstack_protector))
3446 StackProtectorLevel =
3447 std::max<>(a: LangOptions::SSPOn, b: DefaultStackProtectorLevel);
3448 else if (A->getOption().matches(ID: options::OPT_fstack_protector_strong))
3449 StackProtectorLevel = LangOptions::SSPStrong;
3450 else if (A->getOption().matches(ID: options::OPT_fstack_protector_all))
3451 StackProtectorLevel = LangOptions::SSPReq;
3452
3453 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3454 D.Diag(DiagID: diag::warn_drv_unsupported_option_for_target)
3455 << A->getSpelling() << EffectiveTriple.getTriple();
3456 StackProtectorLevel = DefaultStackProtectorLevel;
3457 }
3458 } else {
3459 StackProtectorLevel = DefaultStackProtectorLevel;
3460 }
3461
3462 if (StackProtectorLevel) {
3463 CmdArgs.push_back(Elt: "-stack-protector");
3464 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(StackProtectorLevel)));
3465 }
3466
3467 // --param ssp-buffer-size=
3468 for (const Arg *A : Args.filtered(Ids: options::OPT__param)) {
3469 StringRef Str(A->getValue());
3470 if (Str.consume_front(Prefix: "ssp-buffer-size=")) {
3471 if (StackProtectorLevel) {
3472 CmdArgs.push_back(Elt: "-stack-protector-buffer-size");
3473 // FIXME: Verify the argument is a valid integer.
3474 CmdArgs.push_back(Elt: Args.MakeArgString(Str));
3475 }
3476 A->claim();
3477 }
3478 }
3479
3480 const std::string &TripleStr = EffectiveTriple.getTriple();
3481 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_EQ)) {
3482 StringRef Value = A->getValue();
3483 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3484 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3485 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3486 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3487 << A->getAsString(Args) << TripleStr;
3488 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3489 EffectiveTriple.isThumb()) &&
3490 Value != "tls" && Value != "global") {
3491 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3492 << A->getOption().getName() << Value << "tls global";
3493 return;
3494 }
3495 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3496 Value == "tls") {
3497 if (!Args.hasArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3498 D.Diag(DiagID: diag::err_drv_ssp_missing_offset_argument)
3499 << A->getAsString(Args);
3500 return;
3501 }
3502 // Check whether the target subarch supports the hardware TLS register
3503 if (!arm::isHardTPSupported(Triple: EffectiveTriple)) {
3504 D.Diag(DiagID: diag::err_target_unsupported_tp_hard)
3505 << EffectiveTriple.getArchName();
3506 return;
3507 }
3508 // Check whether the user asked for something other than -mtp=cp15
3509 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtp_mode_EQ)) {
3510 StringRef Value = A->getValue();
3511 if (Value != "cp15") {
3512 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
3513 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3514 return;
3515 }
3516 }
3517 CmdArgs.push_back(Elt: "-target-feature");
3518 CmdArgs.push_back(Elt: "+read-tp-tpidruro");
3519 }
3520 if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3521 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3522 << A->getOption().getName() << Value << "sysreg global";
3523 return;
3524 }
3525 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3526 if (Value != "tls" && Value != "global") {
3527 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3528 << A->getOption().getName() << Value << "tls global";
3529 return;
3530 }
3531 if (Value == "tls") {
3532 if (!Args.hasArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3533 D.Diag(DiagID: diag::err_drv_ssp_missing_offset_argument)
3534 << A->getAsString(Args);
3535 return;
3536 }
3537 }
3538 }
3539 A->render(Args, Output&: CmdArgs);
3540 }
3541
3542 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3543 StringRef Value = A->getValue();
3544 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3545 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3546 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3547 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3548 << A->getAsString(Args) << TripleStr;
3549 int Offset;
3550 if (Value.getAsInteger(Radix: 10, Result&: Offset)) {
3551 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3552 return;
3553 }
3554 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3555 (Offset < 0 || Offset > 0xfffff)) {
3556 D.Diag(DiagID: diag::err_drv_invalid_int_value)
3557 << A->getOption().getName() << Value;
3558 return;
3559 }
3560 A->render(Args, Output&: CmdArgs);
3561 }
3562
3563 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_reg_EQ)) {
3564 StringRef Value = A->getValue();
3565 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3566 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3567 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3568 << A->getAsString(Args) << TripleStr;
3569 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3570 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3571 << A->getOption().getName() << Value << "fs gs";
3572 return;
3573 }
3574 if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3575 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3576 return;
3577 }
3578 if (EffectiveTriple.isRISCV() && Value != "tp") {
3579 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3580 << A->getOption().getName() << Value << "tp";
3581 return;
3582 }
3583 if (EffectiveTriple.isPPC64() && Value != "r13") {
3584 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3585 << A->getOption().getName() << Value << "r13";
3586 return;
3587 }
3588 if (EffectiveTriple.isPPC32() && Value != "r2") {
3589 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3590 << A->getOption().getName() << Value << "r2";
3591 return;
3592 }
3593 A->render(Args, Output&: CmdArgs);
3594 }
3595
3596 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_symbol_EQ)) {
3597 StringRef Value = A->getValue();
3598 if (!isValidSymbolName(S: Value)) {
3599 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
3600 << A->getOption().getName() << "legal symbol name";
3601 return;
3602 }
3603 A->render(Args, Output&: CmdArgs);
3604 }
3605}
3606
3607static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3608 ArgStringList &CmdArgs) {
3609 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3610
3611 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3612 !EffectiveTriple.isOSFuchsia())
3613 return;
3614
3615 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3616 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3617 !EffectiveTriple.isRISCV())
3618 return;
3619
3620 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstack_clash_protection,
3621 Neg: options::OPT_fno_stack_clash_protection);
3622}
3623
3624static void RenderTrivialAutoVarInitOptions(const Driver &D,
3625 const ToolChain &TC,
3626 const ArgList &Args,
3627 ArgStringList &CmdArgs) {
3628 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3629 StringRef TrivialAutoVarInit = "";
3630
3631 for (const Arg *A : Args) {
3632 switch (A->getOption().getID()) {
3633 default:
3634 continue;
3635 case options::OPT_ftrivial_auto_var_init: {
3636 A->claim();
3637 StringRef Val = A->getValue();
3638 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3639 TrivialAutoVarInit = Val;
3640 else
3641 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3642 << A->getSpelling() << Val;
3643 break;
3644 }
3645 }
3646 }
3647
3648 if (TrivialAutoVarInit.empty())
3649 switch (DefaultTrivialAutoVarInit) {
3650 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3651 break;
3652 case LangOptions::TrivialAutoVarInitKind::Pattern:
3653 TrivialAutoVarInit = "pattern";
3654 break;
3655 case LangOptions::TrivialAutoVarInitKind::Zero:
3656 TrivialAutoVarInit = "zero";
3657 break;
3658 }
3659
3660 if (!TrivialAutoVarInit.empty()) {
3661 CmdArgs.push_back(
3662 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3663 }
3664
3665 if (Arg *A =
3666 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init_stop_after)) {
3667 if (!Args.hasArg(Ids: options::OPT_ftrivial_auto_var_init) ||
3668 StringRef(
3669 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init)->getValue()) ==
3670 "uninitialized")
3671 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3672 A->claim();
3673 StringRef Val = A->getValue();
3674 if (std::stoi(str: Val.str()) <= 0)
3675 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3676 CmdArgs.push_back(
3677 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init-stop-after=" + Val));
3678 }
3679
3680 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init_max_size)) {
3681 if (!Args.hasArg(Ids: options::OPT_ftrivial_auto_var_init) ||
3682 StringRef(
3683 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init)->getValue()) ==
3684 "uninitialized")
3685 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3686 A->claim();
3687 StringRef Val = A->getValue();
3688 if (std::stoi(str: Val.str()) <= 0)
3689 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3690 CmdArgs.push_back(
3691 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init-max-size=" + Val));
3692 }
3693}
3694
3695static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3696 types::ID InputType) {
3697 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3698 // for denormal flushing handling based on the target.
3699 const unsigned ForwardedArguments[] = {
3700 options::OPT_cl_opt_disable,
3701 options::OPT_cl_strict_aliasing,
3702 options::OPT_cl_single_precision_constant,
3703 options::OPT_cl_finite_math_only,
3704 options::OPT_cl_kernel_arg_info,
3705 options::OPT_cl_unsafe_math_optimizations,
3706 options::OPT_cl_fast_relaxed_math,
3707 options::OPT_cl_mad_enable,
3708 options::OPT_cl_no_signed_zeros,
3709 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3710 options::OPT_cl_uniform_work_group_size
3711 };
3712
3713 if (Arg *A = Args.getLastArg(Ids: options::OPT_cl_std_EQ)) {
3714 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3715 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CLStdStr));
3716 } else if (Arg *A = Args.getLastArg(Ids: options::OPT_cl_ext_EQ)) {
3717 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3718 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CLExtStr));
3719 }
3720
3721 if (Args.hasArg(Ids: options::OPT_cl_finite_math_only)) {
3722 CmdArgs.push_back(Elt: "-menable-no-infs");
3723 CmdArgs.push_back(Elt: "-menable-no-nans");
3724 }
3725
3726 for (const auto &Arg : ForwardedArguments)
3727 if (const auto *A = Args.getLastArg(Ids: Arg))
3728 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getOption().getPrefixedName()));
3729
3730 // Only add the default headers if we are compiling OpenCL sources.
3731 if ((types::isOpenCL(Id: InputType) ||
3732 (Args.hasArg(Ids: options::OPT_cl_std_EQ) && types::isSrcFile(Id: InputType))) &&
3733 !Args.hasArg(Ids: options::OPT_cl_no_stdinc)) {
3734 CmdArgs.push_back(Elt: "-finclude-default-header");
3735 CmdArgs.push_back(Elt: "-fdeclare-opencl-builtins");
3736 }
3737}
3738
3739static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3740 types::ID InputType) {
3741 const unsigned ForwardedArguments[] = {
3742 options::OPT_hlsl_all_resources_bound,
3743 options::OPT_dxil_validator_version,
3744 options::OPT_res_may_alias,
3745 options::OPT_D,
3746 options::OPT_I,
3747 options::OPT_O,
3748 options::OPT_emit_llvm,
3749 options::OPT_emit_obj,
3750 options::OPT_disable_llvm_passes,
3751 options::OPT_fnative_half_type,
3752 options::OPT_fnative_int16_type,
3753 options::OPT_fmatrix_memory_layout_EQ,
3754 options::OPT_hlsl_entrypoint,
3755 options::OPT_fdx_rootsignature_define,
3756 options::OPT_fdx_rootsignature_version,
3757 options::OPT_fhlsl_spv_use_unknown_image_format,
3758 options::OPT_fhlsl_spv_enable_maximal_reconvergence};
3759 if (!types::isHLSL(Id: InputType))
3760 return;
3761 for (const auto &Arg : ForwardedArguments)
3762 if (const auto *A = Args.getLastArg(Ids: Arg))
3763 A->renderAsInput(Args, Output&: CmdArgs);
3764 // Add the default headers if dxc_no_stdinc is not set.
3765 if (!Args.hasArg(Ids: options::OPT_dxc_no_stdinc) &&
3766 !Args.hasArg(Ids: options::OPT_nostdinc))
3767 CmdArgs.push_back(Elt: "-finclude-default-header");
3768}
3769
3770static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
3771 ArgStringList &CmdArgs, types::ID InputType) {
3772 if (!Args.hasArg(Ids: options::OPT_fopenacc))
3773 return;
3774
3775 CmdArgs.push_back(Elt: "-fopenacc");
3776}
3777
3778static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3779 const ArgList &Args, ArgStringList &CmdArgs) {
3780 // -fbuiltin is default unless -mkernel is used.
3781 bool UseBuiltins =
3782 Args.hasFlag(Pos: options::OPT_fbuiltin, Neg: options::OPT_fno_builtin,
3783 Default: !Args.hasArg(Ids: options::OPT_mkernel));
3784 if (!UseBuiltins)
3785 CmdArgs.push_back(Elt: "-fno-builtin");
3786
3787 // -ffreestanding implies -fno-builtin.
3788 if (Args.hasArg(Ids: options::OPT_ffreestanding))
3789 UseBuiltins = false;
3790
3791 // Process the -fno-builtin-* options.
3792 for (const Arg *A : Args.filtered(Ids: options::OPT_fno_builtin_)) {
3793 A->claim();
3794
3795 // If -fno-builtin is specified, then there's no need to pass the option to
3796 // the frontend.
3797 if (UseBuiltins)
3798 A->render(Args, Output&: CmdArgs);
3799 }
3800}
3801
3802bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
3803 if (const char *Str = std::getenv(name: "CLANG_MODULE_CACHE_PATH")) {
3804 Twine Path{Str};
3805 Path.toVector(Out&: Result);
3806 return Path.getSingleStringRef() != "";
3807 }
3808 if (llvm::sys::path::cache_directory(result&: Result)) {
3809 llvm::sys::path::append(path&: Result, a: "clang");
3810 llvm::sys::path::append(path&: Result, a: "ModuleCache");
3811 return true;
3812 }
3813 return false;
3814}
3815
3816llvm::SmallString<256>
3817clang::driver::tools::getCXX20NamedModuleOutputPath(const ArgList &Args,
3818 const char *BaseInput) {
3819 if (Arg *ModuleOutputEQ = Args.getLastArg(Ids: options::OPT_fmodule_output_EQ))
3820 return StringRef(ModuleOutputEQ->getValue());
3821
3822 SmallString<256> OutputPath;
3823 if (Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o);
3824 FinalOutput && Args.hasArg(Ids: options::OPT_c))
3825 OutputPath = FinalOutput->getValue();
3826 else {
3827 llvm::sys::fs::current_path(result&: OutputPath);
3828 llvm::sys::path::append(path&: OutputPath, a: llvm::sys::path::filename(path: BaseInput));
3829 }
3830
3831 const char *Extension = types::getTypeTempSuffix(Id: types::TY_ModuleFile);
3832 llvm::sys::path::replace_extension(path&: OutputPath, extension: Extension);
3833 return OutputPath;
3834}
3835
3836static bool RenderModulesOptions(Compilation &C, const Driver &D,
3837 const ArgList &Args, const InputInfo &Input,
3838 const InputInfo &Output, bool HaveStd20,
3839 ArgStringList &CmdArgs) {
3840 const bool IsCXX = types::isCXX(Id: Input.getType());
3841 const bool HaveStdCXXModules = IsCXX && HaveStd20;
3842 bool HaveModules = HaveStdCXXModules;
3843
3844 // -fmodules enables the use of precompiled modules (off by default).
3845 // Users can pass -fno-cxx-modules to turn off modules support for
3846 // C++/Objective-C++ programs.
3847 const bool AllowedInCXX = Args.hasFlag(Pos: options::OPT_fcxx_modules,
3848 Neg: options::OPT_fno_cxx_modules, Default: true);
3849 bool HaveClangModules = false;
3850 if (Args.hasFlag(Pos: options::OPT_fmodules, Neg: options::OPT_fno_modules, Default: false)) {
3851 if (AllowedInCXX || !IsCXX) {
3852 CmdArgs.push_back(Elt: "-fmodules");
3853 HaveClangModules = true;
3854 }
3855 }
3856
3857 HaveModules |= HaveClangModules;
3858
3859 if (HaveModules && !AllowedInCXX)
3860 CmdArgs.push_back(Elt: "-fno-cxx-modules");
3861
3862 // -fmodule-maps enables implicit reading of module map files. By default,
3863 // this is enabled if we are using Clang's flavor of precompiled modules.
3864 if (Args.hasFlag(Pos: options::OPT_fimplicit_module_maps,
3865 Neg: options::OPT_fno_implicit_module_maps, Default: HaveClangModules))
3866 CmdArgs.push_back(Elt: "-fimplicit-module-maps");
3867
3868 // -fmodules-decluse checks that modules used are declared so (off by default)
3869 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fmodules_decluse,
3870 Neg: options::OPT_fno_modules_decluse);
3871
3872 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3873 // all #included headers are part of modules.
3874 if (Args.hasFlag(Pos: options::OPT_fmodules_strict_decluse,
3875 Neg: options::OPT_fno_modules_strict_decluse, Default: false))
3876 CmdArgs.push_back(Elt: "-fmodules-strict-decluse");
3877
3878 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fmodulemap_allow_subdirectory_search,
3879 Neg: options::OPT_fno_modulemap_allow_subdirectory_search);
3880
3881 // -fno-implicit-modules turns off implicitly compiling modules on demand.
3882 bool ImplicitModules = false;
3883 if (!Args.hasFlag(Pos: options::OPT_fimplicit_modules,
3884 Neg: options::OPT_fno_implicit_modules, Default: HaveClangModules)) {
3885 if (HaveModules)
3886 CmdArgs.push_back(Elt: "-fno-implicit-modules");
3887 } else if (HaveModules) {
3888 ImplicitModules = true;
3889 // -fmodule-cache-path specifies where our implicitly-built module files
3890 // should be written.
3891 SmallString<128> Path;
3892 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmodules_cache_path))
3893 Path = A->getValue();
3894
3895 bool HasPath = true;
3896 if (C.isForDiagnostics()) {
3897 // When generating crash reports, we want to emit the modules along with
3898 // the reproduction sources, so we ignore any provided module path.
3899 Path = Output.getFilename();
3900 llvm::sys::path::replace_extension(path&: Path, extension: ".cache");
3901 llvm::sys::path::append(path&: Path, a: "modules");
3902 } else if (Path.empty()) {
3903 // No module path was provided: use the default.
3904 HasPath = Driver::getDefaultModuleCachePath(Result&: Path);
3905 }
3906
3907 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3908 // That being said, that failure is unlikely and not caching is harmless.
3909 if (HasPath) {
3910 const char Arg[] = "-fmodules-cache-path=";
3911 Path.insert(I: Path.begin(), From: Arg, To: Arg + strlen(s: Arg));
3912 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Path));
3913 }
3914 }
3915
3916 if (HaveModules) {
3917 if (Args.hasFlag(Pos: options::OPT_fprebuilt_implicit_modules,
3918 Neg: options::OPT_fno_prebuilt_implicit_modules, Default: false))
3919 CmdArgs.push_back(Elt: "-fprebuilt-implicit-modules");
3920 if (Args.hasFlag(Pos: options::OPT_fmodules_validate_input_files_content,
3921 Neg: options::OPT_fno_modules_validate_input_files_content,
3922 Default: false))
3923 CmdArgs.push_back(Elt: "-fvalidate-ast-input-files-content");
3924 }
3925
3926 // -fmodule-name specifies the module that is currently being built (or
3927 // used for header checking by -fmodule-maps).
3928 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodule_name_EQ);
3929
3930 // -fmodule-map-file can be used to specify files containing module
3931 // definitions.
3932 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodule_map_file);
3933
3934 // -fbuiltin-module-map can be used to load the clang
3935 // builtin headers modulemap file.
3936 if (Args.hasArg(Ids: options::OPT_fbuiltin_module_map)) {
3937 SmallString<128> BuiltinModuleMap(D.ResourceDir);
3938 llvm::sys::path::append(path&: BuiltinModuleMap, a: "include");
3939 llvm::sys::path::append(path&: BuiltinModuleMap, a: "module.modulemap");
3940 if (llvm::sys::fs::exists(Path: BuiltinModuleMap))
3941 CmdArgs.push_back(
3942 Elt: Args.MakeArgString(Str: "-fmodule-map-file=" + BuiltinModuleMap));
3943 }
3944
3945 // The -fmodule-file=<name>=<file> form specifies the mapping of module
3946 // names to precompiled module files (the module is loaded only if used).
3947 // The -fmodule-file=<file> form can be used to unconditionally load
3948 // precompiled module files (whether used or not).
3949 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
3950 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodule_file);
3951
3952 // -fprebuilt-module-path specifies where to load the prebuilt module files.
3953 for (const Arg *A : Args.filtered(Ids: options::OPT_fprebuilt_module_path)) {
3954 CmdArgs.push_back(Elt: Args.MakeArgString(
3955 Str: std::string("-fprebuilt-module-path=") + A->getValue()));
3956 A->claim();
3957 }
3958 } else
3959 Args.ClaimAllArgs(Id0: options::OPT_fmodule_file);
3960
3961 // When building modules and generating crashdumps, we need to dump a module
3962 // dependency VFS alongside the output.
3963 if (HaveClangModules && C.isForDiagnostics()) {
3964 SmallString<128> VFSDir(Output.getFilename());
3965 llvm::sys::path::replace_extension(path&: VFSDir, extension: ".cache");
3966 // Add the cache directory as a temp so the crash diagnostics pick it up.
3967 C.addTempFile(Name: Args.MakeArgString(Str: VFSDir));
3968
3969 llvm::sys::path::append(path&: VFSDir, a: "vfs");
3970 CmdArgs.push_back(Elt: "-module-dependency-dir");
3971 CmdArgs.push_back(Elt: Args.MakeArgString(Str: VFSDir));
3972 }
3973
3974 if (HaveClangModules)
3975 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_user_build_path);
3976
3977 // Pass through all -fmodules-ignore-macro arguments.
3978 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodules_ignore_macro);
3979 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_prune_interval);
3980 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_prune_after);
3981
3982 if (HaveClangModules) {
3983 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fbuild_session_timestamp);
3984
3985 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbuild_session_file)) {
3986 if (Args.hasArg(Ids: options::OPT_fbuild_session_timestamp))
3987 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
3988 << A->getAsString(Args) << "-fbuild-session-timestamp";
3989
3990 llvm::sys::fs::file_status Status;
3991 if (llvm::sys::fs::status(path: A->getValue(), result&: Status))
3992 D.Diag(DiagID: diag::err_drv_no_such_file) << A->getValue();
3993 CmdArgs.push_back(Elt: Args.MakeArgString(
3994 Str: "-fbuild-session-timestamp=" +
3995 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
3996 d: Status.getLastModificationTime().time_since_epoch())
3997 .count())));
3998 }
3999
4000 if (Args.getLastArg(
4001 Ids: options::OPT_fmodules_validate_once_per_build_session)) {
4002 if (!Args.getLastArg(Ids: options::OPT_fbuild_session_timestamp,
4003 Ids: options::OPT_fbuild_session_file))
4004 D.Diag(DiagID: diag::err_drv_modules_validate_once_requires_timestamp);
4005
4006 Args.AddLastArg(Output&: CmdArgs,
4007 Ids: options::OPT_fmodules_validate_once_per_build_session);
4008 }
4009
4010 if (Args.hasFlag(Pos: options::OPT_fmodules_validate_system_headers,
4011 Neg: options::OPT_fno_modules_validate_system_headers,
4012 Default: ImplicitModules))
4013 CmdArgs.push_back(Elt: "-fmodules-validate-system-headers");
4014
4015 Args.AddLastArg(Output&: CmdArgs,
4016 Ids: options::OPT_fmodules_disable_diagnostic_validation);
4017 } else {
4018 Args.ClaimAllArgs(Id0: options::OPT_fbuild_session_timestamp);
4019 Args.ClaimAllArgs(Id0: options::OPT_fbuild_session_file);
4020 Args.ClaimAllArgs(Id0: options::OPT_fmodules_validate_once_per_build_session);
4021 Args.ClaimAllArgs(Id0: options::OPT_fmodules_validate_system_headers);
4022 Args.ClaimAllArgs(Id0: options::OPT_fno_modules_validate_system_headers);
4023 Args.ClaimAllArgs(Id0: options::OPT_fmodules_disable_diagnostic_validation);
4024 }
4025
4026 // FIXME: We provisionally don't check ODR violations for decls in the global
4027 // module fragment.
4028 CmdArgs.push_back(Elt: "-fskip-odr-check-in-gmf");
4029
4030 if (Input.getType() == driver::types::TY_CXXModule ||
4031 Input.getType() == driver::types::TY_PP_CXXModule) {
4032 if (!Args.hasArg(Ids: options::OPT_fno_modules_reduced_bmi))
4033 CmdArgs.push_back(Elt: "-fmodules-reduced-bmi");
4034
4035 if (Args.hasArg(Ids: options::OPT_fmodule_output_EQ))
4036 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodule_output_EQ);
4037 else if (!(Args.hasArg(Ids: options::OPT__precompile) ||
4038 Args.hasArg(Ids: options::OPT__precompile_reduced_bmi)) ||
4039 Args.hasArg(Ids: options::OPT_fmodule_output))
4040 // If --precompile is specified, we will always generate a module file if
4041 // we're compiling an importable module unit. This is fine even if the
4042 // compilation process won't reach the point of generating the module file
4043 // (e.g., in the preprocessing mode), since the attached flag
4044 // '-fmodule-output' is useless.
4045 //
4046 // But if '--precompile' is specified, it might be annoying to always
4047 // generate the module file as '--precompile' will generate the module
4048 // file anyway.
4049 CmdArgs.push_back(Elt: Args.MakeArgString(
4050 Str: "-fmodule-output=" +
4051 getCXX20NamedModuleOutputPath(Args, BaseInput: Input.getBaseInput())));
4052 }
4053
4054 if (Args.hasArg(Ids: options::OPT_fmodules_reduced_bmi) &&
4055 Args.hasArg(Ids: options::OPT__precompile) &&
4056 (!Args.hasArg(Ids: options::OPT_o) ||
4057 Args.getLastArg(Ids: options::OPT_o)->getValue() ==
4058 getCXX20NamedModuleOutputPath(Args, BaseInput: Input.getBaseInput()))) {
4059 D.Diag(DiagID: diag::err_drv_reduced_module_output_overrided);
4060 }
4061
4062 // Noop if we see '-fmodules-reduced-bmi' or `-fno-modules-reduced-bmi` with
4063 // other translation units than module units. This is more user friendly to
4064 // allow end uers to enable this feature without asking for help from build
4065 // systems.
4066 Args.ClaimAllArgs(Id0: options::OPT_fmodules_reduced_bmi);
4067 Args.ClaimAllArgs(Id0: options::OPT_fno_modules_reduced_bmi);
4068
4069 // We need to include the case the input file is a module file here.
4070 // Since the default compilation model for C++ module interface unit will
4071 // create temporary module file and compile the temporary module file
4072 // to get the object file. Then the `-fmodule-output` flag will be
4073 // brought to the second compilation process. So we have to claim it for
4074 // the case too.
4075 if (Input.getType() == driver::types::TY_CXXModule ||
4076 Input.getType() == driver::types::TY_PP_CXXModule ||
4077 Input.getType() == driver::types::TY_ModuleFile) {
4078 Args.ClaimAllArgs(Id0: options::OPT_fmodule_output);
4079 Args.ClaimAllArgs(Id0: options::OPT_fmodule_output_EQ);
4080 }
4081
4082 if (Args.hasArg(Ids: options::OPT_fmodules_embed_all_files))
4083 CmdArgs.push_back(Elt: "-fmodules-embed-all-files");
4084
4085 return HaveModules;
4086}
4087
4088static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4089 ArgStringList &CmdArgs) {
4090 // -fsigned-char is default.
4091 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsigned_char,
4092 Ids: options::OPT_fno_signed_char,
4093 Ids: options::OPT_funsigned_char,
4094 Ids: options::OPT_fno_unsigned_char)) {
4095 if (A->getOption().matches(ID: options::OPT_funsigned_char) ||
4096 A->getOption().matches(ID: options::OPT_fno_signed_char)) {
4097 CmdArgs.push_back(Elt: "-fno-signed-char");
4098 }
4099 } else if (!isSignedCharDefault(Triple: T)) {
4100 CmdArgs.push_back(Elt: "-fno-signed-char");
4101 }
4102
4103 // The default depends on the language standard.
4104 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fchar8__t, Ids: options::OPT_fno_char8__t);
4105
4106 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fshort_wchar,
4107 Ids: options::OPT_fno_short_wchar)) {
4108 if (A->getOption().matches(ID: options::OPT_fshort_wchar)) {
4109 CmdArgs.push_back(Elt: "-fwchar-type=short");
4110 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4111 } else {
4112 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4113 CmdArgs.push_back(Elt: "-fwchar-type=int");
4114 if (T.isOSzOS() ||
4115 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4116 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4117 else
4118 CmdArgs.push_back(Elt: "-fsigned-wchar");
4119 }
4120 } else if (T.isOSzOS())
4121 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4122}
4123
4124static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4125 const llvm::Triple &T, const ArgList &Args,
4126 ObjCRuntime &Runtime, bool InferCovariantReturns,
4127 const InputInfo &Input, ArgStringList &CmdArgs) {
4128 const llvm::Triple::ArchType Arch = TC.getArch();
4129
4130 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4131 // is the default. Except for deployment target of 10.5, next runtime is
4132 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4133 if (Runtime.isNonFragile()) {
4134 if (!Args.hasFlag(Pos: options::OPT_fobjc_legacy_dispatch,
4135 Neg: options::OPT_fno_objc_legacy_dispatch,
4136 Default: Runtime.isLegacyDispatchDefaultForArch(Arch))) {
4137 if (TC.UseObjCMixedDispatch())
4138 CmdArgs.push_back(Elt: "-fobjc-dispatch-method=mixed");
4139 else
4140 CmdArgs.push_back(Elt: "-fobjc-dispatch-method=non-legacy");
4141 }
4142 }
4143
4144 // Forward -fobjc-direct-precondition-thunk to cc1
4145 // Defaults to false and needs explict turn on for now
4146 // TODO: switch to default true and needs explict turn off in the future.
4147 // TODO: add support for other runtimes
4148 if (Args.hasFlag(Pos: options::OPT_fobjc_direct_precondition_thunk,
4149 Neg: options::OPT_fno_objc_direct_precondition_thunk, Default: false)) {
4150 if (Runtime.isNeXTFamily()) {
4151 CmdArgs.push_back(Elt: "-fobjc-direct-precondition-thunk");
4152 } else {
4153 D.Diag(DiagID: diag::warn_drv_unsupported_option_for_runtime)
4154 << "-fobjc-direct-precondition-thunk" << Runtime.getAsString();
4155 }
4156 }
4157 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4158 // to do Array/Dictionary subscripting by default.
4159 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4160 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4161 CmdArgs.push_back(Elt: "-fobjc-subscripting-legacy-runtime");
4162
4163 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4164 // NOTE: This logic is duplicated in ToolChains.cpp.
4165 if (isObjCAutoRefCount(Args)) {
4166 TC.CheckObjCARC();
4167
4168 CmdArgs.push_back(Elt: "-fobjc-arc");
4169
4170 // FIXME: It seems like this entire block, and several around it should be
4171 // wrapped in isObjC, but for now we just use it here as this is where it
4172 // was being used previously.
4173 if (types::isCXX(Id: Input.getType()) && types::isObjC(Id: Input.getType())) {
4174 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4175 CmdArgs.push_back(Elt: "-fobjc-arc-cxxlib=libc++");
4176 else
4177 CmdArgs.push_back(Elt: "-fobjc-arc-cxxlib=libstdc++");
4178 }
4179
4180 // Allow the user to enable full exceptions code emission.
4181 // We default off for Objective-C, on for Objective-C++.
4182 if (Args.hasFlag(Pos: options::OPT_fobjc_arc_exceptions,
4183 Neg: options::OPT_fno_objc_arc_exceptions,
4184 /*Default=*/types::isCXX(Id: Input.getType())))
4185 CmdArgs.push_back(Elt: "-fobjc-arc-exceptions");
4186 }
4187
4188 // Silence warning for full exception code emission options when explicitly
4189 // set to use no ARC.
4190 if (Args.hasArg(Ids: options::OPT_fno_objc_arc)) {
4191 Args.ClaimAllArgs(Id0: options::OPT_fobjc_arc_exceptions);
4192 Args.ClaimAllArgs(Id0: options::OPT_fno_objc_arc_exceptions);
4193 }
4194
4195 // Allow the user to control whether messages can be converted to runtime
4196 // functions.
4197 if (types::isObjC(Id: Input.getType())) {
4198 auto *Arg = Args.getLastArg(
4199 Ids: options::OPT_fobjc_convert_messages_to_runtime_calls,
4200 Ids: options::OPT_fno_objc_convert_messages_to_runtime_calls);
4201 if (Arg &&
4202 Arg->getOption().matches(
4203 ID: options::OPT_fno_objc_convert_messages_to_runtime_calls))
4204 CmdArgs.push_back(Elt: "-fno-objc-convert-messages-to-runtime-calls");
4205 }
4206
4207 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4208 // rewriter.
4209 if (InferCovariantReturns)
4210 CmdArgs.push_back(Elt: "-fno-objc-infer-related-result-type");
4211
4212 // Pass down -fobjc-weak or -fno-objc-weak if present.
4213 if (types::isObjC(Id: Input.getType())) {
4214 auto WeakArg =
4215 Args.getLastArg(Ids: options::OPT_fobjc_weak, Ids: options::OPT_fno_objc_weak);
4216 if (!WeakArg) {
4217 // nothing to do
4218 } else if (!Runtime.allowsWeak()) {
4219 if (WeakArg->getOption().matches(ID: options::OPT_fobjc_weak))
4220 D.Diag(DiagID: diag::err_objc_weak_unsupported);
4221 } else {
4222 WeakArg->render(Args, Output&: CmdArgs);
4223 }
4224 }
4225
4226 if (Args.hasArg(Ids: options::OPT_fobjc_disable_direct_methods_for_testing))
4227 CmdArgs.push_back(Elt: "-fobjc-disable-direct-methods-for-testing");
4228}
4229
4230static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4231 ArgStringList &CmdArgs) {
4232 bool CaretDefault = true;
4233 bool ColumnDefault = true;
4234
4235 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_diagnostics_classic,
4236 Ids: options::OPT__SLASH_diagnostics_column,
4237 Ids: options::OPT__SLASH_diagnostics_caret)) {
4238 switch (A->getOption().getID()) {
4239 case options::OPT__SLASH_diagnostics_caret:
4240 CaretDefault = true;
4241 ColumnDefault = true;
4242 break;
4243 case options::OPT__SLASH_diagnostics_column:
4244 CaretDefault = false;
4245 ColumnDefault = true;
4246 break;
4247 case options::OPT__SLASH_diagnostics_classic:
4248 CaretDefault = false;
4249 ColumnDefault = false;
4250 break;
4251 }
4252 }
4253
4254 // -fcaret-diagnostics is default.
4255 if (!Args.hasFlag(Pos: options::OPT_fcaret_diagnostics,
4256 Neg: options::OPT_fno_caret_diagnostics, Default: CaretDefault))
4257 CmdArgs.push_back(Elt: "-fno-caret-diagnostics");
4258
4259 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_fixit_info,
4260 Neg: options::OPT_fno_diagnostics_fixit_info);
4261 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_option,
4262 Neg: options::OPT_fno_diagnostics_show_option);
4263
4264 if (const Arg *A =
4265 Args.getLastArg(Ids: options::OPT_fdiagnostics_show_category_EQ)) {
4266 CmdArgs.push_back(Elt: "-fdiagnostics-show-category");
4267 CmdArgs.push_back(Elt: A->getValue());
4268 }
4269
4270 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_hotness,
4271 Neg: options::OPT_fno_diagnostics_show_hotness);
4272
4273 if (const Arg *A =
4274 Args.getLastArg(Ids: options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4275 std::string Opt =
4276 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4277 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
4278 }
4279
4280 if (const Arg *A =
4281 Args.getLastArg(Ids: options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4282 std::string Opt =
4283 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4284 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
4285 }
4286
4287 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fdiagnostics_format_EQ)) {
4288 CmdArgs.push_back(Elt: "-fdiagnostics-format");
4289 CmdArgs.push_back(Elt: A->getValue());
4290 if (StringRef(A->getValue()) == "sarif" ||
4291 StringRef(A->getValue()) == "SARIF")
4292 D.Diag(DiagID: diag::warn_drv_sarif_format_unstable);
4293 }
4294
4295 if (const Arg *A = Args.getLastArg(
4296 Ids: options::OPT_fdiagnostics_show_note_include_stack,
4297 Ids: options::OPT_fno_diagnostics_show_note_include_stack)) {
4298 const Option &O = A->getOption();
4299 if (O.matches(ID: options::OPT_fdiagnostics_show_note_include_stack))
4300 CmdArgs.push_back(Elt: "-fdiagnostics-show-note-include-stack");
4301 else
4302 CmdArgs.push_back(Elt: "-fno-diagnostics-show-note-include-stack");
4303 }
4304
4305 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4306
4307 if (Args.hasArg(Ids: options::OPT_fansi_escape_codes))
4308 CmdArgs.push_back(Elt: "-fansi-escape-codes");
4309
4310 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fshow_source_location,
4311 Neg: options::OPT_fno_show_source_location);
4312
4313 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_line_numbers,
4314 Neg: options::OPT_fno_diagnostics_show_line_numbers);
4315
4316 if (Args.hasArg(Ids: options::OPT_fdiagnostics_absolute_paths))
4317 CmdArgs.push_back(Elt: "-fdiagnostics-absolute-paths");
4318
4319 if (!Args.hasFlag(Pos: options::OPT_fshow_column, Neg: options::OPT_fno_show_column,
4320 Default: ColumnDefault))
4321 CmdArgs.push_back(Elt: "-fno-show-column");
4322
4323 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fspell_checking,
4324 Neg: options::OPT_fno_spell_checking);
4325
4326 Args.addLastArg(Output&: CmdArgs, Ids: options::OPT_warning_suppression_mappings_EQ);
4327}
4328
4329static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4330 const ArgList &Args, ArgStringList &CmdArgs,
4331 unsigned DwarfVersion) {
4332 auto *DwarfFormatArg =
4333 Args.getLastArg(Ids: options::OPT_gdwarf64, Ids: options::OPT_gdwarf32);
4334 if (!DwarfFormatArg)
4335 return;
4336
4337 if (DwarfFormatArg->getOption().matches(ID: options::OPT_gdwarf64)) {
4338 if (DwarfVersion < 3)
4339 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4340 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4341 else if (!T.isArch64Bit())
4342 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4343 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4344 else if (!T.isOSBinFormatELF())
4345 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4346 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4347 }
4348
4349 DwarfFormatArg->render(Args, Output&: CmdArgs);
4350}
4351
4352static bool getDebugSimpleTemplateNames(const ToolChain &TC, const Driver &D,
4353 const ArgList &Args) {
4354 bool NeedsSimpleTemplateNames =
4355 Args.hasFlag(Pos: options::OPT_gsimple_template_names,
4356 Neg: options::OPT_gno_simple_template_names,
4357 Default: TC.getDefaultDebugSimpleTemplateNames());
4358 if (!NeedsSimpleTemplateNames)
4359 return false;
4360
4361 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gsimple_template_names))
4362 if (!checkDebugInfoOption(A, Args, D, TC))
4363 return false;
4364
4365 return true;
4366}
4367
4368static void
4369renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4370 const ArgList &Args, types::ID InputType,
4371 ArgStringList &CmdArgs, const InputInfo &Output,
4372 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4373 DwarfFissionKind &DwarfFission) {
4374 bool IRInput = isLLVMIR(Id: InputType);
4375 bool PlainCOrCXX = isDerivedFromC(Id: InputType) && !isCuda(Id: InputType) &&
4376 !isHIP(Id: InputType) && !isObjC(Id: InputType) &&
4377 !isOpenCL(Id: InputType);
4378
4379 if (Args.hasFlag(Pos: options::OPT_fdebug_info_for_profiling,
4380 Neg: options::OPT_fno_debug_info_for_profiling, Default: false) &&
4381 checkDebugInfoOption(
4382 A: Args.getLastArg(Ids: options::OPT_fdebug_info_for_profiling), Args, D, TC))
4383 CmdArgs.push_back(Elt: "-fdebug-info-for-profiling");
4384
4385 // The 'g' groups options involve a somewhat intricate sequence of decisions
4386 // about what to pass from the driver to the frontend, but by the time they
4387 // reach cc1 they've been factored into three well-defined orthogonal choices:
4388 // * what level of debug info to generate
4389 // * what dwarf version to write
4390 // * what debugger tuning to use
4391 // This avoids having to monkey around further in cc1 other than to disable
4392 // codeview if not running in a Windows environment. Perhaps even that
4393 // decision should be made in the driver as well though.
4394 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4395
4396 bool SplitDWARFInlining =
4397 Args.hasFlag(Pos: options::OPT_fsplit_dwarf_inlining,
4398 Neg: options::OPT_fno_split_dwarf_inlining, Default: false);
4399
4400 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4401 // object file generation and no IR generation, -gN should not be needed. So
4402 // allow -gsplit-dwarf with either -gN or IR input.
4403 if (IRInput || Args.hasArg(Ids: options::OPT_g_Group)) {
4404 // FIXME: -gsplit-dwarf on AIX is currently unimplemented.
4405 if (TC.getTriple().isOSAIX() && Args.hasArg(Ids: options::OPT_gsplit_dwarf)) {
4406 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
4407 << Args.getLastArg(Ids: options::OPT_gsplit_dwarf)->getSpelling()
4408 << TC.getTriple().str();
4409 return;
4410 }
4411 Arg *SplitDWARFArg;
4412 DwarfFission = getDebugFissionKind(D, Args, Arg&: SplitDWARFArg);
4413 if (DwarfFission != DwarfFissionKind::None &&
4414 !checkDebugInfoOption(A: SplitDWARFArg, Args, D, TC)) {
4415 DwarfFission = DwarfFissionKind::None;
4416 SplitDWARFInlining = false;
4417 }
4418 }
4419 if (const Arg *A = Args.getLastArg(Ids: options::OPT_g_Group)) {
4420 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4421
4422 // If the last option explicitly specified a debug-info level, use it.
4423 if (checkDebugInfoOption(A, Args, D, TC) &&
4424 A->getOption().matches(ID: options::OPT_gN_Group)) {
4425 DebugInfoKind = debugLevelToInfoKind(A: *A);
4426 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4427 // complicated if you've disabled inline info in the skeleton CUs
4428 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4429 // line-tables-only, so let those compose naturally in that case.
4430 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4431 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4432 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4433 SplitDWARFInlining))
4434 DwarfFission = DwarfFissionKind::None;
4435 }
4436 }
4437
4438 // If a debugger tuning argument appeared, remember it.
4439 bool HasDebuggerTuning = false;
4440 if (const Arg *A =
4441 Args.getLastArg(Ids: options::OPT_gTune_Group, Ids: options::OPT_ggdbN_Group)) {
4442 HasDebuggerTuning = true;
4443 if (checkDebugInfoOption(A, Args, D, TC)) {
4444 if (A->getOption().matches(ID: options::OPT_glldb))
4445 DebuggerTuning = llvm::DebuggerKind::LLDB;
4446 else if (A->getOption().matches(ID: options::OPT_gsce))
4447 DebuggerTuning = llvm::DebuggerKind::SCE;
4448 else if (A->getOption().matches(ID: options::OPT_gdbx))
4449 DebuggerTuning = llvm::DebuggerKind::DBX;
4450 else
4451 DebuggerTuning = llvm::DebuggerKind::GDB;
4452 }
4453 }
4454
4455 // If a -gdwarf argument appeared, remember it.
4456 bool EmitDwarf = false;
4457 if (const Arg *A = getDwarfNArg(Args))
4458 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4459
4460 bool EmitCodeView = false;
4461 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcodeview))
4462 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4463
4464 // If the user asked for debug info but did not explicitly specify -gcodeview
4465 // or -gdwarf, ask the toolchain for the default format.
4466 if (!EmitCodeView && !EmitDwarf &&
4467 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4468 switch (TC.getDefaultDebugFormat()) {
4469 case llvm::codegenoptions::DIF_CodeView:
4470 EmitCodeView = true;
4471 break;
4472 case llvm::codegenoptions::DIF_DWARF:
4473 EmitDwarf = true;
4474 break;
4475 }
4476 }
4477
4478 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4479 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4480 // be lower than what the user wanted.
4481 if (EmitDwarf) {
4482 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4483 // Clamp effective DWARF version to the max supported by the toolchain.
4484 EffectiveDWARFVersion =
4485 std::min(a: RequestedDWARFVersion, b: TC.getMaxDwarfVersion());
4486 } else {
4487 Args.ClaimAllArgs(Id0: options::OPT_fdebug_default_version);
4488 }
4489
4490 // -gline-directives-only supported only for the DWARF debug info.
4491 if (RequestedDWARFVersion == 0 &&
4492 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4493 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4494
4495 // strict DWARF is set to false by default. But for DBX, we need it to be set
4496 // as true by default.
4497 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gstrict_dwarf))
4498 (void)checkDebugInfoOption(A, Args, D, TC);
4499 if (Args.hasFlag(Pos: options::OPT_gstrict_dwarf, Neg: options::OPT_gno_strict_dwarf,
4500 Default: DebuggerTuning == llvm::DebuggerKind::DBX))
4501 CmdArgs.push_back(Elt: "-gstrict-dwarf");
4502
4503 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4504 Args.ClaimAllArgs(Id0: options::OPT_g_flags_Group);
4505
4506 // Column info is included by default for everything except SCE and
4507 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4508 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4509 // practice, however, the Microsoft debuggers don't handle missing end columns
4510 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4511 // it's better not to include any column info.
4512 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcolumn_info))
4513 (void)checkDebugInfoOption(A, Args, D, TC);
4514 if (!Args.hasFlag(Pos: options::OPT_gcolumn_info, Neg: options::OPT_gno_column_info,
4515 Default: !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4516 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4517 DebuggerTuning != llvm::DebuggerKind::DBX)))
4518 CmdArgs.push_back(Elt: "-gno-column-info");
4519
4520 if (!Args.hasFlag(Pos: options::OPT_gcall_site_info,
4521 Neg: options::OPT_gno_call_site_info, Default: true))
4522 CmdArgs.push_back(Elt: "-gno-call-site-info");
4523
4524 // FIXME: Move backend command line options to the module.
4525 if (Args.hasFlag(Pos: options::OPT_gmodules, Neg: options::OPT_gno_modules, Default: false)) {
4526 // If -gline-tables-only or -gline-directives-only is the last option it
4527 // wins.
4528 if (checkDebugInfoOption(A: Args.getLastArg(Ids: options::OPT_gmodules), Args, D,
4529 TC)) {
4530 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4531 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4532 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4533 CmdArgs.push_back(Elt: "-dwarf-ext-refs");
4534 CmdArgs.push_back(Elt: "-fmodule-format=obj");
4535 }
4536 }
4537 }
4538
4539 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4540 CmdArgs.push_back(Elt: "-fsplit-dwarf-inlining");
4541
4542 // After we've dealt with all combinations of things that could
4543 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4544 // figure out if we need to "upgrade" it to standalone debug info.
4545 // We parse these two '-f' options whether or not they will be used,
4546 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4547 bool NeedFullDebug = Args.hasFlag(
4548 Pos: options::OPT_fstandalone_debug, Neg: options::OPT_fno_standalone_debug,
4549 Default: DebuggerTuning == llvm::DebuggerKind::LLDB ||
4550 TC.GetDefaultStandaloneDebug());
4551 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fstandalone_debug))
4552 (void)checkDebugInfoOption(A, Args, D, TC);
4553
4554 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4555 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4556 if (Args.hasFlag(Pos: options::OPT_fno_eliminate_unused_debug_types,
4557 Neg: options::OPT_feliminate_unused_debug_types, Default: false))
4558 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4559 else if (NeedFullDebug)
4560 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4561 }
4562
4563 if (Args.hasFlag(Pos: options::OPT_gembed_source, Neg: options::OPT_gno_embed_source,
4564 Default: false)) {
4565 // Source embedding is a vendor extension to DWARF v5. By now we have
4566 // checked if a DWARF version was stated explicitly, and have otherwise
4567 // fallen back to the target default, so if this is still not at least 5
4568 // we emit an error.
4569 const Arg *A = Args.getLastArg(Ids: options::OPT_gembed_source);
4570 if (RequestedDWARFVersion < 5)
4571 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4572 << A->getAsString(Args) << "-gdwarf-5";
4573 else if (EffectiveDWARFVersion < 5)
4574 // The toolchain has reduced allowed dwarf version, so we can't enable
4575 // -gembed-source.
4576 D.Diag(DiagID: diag::warn_drv_dwarf_version_limited_by_target)
4577 << A->getAsString(Args) << TC.getTripleString() << 5
4578 << EffectiveDWARFVersion;
4579 else if (checkDebugInfoOption(A, Args, D, TC))
4580 CmdArgs.push_back(Elt: "-gembed-source");
4581 }
4582
4583 // Enable Key Instructions by default if we're emitting DWARF, the language is
4584 // plain C or C++, and optimisations are enabled.
4585 Arg *OptLevel = Args.getLastArg(Ids: options::OPT_O_Group);
4586 bool KeyInstructionsOnByDefault =
4587 EmitDwarf && PlainCOrCXX && OptLevel &&
4588 !OptLevel->getOption().matches(ID: options::OPT_O0);
4589 if (Args.hasFlag(Pos: options::OPT_gkey_instructions,
4590 Neg: options::OPT_gno_key_instructions,
4591 Default: KeyInstructionsOnByDefault))
4592 CmdArgs.push_back(Elt: "-gkey-instructions");
4593
4594 if (!Args.hasFlag(Pos: options::OPT_gstructor_decl_linkage_names,
4595 Neg: options::OPT_gno_structor_decl_linkage_names, Default: true))
4596 CmdArgs.push_back(Elt: "-gno-structor-decl-linkage-names");
4597
4598 if (EmitCodeView) {
4599 CmdArgs.push_back(Elt: "-gcodeview");
4600
4601 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_gcodeview_ghash,
4602 Neg: options::OPT_gno_codeview_ghash);
4603
4604 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_gcodeview_command_line,
4605 Neg: options::OPT_gno_codeview_command_line);
4606 }
4607
4608 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_ginline_line_tables,
4609 Neg: options::OPT_gno_inline_line_tables);
4610
4611 // When emitting remarks, we need at least debug lines in the output.
4612 if (willEmitRemarks(Args) &&
4613 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4614 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4615
4616 // Adjust the debug info kind for the given toolchain.
4617 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4618
4619 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4620 // set.
4621 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion: EffectiveDWARFVersion,
4622 DebuggerTuning: T.isOSAIX() && !HasDebuggerTuning
4623 ? llvm::DebuggerKind::Default
4624 : DebuggerTuning);
4625
4626 // -fdebug-macro turns on macro debug info generation.
4627 if (Args.hasFlag(Pos: options::OPT_fdebug_macro, Neg: options::OPT_fno_debug_macro,
4628 Default: false))
4629 if (checkDebugInfoOption(A: Args.getLastArg(Ids: options::OPT_fdebug_macro), Args,
4630 D, TC))
4631 CmdArgs.push_back(Elt: "-debug-info-macro");
4632
4633 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4634 const auto *PubnamesArg =
4635 Args.getLastArg(Ids: options::OPT_ggnu_pubnames, Ids: options::OPT_gno_gnu_pubnames,
4636 Ids: options::OPT_gpubnames, Ids: options::OPT_gno_pubnames);
4637 if (DwarfFission != DwarfFissionKind::None ||
4638 (PubnamesArg && checkDebugInfoOption(A: PubnamesArg, Args, D, TC))) {
4639 const bool OptionSet =
4640 (PubnamesArg &&
4641 (PubnamesArg->getOption().matches(ID: options::OPT_gpubnames) ||
4642 PubnamesArg->getOption().matches(ID: options::OPT_ggnu_pubnames)));
4643 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
4644 (!PubnamesArg ||
4645 (!PubnamesArg->getOption().matches(ID: options::OPT_gno_gnu_pubnames) &&
4646 !PubnamesArg->getOption().matches(ID: options::OPT_gno_pubnames))))
4647 CmdArgs.push_back(Elt: PubnamesArg && PubnamesArg->getOption().matches(
4648 ID: options::OPT_gpubnames)
4649 ? "-gpubnames"
4650 : "-ggnu-pubnames");
4651 }
4652
4653 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4654 if (getDebugSimpleTemplateNames(TC, D, Args)) {
4655 ForwardTemplateParams = true;
4656 CmdArgs.push_back(Elt: "-gsimple-template-names=simple");
4657 }
4658
4659 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
4660 bool UseDebugTemplateAlias =
4661 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
4662 if (const auto *DebugTemplateAlias = Args.getLastArg(
4663 Ids: options::OPT_gtemplate_alias, Ids: options::OPT_gno_template_alias)) {
4664 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
4665 // asks for it we should let them have it (if the target supports it).
4666 if (checkDebugInfoOption(A: DebugTemplateAlias, Args, D, TC)) {
4667 const auto &Opt = DebugTemplateAlias->getOption();
4668 UseDebugTemplateAlias = Opt.matches(ID: options::OPT_gtemplate_alias);
4669 }
4670 }
4671 if (UseDebugTemplateAlias)
4672 CmdArgs.push_back(Elt: "-gtemplate-alias");
4673
4674 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gsrc_hash_EQ)) {
4675 StringRef v = A->getValue();
4676 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-gsrc-hash=" + v));
4677 }
4678
4679 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdebug_ranges_base_address,
4680 Neg: options::OPT_fno_debug_ranges_base_address);
4681
4682 // -gdwarf-aranges turns on the emission of the aranges section in the
4683 // backend.
4684 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gdwarf_aranges);
4685 A && checkDebugInfoOption(A, Args, D, TC)) {
4686 CmdArgs.push_back(Elt: "-mllvm");
4687 CmdArgs.push_back(Elt: "-generate-arange-section");
4688 }
4689
4690 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fforce_dwarf_frame,
4691 Neg: options::OPT_fno_force_dwarf_frame);
4692
4693 bool EnableTypeUnits = false;
4694 if (Args.hasFlag(Pos: options::OPT_fdebug_types_section,
4695 Neg: options::OPT_fno_debug_types_section, Default: false)) {
4696 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4697 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
4698 << Args.getLastArg(Ids: options::OPT_fdebug_types_section)
4699 ->getAsString(Args)
4700 << T.getTriple();
4701 } else if (checkDebugInfoOption(
4702 A: Args.getLastArg(Ids: options::OPT_fdebug_types_section), Args, D,
4703 TC)) {
4704 EnableTypeUnits = true;
4705 CmdArgs.push_back(Elt: "-mllvm");
4706 CmdArgs.push_back(Elt: "-generate-type-units");
4707 }
4708 }
4709
4710 if (const Arg *A =
4711 Args.getLastArg(Ids: options::OPT_gomit_unreferenced_methods,
4712 Ids: options::OPT_gno_omit_unreferenced_methods))
4713 (void)checkDebugInfoOption(A, Args, D, TC);
4714 if (Args.hasFlag(Pos: options::OPT_gomit_unreferenced_methods,
4715 Neg: options::OPT_gno_omit_unreferenced_methods, Default: false) &&
4716 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
4717 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
4718 !EnableTypeUnits) {
4719 CmdArgs.push_back(Elt: "-gomit-unreferenced-methods");
4720 }
4721
4722 // To avoid join/split of directory+filename, the integrated assembler prefers
4723 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4724 // form before DWARF v5.
4725 if (!Args.hasFlag(Pos: options::OPT_fdwarf_directory_asm,
4726 Neg: options::OPT_fno_dwarf_directory_asm,
4727 Default: TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4728 CmdArgs.push_back(Elt: "-fno-dwarf-directory-asm");
4729
4730 // Decide how to render forward declarations of template instantiations.
4731 // SCE wants full descriptions, others just get them in the name.
4732 if (ForwardTemplateParams)
4733 CmdArgs.push_back(Elt: "-debug-forward-template-params");
4734
4735 // Do we need to explicitly import anonymous namespaces into the parent
4736 // scope?
4737 if (DebuggerTuning == llvm::DebuggerKind::SCE)
4738 CmdArgs.push_back(Elt: "-dwarf-explicit-import");
4739
4740 renderDwarfFormat(D, T, Args, CmdArgs, DwarfVersion: EffectiveDWARFVersion);
4741 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4742
4743 // This controls whether or not we perform JustMyCode instrumentation.
4744 if (Args.hasFlag(Pos: options::OPT_fjmc, Neg: options::OPT_fno_jmc, Default: false)) {
4745 if (TC.getTriple().isOSBinFormatELF() ||
4746 TC.getTriple().isWindowsMSVCEnvironment()) {
4747 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
4748 CmdArgs.push_back(Elt: "-fjmc");
4749 else if (D.IsCLMode())
4750 D.Diag(DiagID: clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
4751 << "'/Zi', '/Z7'";
4752 else
4753 D.Diag(DiagID: clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
4754 << "-g";
4755 } else {
4756 D.Diag(DiagID: clang::diag::warn_drv_fjmc_for_elf_only);
4757 }
4758 }
4759
4760 // Add in -fdebug-compilation-dir if necessary.
4761 const char *DebugCompilationDir =
4762 addDebugCompDirArg(Args, CmdArgs, VFS: D.getVFS());
4763
4764 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
4765
4766 // Add the output path to the object file for CodeView debug infos.
4767 if (EmitCodeView && Output.isFilename())
4768 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
4769 OutputFileName: Output.getFilename());
4770}
4771
4772static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
4773 ArgStringList &CmdArgs) {
4774 unsigned RTOptionID = options::OPT__SLASH_MT;
4775
4776 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
4777 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4778 // but defining _DEBUG is sticky.
4779 RTOptionID = options::OPT__SLASH_MTd;
4780
4781 if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_M_Group))
4782 RTOptionID = A->getOption().getID();
4783
4784 if (Arg *A = Args.getLastArg(Ids: options::OPT_fms_runtime_lib_EQ)) {
4785 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4786 .Case(S: "static", Value: options::OPT__SLASH_MT)
4787 .Case(S: "static_dbg", Value: options::OPT__SLASH_MTd)
4788 .Case(S: "dll", Value: options::OPT__SLASH_MD)
4789 .Case(S: "dll_dbg", Value: options::OPT__SLASH_MDd)
4790 .Default(Value: options::OPT__SLASH_MT);
4791 }
4792
4793 StringRef FlagForCRT;
4794 switch (RTOptionID) {
4795 case options::OPT__SLASH_MD:
4796 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
4797 CmdArgs.push_back(Elt: "-D_DEBUG");
4798 CmdArgs.push_back(Elt: "-D_MT");
4799 CmdArgs.push_back(Elt: "-D_DLL");
4800 FlagForCRT = "--dependent-lib=msvcrt";
4801 break;
4802 case options::OPT__SLASH_MDd:
4803 CmdArgs.push_back(Elt: "-D_DEBUG");
4804 CmdArgs.push_back(Elt: "-D_MT");
4805 CmdArgs.push_back(Elt: "-D_DLL");
4806 FlagForCRT = "--dependent-lib=msvcrtd";
4807 break;
4808 case options::OPT__SLASH_MT:
4809 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
4810 CmdArgs.push_back(Elt: "-D_DEBUG");
4811 CmdArgs.push_back(Elt: "-D_MT");
4812 CmdArgs.push_back(Elt: "-flto-visibility-public-std");
4813 FlagForCRT = "--dependent-lib=libcmt";
4814 break;
4815 case options::OPT__SLASH_MTd:
4816 CmdArgs.push_back(Elt: "-D_DEBUG");
4817 CmdArgs.push_back(Elt: "-D_MT");
4818 CmdArgs.push_back(Elt: "-flto-visibility-public-std");
4819 FlagForCRT = "--dependent-lib=libcmtd";
4820 break;
4821 default:
4822 llvm_unreachable("Unexpected option ID.");
4823 }
4824
4825 if (Args.hasArg(Ids: options::OPT_fms_omit_default_lib)) {
4826 CmdArgs.push_back(Elt: "-D_VC_NODEFAULTLIB");
4827 } else {
4828 CmdArgs.push_back(Elt: FlagForCRT.data());
4829
4830 // This provides POSIX compatibility (maps 'open' to '_open'), which most
4831 // users want. The /Za flag to cl.exe turns this off, but it's not
4832 // implemented in clang.
4833 CmdArgs.push_back(Elt: "--dependent-lib=oldnames");
4834 }
4835
4836 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
4837 // even if the file doesn't actually refer to any of the routines because
4838 // the CRT itself has incomplete dependency markings.
4839 if (TC.getTriple().isWindowsArm64EC())
4840 CmdArgs.push_back(Elt: "--dependent-lib=softintrin");
4841}
4842
4843void Clang::ConstructJob(Compilation &C, const JobAction &JA,
4844 const InputInfo &Output, const InputInfoList &Inputs,
4845 const ArgList &Args, const char *LinkingOutput) const {
4846 const auto &TC = getToolChain();
4847 const llvm::Triple &RawTriple = TC.getTriple();
4848 const llvm::Triple &Triple = TC.getEffectiveTriple();
4849 const std::string &TripleStr = Triple.getTriple();
4850
4851 bool KernelOrKext =
4852 Args.hasArg(Ids: options::OPT_mkernel, Ids: options::OPT_fapple_kext);
4853 const Driver &D = TC.getDriver();
4854 ArgStringList CmdArgs;
4855
4856 assert(Inputs.size() >= 1 && "Must have at least one input.");
4857 // CUDA/HIP compilation may have multiple inputs (source file + results of
4858 // device-side compilations). OpenMP device jobs also take the host IR as a
4859 // second input. Module precompilation accepts a list of header files to
4860 // include as part of the module. API extraction accepts a list of header
4861 // files whose API information is emitted in the output. All other jobs are
4862 // expected to have exactly one input. SYCL compilation only expects a
4863 // single input.
4864 bool IsCuda = JA.isOffloading(OKind: Action::OFK_Cuda);
4865 bool IsCudaDevice = JA.isDeviceOffloading(OKind: Action::OFK_Cuda);
4866 bool IsHIP = JA.isOffloading(OKind: Action::OFK_HIP);
4867 bool IsHIPDevice = JA.isDeviceOffloading(OKind: Action::OFK_HIP);
4868 bool IsSYCL = JA.isOffloading(OKind: Action::OFK_SYCL);
4869 bool IsSYCLDevice = JA.isDeviceOffloading(OKind: Action::OFK_SYCL);
4870 bool IsOpenMPDevice = JA.isDeviceOffloading(OKind: Action::OFK_OpenMP);
4871 bool IsExtractAPI = isa<ExtractAPIJobAction>(Val: JA);
4872 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(OKind: Action::OFK_None) ||
4873 JA.isDeviceOffloading(OKind: Action::OFK_Host));
4874 bool IsHostOffloadingAction =
4875 JA.isHostOffloading(OKind: Action::OFK_OpenMP) ||
4876 JA.isHostOffloading(OKind: Action::OFK_SYCL) ||
4877 (JA.isHostOffloading(OKind: C.getActiveOffloadKinds()) &&
4878 Args.hasFlag(Pos: options::OPT_offload_new_driver,
4879 Neg: options::OPT_no_offload_new_driver,
4880 Default: C.getActiveOffloadKinds() != Action::OFK_None));
4881
4882 bool IsRDCMode =
4883 Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false);
4884
4885 auto LTOMode = IsDeviceOffloadAction ? D.getOffloadLTOMode() : D.getLTOMode();
4886 bool IsUsingLTO = LTOMode != LTOK_None;
4887
4888 // Extract API doesn't have a main input file, so invent a fake one as a
4889 // placeholder.
4890 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
4891 "extract-api");
4892
4893 const InputInfo &Input =
4894 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
4895
4896 InputInfoList ExtractAPIInputs;
4897 InputInfoList HostOffloadingInputs;
4898 const InputInfo *CudaDeviceInput = nullptr;
4899 const InputInfo *OpenMPDeviceInput = nullptr;
4900 for (const InputInfo &I : Inputs) {
4901 if (&I == &Input || I.getType() == types::TY_Nothing) {
4902 // This is the primary input or contains nothing.
4903 } else if (IsExtractAPI) {
4904 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
4905 if (I.getType() != ExpectedInputType) {
4906 D.Diag(DiagID: diag::err_drv_extract_api_wrong_kind)
4907 << I.getFilename() << types::getTypeName(Id: I.getType())
4908 << types::getTypeName(Id: ExpectedInputType);
4909 }
4910 ExtractAPIInputs.push_back(Elt: I);
4911 } else if (IsHostOffloadingAction) {
4912 HostOffloadingInputs.push_back(Elt: I);
4913 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
4914 CudaDeviceInput = &I;
4915 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
4916 OpenMPDeviceInput = &I;
4917 } else {
4918 llvm_unreachable("unexpectedly given multiple inputs");
4919 }
4920 }
4921
4922 const llvm::Triple *AuxTriple =
4923 (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
4924 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
4925 bool IsUEFI = RawTriple.isUEFI();
4926 bool IsIAMCU = RawTriple.isOSIAMCU();
4927
4928 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling in
4929 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
4930 // Windows), we need to pass Windows-specific flags to cc1.
4931 if (IsCuda || IsHIP || IsSYCL)
4932 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
4933
4934 // C++ is not supported for IAMCU.
4935 if (IsIAMCU && types::isCXX(Id: Input.getType()))
4936 D.Diag(DiagID: diag::err_drv_clang_unsupported) << "C++ for IAMCU";
4937
4938 // Invoke ourselves in -cc1 mode.
4939 //
4940 // FIXME: Implement custom jobs for internal actions.
4941 CmdArgs.push_back(Elt: "-cc1");
4942
4943 // Add the "effective" target triple.
4944 CmdArgs.push_back(Elt: "-triple");
4945 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TripleStr));
4946
4947 if (const Arg *MJ = Args.getLastArg(Ids: options::OPT_MJ)) {
4948 DumpCompilationDatabase(C, Filename: MJ->getValue(), Target: TripleStr, Output, Input, Args);
4949 Args.ClaimAllArgs(Id0: options::OPT_MJ);
4950 } else if (const Arg *GenCDBFragment =
4951 Args.getLastArg(Ids: options::OPT_gen_cdb_fragment_path)) {
4952 DumpCompilationDatabaseFragmentToDir(Dir: GenCDBFragment->getValue(), C,
4953 Target: TripleStr, Output, Input, Args);
4954 Args.ClaimAllArgs(Id0: options::OPT_gen_cdb_fragment_path);
4955 }
4956
4957 if (IsCuda || IsHIP) {
4958 // We have to pass the triple of the host if compiling for a CUDA/HIP device
4959 // and vice-versa.
4960 std::string NormalizedTriple;
4961 if (JA.isDeviceOffloading(OKind: Action::OFK_Cuda) ||
4962 JA.isDeviceOffloading(OKind: Action::OFK_HIP))
4963 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
4964 ->getTriple()
4965 .normalize();
4966 else {
4967 // Host-side compilation.
4968 NormalizedTriple =
4969 (IsCuda ? C.getOffloadToolChains(Kind: Action::OFK_Cuda).first->second
4970 : C.getOffloadToolChains(Kind: Action::OFK_HIP).first->second)
4971 ->getTriple()
4972 .normalize();
4973 if (IsCuda) {
4974 // We need to figure out which CUDA version we're compiling for, as that
4975 // determines how we load and launch GPU kernels.
4976 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
4977 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
4978 assert(CTC && "Expected valid CUDA Toolchain.");
4979 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
4980 CmdArgs.push_back(Elt: Args.MakeArgString(
4981 Str: Twine("-target-sdk-version=") +
4982 CudaVersionToString(V: CTC->CudaInstallation.version())));
4983 }
4984 }
4985 CmdArgs.push_back(Elt: "-aux-triple");
4986 CmdArgs.push_back(Elt: Args.MakeArgString(Str: NormalizedTriple));
4987
4988 if (JA.isDeviceOffloading(OKind: Action::OFK_HIP) &&
4989 (getToolChain().getTriple().isAMDGPU() ||
4990 (getToolChain().getTriple().isSPIRV() &&
4991 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
4992 // Device side compilation printf
4993 if (Args.getLastArg(Ids: options::OPT_mprintf_kind_EQ)) {
4994 CmdArgs.push_back(Elt: Args.MakeArgString(
4995 Str: "-mprintf-kind=" +
4996 Args.getLastArgValue(Id: options::OPT_mprintf_kind_EQ)));
4997 // Force compiler error on invalid conversion specifiers
4998 CmdArgs.push_back(
4999 Elt: Args.MakeArgString(Str: "-Werror=format-invalid-specifier"));
5000 }
5001 }
5002 }
5003
5004 // Optimization level for CodeGen.
5005 if (const Arg *A = Args.getLastArg(Ids: options::OPT_O_Group)) {
5006 if (A->getOption().matches(ID: options::OPT_O4)) {
5007 CmdArgs.push_back(Elt: "-O3");
5008 D.Diag(DiagID: diag::warn_O4_is_O3);
5009 } else {
5010 A->render(Args, Output&: CmdArgs);
5011 }
5012 }
5013
5014 // Unconditionally claim the printf option now to avoid unused diagnostic.
5015 if (const Arg *PF = Args.getLastArg(Ids: options::OPT_mprintf_kind_EQ))
5016 PF->claim();
5017
5018 if (IsSYCL) {
5019 if (IsSYCLDevice) {
5020 // Host triple is needed when doing SYCL device compilations.
5021 llvm::Triple AuxT = C.getDefaultToolChain().getTriple();
5022 std::string NormalizedTriple = AuxT.normalize();
5023 CmdArgs.push_back(Elt: "-aux-triple");
5024 CmdArgs.push_back(Elt: Args.MakeArgString(Str: NormalizedTriple));
5025
5026 // We want to compile sycl kernels.
5027 CmdArgs.push_back(Elt: "-fsycl-is-device");
5028
5029 // Set O2 optimization level by default
5030 if (!Args.getLastArg(Ids: options::OPT_O_Group))
5031 CmdArgs.push_back(Elt: "-O2");
5032 } else {
5033 // Add any options that are needed specific to SYCL offload while
5034 // performing the host side compilation.
5035
5036 // Let the front-end host compilation flow know about SYCL offload
5037 // compilation.
5038 CmdArgs.push_back(Elt: "-fsycl-is-host");
5039 }
5040
5041 // Set options for both host and device.
5042 Arg *SYCLStdArg = Args.getLastArg(Ids: options::OPT_sycl_std_EQ);
5043 if (SYCLStdArg) {
5044 SYCLStdArg->render(Args, Output&: CmdArgs);
5045 } else {
5046 // Ensure the default version in SYCL mode is 2020.
5047 CmdArgs.push_back(Elt: "-sycl-std=2020");
5048 }
5049 }
5050
5051 if (Args.hasArg(Ids: options::OPT_fclangir))
5052 CmdArgs.push_back(Elt: "-fclangir");
5053
5054 if (IsOpenMPDevice) {
5055 // We have to pass the triple of the host if compiling for an OpenMP device.
5056 std::string NormalizedTriple =
5057 C.getSingleOffloadToolChain<Action::OFK_Host>()
5058 ->getTriple()
5059 .normalize();
5060 CmdArgs.push_back(Elt: "-aux-triple");
5061 CmdArgs.push_back(Elt: Args.MakeArgString(Str: NormalizedTriple));
5062 }
5063
5064 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5065 Triple.getArch() == llvm::Triple::thumb)) {
5066 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5067 unsigned Version = 0;
5068 bool Failure =
5069 Triple.getArchName().substr(Start: Offset).consumeInteger(Radix: 10, Result&: Version);
5070 if (Failure || Version < 7)
5071 D.Diag(DiagID: diag::err_target_unsupported_arch) << Triple.getArchName()
5072 << TripleStr;
5073 }
5074
5075 // Push all default warning arguments that are specific to
5076 // the given target. These come before user provided warning options
5077 // are provided.
5078 TC.addClangWarningOptions(CC1Args&: CmdArgs);
5079
5080 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5081 if (Triple.isSPIR() || Triple.isSPIRV())
5082 CmdArgs.push_back(Elt: "-Wspir-compat");
5083
5084 // Select the appropriate action.
5085 RewriteKind rewriteKind = RK_None;
5086
5087 bool UnifiedLTO = false;
5088 if (IsUsingLTO) {
5089 UnifiedLTO = Args.hasFlag(Pos: options::OPT_funified_lto,
5090 Neg: options::OPT_fno_unified_lto, Default: Triple.isPS());
5091 if (UnifiedLTO)
5092 CmdArgs.push_back(Elt: "-funified-lto");
5093 }
5094
5095 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5096 // it claims when not running an assembler. Otherwise, clang would emit
5097 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5098 // flags while debugging something. That'd be somewhat inconvenient, and it's
5099 // also inconsistent with most other flags -- we don't warn on
5100 // -ffunction-sections not being used in -E mode either for example, even
5101 // though it's not really used either.
5102 if (!isa<AssembleJobAction>(Val: JA)) {
5103 // The args claimed here should match the args used in
5104 // CollectArgsForIntegratedAssembler().
5105 if (TC.useIntegratedAs()) {
5106 Args.ClaimAllArgs(Id0: options::OPT_mrelax_all);
5107 Args.ClaimAllArgs(Id0: options::OPT_mno_relax_all);
5108 Args.ClaimAllArgs(Id0: options::OPT_mincremental_linker_compatible);
5109 Args.ClaimAllArgs(Id0: options::OPT_mno_incremental_linker_compatible);
5110 switch (C.getDefaultToolChain().getArch()) {
5111 case llvm::Triple::arm:
5112 case llvm::Triple::armeb:
5113 case llvm::Triple::thumb:
5114 case llvm::Triple::thumbeb:
5115 Args.ClaimAllArgs(Id0: options::OPT_mimplicit_it_EQ);
5116 break;
5117 default:
5118 break;
5119 }
5120 }
5121 Args.ClaimAllArgs(Id0: options::OPT_Wa_COMMA);
5122 Args.ClaimAllArgs(Id0: options::OPT_Xassembler);
5123 Args.ClaimAllArgs(Id0: options::OPT_femit_dwarf_unwind_EQ);
5124 }
5125
5126 bool IsAMDSPIRVForHIPDevice =
5127 IsHIPDevice && getToolChain().getTriple().isSPIRV() &&
5128 getToolChain().getTriple().getVendor() == llvm::Triple::AMD;
5129
5130 if (isa<AnalyzeJobAction>(Val: JA)) {
5131 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5132 CmdArgs.push_back(Elt: "-analyze");
5133 } else if (isa<PreprocessJobAction>(Val: JA)) {
5134 if (Output.getType() == types::TY_Dependencies)
5135 CmdArgs.push_back(Elt: "-Eonly");
5136 else {
5137 CmdArgs.push_back(Elt: "-E");
5138 if (Args.hasArg(Ids: options::OPT_rewrite_objc) &&
5139 !Args.hasArg(Ids: options::OPT_g_Group))
5140 CmdArgs.push_back(Elt: "-P");
5141 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5142 CmdArgs.push_back(Elt: "-fdirectives-only");
5143 }
5144 } else if (isa<AssembleJobAction>(Val: JA)) {
5145 CmdArgs.push_back(Elt: "-emit-obj");
5146
5147 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5148
5149 // Also ignore explicit -force_cpusubtype_ALL option.
5150 (void)Args.hasArg(Ids: options::OPT_force__cpusubtype__ALL);
5151 } else if (isa<PrecompileJobAction>(Val: JA)) {
5152 if (JA.getType() == types::TY_Nothing)
5153 CmdArgs.push_back(Elt: "-fsyntax-only");
5154 else if (JA.getType() == types::TY_ModuleFile) {
5155 if (Args.hasArg(Ids: options::OPT__precompile_reduced_bmi))
5156 CmdArgs.push_back(Elt: "-emit-reduced-module-interface");
5157 else
5158 CmdArgs.push_back(Elt: "-emit-module-interface");
5159 } else if (JA.getType() == types::TY_HeaderUnit)
5160 CmdArgs.push_back(Elt: "-emit-header-unit");
5161 else if (!Args.hasArg(Ids: options::OPT_ignore_pch))
5162 CmdArgs.push_back(Elt: "-emit-pch");
5163 } else if (isa<VerifyPCHJobAction>(Val: JA)) {
5164 CmdArgs.push_back(Elt: "-verify-pch");
5165 } else if (isa<ExtractAPIJobAction>(Val: JA)) {
5166 assert(JA.getType() == types::TY_API_INFO &&
5167 "Extract API actions must generate a API information.");
5168 CmdArgs.push_back(Elt: "-extract-api");
5169
5170 if (Arg *PrettySGFArg = Args.getLastArg(Ids: options::OPT_emit_pretty_sgf))
5171 PrettySGFArg->render(Args, Output&: CmdArgs);
5172
5173 Arg *SymbolGraphDirArg = Args.getLastArg(Ids: options::OPT_symbol_graph_dir_EQ);
5174
5175 if (Arg *ProductNameArg = Args.getLastArg(Ids: options::OPT_product_name_EQ))
5176 ProductNameArg->render(Args, Output&: CmdArgs);
5177 if (Arg *ExtractAPIIgnoresFileArg =
5178 Args.getLastArg(Ids: options::OPT_extract_api_ignores_EQ))
5179 ExtractAPIIgnoresFileArg->render(Args, Output&: CmdArgs);
5180 if (Arg *EmitExtensionSymbolGraphs =
5181 Args.getLastArg(Ids: options::OPT_emit_extension_symbol_graphs)) {
5182 if (!SymbolGraphDirArg)
5183 D.Diag(DiagID: diag::err_drv_missing_symbol_graph_dir);
5184
5185 EmitExtensionSymbolGraphs->render(Args, Output&: CmdArgs);
5186 }
5187 if (SymbolGraphDirArg)
5188 SymbolGraphDirArg->render(Args, Output&: CmdArgs);
5189 } else {
5190 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5191 "Invalid action for clang tool.");
5192 if (JA.getType() == types::TY_Nothing) {
5193 CmdArgs.push_back(Elt: "-fsyntax-only");
5194 } else if (JA.getType() == types::TY_LLVM_IR ||
5195 JA.getType() == types::TY_LTO_IR) {
5196 CmdArgs.push_back(Elt: "-emit-llvm");
5197 } else if (JA.getType() == types::TY_LLVM_BC ||
5198 JA.getType() == types::TY_LTO_BC) {
5199 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5200 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(Ids: options::OPT_S) &&
5201 Args.hasArg(Ids: options::OPT_emit_llvm)) {
5202 CmdArgs.push_back(Elt: "-emit-llvm");
5203 } else {
5204 CmdArgs.push_back(Elt: "-emit-llvm-bc");
5205 }
5206 } else if (JA.getType() == types::TY_IFS ||
5207 JA.getType() == types::TY_IFS_CPP) {
5208 StringRef ArgStr =
5209 Args.hasArg(Ids: options::OPT_interface_stub_version_EQ)
5210 ? Args.getLastArgValue(Id: options::OPT_interface_stub_version_EQ)
5211 : "ifs-v1";
5212 CmdArgs.push_back(Elt: "-emit-interface-stubs");
5213 CmdArgs.push_back(
5214 Elt: Args.MakeArgString(Str: Twine("-interface-stub-version=") + ArgStr.str()));
5215 } else if (JA.getType() == types::TY_PP_Asm) {
5216 CmdArgs.push_back(Elt: "-S");
5217 } else if (JA.getType() == types::TY_AST) {
5218 if (!Args.hasArg(Ids: options::OPT_ignore_pch))
5219 CmdArgs.push_back(Elt: "-emit-pch");
5220 } else if (JA.getType() == types::TY_ModuleFile) {
5221 CmdArgs.push_back(Elt: "-module-file-info");
5222 } else if (JA.getType() == types::TY_RewrittenObjC) {
5223 CmdArgs.push_back(Elt: "-rewrite-objc");
5224 rewriteKind = RK_NonFragile;
5225 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5226 CmdArgs.push_back(Elt: "-rewrite-objc");
5227 rewriteKind = RK_Fragile;
5228 } else if (JA.getType() == types::TY_CIR) {
5229 CmdArgs.push_back(Elt: "-emit-cir");
5230 } else if (JA.getType() == types::TY_Image && IsAMDSPIRVForHIPDevice) {
5231 CmdArgs.push_back(Elt: "-emit-obj");
5232 } else {
5233 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5234 }
5235
5236 // Preserve use-list order by default when emitting bitcode, so that
5237 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5238 // same result as running passes here. For LTO, we don't need to preserve
5239 // the use-list order, since serialization to bitcode is part of the flow.
5240 if (JA.getType() == types::TY_LLVM_BC)
5241 CmdArgs.push_back(Elt: "-emit-llvm-uselists");
5242
5243 if (IsUsingLTO) {
5244 if (IsDeviceOffloadAction && !JA.isDeviceOffloading(OKind: Action::OFK_OpenMP) &&
5245 !Args.hasFlag(Pos: options::OPT_offload_new_driver,
5246 Neg: options::OPT_no_offload_new_driver,
5247 Default: C.getActiveOffloadKinds() != Action::OFK_None) &&
5248 !Triple.isAMDGPU()) {
5249 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5250 << Args.getLastArg(Ids: options::OPT_foffload_lto,
5251 Ids: options::OPT_foffload_lto_EQ)
5252 ->getAsString(Args)
5253 << Triple.getTriple();
5254 } else if (Triple.isNVPTX() && !IsRDCMode &&
5255 JA.isDeviceOffloading(OKind: Action::OFK_Cuda)) {
5256 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_language_mode)
5257 << Args.getLastArg(Ids: options::OPT_foffload_lto,
5258 Ids: options::OPT_foffload_lto_EQ)
5259 ->getAsString(Args)
5260 << "-fno-gpu-rdc";
5261 } else {
5262 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5263 CmdArgs.push_back(Elt: Args.MakeArgString(
5264 Str: Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5265 // PS4 uses the legacy LTO API, which does not support some of the
5266 // features enabled by -flto-unit.
5267 if (!RawTriple.isPS4() ||
5268 (D.getLTOMode() == LTOK_Full) || !UnifiedLTO)
5269 CmdArgs.push_back(Elt: "-flto-unit");
5270 }
5271 }
5272 }
5273
5274 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dumpdir);
5275
5276 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fthinlto_index_EQ)) {
5277 if (!types::isLLVMIR(Id: Input.getType()))
5278 D.Diag(DiagID: diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5279 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fthinlto_index_EQ);
5280 }
5281
5282 if (Triple.isPPC())
5283 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mregnames,
5284 Neg: options::OPT_mno_regnames);
5285
5286 if (Args.getLastArg(Ids: options::OPT_fthin_link_bitcode_EQ))
5287 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fthin_link_bitcode_EQ);
5288
5289 if (Args.getLastArg(Ids: options::OPT_save_temps_EQ))
5290 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_save_temps_EQ);
5291
5292 auto *MemProfArg = Args.getLastArg(Ids: options::OPT_fmemory_profile,
5293 Ids: options::OPT_fmemory_profile_EQ,
5294 Ids: options::OPT_fno_memory_profile);
5295 if (MemProfArg &&
5296 !MemProfArg->getOption().matches(ID: options::OPT_fno_memory_profile))
5297 MemProfArg->render(Args, Output&: CmdArgs);
5298
5299 if (auto *MemProfUseArg =
5300 Args.getLastArg(Ids: options::OPT_fmemory_profile_use_EQ)) {
5301 if (MemProfArg)
5302 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
5303 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5304 if (auto *PGOInstrArg = Args.getLastArg(Ids: options::OPT_fprofile_generate,
5305 Ids: options::OPT_fprofile_generate_EQ))
5306 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
5307 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5308 MemProfUseArg->render(Args, Output&: CmdArgs);
5309 }
5310
5311 // Embed-bitcode option.
5312 // Only white-listed flags below are allowed to be embedded.
5313 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5314 (isa<BackendJobAction>(Val: JA) || isa<AssembleJobAction>(Val: JA))) {
5315 // Add flags implied by -fembed-bitcode.
5316 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fembed_bitcode_EQ);
5317 // Disable all llvm IR level optimizations.
5318 CmdArgs.push_back(Elt: "-disable-llvm-passes");
5319
5320 // Render target options.
5321 TC.addClangTargetOptions(DriverArgs: Args, CC1Args&: CmdArgs, DeviceOffloadKind: JA.getOffloadingDeviceKind());
5322
5323 // reject options that shouldn't be supported in bitcode
5324 // also reject kernel/kext
5325 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5326 options::OPT_mkernel,
5327 options::OPT_fapple_kext,
5328 options::OPT_ffunction_sections,
5329 options::OPT_fno_function_sections,
5330 options::OPT_fdata_sections,
5331 options::OPT_fno_data_sections,
5332 options::OPT_fbasic_block_sections_EQ,
5333 options::OPT_funique_internal_linkage_names,
5334 options::OPT_fno_unique_internal_linkage_names,
5335 options::OPT_funique_section_names,
5336 options::OPT_fno_unique_section_names,
5337 options::OPT_funique_basic_block_section_names,
5338 options::OPT_fno_unique_basic_block_section_names,
5339 options::OPT_mrestrict_it,
5340 options::OPT_mno_restrict_it,
5341 options::OPT_mstackrealign,
5342 options::OPT_mno_stackrealign,
5343 options::OPT_mstack_alignment,
5344 options::OPT_mcmodel_EQ,
5345 options::OPT_mlong_calls,
5346 options::OPT_mno_long_calls,
5347 options::OPT_ggnu_pubnames,
5348 options::OPT_gdwarf_aranges,
5349 options::OPT_fdebug_types_section,
5350 options::OPT_fno_debug_types_section,
5351 options::OPT_fdwarf_directory_asm,
5352 options::OPT_fno_dwarf_directory_asm,
5353 options::OPT_mrelax_all,
5354 options::OPT_mno_relax_all,
5355 options::OPT_ftrap_function_EQ,
5356 options::OPT_ffixed_r9,
5357 options::OPT_mfix_cortex_a53_835769,
5358 options::OPT_mno_fix_cortex_a53_835769,
5359 options::OPT_ffixed_x18,
5360 options::OPT_mglobal_merge,
5361 options::OPT_mno_global_merge,
5362 options::OPT_mred_zone,
5363 options::OPT_mno_red_zone,
5364 options::OPT_Wa_COMMA,
5365 options::OPT_Xassembler,
5366 options::OPT_mllvm,
5367 options::OPT_mmlir,
5368 };
5369 for (const auto &A : Args)
5370 if (llvm::is_contained(Range: kBitcodeOptionIgnorelist, Element: A->getOption().getID()))
5371 D.Diag(DiagID: diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5372
5373 // Render the CodeGen options that need to be passed.
5374 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_foptimize_sibling_calls,
5375 Neg: options::OPT_fno_optimize_sibling_calls);
5376
5377 RenderFloatingPointOptions(TC, D, OFastEnabled: isOptimizationLevelFast(Args), Args,
5378 CmdArgs, JA);
5379
5380 // Render ABI arguments
5381 switch (TC.getArch()) {
5382 default: break;
5383 case llvm::Triple::arm:
5384 case llvm::Triple::armeb:
5385 case llvm::Triple::thumbeb:
5386 RenderARMABI(D, Triple, Args, CmdArgs);
5387 break;
5388 case llvm::Triple::aarch64:
5389 case llvm::Triple::aarch64_32:
5390 case llvm::Triple::aarch64_be:
5391 RenderAArch64ABI(Triple, Args, CmdArgs);
5392 break;
5393 }
5394
5395 // Input/Output file.
5396 if (Output.getType() == types::TY_Dependencies) {
5397 // Handled with other dependency code.
5398 } else if (Output.isFilename()) {
5399 CmdArgs.push_back(Elt: "-o");
5400 CmdArgs.push_back(Elt: Output.getFilename());
5401 } else {
5402 assert(Output.isNothing() && "Input output.");
5403 }
5404
5405 for (const auto &II : Inputs) {
5406 addDashXForInput(Args, Input: II, CmdArgs);
5407 if (II.isFilename())
5408 CmdArgs.push_back(Elt: II.getFilename());
5409 else
5410 II.getInputArg().renderAsInput(Args, Output&: CmdArgs);
5411 }
5412
5413 C.addCommand(C: std::make_unique<Command>(
5414 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args: D.getClangProgramPath(),
5415 args&: CmdArgs, args: Inputs, args: Output, args: D.getPrependArg()));
5416 return;
5417 }
5418
5419 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5420 CmdArgs.push_back(Elt: "-fembed-bitcode=marker");
5421
5422 // We normally speed up the clang process a bit by skipping destructors at
5423 // exit, but when we're generating diagnostics we can rely on some of the
5424 // cleanup.
5425 if (!C.isForDiagnostics())
5426 CmdArgs.push_back(Elt: "-disable-free");
5427 CmdArgs.push_back(Elt: "-clear-ast-before-backend");
5428
5429#ifdef NDEBUG
5430 const bool IsAssertBuild = false;
5431#else
5432 const bool IsAssertBuild = true;
5433#endif
5434
5435 // Disable the verification pass in no-asserts builds unless otherwise
5436 // specified.
5437 if (Args.hasFlag(Pos: options::OPT_fno_verify_intermediate_code,
5438 Neg: options::OPT_fverify_intermediate_code, Default: !IsAssertBuild)) {
5439 CmdArgs.push_back(Elt: "-disable-llvm-verifier");
5440 }
5441
5442 // Discard value names in no-asserts builds unless otherwise specified.
5443 if (Args.hasFlag(Pos: options::OPT_fdiscard_value_names,
5444 Neg: options::OPT_fno_discard_value_names, Default: !IsAssertBuild)) {
5445 if (Args.hasArg(Ids: options::OPT_fdiscard_value_names) &&
5446 llvm::any_of(Range: Inputs, P: [](const clang::driver::InputInfo &II) {
5447 return types::isLLVMIR(Id: II.getType());
5448 })) {
5449 D.Diag(DiagID: diag::warn_ignoring_fdiscard_for_bitcode);
5450 }
5451 CmdArgs.push_back(Elt: "-discard-value-names");
5452 }
5453
5454 // Set the main file name, so that debug info works even with
5455 // -save-temps.
5456 CmdArgs.push_back(Elt: "-main-file-name");
5457 CmdArgs.push_back(Elt: getBaseInputName(Args, Input));
5458
5459 // Some flags which affect the language (via preprocessor
5460 // defines).
5461 if (Args.hasArg(Ids: options::OPT_static))
5462 CmdArgs.push_back(Elt: "-static-define");
5463
5464 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_static_libclosure);
5465
5466 if (Args.hasArg(Ids: options::OPT_municode))
5467 CmdArgs.push_back(Elt: "-DUNICODE");
5468
5469 if (isa<AnalyzeJobAction>(Val: JA))
5470 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5471
5472 if (isa<AnalyzeJobAction>(Val: JA) ||
5473 (isa<PreprocessJobAction>(Val: JA) && Args.hasArg(Ids: options::OPT__analyze)))
5474 CmdArgs.push_back(Elt: "-setup-static-analyzer");
5475
5476 // Enable compatilibily mode to avoid analyzer-config related errors.
5477 // Since we can't access frontend flags through hasArg, let's manually iterate
5478 // through them.
5479 bool FoundAnalyzerConfig = false;
5480 for (auto *Arg : Args.filtered(Ids: options::OPT_Xclang))
5481 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5482 FoundAnalyzerConfig = true;
5483 break;
5484 }
5485 if (!FoundAnalyzerConfig)
5486 for (auto *Arg : Args.filtered(Ids: options::OPT_Xanalyzer))
5487 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5488 FoundAnalyzerConfig = true;
5489 break;
5490 }
5491 if (FoundAnalyzerConfig)
5492 CmdArgs.push_back(Elt: "-analyzer-config-compatibility-mode=true");
5493
5494 CheckCodeGenerationOptions(D, Args);
5495
5496 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5497 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5498 if (FunctionAlignment) {
5499 CmdArgs.push_back(Elt: "-function-alignment");
5500 CmdArgs.push_back(Elt: Args.MakeArgString(Str: std::to_string(val: FunctionAlignment)));
5501 }
5502
5503 // We support -falign-loops=N where N is a power of 2. GCC supports more
5504 // forms.
5505 if (const Arg *A = Args.getLastArg(Ids: options::OPT_falign_loops_EQ)) {
5506 unsigned Value = 0;
5507 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: Value) || Value > 65536)
5508 TC.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
5509 << A->getAsString(Args) << A->getValue();
5510 else if (Value & (Value - 1))
5511 TC.getDriver().Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
5512 << A->getAsString(Args) << A->getValue();
5513 // Treat =0 as unspecified (use the target preference).
5514 if (Value)
5515 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-falign-loops=" +
5516 Twine(std::min(a: Value, b: 65536u))));
5517 }
5518
5519 if (Triple.isOSzOS()) {
5520 // On z/OS some of the system header feature macros need to
5521 // be defined to enable most cross platform projects to build
5522 // successfully. Ths include the libc++ library. A
5523 // complicating factor is that users can define these
5524 // macros to the same or different values. We need to add
5525 // the definition for these macros to the compilation command
5526 // if the user hasn't already defined them.
5527
5528 auto findMacroDefinition = [&](const std::string &Macro) {
5529 auto MacroDefs = Args.getAllArgValues(Id: options::OPT_D);
5530 return llvm::any_of(Range&: MacroDefs, P: [&](const std::string &M) {
5531 return M == Macro || M.find(str: Macro + '=') != std::string::npos;
5532 });
5533 };
5534
5535 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5536 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5537 CmdArgs.push_back(Elt: "-D_UNIX03_WITHDRAWN");
5538 // _OPEN_DEFAULT is required for XL compat
5539 if (!findMacroDefinition("_OPEN_DEFAULT"))
5540 CmdArgs.push_back(Elt: "-D_OPEN_DEFAULT");
5541 if (D.CCCIsCXX() || types::isCXX(Id: Input.getType())) {
5542 // _XOPEN_SOURCE=600 is required for libcxx.
5543 if (!findMacroDefinition("_XOPEN_SOURCE"))
5544 CmdArgs.push_back(Elt: "-D_XOPEN_SOURCE=600");
5545 }
5546 }
5547
5548 llvm::Reloc::Model RelocationModel;
5549 unsigned PICLevel;
5550 bool IsPIE;
5551 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) = ParsePICArgs(ToolChain: TC, Args);
5552 Arg *LastPICDataRelArg =
5553 Args.getLastArg(Ids: options::OPT_mno_pic_data_is_text_relative,
5554 Ids: options::OPT_mpic_data_is_text_relative);
5555 bool NoPICDataIsTextRelative = false;
5556 if (LastPICDataRelArg) {
5557 if (LastPICDataRelArg->getOption().matches(
5558 ID: options::OPT_mno_pic_data_is_text_relative)) {
5559 NoPICDataIsTextRelative = true;
5560 if (!PICLevel)
5561 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
5562 << "-mno-pic-data-is-text-relative"
5563 << "-fpic/-fpie";
5564 }
5565 if (!Triple.isSystemZ())
5566 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5567 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5568 : "-mpic-data-is-text-relative")
5569 << RawTriple.str();
5570 }
5571
5572 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5573 RelocationModel == llvm::Reloc::ROPI_RWPI;
5574 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5575 RelocationModel == llvm::Reloc::ROPI_RWPI;
5576
5577 if (Args.hasArg(Ids: options::OPT_mcmse) &&
5578 !Args.hasArg(Ids: options::OPT_fallow_unsupported)) {
5579 if (IsROPI)
5580 D.Diag(DiagID: diag::err_cmse_pi_are_incompatible) << IsROPI;
5581 if (IsRWPI)
5582 D.Diag(DiagID: diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5583 }
5584
5585 if (IsROPI && types::isCXX(Id: Input.getType()) &&
5586 !Args.hasArg(Ids: options::OPT_fallow_unsupported))
5587 D.Diag(DiagID: diag::err_drv_ropi_incompatible_with_cxx);
5588
5589 const char *RMName = RelocationModelName(Model: RelocationModel);
5590 if (RMName) {
5591 CmdArgs.push_back(Elt: "-mrelocation-model");
5592 CmdArgs.push_back(Elt: RMName);
5593 }
5594 if (PICLevel > 0) {
5595 CmdArgs.push_back(Elt: "-pic-level");
5596 CmdArgs.push_back(Elt: PICLevel == 1 ? "1" : "2");
5597 if (IsPIE)
5598 CmdArgs.push_back(Elt: "-pic-is-pie");
5599 if (NoPICDataIsTextRelative)
5600 CmdArgs.push_back(Elt: "-mcmodel=medium");
5601 }
5602
5603 if (RelocationModel == llvm::Reloc::ROPI ||
5604 RelocationModel == llvm::Reloc::ROPI_RWPI)
5605 CmdArgs.push_back(Elt: "-fropi");
5606 if (RelocationModel == llvm::Reloc::RWPI ||
5607 RelocationModel == llvm::Reloc::ROPI_RWPI)
5608 CmdArgs.push_back(Elt: "-frwpi");
5609
5610 if (Arg *A = Args.getLastArg(Ids: options::OPT_meabi)) {
5611 CmdArgs.push_back(Elt: "-meabi");
5612 CmdArgs.push_back(Elt: A->getValue());
5613 }
5614
5615 // -fsemantic-interposition is forwarded to CC1: set the
5616 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5617 // make default visibility external linkage definitions dso_preemptable.
5618 //
5619 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5620 // aliases (make default visibility external linkage definitions dso_local).
5621 // This is the CC1 default for ELF to match COFF/Mach-O.
5622 //
5623 // Otherwise use Clang's traditional behavior: like
5624 // -fno-semantic-interposition but local aliases are not used. So references
5625 // can be interposed if not optimized out.
5626 if (Triple.isOSBinFormatELF()) {
5627 Arg *A = Args.getLastArg(Ids: options::OPT_fsemantic_interposition,
5628 Ids: options::OPT_fno_semantic_interposition);
5629 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5630 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5631 bool SupportsLocalAlias =
5632 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5633 if (!A)
5634 CmdArgs.push_back(Elt: "-fhalf-no-semantic-interposition");
5635 else if (A->getOption().matches(ID: options::OPT_fsemantic_interposition))
5636 A->render(Args, Output&: CmdArgs);
5637 else if (!SupportsLocalAlias)
5638 CmdArgs.push_back(Elt: "-fhalf-no-semantic-interposition");
5639 }
5640 }
5641
5642 {
5643 std::string Model;
5644 if (Arg *A = Args.getLastArg(Ids: options::OPT_mthread_model)) {
5645 if (!TC.isThreadModelSupported(Model: A->getValue()))
5646 D.Diag(DiagID: diag::err_drv_invalid_thread_model_for_target)
5647 << A->getValue() << A->getAsString(Args);
5648 Model = A->getValue();
5649 } else
5650 Model = TC.getThreadModel();
5651 if (Model != "posix") {
5652 CmdArgs.push_back(Elt: "-mthread-model");
5653 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Model));
5654 }
5655 }
5656
5657 if (Arg *A = Args.getLastArg(Ids: options::OPT_fveclib)) {
5658 StringRef Name = A->getValue();
5659 if (Name == "SVML") {
5660 if (Triple.getArch() != llvm::Triple::x86 &&
5661 Triple.getArch() != llvm::Triple::x86_64)
5662 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5663 << Name << Triple.getArchName();
5664 } else if (Name == "AMDLIBM") {
5665 if (Triple.getArch() != llvm::Triple::x86 &&
5666 Triple.getArch() != llvm::Triple::x86_64)
5667 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5668 << Name << Triple.getArchName();
5669 } else if (Name == "libmvec") {
5670 if (Triple.getArch() != llvm::Triple::x86 &&
5671 Triple.getArch() != llvm::Triple::x86_64 &&
5672 Triple.getArch() != llvm::Triple::aarch64 &&
5673 Triple.getArch() != llvm::Triple::aarch64_be)
5674 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5675 << Name << Triple.getArchName();
5676 } else if (Name == "SLEEF" || Name == "ArmPL") {
5677 if (Triple.getArch() != llvm::Triple::aarch64 &&
5678 Triple.getArch() != llvm::Triple::aarch64_be && !Triple.isRISCV64())
5679 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5680 << Name << Triple.getArchName();
5681 }
5682 A->render(Args, Output&: CmdArgs);
5683 }
5684
5685 if (Args.hasFlag(Pos: options::OPT_fmerge_all_constants,
5686 Neg: options::OPT_fno_merge_all_constants, Default: false))
5687 CmdArgs.push_back(Elt: "-fmerge-all-constants");
5688
5689 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdelete_null_pointer_checks,
5690 Neg: options::OPT_fno_delete_null_pointer_checks);
5691
5692 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_flifetime_dse,
5693 Neg: options::OPT_fno_lifetime_dse);
5694
5695 // LLVM Code Generator Options.
5696
5697 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ_quadword_atomics)) {
5698 if (!Triple.isOSAIX() || Triple.isPPC32())
5699 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5700 << A->getSpelling() << RawTriple.str();
5701 CmdArgs.push_back(Elt: "-mabi=quadword-atomics");
5702 }
5703
5704 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlong_double_128)) {
5705 // Emit the unsupported option error until the Clang's library integration
5706 // support for 128-bit long double is available for AIX.
5707 if (Triple.isOSAIX())
5708 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5709 << A->getSpelling() << RawTriple.str();
5710 }
5711
5712 if (Arg *A = Args.getLastArg(Ids: options::OPT_Wframe_larger_than_EQ)) {
5713 StringRef V = A->getValue(), V1 = V;
5714 unsigned Size;
5715 if (V1.consumeInteger(Radix: 10, Result&: Size) || !V1.empty())
5716 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
5717 << V << A->getOption().getName();
5718 else
5719 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fwarn-stack-size=" + V));
5720 }
5721
5722 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fjump_tables,
5723 Neg: options::OPT_fno_jump_tables);
5724 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fprofile_sample_accurate,
5725 Neg: options::OPT_fno_profile_sample_accurate);
5726 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fpreserve_as_comments,
5727 Neg: options::OPT_fno_preserve_as_comments);
5728
5729 if (Arg *A = Args.getLastArg(Ids: options::OPT_mregparm_EQ)) {
5730 CmdArgs.push_back(Elt: "-mregparm");
5731 CmdArgs.push_back(Elt: A->getValue());
5732 }
5733
5734 if (Arg *A = Args.getLastArg(Ids: options::OPT_maix_struct_return,
5735 Ids: options::OPT_msvr4_struct_return)) {
5736 if (!TC.getTriple().isPPC32()) {
5737 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5738 << A->getSpelling() << RawTriple.str();
5739 } else if (A->getOption().matches(ID: options::OPT_maix_struct_return)) {
5740 CmdArgs.push_back(Elt: "-maix-struct-return");
5741 } else {
5742 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5743 CmdArgs.push_back(Elt: "-msvr4-struct-return");
5744 }
5745 }
5746
5747 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpcc_struct_return,
5748 Ids: options::OPT_freg_struct_return)) {
5749 if (TC.getArch() != llvm::Triple::x86) {
5750 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5751 << A->getSpelling() << RawTriple.str();
5752 } else if (A->getOption().matches(ID: options::OPT_fpcc_struct_return)) {
5753 CmdArgs.push_back(Elt: "-fpcc-struct-return");
5754 } else {
5755 assert(A->getOption().matches(options::OPT_freg_struct_return));
5756 CmdArgs.push_back(Elt: "-freg-struct-return");
5757 }
5758 }
5759
5760 if (Args.hasFlag(Pos: options::OPT_mrtd, Neg: options::OPT_mno_rtd, Default: false)) {
5761 if (Triple.getArch() == llvm::Triple::m68k)
5762 CmdArgs.push_back(Elt: "-fdefault-calling-conv=rtdcall");
5763 else
5764 CmdArgs.push_back(Elt: "-fdefault-calling-conv=stdcall");
5765 }
5766
5767 if (Args.hasArg(Ids: options::OPT_fenable_matrix)) {
5768 // enable-matrix is needed by both the LangOpts and by LLVM.
5769 CmdArgs.push_back(Elt: "-fenable-matrix");
5770 CmdArgs.push_back(Elt: "-mllvm");
5771 CmdArgs.push_back(Elt: "-enable-matrix");
5772 // Only handle default layout if matrix is enabled
5773 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fmatrix_memory_layout_EQ)) {
5774 StringRef Val = A->getValue();
5775 if (Val == "row-major" || Val == "column-major") {
5776 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fmatrix-memory-layout=" + Val));
5777 CmdArgs.push_back(Elt: "-mllvm");
5778 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-matrix-default-layout=" + Val));
5779
5780 } else {
5781 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
5782 }
5783 }
5784 }
5785
5786 CodeGenOptions::FramePointerKind FPKeepKind =
5787 getFramePointerKind(Args, Triple: RawTriple);
5788 const char *FPKeepKindStr = nullptr;
5789 switch (FPKeepKind) {
5790 case CodeGenOptions::FramePointerKind::None:
5791 FPKeepKindStr = "-mframe-pointer=none";
5792 break;
5793 case CodeGenOptions::FramePointerKind::Reserved:
5794 FPKeepKindStr = "-mframe-pointer=reserved";
5795 break;
5796 case CodeGenOptions::FramePointerKind::NonLeafNoReserve:
5797 FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";
5798 break;
5799 case CodeGenOptions::FramePointerKind::NonLeaf:
5800 FPKeepKindStr = "-mframe-pointer=non-leaf";
5801 break;
5802 case CodeGenOptions::FramePointerKind::All:
5803 FPKeepKindStr = "-mframe-pointer=all";
5804 break;
5805 }
5806 assert(FPKeepKindStr && "unknown FramePointerKind");
5807 CmdArgs.push_back(Elt: FPKeepKindStr);
5808
5809 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fzero_initialized_in_bss,
5810 Neg: options::OPT_fno_zero_initialized_in_bss);
5811
5812 bool OFastEnabled = isOptimizationLevelFast(Args);
5813 if (OFastEnabled)
5814 D.Diag(DiagID: diag::warn_drv_deprecated_arg_ofast);
5815 // If -Ofast is the optimization level, then -fstrict-aliasing should be
5816 // enabled. This alias option is being used to simplify the hasFlag logic.
5817 OptSpecifier StrictAliasingAliasOption =
5818 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
5819 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
5820 // doesn't do any TBAA.
5821 if (!Args.hasFlag(Pos: options::OPT_fstrict_aliasing, PosAlias: StrictAliasingAliasOption,
5822 Neg: options::OPT_fno_strict_aliasing,
5823 Default: !IsWindowsMSVC && !IsUEFI))
5824 CmdArgs.push_back(Elt: "-relaxed-aliasing");
5825 if (Args.hasFlag(Pos: options::OPT_fno_pointer_tbaa, Neg: options::OPT_fpointer_tbaa,
5826 Default: false))
5827 CmdArgs.push_back(Elt: "-no-pointer-tbaa");
5828 if (!Args.hasFlag(Pos: options::OPT_fstruct_path_tbaa,
5829 Neg: options::OPT_fno_struct_path_tbaa, Default: true))
5830 CmdArgs.push_back(Elt: "-no-struct-path-tbaa");
5831 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_enums,
5832 Neg: options::OPT_fno_strict_enums);
5833 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_return,
5834 Neg: options::OPT_fno_strict_return);
5835 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fallow_editor_placeholders,
5836 Neg: options::OPT_fno_allow_editor_placeholders);
5837 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_vtable_pointers,
5838 Neg: options::OPT_fno_strict_vtable_pointers);
5839 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fforce_emit_vtables,
5840 Neg: options::OPT_fno_force_emit_vtables);
5841 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_foptimize_sibling_calls,
5842 Neg: options::OPT_fno_optimize_sibling_calls);
5843 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fescaping_block_tail_calls,
5844 Neg: options::OPT_fno_escaping_block_tail_calls);
5845
5846 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffine_grained_bitfield_accesses,
5847 Ids: options::OPT_fno_fine_grained_bitfield_accesses);
5848
5849 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_relative_cxx_abi_vtables,
5850 Ids: options::OPT_fno_experimental_relative_cxx_abi_vtables);
5851
5852 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_omit_vtable_rtti,
5853 Ids: options::OPT_fno_experimental_omit_vtable_rtti);
5854
5855 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdisable_block_signature_string,
5856 Ids: options::OPT_fno_disable_block_signature_string);
5857
5858 // Handle segmented stacks.
5859 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fsplit_stack,
5860 Neg: options::OPT_fno_split_stack);
5861
5862 // -fprotect-parens=0 is default.
5863 if (Args.hasFlag(Pos: options::OPT_fprotect_parens,
5864 Neg: options::OPT_fno_protect_parens, Default: false))
5865 CmdArgs.push_back(Elt: "-fprotect-parens");
5866
5867 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
5868
5869 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_remote_memory,
5870 Neg: options::OPT_fno_atomic_remote_memory);
5871 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_fine_grained_memory,
5872 Neg: options::OPT_fno_atomic_fine_grained_memory);
5873 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_ignore_denormal_mode,
5874 Neg: options::OPT_fno_atomic_ignore_denormal_mode);
5875
5876 if (Arg *A = Args.getLastArg(Ids: options::OPT_fextend_args_EQ)) {
5877 const llvm::Triple::ArchType Arch = TC.getArch();
5878 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5879 StringRef V = A->getValue();
5880 if (V == "64")
5881 CmdArgs.push_back(Elt: "-fextend-arguments=64");
5882 else if (V != "32")
5883 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
5884 << A->getValue() << A->getOption().getName();
5885 } else
5886 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5887 << A->getOption().getName() << TripleStr;
5888 }
5889
5890 if (Arg *A = Args.getLastArg(Ids: options::OPT_mdouble_EQ)) {
5891 if (TC.getArch() == llvm::Triple::avr)
5892 A->render(Args, Output&: CmdArgs);
5893 else
5894 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5895 << A->getAsString(Args) << TripleStr;
5896 }
5897
5898 if (Arg *A = Args.getLastArg(Ids: options::OPT_LongDouble_Group)) {
5899 if (TC.getTriple().isX86())
5900 A->render(Args, Output&: CmdArgs);
5901 else if (TC.getTriple().isPPC() &&
5902 (A->getOption().getID() != options::OPT_mlong_double_80))
5903 A->render(Args, Output&: CmdArgs);
5904 else
5905 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5906 << A->getAsString(Args) << TripleStr;
5907 }
5908
5909 // Decide whether to use verbose asm. Verbose assembly is the default on
5910 // toolchains which have the integrated assembler on by default.
5911 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
5912 if (!Args.hasFlag(Pos: options::OPT_fverbose_asm, Neg: options::OPT_fno_verbose_asm,
5913 Default: IsIntegratedAssemblerDefault))
5914 CmdArgs.push_back(Elt: "-fno-verbose-asm");
5915
5916 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5917 // use that to indicate the MC default in the backend.
5918 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbinutils_version_EQ)) {
5919 StringRef V = A->getValue();
5920 unsigned Num;
5921 if (V == "none")
5922 A->render(Args, Output&: CmdArgs);
5923 else if (!V.consumeInteger(Radix: 10, Result&: Num) && Num > 0 &&
5924 (V.empty() || (V.consume_front(Prefix: ".") &&
5925 !V.consumeInteger(Radix: 10, Result&: Num) && V.empty())))
5926 A->render(Args, Output&: CmdArgs);
5927 else
5928 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
5929 << A->getValue() << A->getOption().getName();
5930 }
5931
5932 // If toolchain choose to use MCAsmParser for inline asm don't pass the
5933 // option to disable integrated-as explicitly.
5934 if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
5935 CmdArgs.push_back(Elt: "-no-integrated-as");
5936
5937 if (Args.hasArg(Ids: options::OPT_fdebug_pass_structure)) {
5938 CmdArgs.push_back(Elt: "-mdebug-pass");
5939 CmdArgs.push_back(Elt: "Structure");
5940 }
5941 if (Args.hasArg(Ids: options::OPT_fdebug_pass_arguments)) {
5942 CmdArgs.push_back(Elt: "-mdebug-pass");
5943 CmdArgs.push_back(Elt: "Arguments");
5944 }
5945
5946 // Enable -mconstructor-aliases except on darwin, where we have to work around
5947 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
5948 // code, where aliases aren't supported.
5949 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
5950 CmdArgs.push_back(Elt: "-mconstructor-aliases");
5951
5952 // Darwin's kernel doesn't support guard variables; just die if we
5953 // try to use them.
5954 if (KernelOrKext && RawTriple.isOSDarwin())
5955 CmdArgs.push_back(Elt: "-fforbid-guard-variables");
5956
5957 if (Arg *A = Args.getLastArg(Ids: options::OPT_mms_bitfields,
5958 Ids: options::OPT_mno_ms_bitfields)) {
5959 if (A->getOption().matches(ID: options::OPT_mms_bitfields))
5960 CmdArgs.push_back(Elt: "-fms-layout-compatibility=microsoft");
5961 else
5962 CmdArgs.push_back(Elt: "-fms-layout-compatibility=itanium");
5963 }
5964
5965 if (Triple.isOSCygMing()) {
5966 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fauto_import,
5967 Neg: options::OPT_fno_auto_import);
5968 }
5969
5970 if (Args.hasFlag(Pos: options::OPT_fms_volatile, Neg: options::OPT_fno_ms_volatile,
5971 Default: Triple.isX86() && IsWindowsMSVC))
5972 CmdArgs.push_back(Elt: "-fms-volatile");
5973
5974 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
5975 // defaults to -fno-direct-access-external-data. Pass the option if different
5976 // from the default.
5977 if (Arg *A = Args.getLastArg(Ids: options::OPT_fdirect_access_external_data,
5978 Ids: options::OPT_fno_direct_access_external_data)) {
5979 if (A->getOption().matches(ID: options::OPT_fdirect_access_external_data) !=
5980 (PICLevel == 0))
5981 A->render(Args, Output&: CmdArgs);
5982 } else if (PICLevel == 0 && Triple.isLoongArch()) {
5983 // Some targets default to -fno-direct-access-external-data even for
5984 // -fno-pic.
5985 CmdArgs.push_back(Elt: "-fno-direct-access-external-data");
5986 }
5987
5988 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
5989 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fplt, Neg: options::OPT_fno_plt);
5990
5991 // -fhosted is default.
5992 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
5993 // use Freestanding.
5994 bool Freestanding =
5995 Args.hasFlag(Pos: options::OPT_ffreestanding, Neg: options::OPT_fhosted, Default: false) ||
5996 KernelOrKext;
5997 if (Freestanding)
5998 CmdArgs.push_back(Elt: "-ffreestanding");
5999
6000 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_knr_functions);
6001
6002 auto SanitizeArgs = TC.getSanitizerArgs(JobArgs: Args);
6003 Args.AddLastArg(Output&: CmdArgs,
6004 Ids: options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
6005
6006 // This is a coarse approximation of what llvm-gcc actually does, both
6007 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
6008 // complicated ways.
6009 bool IsAsyncUnwindTablesDefault =
6010 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
6011 bool IsSyncUnwindTablesDefault =
6012 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
6013
6014 bool AsyncUnwindTables = Args.hasFlag(
6015 Pos: options::OPT_fasynchronous_unwind_tables,
6016 Neg: options::OPT_fno_asynchronous_unwind_tables,
6017 Default: (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6018 !Freestanding);
6019 bool UnwindTables =
6020 Args.hasFlag(Pos: options::OPT_funwind_tables, Neg: options::OPT_fno_unwind_tables,
6021 Default: IsSyncUnwindTablesDefault && !Freestanding);
6022 if (AsyncUnwindTables)
6023 CmdArgs.push_back(Elt: "-funwind-tables=2");
6024 else if (UnwindTables)
6025 CmdArgs.push_back(Elt: "-funwind-tables=1");
6026
6027 // Sframe unwind tables are independent of the other types. Although also
6028 // defined for aarch64, only x86_64 support is implemented at the moment.
6029 if (Arg *A = Args.getLastArg(Ids: options::OPT_gsframe)) {
6030 if (Triple.isOSBinFormatELF() && Triple.isX86())
6031 CmdArgs.push_back(Elt: "--gsframe");
6032 else
6033 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6034 << A->getOption().getName() << TripleStr;
6035 }
6036
6037 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6038 // `--gpu-use-aux-triple-only` is specified.
6039 if (!Args.getLastArg(Ids: options::OPT_gpu_use_aux_triple_only) &&
6040 (IsCudaDevice || IsHIPDevice || IsSYCLDevice)) {
6041 const ArgList &HostArgs =
6042 C.getArgsForToolChain(TC: nullptr, BoundArch: StringRef(), DeviceOffloadKind: Action::OFK_None);
6043 std::string HostCPU =
6044 getCPUName(D, Args: HostArgs, T: *TC.getAuxTriple(), /*FromAs*/ false);
6045 if (!HostCPU.empty()) {
6046 CmdArgs.push_back(Elt: "-aux-target-cpu");
6047 CmdArgs.push_back(Elt: Args.MakeArgString(Str: HostCPU));
6048 }
6049 getTargetFeatures(D, Triple: *TC.getAuxTriple(), Args: HostArgs, CmdArgs,
6050 /*ForAS*/ false, /*IsAux*/ true);
6051 }
6052
6053 TC.addClangTargetOptions(DriverArgs: Args, CC1Args&: CmdArgs, DeviceOffloadKind: JA.getOffloadingDeviceKind());
6054
6055 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6056
6057 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtls_size_EQ)) {
6058 StringRef Value = A->getValue();
6059 unsigned TLSSize = 0;
6060 Value.getAsInteger(Radix: 10, Result&: TLSSize);
6061 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6062 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6063 << A->getOption().getName() << TripleStr;
6064 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6065 D.Diag(DiagID: diag::err_drv_invalid_int_value)
6066 << A->getOption().getName() << Value;
6067 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mtls_size_EQ);
6068 }
6069
6070 if (isTLSDESCEnabled(TC, Args))
6071 CmdArgs.push_back(Elt: "-enable-tlsdesc");
6072
6073 // Add the target cpu
6074 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ false);
6075 if (!CPU.empty()) {
6076 CmdArgs.push_back(Elt: "-target-cpu");
6077 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
6078 }
6079
6080 RenderTargetOptions(EffectiveTriple: Triple, Args, KernelOrKext, CmdArgs);
6081
6082 // Add clang-cl arguments.
6083 types::ID InputType = Input.getType();
6084 if (D.IsCLMode())
6085 AddClangCLArgs(Args, InputType, CmdArgs);
6086
6087 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6088 llvm::codegenoptions::NoDebugInfo;
6089 DwarfFissionKind DwarfFission = DwarfFissionKind::None;
6090 renderDebugOptions(TC, D, T: RawTriple, Args, InputType, CmdArgs, Output,
6091 DebugInfoKind, DwarfFission);
6092
6093 // Add the split debug info name to the command lines here so we
6094 // can propagate it to the backend.
6095 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6096 (TC.getTriple().isOSBinFormatELF() ||
6097 TC.getTriple().isOSBinFormatWasm() ||
6098 TC.getTriple().isOSBinFormatCOFF()) &&
6099 (isa<AssembleJobAction>(Val: JA) || isa<CompileJobAction>(Val: JA) ||
6100 isa<BackendJobAction>(Val: JA));
6101 if (SplitDWARF) {
6102 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6103 CmdArgs.push_back(Elt: "-split-dwarf-file");
6104 CmdArgs.push_back(Elt: SplitDWARFOut);
6105 if (DwarfFission == DwarfFissionKind::Split) {
6106 CmdArgs.push_back(Elt: "-split-dwarf-output");
6107 CmdArgs.push_back(Elt: SplitDWARFOut);
6108 }
6109 }
6110
6111 // Pass the linker version in use.
6112 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlinker_version_EQ)) {
6113 CmdArgs.push_back(Elt: "-target-linker-version");
6114 CmdArgs.push_back(Elt: A->getValue());
6115 }
6116
6117 // Explicitly error on some things we know we don't support and can't just
6118 // ignore.
6119 if (!Args.hasArg(Ids: options::OPT_fallow_unsupported)) {
6120 Arg *Unsupported;
6121 if (types::isCXX(Id: InputType) && RawTriple.isOSDarwin() &&
6122 TC.getArch() == llvm::Triple::x86) {
6123 if ((Unsupported = Args.getLastArg(Ids: options::OPT_fapple_kext)) ||
6124 (Unsupported = Args.getLastArg(Ids: options::OPT_mkernel)))
6125 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6126 << Unsupported->getOption().getName();
6127 }
6128 // The faltivec option has been superseded by the maltivec option.
6129 if ((Unsupported = Args.getLastArg(Ids: options::OPT_faltivec)))
6130 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_faltivec)
6131 << Unsupported->getOption().getName()
6132 << "please use -maltivec and include altivec.h explicitly";
6133 if ((Unsupported = Args.getLastArg(Ids: options::OPT_fno_altivec)))
6134 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_faltivec)
6135 << Unsupported->getOption().getName() << "please use -mno-altivec";
6136 }
6137
6138 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_v);
6139
6140 if (Args.getLastArg(Ids: options::OPT_H)) {
6141 CmdArgs.push_back(Elt: "-H");
6142 CmdArgs.push_back(Elt: "-sys-header-deps");
6143 }
6144 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fshow_skipped_includes);
6145
6146 if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
6147 CmdArgs.push_back(Elt: "-header-include-file");
6148 CmdArgs.push_back(Elt: !D.CCPrintHeadersFilename.empty()
6149 ? D.CCPrintHeadersFilename.c_str()
6150 : "-");
6151 CmdArgs.push_back(Elt: "-sys-header-deps");
6152 CmdArgs.push_back(Elt: Args.MakeArgString(
6153 Str: "-header-include-format=" +
6154 std::string(headerIncludeFormatKindToString(K: D.CCPrintHeadersFormat))));
6155 CmdArgs.push_back(
6156 Elt: Args.MakeArgString(Str: "-header-include-filtering=" +
6157 std::string(headerIncludeFilteringKindToString(
6158 K: D.CCPrintHeadersFiltering))));
6159 }
6160 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_P);
6161 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_print_ivar_layout);
6162
6163 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6164 CmdArgs.push_back(Elt: "-diagnostic-log-file");
6165 CmdArgs.push_back(Elt: !D.CCLogDiagnosticsFilename.empty()
6166 ? D.CCLogDiagnosticsFilename.c_str()
6167 : "-");
6168 }
6169
6170 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6171 // crashes.
6172 if (D.CCGenDiagnostics)
6173 CmdArgs.push_back(Elt: "-disable-pragma-debug-crash");
6174
6175 // Allow backend to put its diagnostic files in the same place as frontend
6176 // crash diagnostics files.
6177 if (Args.hasArg(Ids: options::OPT_fcrash_diagnostics_dir)) {
6178 StringRef Dir = Args.getLastArgValue(Id: options::OPT_fcrash_diagnostics_dir);
6179 CmdArgs.push_back(Elt: "-mllvm");
6180 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-crash-diagnostics-dir=" + Dir));
6181 }
6182
6183 bool UseSeparateSections = isUseSeparateSections(Triple);
6184
6185 if (Args.hasFlag(Pos: options::OPT_ffunction_sections,
6186 Neg: options::OPT_fno_function_sections, Default: UseSeparateSections)) {
6187 CmdArgs.push_back(Elt: "-ffunction-sections");
6188 }
6189
6190 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbasic_block_address_map,
6191 Ids: options::OPT_fno_basic_block_address_map)) {
6192 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6193 if (A->getOption().matches(ID: options::OPT_fbasic_block_address_map))
6194 A->render(Args, Output&: CmdArgs);
6195 } else {
6196 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6197 << A->getAsString(Args) << TripleStr;
6198 }
6199 }
6200
6201 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbasic_block_sections_EQ)) {
6202 StringRef Val = A->getValue();
6203 if (Val == "labels") {
6204 D.Diag(DiagID: diag::warn_drv_deprecated_arg)
6205 << A->getAsString(Args) << /*hasReplacement=*/true
6206 << "-fbasic-block-address-map";
6207 CmdArgs.push_back(Elt: "-fbasic-block-address-map");
6208 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6209 if (Val != "all" && Val != "none" && !Val.starts_with(Prefix: "list="))
6210 D.Diag(DiagID: diag::err_drv_invalid_value)
6211 << A->getAsString(Args) << A->getValue();
6212 else
6213 A->render(Args, Output&: CmdArgs);
6214 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6215 // "all" is not supported on AArch64 since branch relaxation creates new
6216 // basic blocks for some cross-section branches.
6217 if (Val != "labels" && Val != "none" && !Val.starts_with(Prefix: "list="))
6218 D.Diag(DiagID: diag::err_drv_invalid_value)
6219 << A->getAsString(Args) << A->getValue();
6220 else
6221 A->render(Args, Output&: CmdArgs);
6222 } else if (Triple.isNVPTX()) {
6223 // Do not pass the option to the GPU compilation. We still want it enabled
6224 // for the host-side compilation, so seeing it here is not an error.
6225 } else if (Val != "none") {
6226 // =none is allowed everywhere. It's useful for overriding the option
6227 // and is the same as not specifying the option.
6228 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6229 << A->getAsString(Args) << TripleStr;
6230 }
6231 }
6232
6233 bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
6234 if (Args.hasFlag(Pos: options::OPT_fdata_sections, Neg: options::OPT_fno_data_sections,
6235 Default: UseSeparateSections || HasDefaultDataSections)) {
6236 CmdArgs.push_back(Elt: "-fdata-sections");
6237 }
6238
6239 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_funique_section_names,
6240 Neg: options::OPT_fno_unique_section_names);
6241 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fseparate_named_sections,
6242 Neg: options::OPT_fno_separate_named_sections);
6243 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_funique_internal_linkage_names,
6244 Neg: options::OPT_fno_unique_internal_linkage_names);
6245 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_funique_basic_block_section_names,
6246 Neg: options::OPT_fno_unique_basic_block_section_names);
6247
6248 if (Arg *A = Args.getLastArg(Ids: options::OPT_fsplit_machine_functions,
6249 Ids: options::OPT_fno_split_machine_functions)) {
6250 if (!A->getOption().matches(ID: options::OPT_fno_split_machine_functions)) {
6251 // This codegen pass is only available on x86 and AArch64 ELF targets.
6252 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
6253 A->render(Args, Output&: CmdArgs);
6254 else
6255 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6256 << A->getAsString(Args) << TripleStr;
6257 }
6258 }
6259
6260 if (Arg *A =
6261 Args.getLastArg(Ids: options::OPT_fpartition_static_data_sections,
6262 Ids: options::OPT_fno_partition_static_data_sections)) {
6263 if (!A->getOption().matches(
6264 ID: options::OPT_fno_partition_static_data_sections)) {
6265 // This codegen pass is only available on x86 and AArch64 ELF targets.
6266 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6267 A->render(Args, Output&: CmdArgs);
6268 CmdArgs.push_back(Elt: "-mllvm");
6269 CmdArgs.push_back(Elt: "-memprof-annotate-static-data-prefix");
6270 } else
6271 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6272 << A->getAsString(Args) << TripleStr;
6273 }
6274 }
6275
6276 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_finstrument_functions,
6277 Ids: options::OPT_finstrument_functions_after_inlining,
6278 Ids: options::OPT_finstrument_function_entry_bare);
6279 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconvergent_functions,
6280 Ids: options::OPT_fno_convergent_functions);
6281
6282 // NVPTX doesn't support PGO or coverage
6283 if (!Triple.isNVPTX())
6284 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanArgs&: SanitizeArgs, CmdArgs);
6285
6286 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fclang_abi_compat_EQ);
6287
6288 if (getLastProfileSampleUseArg(Args) &&
6289 Args.hasFlag(Pos: options::OPT_fsample_profile_use_profi,
6290 Neg: options::OPT_fno_sample_profile_use_profi, Default: true)) {
6291 CmdArgs.push_back(Elt: "-mllvm");
6292 CmdArgs.push_back(Elt: "-sample-profile-use-profi");
6293 }
6294
6295 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6296 if (RawTriple.isPS() &&
6297 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs)) {
6298 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6299 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6300 }
6301
6302 // Pass options for controlling the default header search paths.
6303 if (Args.hasArg(Ids: options::OPT_nostdinc)) {
6304 CmdArgs.push_back(Elt: "-nostdsysteminc");
6305 CmdArgs.push_back(Elt: "-nobuiltininc");
6306 } else {
6307 if (Args.hasArg(Ids: options::OPT_nostdlibinc))
6308 CmdArgs.push_back(Elt: "-nostdsysteminc");
6309 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_nostdincxx);
6310 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_nobuiltininc);
6311 }
6312
6313 // Pass the path to compiler resource files.
6314 CmdArgs.push_back(Elt: "-resource-dir");
6315 CmdArgs.push_back(Elt: D.ResourceDir.c_str());
6316
6317 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_working_directory);
6318
6319 // Add preprocessing options like -I, -D, etc. if we are using the
6320 // preprocessor.
6321 //
6322 // FIXME: Support -fpreprocessed
6323 if (types::getPreprocessedType(Id: InputType) != types::TY_INVALID)
6324 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6325
6326 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6327 // that "The compiler can only warn and ignore the option if not recognized".
6328 // When building with ccache, it will pass -D options to clang even on
6329 // preprocessed inputs and configure concludes that -fPIC is not supported.
6330 Args.ClaimAllArgs(Id0: options::OPT_D);
6331
6332 // Warn about ignored options to clang.
6333 for (const Arg *A :
6334 Args.filtered(Ids: options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6335 D.Diag(DiagID: diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6336 A->claim();
6337 }
6338
6339 for (const Arg *A :
6340 Args.filtered(Ids: options::OPT_clang_ignored_legacy_options_Group)) {
6341 D.Diag(DiagID: diag::warn_ignored_clang_option) << A->getAsString(Args);
6342 A->claim();
6343 }
6344
6345 claimNoWarnArgs(Args);
6346
6347 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_R_Group);
6348
6349 for (const Arg *A :
6350 Args.filtered(Ids: options::OPT_W_Group, Ids: options::OPT__SLASH_wd)) {
6351 A->claim();
6352 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6353 unsigned WarningNumber;
6354 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: WarningNumber)) {
6355 D.Diag(DiagID: diag::err_drv_invalid_int_value)
6356 << A->getAsString(Args) << A->getValue();
6357 continue;
6358 }
6359
6360 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6361 CmdArgs.push_back(Elt: Args.MakeArgString(
6362 Str: "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6363 }
6364 continue;
6365 }
6366 A->render(Args, Output&: CmdArgs);
6367 }
6368
6369 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_Wsystem_headers_in_module_EQ);
6370
6371 if (Args.hasFlag(Pos: options::OPT_pedantic, Neg: options::OPT_no_pedantic, Default: false))
6372 CmdArgs.push_back(Elt: "-pedantic");
6373 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pedantic_errors);
6374 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_w);
6375
6376 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_ffixed_point,
6377 Neg: options::OPT_fno_fixed_point);
6378
6379 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_overflow_behavior_types,
6380 Neg: options::OPT_fno_experimental_overflow_behavior_types);
6381
6382 if (Arg *A = Args.getLastArg(Ids: options::OPT_fcxx_abi_EQ))
6383 A->render(Args, Output&: CmdArgs);
6384
6385 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_relative_cxx_abi_vtables,
6386 Ids: options::OPT_fno_experimental_relative_cxx_abi_vtables);
6387
6388 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_omit_vtable_rtti,
6389 Ids: options::OPT_fno_experimental_omit_vtable_rtti);
6390
6391 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffuchsia_api_level_EQ))
6392 A->render(Args, Output&: CmdArgs);
6393
6394 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6395 // (-ansi is equivalent to -std=c89 or -std=c++98).
6396 //
6397 // If a std is supplied, only add -trigraphs if it follows the
6398 // option.
6399 bool ImplyVCPPCVer = false;
6400 bool ImplyVCPPCXXVer = false;
6401 const Arg *Std = Args.getLastArg(Ids: options::OPT_std_EQ, Ids: options::OPT_ansi);
6402 if (Std) {
6403 if (Std->getOption().matches(ID: options::OPT_ansi))
6404 if (types::isCXX(Id: InputType))
6405 CmdArgs.push_back(Elt: "-std=c++98");
6406 else
6407 CmdArgs.push_back(Elt: "-std=c89");
6408 else
6409 Std->render(Args, Output&: CmdArgs);
6410
6411 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6412 if (Arg *A = Args.getLastArg(Ids: options::OPT_std_EQ, Ids: options::OPT_ansi,
6413 Ids: options::OPT_ftrigraphs,
6414 Ids: options::OPT_fno_trigraphs))
6415 if (A != Std)
6416 A->render(Args, Output&: CmdArgs);
6417 } else {
6418 // Honor -std-default.
6419 //
6420 // FIXME: Clang doesn't correctly handle -std= when the input language
6421 // doesn't match. For the time being just ignore this for C++ inputs;
6422 // eventually we want to do all the standard defaulting here instead of
6423 // splitting it between the driver and clang -cc1.
6424 if (!types::isCXX(Id: InputType)) {
6425 if (!Args.hasArg(Ids: options::OPT__SLASH_std)) {
6426 Args.AddAllArgsTranslated(Output&: CmdArgs, Id0: options::OPT_std_default_EQ, Translation: "-std=",
6427 /*Joined=*/true);
6428 } else
6429 ImplyVCPPCVer = true;
6430 }
6431 else if (IsWindowsMSVC)
6432 ImplyVCPPCXXVer = true;
6433
6434 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrigraphs,
6435 Ids: options::OPT_fno_trigraphs);
6436 }
6437
6438 // GCC's behavior for -Wwrite-strings is a bit strange:
6439 // * In C, this "warning flag" changes the types of string literals from
6440 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6441 // for the discarded qualifier.
6442 // * In C++, this is just a normal warning flag.
6443 //
6444 // Implementing this warning correctly in C is hard, so we follow GCC's
6445 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6446 // a non-const char* in C, rather than using this crude hack.
6447 if (!types::isCXX(Id: InputType)) {
6448 // FIXME: This should behave just like a warning flag, and thus should also
6449 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6450 Arg *WriteStrings =
6451 Args.getLastArg(Ids: options::OPT_Wwrite_strings,
6452 Ids: options::OPT_Wno_write_strings, Ids: options::OPT_w);
6453 if (WriteStrings &&
6454 WriteStrings->getOption().matches(ID: options::OPT_Wwrite_strings))
6455 CmdArgs.push_back(Elt: "-fconst-strings");
6456 }
6457
6458 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6459 // during C++ compilation, which it is by default. GCC keeps this define even
6460 // in the presence of '-w', match this behavior bug-for-bug.
6461 if (types::isCXX(Id: InputType) &&
6462 Args.hasFlag(Pos: options::OPT_Wdeprecated, Neg: options::OPT_Wno_deprecated,
6463 Default: true)) {
6464 CmdArgs.push_back(Elt: "-fdeprecated-macro");
6465 }
6466
6467 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6468 if (Arg *Asm = Args.getLastArg(Ids: options::OPT_fasm, Ids: options::OPT_fno_asm)) {
6469 if (Asm->getOption().matches(ID: options::OPT_fasm))
6470 CmdArgs.push_back(Elt: "-fgnu-keywords");
6471 else
6472 CmdArgs.push_back(Elt: "-fno-gnu-keywords");
6473 }
6474
6475 if (!ShouldEnableAutolink(Args, TC, JA))
6476 CmdArgs.push_back(Elt: "-fno-autolink");
6477
6478 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftemplate_depth_EQ);
6479 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foperator_arrow_depth_EQ);
6480 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_depth_EQ);
6481 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_steps_EQ);
6482
6483 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_library);
6484
6485 if (Args.hasArg(Ids: options::OPT_fexperimental_new_constant_interpreter))
6486 CmdArgs.push_back(Elt: "-fexperimental-new-constant-interpreter");
6487
6488 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbracket_depth_EQ)) {
6489 CmdArgs.push_back(Elt: "-fbracket-depth");
6490 CmdArgs.push_back(Elt: A->getValue());
6491 }
6492
6493 if (Arg *A = Args.getLastArg(Ids: options::OPT_Wlarge_by_value_copy_EQ,
6494 Ids: options::OPT_Wlarge_by_value_copy_def)) {
6495 if (A->getNumValues()) {
6496 StringRef bytes = A->getValue();
6497 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-Wlarge-by-value-copy=" + bytes));
6498 } else
6499 CmdArgs.push_back(Elt: "-Wlarge-by-value-copy=64"); // default value
6500 }
6501
6502 if (Args.hasArg(Ids: options::OPT_relocatable_pch))
6503 CmdArgs.push_back(Elt: "-relocatable-pch");
6504
6505 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fcf_runtime_abi_EQ)) {
6506 static const char *kCFABIs[] = {
6507 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6508 };
6509
6510 if (!llvm::is_contained(Range&: kCFABIs, Element: StringRef(A->getValue())))
6511 D.Diag(DiagID: diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6512 else
6513 A->render(Args, Output&: CmdArgs);
6514 }
6515
6516 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_string_class_EQ)) {
6517 CmdArgs.push_back(Elt: "-fconstant-string-class");
6518 CmdArgs.push_back(Elt: A->getValue());
6519 }
6520
6521 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftabstop_EQ)) {
6522 CmdArgs.push_back(Elt: "-ftabstop");
6523 CmdArgs.push_back(Elt: A->getValue());
6524 }
6525
6526 if (Args.hasFlag(Pos: options::OPT_fexperimental_call_graph_section,
6527 Neg: options::OPT_fno_experimental_call_graph_section, Default: false))
6528 CmdArgs.push_back(Elt: "-fexperimental-call-graph-section");
6529
6530 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstack_size_section,
6531 Neg: options::OPT_fno_stack_size_section);
6532
6533 if (Args.hasArg(Ids: options::OPT_fstack_usage)) {
6534 CmdArgs.push_back(Elt: "-stack-usage-file");
6535
6536 if (Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o)) {
6537 SmallString<128> OutputFilename(OutputOpt->getValue());
6538 llvm::sys::path::replace_extension(path&: OutputFilename, extension: "su");
6539 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OutputFilename));
6540 } else
6541 CmdArgs.push_back(
6542 Elt: Args.MakeArgString(Str: Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6543 }
6544
6545 CmdArgs.push_back(Elt: "-ferror-limit");
6546 if (Arg *A = Args.getLastArg(Ids: options::OPT_ferror_limit_EQ))
6547 CmdArgs.push_back(Elt: A->getValue());
6548 else
6549 CmdArgs.push_back(Elt: "19");
6550
6551 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_backtrace_limit_EQ);
6552 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmacro_backtrace_limit_EQ);
6553 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftemplate_backtrace_limit_EQ);
6554 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fspell_checking_limit_EQ);
6555 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fcaret_diagnostics_max_lines_EQ);
6556
6557 // Pass -fmessage-length=.
6558 unsigned MessageLength = 0;
6559 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmessage_length_EQ)) {
6560 StringRef V(A->getValue());
6561 if (V.getAsInteger(Radix: 0, Result&: MessageLength))
6562 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6563 << V << A->getOption().getName();
6564 } else {
6565 // If -fmessage-length=N was not specified, determine whether this is a
6566 // terminal and, if so, implicitly define -fmessage-length appropriately.
6567 MessageLength = llvm::sys::Process::StandardErrColumns();
6568 }
6569 if (MessageLength != 0)
6570 CmdArgs.push_back(
6571 Elt: Args.MakeArgString(Str: "-fmessage-length=" + Twine(MessageLength)));
6572
6573 if (Arg *A = Args.getLastArg(Ids: options::OPT_frandomize_layout_seed_EQ))
6574 CmdArgs.push_back(
6575 Elt: Args.MakeArgString(Str: "-frandomize-layout-seed=" + Twine(A->getValue(N: 0))));
6576
6577 if (Arg *A = Args.getLastArg(Ids: options::OPT_frandomize_layout_seed_file_EQ))
6578 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-frandomize-layout-seed-file=" +
6579 Twine(A->getValue(N: 0))));
6580
6581 // -fvisibility= and -fvisibility-ms-compat are of a piece.
6582 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fvisibility_EQ,
6583 Ids: options::OPT_fvisibility_ms_compat)) {
6584 if (A->getOption().matches(ID: options::OPT_fvisibility_EQ)) {
6585 A->render(Args, Output&: CmdArgs);
6586 } else {
6587 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6588 CmdArgs.push_back(Elt: "-fvisibility=hidden");
6589 CmdArgs.push_back(Elt: "-ftype-visibility=default");
6590 }
6591 } else if (IsOpenMPDevice) {
6592 // When compiling for the OpenMP device we want protected visibility by
6593 // default. This prevents the device from accidentally preempting code on
6594 // the host, makes the system more robust, and improves performance.
6595 CmdArgs.push_back(Elt: "-fvisibility=protected");
6596 }
6597
6598 // PS4/PS5 process these options in addClangTargetOptions.
6599 if (!RawTriple.isPS()) {
6600 if (const Arg *A =
6601 Args.getLastArg(Ids: options::OPT_fvisibility_from_dllstorageclass,
6602 Ids: options::OPT_fno_visibility_from_dllstorageclass)) {
6603 if (A->getOption().matches(
6604 ID: options::OPT_fvisibility_from_dllstorageclass)) {
6605 CmdArgs.push_back(Elt: "-fvisibility-from-dllstorageclass");
6606 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_dllexport_EQ);
6607 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_nodllstorageclass_EQ);
6608 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_externs_dllimport_EQ);
6609 Args.AddLastArg(Output&: CmdArgs,
6610 Ids: options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6611 }
6612 }
6613 }
6614
6615 if (Args.hasFlag(Pos: options::OPT_fvisibility_inlines_hidden,
6616 Neg: options::OPT_fno_visibility_inlines_hidden, Default: false))
6617 CmdArgs.push_back(Elt: "-fvisibility-inlines-hidden");
6618
6619 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_inlines_hidden_static_local_var,
6620 Ids: options::OPT_fno_visibility_inlines_hidden_static_local_var);
6621
6622 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
6623 // -fvisibility-global-new-delete=force-hidden.
6624 if (const Arg *A =
6625 Args.getLastArg(Ids: options::OPT_fvisibility_global_new_delete_hidden)) {
6626 D.Diag(DiagID: diag::warn_drv_deprecated_arg)
6627 << A->getAsString(Args) << /*hasReplacement=*/true
6628 << "-fvisibility-global-new-delete=force-hidden";
6629 }
6630
6631 if (const Arg *A =
6632 Args.getLastArg(Ids: options::OPT_fvisibility_global_new_delete_EQ,
6633 Ids: options::OPT_fvisibility_global_new_delete_hidden)) {
6634 if (A->getOption().matches(ID: options::OPT_fvisibility_global_new_delete_EQ)) {
6635 A->render(Args, Output&: CmdArgs);
6636 } else {
6637 assert(A->getOption().matches(
6638 options::OPT_fvisibility_global_new_delete_hidden));
6639 CmdArgs.push_back(Elt: "-fvisibility-global-new-delete=force-hidden");
6640 }
6641 }
6642
6643 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftlsmodel_EQ);
6644
6645 if (Args.hasFlag(Pos: options::OPT_fnew_infallible,
6646 Neg: options::OPT_fno_new_infallible, Default: false))
6647 CmdArgs.push_back(Elt: "-fnew-infallible");
6648
6649 if (Args.hasFlag(Pos: options::OPT_fno_operator_names,
6650 Neg: options::OPT_foperator_names, Default: false))
6651 CmdArgs.push_back(Elt: "-fno-operator-names");
6652
6653 // Forward -f (flag) options which we can pass directly.
6654 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_femit_all_decls);
6655 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fheinous_gnu_extensions);
6656 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdigraphs, Ids: options::OPT_fno_digraphs);
6657 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fzero_call_used_regs_EQ);
6658 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fraw_string_literals,
6659 Ids: options::OPT_fno_raw_string_literals);
6660
6661 if (Args.hasFlag(Pos: options::OPT_femulated_tls, Neg: options::OPT_fno_emulated_tls,
6662 Default: Triple.hasDefaultEmulatedTLS()))
6663 CmdArgs.push_back(Elt: "-femulated-tls");
6664
6665 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcheck_new,
6666 Neg: options::OPT_fno_check_new);
6667
6668 if (Arg *A = Args.getLastArg(Ids: options::OPT_fzero_call_used_regs_EQ)) {
6669 // FIXME: There's no reason for this to be restricted to X86. The backend
6670 // code needs to be changed to include the appropriate function calls
6671 // automatically.
6672 if (!Triple.isX86() && !Triple.isAArch64())
6673 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6674 << A->getAsString(Args) << TripleStr;
6675 }
6676
6677 // AltiVec-like language extensions aren't relevant for assembling.
6678 if (!isa<PreprocessJobAction>(Val: JA) || Output.getType() != types::TY_PP_Asm)
6679 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fzvector);
6680
6681 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_show_template_tree);
6682 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_elide_type);
6683
6684 // Forward flags for OpenMP. We don't do this if the current action is an
6685 // device offloading action other than OpenMP.
6686 if (Args.hasFlag(Pos: options::OPT_fopenmp, PosAlias: options::OPT_fopenmp_EQ,
6687 Neg: options::OPT_fno_openmp, Default: false) &&
6688 !Args.hasFlag(Pos: options::OPT_foffload_via_llvm,
6689 Neg: options::OPT_fno_offload_via_llvm, Default: false) &&
6690 (JA.isDeviceOffloading(OKind: Action::OFK_None) ||
6691 JA.isDeviceOffloading(OKind: Action::OFK_OpenMP))) {
6692
6693 // Determine if target-fast optimizations should be enabled
6694 bool TargetFastUsed =
6695 Args.hasFlag(Pos: options::OPT_fopenmp_target_fast,
6696 Neg: options::OPT_fno_openmp_target_fast, Default: OFastEnabled);
6697 switch (D.getOpenMPRuntime(Args)) {
6698 case Driver::OMPRT_OMP:
6699 case Driver::OMPRT_IOMP5:
6700 // Clang can generate useful OpenMP code for these two runtime libraries.
6701 CmdArgs.push_back(Elt: "-fopenmp");
6702
6703 // If no option regarding the use of TLS in OpenMP codegeneration is
6704 // given, decide a default based on the target. Otherwise rely on the
6705 // options and pass the right information to the frontend.
6706 if (!Args.hasFlag(Pos: options::OPT_fopenmp_use_tls,
6707 Neg: options::OPT_fnoopenmp_use_tls, /*Default=*/true))
6708 CmdArgs.push_back(Elt: "-fnoopenmp-use-tls");
6709 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fopenmp_simd,
6710 Ids: options::OPT_fno_openmp_simd);
6711 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_enable_irbuilder);
6712 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_version_EQ);
6713 if (!Args.hasFlag(Pos: options::OPT_fopenmp_extensions,
6714 Neg: options::OPT_fno_openmp_extensions, /*Default=*/true))
6715 CmdArgs.push_back(Elt: "-fno-openmp-extensions");
6716 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_cuda_number_of_sm_EQ);
6717 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
6718 Args.AddAllArgs(Output&: CmdArgs,
6719 Id0: options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
6720 if (Args.hasFlag(Pos: options::OPT_fopenmp_optimistic_collapse,
6721 Neg: options::OPT_fno_openmp_optimistic_collapse,
6722 /*Default=*/false))
6723 CmdArgs.push_back(Elt: "-fopenmp-optimistic-collapse");
6724
6725 // When in OpenMP offloading mode with NVPTX target, forward
6726 // cuda-mode flag
6727 if (Args.hasFlag(Pos: options::OPT_fopenmp_cuda_mode,
6728 Neg: options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
6729 CmdArgs.push_back(Elt: "-fopenmp-cuda-mode");
6730
6731 // When in OpenMP offloading mode, enable debugging on the device.
6732 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_target_debug_EQ);
6733 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_debug,
6734 Neg: options::OPT_fno_openmp_target_debug, /*Default=*/false))
6735 CmdArgs.push_back(Elt: "-fopenmp-target-debug");
6736
6737 // When in OpenMP offloading mode, forward assumptions information about
6738 // thread and team counts in the device.
6739 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_teams_oversubscription,
6740 Neg: options::OPT_fno_openmp_assume_teams_oversubscription,
6741 /*Default=*/false))
6742 CmdArgs.push_back(Elt: "-fopenmp-assume-teams-oversubscription");
6743 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_threads_oversubscription,
6744 Neg: options::OPT_fno_openmp_assume_threads_oversubscription,
6745 /*Default=*/false))
6746 CmdArgs.push_back(Elt: "-fopenmp-assume-threads-oversubscription");
6747
6748 // Handle -fopenmp-assume-no-thread-state (implied by target-fast)
6749 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_no_thread_state,
6750 Neg: options::OPT_fno_openmp_assume_no_thread_state,
6751 /*Default=*/TargetFastUsed))
6752 CmdArgs.push_back(Elt: "-fopenmp-assume-no-thread-state");
6753
6754 // Handle -fopenmp-assume-no-nested-parallelism (implied by target-fast)
6755 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_no_nested_parallelism,
6756 Neg: options::OPT_fno_openmp_assume_no_nested_parallelism,
6757 /*Default=*/TargetFastUsed))
6758 CmdArgs.push_back(Elt: "-fopenmp-assume-no-nested-parallelism");
6759
6760 if (Args.hasArg(Ids: options::OPT_fopenmp_offload_mandatory))
6761 CmdArgs.push_back(Elt: "-fopenmp-offload-mandatory");
6762 if (Args.hasArg(Ids: options::OPT_fopenmp_force_usm))
6763 CmdArgs.push_back(Elt: "-fopenmp-force-usm");
6764 break;
6765 default:
6766 // By default, if Clang doesn't know how to generate useful OpenMP code
6767 // for a specific runtime library, we just don't pass the '-fopenmp' flag
6768 // down to the actual compilation.
6769 // FIXME: It would be better to have a mode which *only* omits IR
6770 // generation based on the OpenMP support so that we get consistent
6771 // semantic analysis, etc.
6772 break;
6773 }
6774 } else {
6775 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fopenmp_simd,
6776 Ids: options::OPT_fno_openmp_simd);
6777 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_version_EQ);
6778 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fopenmp_extensions,
6779 Neg: options::OPT_fno_openmp_extensions);
6780 }
6781 // Forward the offload runtime change to code generation, liboffload implies
6782 // new driver. Otherwise, check if we should forward the new driver to change
6783 // offloading code generation.
6784 if (Args.hasFlag(Pos: options::OPT_foffload_via_llvm,
6785 Neg: options::OPT_fno_offload_via_llvm, Default: false)) {
6786 CmdArgs.append(IL: {"--offload-new-driver", "-foffload-via-llvm"});
6787 } else if (Args.hasFlag(Pos: options::OPT_offload_new_driver,
6788 Neg: options::OPT_no_offload_new_driver,
6789 Default: C.getActiveOffloadKinds() != Action::OFK_None)) {
6790 CmdArgs.push_back(Elt: "--offload-new-driver");
6791 }
6792
6793 const XRayArgs &XRay = TC.getXRayArgs(Args);
6794 XRay.addArgs(TC, Args, CmdArgs, InputType);
6795
6796 for (const auto &Filename :
6797 Args.getAllArgValues(Id: options::OPT_fprofile_list_EQ)) {
6798 if (D.getVFS().exists(Path: Filename))
6799 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-list=" + Filename));
6800 else
6801 D.Diag(DiagID: clang::diag::err_drv_no_such_file) << Filename;
6802 }
6803
6804 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpatchable_function_entry_EQ)) {
6805 StringRef S0 = A->getValue(), S = S0;
6806 unsigned Size, Offset = 0;
6807 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
6808 !Triple.isX86() && !Triple.isSystemZ() &&
6809 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
6810 Triple.getArch() == llvm::Triple::ppc64 ||
6811 Triple.getArch() == llvm::Triple::ppc64le)))
6812 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6813 << A->getAsString(Args) << TripleStr;
6814 else if (S.consumeInteger(Radix: 10, Result&: Size) ||
6815 (!S.empty() &&
6816 (!S.consume_front(Prefix: ",") || S.consumeInteger(Radix: 10, Result&: Offset))) ||
6817 (!S.empty() && (!S.consume_front(Prefix: ",") || S.empty())))
6818 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6819 << S0 << A->getOption().getName();
6820 else if (Size < Offset)
6821 D.Diag(DiagID: diag::err_drv_unsupported_fpatchable_function_entry_argument);
6822 else {
6823 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getSpelling() + Twine(Size)));
6824 CmdArgs.push_back(Elt: Args.MakeArgString(
6825 Str: "-fpatchable-function-entry-offset=" + Twine(Offset)));
6826 if (!S.empty())
6827 CmdArgs.push_back(
6828 Elt: Args.MakeArgString(Str: "-fpatchable-function-entry-section=" + S));
6829 }
6830 }
6831
6832 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fms_hotpatch);
6833
6834 if (Args.hasArg(Ids: options::OPT_fms_secure_hotpatch_functions_file))
6835 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fms_secure_hotpatch_functions_file);
6836
6837 for (const auto &A :
6838 Args.getAllArgValues(Id: options::OPT_fms_secure_hotpatch_functions_list))
6839 CmdArgs.push_back(
6840 Elt: Args.MakeArgString(Str: "-fms-secure-hotpatch-functions-list=" + Twine(A)));
6841
6842 if (TC.SupportsProfiling()) {
6843 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pg);
6844
6845 llvm::Triple::ArchType Arch = TC.getArch();
6846 if (Arg *A = Args.getLastArg(Ids: options::OPT_mfentry)) {
6847 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
6848 A->render(Args, Output&: CmdArgs);
6849 else
6850 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6851 << A->getAsString(Args) << TripleStr;
6852 }
6853 if (Arg *A = Args.getLastArg(Ids: options::OPT_mnop_mcount)) {
6854 if (Arch == llvm::Triple::systemz)
6855 A->render(Args, Output&: CmdArgs);
6856 else
6857 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6858 << A->getAsString(Args) << TripleStr;
6859 }
6860 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrecord_mcount)) {
6861 if (Arch == llvm::Triple::systemz)
6862 A->render(Args, Output&: CmdArgs);
6863 else
6864 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6865 << A->getAsString(Args) << TripleStr;
6866 }
6867 }
6868
6869 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_pg)) {
6870 if (TC.getTriple().isOSzOS()) {
6871 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6872 << A->getAsString(Args) << TripleStr;
6873 }
6874 }
6875 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_p)) {
6876 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
6877 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6878 << A->getAsString(Args) << TripleStr;
6879 }
6880 }
6881 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_p, Ids: options::OPT_pg)) {
6882 if (A->getOption().matches(ID: options::OPT_p)) {
6883 A->claim();
6884 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(Ids: options::OPT_pg))
6885 CmdArgs.push_back(Elt: "-pg");
6886 }
6887 }
6888
6889 // Reject AIX-specific link options on other targets.
6890 if (!TC.getTriple().isOSAIX()) {
6891 for (const Arg *A : Args.filtered(Ids: options::OPT_b, Ids: options::OPT_K,
6892 Ids: options::OPT_mxcoff_build_id_EQ)) {
6893 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6894 << A->getSpelling() << TripleStr;
6895 }
6896 }
6897
6898 if (Args.getLastArg(Ids: options::OPT_fapple_kext) ||
6899 (Args.hasArg(Ids: options::OPT_mkernel) && types::isCXX(Id: InputType)))
6900 CmdArgs.push_back(Elt: "-fapple-kext");
6901
6902 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_altivec_src_compat);
6903 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_flax_vector_conversions_EQ);
6904 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fobjc_sender_dependent_dispatch);
6905 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_print_source_range_info);
6906 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_parseable_fixits);
6907 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report);
6908 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report_EQ);
6909 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report_json);
6910 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrapv);
6911 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_malign_double);
6912 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_temp_file);
6913
6914 if (const char *Name = C.getTimeTraceFile(JA: &JA)) {
6915 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ftime-trace=" + Twine(Name)));
6916 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_trace_granularity_EQ);
6917 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_trace_verbose);
6918 }
6919
6920 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftrapv_handler_EQ)) {
6921 CmdArgs.push_back(Elt: "-ftrapv-handler");
6922 CmdArgs.push_back(Elt: A->getValue());
6923 }
6924
6925 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrap_function_EQ);
6926
6927 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
6928 // clang and flang.
6929 renderCommonIntegerOverflowOptions(Args, CmdArgs);
6930
6931 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffinite_loops,
6932 Ids: options::OPT_fno_finite_loops);
6933
6934 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fwritable_strings);
6935 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_funroll_loops,
6936 Ids: options::OPT_fno_unroll_loops);
6937 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_floop_interchange,
6938 Ids: options::OPT_fno_loop_interchange);
6939 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_loop_fusion,
6940 Neg: options::OPT_fno_experimental_loop_fusion);
6941
6942 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fstrict_flex_arrays_EQ);
6943
6944 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pthread);
6945
6946 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mspeculative_load_hardening,
6947 Neg: options::OPT_mno_speculative_load_hardening);
6948
6949 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
6950 RenderSCPOptions(TC, Args, CmdArgs);
6951 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
6952
6953 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fswift_async_fp_EQ);
6954
6955 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mstackrealign,
6956 Neg: options::OPT_mno_stackrealign);
6957
6958 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mstack_alignment)) {
6959 StringRef Value = A->getValue();
6960 int64_t Alignment = 0;
6961 if (Value.getAsInteger(Radix: 10, Result&: Alignment) || Alignment < 0)
6962 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6963 << Value << A->getOption().getName();
6964 else if (Alignment & (Alignment - 1))
6965 D.Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
6966 << A->getAsString(Args) << Value;
6967 else
6968 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mstack-alignment=" + Value));
6969 }
6970
6971 if (Args.hasArg(Ids: options::OPT_mstack_probe_size)) {
6972 StringRef Size = Args.getLastArgValue(Id: options::OPT_mstack_probe_size);
6973
6974 if (!Size.empty())
6975 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mstack-probe-size=" + Size));
6976 else
6977 CmdArgs.push_back(Elt: "-mstack-probe-size=0");
6978 }
6979
6980 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_mstack_arg_probe,
6981 Neg: options::OPT_mno_stack_arg_probe);
6982
6983 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrestrict_it,
6984 Ids: options::OPT_mno_restrict_it)) {
6985 if (A->getOption().matches(ID: options::OPT_mrestrict_it)) {
6986 CmdArgs.push_back(Elt: "-mllvm");
6987 CmdArgs.push_back(Elt: "-arm-restrict-it");
6988 } else {
6989 CmdArgs.push_back(Elt: "-mllvm");
6990 CmdArgs.push_back(Elt: "-arm-default-it");
6991 }
6992 }
6993
6994 // Forward -cl options to -cc1
6995 RenderOpenCLOptions(Args, CmdArgs, InputType);
6996
6997 // Forward hlsl options to -cc1
6998 RenderHLSLOptions(Args, CmdArgs, InputType);
6999
7000 // Forward OpenACC options to -cc1
7001 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
7002
7003 if (IsHIP) {
7004 if (Args.hasFlag(Pos: options::OPT_fhip_new_launch_api,
7005 Neg: options::OPT_fno_hip_new_launch_api, Default: true))
7006 CmdArgs.push_back(Elt: "-fhip-new-launch-api");
7007 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgpu_allow_device_init,
7008 Neg: options::OPT_fno_gpu_allow_device_init);
7009 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_hipstdpar);
7010 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_hipstdpar_interpose_alloc);
7011 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fhip_kernel_arg_name,
7012 Neg: options::OPT_fno_hip_kernel_arg_name);
7013 }
7014
7015 if (IsCuda || IsHIP) {
7016 if (IsRDCMode)
7017 CmdArgs.push_back(Elt: "-fgpu-rdc");
7018 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgpu_defer_diag,
7019 Neg: options::OPT_fno_gpu_defer_diag);
7020 if (Args.hasFlag(Pos: options::OPT_fgpu_exclude_wrong_side_overloads,
7021 Neg: options::OPT_fno_gpu_exclude_wrong_side_overloads,
7022 Default: false)) {
7023 CmdArgs.push_back(Elt: "-fgpu-exclude-wrong-side-overloads");
7024 CmdArgs.push_back(Elt: "-fgpu-defer-diag");
7025 }
7026 }
7027
7028 // Forward --no-offloadlib to -cc1.
7029 if (!Args.hasFlag(Pos: options::OPT_offloadlib, Neg: options::OPT_no_offloadlib, Default: true))
7030 CmdArgs.push_back(Elt: "--no-offloadlib");
7031
7032 if (Arg *A = Args.getLastArg(Ids: options::OPT_fcf_protection_EQ)) {
7033 CmdArgs.push_back(
7034 Elt: Args.MakeArgString(Str: Twine("-fcf-protection=") + A->getValue()));
7035
7036 if (Arg *SA = Args.getLastArg(Ids: options::OPT_mcf_branch_label_scheme_EQ))
7037 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-mcf-branch-label-scheme=") +
7038 SA->getValue()));
7039 } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
7040 // Emit IBT endbr64 instructions by default
7041 CmdArgs.push_back(Elt: "-fcf-protection=branch");
7042 // jump-table can generate indirect jumps, which are not permitted
7043 CmdArgs.push_back(Elt: "-fno-jump-tables");
7044 }
7045
7046 if (Arg *A = Args.getLastArg(Ids: options::OPT_mfunction_return_EQ))
7047 CmdArgs.push_back(
7048 Elt: Args.MakeArgString(Str: Twine("-mfunction-return=") + A->getValue()));
7049
7050 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mindirect_branch_cs_prefix);
7051
7052 // Forward -f options with positive and negative forms; we translate these by
7053 // hand. Do not propagate PGO options to the GPU-side compilations as the
7054 // profile info is for the host-side compilation only.
7055 if (!(IsCudaDevice || IsHIPDevice)) {
7056 if (Arg *A = getLastProfileSampleUseArg(Args)) {
7057 auto *PGOArg = Args.getLastArg(
7058 Ids: options::OPT_fprofile_generate, Ids: options::OPT_fprofile_generate_EQ,
7059 Ids: options::OPT_fcs_profile_generate,
7060 Ids: options::OPT_fcs_profile_generate_EQ, Ids: options::OPT_fprofile_use,
7061 Ids: options::OPT_fprofile_use_EQ);
7062 if (PGOArg)
7063 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
7064 << "SampleUse with PGO options";
7065
7066 StringRef fname = A->getValue();
7067 if (!llvm::sys::fs::exists(Path: fname))
7068 D.Diag(DiagID: diag::err_drv_no_such_file) << fname;
7069 else
7070 A->render(Args, Output&: CmdArgs);
7071 }
7072 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fprofile_remapping_file_EQ);
7073
7074 if (Args.hasFlag(Pos: options::OPT_fpseudo_probe_for_profiling,
7075 Neg: options::OPT_fno_pseudo_probe_for_profiling, Default: false)) {
7076 CmdArgs.push_back(Elt: "-fpseudo-probe-for-profiling");
7077 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7078 // off.
7079 if (Args.hasFlag(Pos: options::OPT_funique_internal_linkage_names,
7080 Neg: options::OPT_fno_unique_internal_linkage_names, Default: true))
7081 CmdArgs.push_back(Elt: "-funique-internal-linkage-names");
7082 }
7083 }
7084 RenderBuiltinOptions(TC, T: RawTriple, Args, CmdArgs);
7085
7086 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_sane_operator_new,
7087 Neg: options::OPT_fno_assume_sane_operator_new);
7088
7089 if (Args.hasFlag(Pos: options::OPT_fapinotes, Neg: options::OPT_fno_apinotes, Default: false))
7090 CmdArgs.push_back(Elt: "-fapinotes");
7091 if (Args.hasFlag(Pos: options::OPT_fapinotes_modules,
7092 Neg: options::OPT_fno_apinotes_modules, Default: false))
7093 CmdArgs.push_back(Elt: "-fapinotes-modules");
7094 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fapinotes_swift_version);
7095
7096 if (Args.hasFlag(Pos: options::OPT_fswift_version_independent_apinotes,
7097 Neg: options::OPT_fno_swift_version_independent_apinotes, Default: false))
7098 CmdArgs.push_back(Elt: "-fswift-version-independent-apinotes");
7099
7100 // -fblocks=0 is default.
7101 if (Args.hasFlag(Pos: options::OPT_fblocks, Neg: options::OPT_fno_blocks,
7102 Default: TC.IsBlocksDefault()) ||
7103 (Args.hasArg(Ids: options::OPT_fgnu_runtime) &&
7104 Args.hasArg(Ids: options::OPT_fobjc_nonfragile_abi) &&
7105 !Args.hasArg(Ids: options::OPT_fno_blocks))) {
7106 CmdArgs.push_back(Elt: "-fblocks");
7107
7108 if (!Args.hasArg(Ids: options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7109 CmdArgs.push_back(Elt: "-fblocks-runtime-optional");
7110 }
7111
7112 // -fencode-extended-block-signature=1 is default.
7113 if (TC.IsEncodeExtendedBlockSignatureDefault())
7114 CmdArgs.push_back(Elt: "-fencode-extended-block-signature");
7115
7116 if (Args.hasFlag(Pos: options::OPT_fcoro_aligned_allocation,
7117 Neg: options::OPT_fno_coro_aligned_allocation, Default: false) &&
7118 types::isCXX(Id: InputType))
7119 CmdArgs.push_back(Elt: "-fcoro-aligned-allocation");
7120
7121 if (Args.hasFlag(Pos: options::OPT_fdefer_ts, Neg: options::OPT_fno_defer_ts,
7122 /*Default=*/false))
7123 CmdArgs.push_back(Elt: "-fdefer-ts");
7124
7125 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdouble_square_bracket_attributes,
7126 Ids: options::OPT_fno_double_square_bracket_attributes);
7127
7128 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_faccess_control,
7129 Neg: options::OPT_fno_access_control);
7130 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_felide_constructors,
7131 Neg: options::OPT_fno_elide_constructors);
7132
7133 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7134
7135 if (KernelOrKext || (types::isCXX(Id: InputType) &&
7136 (RTTIMode == ToolChain::RM_Disabled)))
7137 CmdArgs.push_back(Elt: "-fno-rtti");
7138
7139 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7140 if (Args.hasFlag(Pos: options::OPT_fshort_enums, Neg: options::OPT_fno_short_enums,
7141 Default: TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7142 CmdArgs.push_back(Elt: "-fshort-enums");
7143
7144 RenderCharacterOptions(Args, T: AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7145
7146 // -fuse-cxa-atexit is default.
7147 if (!Args.hasFlag(
7148 Pos: options::OPT_fuse_cxa_atexit, Neg: options::OPT_fno_use_cxa_atexit,
7149 Default: !RawTriple.isOSAIX() &&
7150 (!RawTriple.isOSWindows() ||
7151 RawTriple.isWindowsCygwinEnvironment()) &&
7152 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7153 RawTriple.hasEnvironment())) ||
7154 KernelOrKext)
7155 CmdArgs.push_back(Elt: "-fno-use-cxa-atexit");
7156
7157 if (Args.hasFlag(Pos: options::OPT_fregister_global_dtors_with_atexit,
7158 Neg: options::OPT_fno_register_global_dtors_with_atexit,
7159 Default: RawTriple.isOSDarwin() && !KernelOrKext))
7160 CmdArgs.push_back(Elt: "-fregister-global-dtors-with-atexit");
7161
7162 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fuse_line_directives,
7163 Neg: options::OPT_fno_use_line_directives);
7164
7165 // -fno-minimize-whitespace is default.
7166 if (Args.hasFlag(Pos: options::OPT_fminimize_whitespace,
7167 Neg: options::OPT_fno_minimize_whitespace, Default: false)) {
7168 types::ID InputType = Inputs[0].getType();
7169 if (!isDerivedFromC(Id: InputType))
7170 D.Diag(DiagID: diag::err_drv_opt_unsupported_input_type)
7171 << "-fminimize-whitespace" << types::getTypeName(Id: InputType);
7172 CmdArgs.push_back(Elt: "-fminimize-whitespace");
7173 }
7174
7175 // -fno-keep-system-includes is default.
7176 if (Args.hasFlag(Pos: options::OPT_fkeep_system_includes,
7177 Neg: options::OPT_fno_keep_system_includes, Default: false)) {
7178 types::ID InputType = Inputs[0].getType();
7179 if (!isDerivedFromC(Id: InputType))
7180 D.Diag(DiagID: diag::err_drv_opt_unsupported_input_type)
7181 << "-fkeep-system-includes" << types::getTypeName(Id: InputType);
7182 CmdArgs.push_back(Elt: "-fkeep-system-includes");
7183 }
7184
7185 // -fms-extensions=0 is default.
7186 if (Args.hasFlag(Pos: options::OPT_fms_extensions, Neg: options::OPT_fno_ms_extensions,
7187 Default: IsWindowsMSVC || IsUEFI))
7188 CmdArgs.push_back(Elt: "-fms-extensions");
7189
7190 // -fms-compatibility=0 is default.
7191 bool IsMSVCCompat = Args.hasFlag(
7192 Pos: options::OPT_fms_compatibility, Neg: options::OPT_fno_ms_compatibility,
7193 Default: (IsWindowsMSVC && Args.hasFlag(Pos: options::OPT_fms_extensions,
7194 Neg: options::OPT_fno_ms_extensions, Default: true)));
7195 if (IsMSVCCompat) {
7196 CmdArgs.push_back(Elt: "-fms-compatibility");
7197 if (!types::isCXX(Id: Input.getType()) &&
7198 Args.hasArg(Ids: options::OPT_fms_define_stdc))
7199 CmdArgs.push_back(Elt: "-fms-define-stdc");
7200 }
7201
7202 // -fms-anonymous-structs is disabled by default.
7203 // Determine whether to enable Microsoft named anonymous struct/union support.
7204 // This implements "last flag wins" semantics for -fms-anonymous-structs,
7205 // where the feature can be:
7206 // - Explicitly enabled via -fms-anonymous-structs.
7207 // - Explicitly disabled via fno-ms-anonymous-structs
7208 // - Implicitly enabled via -fms-extensions or -fms-compatibility
7209 // - Implicitly disabled via -fno-ms-extensions or -fno-ms-compatibility
7210 //
7211 // When multiple relevent options are present, the last option on the command
7212 // line takes precedence. This allows users to selectively override implicit
7213 // enablement. Examples:
7214 // -fms-extensions -fno-ms-anonymous-structs -> disabled (explicit override)
7215 // -fno-ms-anonymous-structs -fms-extensions -> enabled (last flag wins)
7216 auto MSAnonymousStructsOptionToUseOrNull =
7217 [](const ArgList &Args) -> const char * {
7218 const char *Option = nullptr;
7219 constexpr const char *Enable = "-fms-anonymous-structs";
7220 constexpr const char *Disable = "-fno-ms-anonymous-structs";
7221
7222 // Iterate through all arguments in order to implement "last flag wins".
7223 for (const Arg *A : Args) {
7224 switch (A->getOption().getID()) {
7225 case options::OPT_fms_anonymous_structs:
7226 A->claim();
7227 Option = Enable;
7228 break;
7229 case options::OPT_fno_ms_anonymous_structs:
7230 A->claim();
7231 Option = Disable;
7232 break;
7233 // Each of -fms-extensions and -fms-compatibility implicitly enables the
7234 // feature.
7235 case options::OPT_fms_extensions:
7236 case options::OPT_fms_compatibility:
7237 Option = Enable;
7238 break;
7239 // Each of -fno-ms-extensions and -fno-ms-compatibility implicitly
7240 // disables the feature.
7241 case options::OPT_fno_ms_extensions:
7242 case options::OPT_fno_ms_compatibility:
7243 Option = Disable;
7244 break;
7245 default:
7246 break;
7247 }
7248 }
7249 return Option;
7250 };
7251
7252 // Only pass a flag to CC1 if a relevant option was seen
7253 if (auto MSAnonOpt = MSAnonymousStructsOptionToUseOrNull(Args))
7254 CmdArgs.push_back(Elt: MSAnonOpt);
7255
7256 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7257 Args.hasArg(Ids: options::OPT_fms_runtime_lib_EQ))
7258 ProcessVSRuntimeLibrary(TC: getToolChain(), Args, CmdArgs);
7259
7260 // Handle -fgcc-version, if present.
7261 VersionTuple GNUCVer;
7262 if (Arg *A = Args.getLastArg(Ids: options::OPT_fgnuc_version_EQ)) {
7263 // Check that the version has 1 to 3 components and the minor and patch
7264 // versions fit in two decimal digits.
7265 StringRef Val = A->getValue();
7266 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7267 bool Invalid = GNUCVer.tryParse(string: Val);
7268 unsigned Minor = GNUCVer.getMinor().value_or(u: 0);
7269 unsigned Patch = GNUCVer.getSubminor().value_or(u: 0);
7270 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7271 D.Diag(DiagID: diag::err_drv_invalid_value)
7272 << A->getAsString(Args) << A->getValue();
7273 }
7274 } else if (!IsMSVCCompat) {
7275 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7276 GNUCVer = VersionTuple(4, 2, 1);
7277 }
7278 if (!GNUCVer.empty()) {
7279 CmdArgs.push_back(
7280 Elt: Args.MakeArgString(Str: "-fgnuc-version=" + GNUCVer.getAsString()));
7281 }
7282
7283 VersionTuple MSVT = TC.computeMSVCVersion(D: &D, Args);
7284 if (!MSVT.empty())
7285 CmdArgs.push_back(
7286 Elt: Args.MakeArgString(Str: "-fms-compatibility-version=" + MSVT.getAsString()));
7287
7288 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7289 if (ImplyVCPPCVer) {
7290 StringRef LanguageStandard;
7291 if (const Arg *StdArg = Args.getLastArg(Ids: options::OPT__SLASH_std)) {
7292 Std = StdArg;
7293 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7294 .Case(S: "c11", Value: "-std=c11")
7295 .Case(S: "c17", Value: "-std=c17")
7296 // If you add cases below for spellings that are
7297 // not in LangStandards.def, update
7298 // TransferableCommand::tryParseStdArg() in
7299 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7300 // to match.
7301 // TODO: add c23 when MSVC supports it.
7302 .Case(S: "clatest", Value: "-std=c23")
7303 .Default(Value: "");
7304 if (LanguageStandard.empty())
7305 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
7306 << StdArg->getAsString(Args);
7307 }
7308 CmdArgs.push_back(Elt: LanguageStandard.data());
7309 }
7310 if (ImplyVCPPCXXVer) {
7311 StringRef LanguageStandard;
7312 if (const Arg *StdArg = Args.getLastArg(Ids: options::OPT__SLASH_std)) {
7313 Std = StdArg;
7314 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7315 .Case(S: "c++14", Value: "-std=c++14")
7316 .Case(S: "c++17", Value: "-std=c++17")
7317 .Case(S: "c++20", Value: "-std=c++20")
7318 // If you add cases below for spellings that are
7319 // not in LangStandards.def, update
7320 // TransferableCommand::tryParseStdArg() in
7321 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7322 // to match.
7323 // TODO add c++23 and c++26 when MSVC supports it.
7324 .Case(S: "c++23preview", Value: "-std=c++23")
7325 .Case(S: "c++latest", Value: "-std=c++26")
7326 .Default(Value: "");
7327 if (LanguageStandard.empty())
7328 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
7329 << StdArg->getAsString(Args);
7330 }
7331
7332 if (LanguageStandard.empty()) {
7333 if (IsMSVC2015Compatible)
7334 LanguageStandard = "-std=c++14";
7335 else
7336 LanguageStandard = "-std=c++11";
7337 }
7338
7339 CmdArgs.push_back(Elt: LanguageStandard.data());
7340 }
7341
7342 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fborland_extensions,
7343 Neg: options::OPT_fno_borland_extensions);
7344
7345 // -fno-declspec is default, except for PS4/PS5.
7346 if (Args.hasFlag(Pos: options::OPT_fdeclspec, Neg: options::OPT_fno_declspec,
7347 Default: RawTriple.isPS()))
7348 CmdArgs.push_back(Elt: "-fdeclspec");
7349 else if (Args.hasArg(Ids: options::OPT_fno_declspec))
7350 CmdArgs.push_back(Elt: "-fno-declspec"); // Explicitly disabling __declspec.
7351
7352 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7353 // than 19.
7354 if (!Args.hasFlag(Pos: options::OPT_fthreadsafe_statics,
7355 Neg: options::OPT_fno_threadsafe_statics,
7356 Default: !types::isOpenCL(Id: InputType) &&
7357 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7358 CmdArgs.push_back(Elt: "-fno-threadsafe-statics");
7359
7360 if (!Args.hasFlag(Pos: options::OPT_fms_tls_guards, Neg: options::OPT_fno_ms_tls_guards,
7361 Default: true))
7362 CmdArgs.push_back(Elt: "-fno-ms-tls-guards");
7363
7364 // Add -fno-assumptions, if it was specified.
7365 if (!Args.hasFlag(Pos: options::OPT_fassumptions, Neg: options::OPT_fno_assumptions,
7366 Default: true))
7367 CmdArgs.push_back(Elt: "-fno-assumptions");
7368
7369 // -fgnu-keywords default varies depending on language; only pass if
7370 // specified.
7371 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fgnu_keywords,
7372 Ids: options::OPT_fno_gnu_keywords);
7373
7374 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgnu89_inline,
7375 Neg: options::OPT_fno_gnu89_inline);
7376
7377 const Arg *InlineArg = Args.getLastArg(Ids: options::OPT_finline_functions,
7378 Ids: options::OPT_finline_hint_functions,
7379 Ids: options::OPT_fno_inline_functions);
7380 if (Arg *A = Args.getLastArg(Ids: options::OPT_finline, Ids: options::OPT_fno_inline)) {
7381 if (A->getOption().matches(ID: options::OPT_fno_inline))
7382 A->render(Args, Output&: CmdArgs);
7383 } else if (InlineArg) {
7384 InlineArg->render(Args, Output&: CmdArgs);
7385 }
7386
7387 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_finline_max_stacksize_EQ);
7388
7389 // FIXME: Find a better way to determine whether we are in C++20.
7390 bool HaveCxx20 =
7391 Std &&
7392 (Std->containsValue(Value: "c++2a") || Std->containsValue(Value: "gnu++2a") ||
7393 Std->containsValue(Value: "c++20") || Std->containsValue(Value: "gnu++20") ||
7394 Std->containsValue(Value: "c++2b") || Std->containsValue(Value: "gnu++2b") ||
7395 Std->containsValue(Value: "c++23") || Std->containsValue(Value: "gnu++23") ||
7396 Std->containsValue(Value: "c++23preview") || Std->containsValue(Value: "c++2c") ||
7397 Std->containsValue(Value: "gnu++2c") || Std->containsValue(Value: "c++26") ||
7398 Std->containsValue(Value: "gnu++26") || Std->containsValue(Value: "c++latest") ||
7399 Std->containsValue(Value: "gnu++latest"));
7400 bool HaveModules =
7401 RenderModulesOptions(C, D, Args, Input, Output, HaveStd20: HaveCxx20, CmdArgs);
7402
7403 // -fdelayed-template-parsing is default when targeting MSVC.
7404 // Many old Windows SDK versions require this to parse.
7405 //
7406 // According to
7407 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7408 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7409 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7410 // not enable -fdelayed-template-parsing by default after C++20.
7411 //
7412 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7413 // able to disable this by default at some point.
7414 if (Args.hasFlag(Pos: options::OPT_fdelayed_template_parsing,
7415 Neg: options::OPT_fno_delayed_template_parsing,
7416 Default: IsWindowsMSVC && !HaveCxx20)) {
7417 if (HaveCxx20)
7418 D.Diag(DiagID: clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7419
7420 CmdArgs.push_back(Elt: "-fdelayed-template-parsing");
7421 }
7422
7423 if (Args.hasFlag(Pos: options::OPT_fpch_validate_input_files_content,
7424 Neg: options::OPT_fno_pch_validate_input_files_content, Default: false))
7425 CmdArgs.push_back(Elt: "-fvalidate-ast-input-files-content");
7426 if (Args.hasFlag(Pos: options::OPT_fpch_instantiate_templates,
7427 Neg: options::OPT_fno_pch_instantiate_templates, Default: false))
7428 CmdArgs.push_back(Elt: "-fpch-instantiate-templates");
7429 if (Args.hasFlag(Pos: options::OPT_fpch_codegen, Neg: options::OPT_fno_pch_codegen,
7430 Default: false))
7431 CmdArgs.push_back(Elt: "-fmodules-codegen");
7432 if (Args.hasFlag(Pos: options::OPT_fpch_debuginfo, Neg: options::OPT_fno_pch_debuginfo,
7433 Default: false))
7434 CmdArgs.push_back(Elt: "-fmodules-debuginfo");
7435
7436 ObjCRuntime Runtime = AddObjCRuntimeArgs(args: Args, inputs: Inputs, cmdArgs&: CmdArgs, rewrite: rewriteKind);
7437 RenderObjCOptions(TC, D, T: RawTriple, Args, Runtime, InferCovariantReturns: rewriteKind != RK_None,
7438 Input, CmdArgs);
7439
7440 if (types::isObjC(Id: Input.getType()) &&
7441 Args.hasFlag(Pos: options::OPT_fobjc_encode_cxx_class_template_spec,
7442 Neg: options::OPT_fno_objc_encode_cxx_class_template_spec,
7443 Default: !Runtime.isNeXTFamily()))
7444 CmdArgs.push_back(Elt: "-fobjc-encode-cxx-class-template-spec");
7445
7446 if (Args.hasFlag(Pos: options::OPT_fapplication_extension,
7447 Neg: options::OPT_fno_application_extension, Default: false))
7448 CmdArgs.push_back(Elt: "-fapplication-extension");
7449
7450 // Handle GCC-style exception args.
7451 bool EH = false;
7452 if (!C.getDriver().IsCLMode())
7453 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, objcRuntime: Runtime, CmdArgs);
7454
7455 // Handle exception personalities
7456 Arg *A = Args.getLastArg(
7457 Ids: options::OPT_fsjlj_exceptions, Ids: options::OPT_fseh_exceptions,
7458 Ids: options::OPT_fdwarf_exceptions, Ids: options::OPT_fwasm_exceptions);
7459 if (A) {
7460 const Option &Opt = A->getOption();
7461 if (Opt.matches(ID: options::OPT_fsjlj_exceptions))
7462 CmdArgs.push_back(Elt: "-exception-model=sjlj");
7463 if (Opt.matches(ID: options::OPT_fseh_exceptions))
7464 CmdArgs.push_back(Elt: "-exception-model=seh");
7465 if (Opt.matches(ID: options::OPT_fdwarf_exceptions))
7466 CmdArgs.push_back(Elt: "-exception-model=dwarf");
7467 if (Opt.matches(ID: options::OPT_fwasm_exceptions))
7468 CmdArgs.push_back(Elt: "-exception-model=wasm");
7469 } else {
7470 switch (TC.GetExceptionModel(Args)) {
7471 default:
7472 break;
7473 case llvm::ExceptionHandling::DwarfCFI:
7474 CmdArgs.push_back(Elt: "-exception-model=dwarf");
7475 break;
7476 case llvm::ExceptionHandling::SjLj:
7477 CmdArgs.push_back(Elt: "-exception-model=sjlj");
7478 break;
7479 case llvm::ExceptionHandling::WinEH:
7480 CmdArgs.push_back(Elt: "-exception-model=seh");
7481 break;
7482 }
7483 }
7484
7485 // Unwind v2 (epilog) information for x64 Windows.
7486 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_winx64_eh_unwindv2);
7487
7488 // C++ "sane" operator new.
7489 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_sane_operator_new,
7490 Neg: options::OPT_fno_assume_sane_operator_new);
7491
7492 // -fassume-unique-vtables is on by default.
7493 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_unique_vtables,
7494 Neg: options::OPT_fno_assume_unique_vtables);
7495
7496 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
7497 // by default.
7498 Args.addLastArg(Output&: CmdArgs, Ids: options::OPT_fsized_deallocation,
7499 Ids: options::OPT_fno_sized_deallocation);
7500
7501 // -faligned-allocation is on by default in C++17 onwards and otherwise off
7502 // by default.
7503 if (Arg *A = Args.getLastArg(Ids: options::OPT_faligned_allocation,
7504 Ids: options::OPT_fno_aligned_allocation,
7505 Ids: options::OPT_faligned_new_EQ)) {
7506 if (A->getOption().matches(ID: options::OPT_fno_aligned_allocation))
7507 CmdArgs.push_back(Elt: "-fno-aligned-allocation");
7508 else
7509 CmdArgs.push_back(Elt: "-faligned-allocation");
7510 }
7511
7512 // The default new alignment can be specified using a dedicated option or via
7513 // a GCC-compatible option that also turns on aligned allocation.
7514 if (Arg *A = Args.getLastArg(Ids: options::OPT_fnew_alignment_EQ,
7515 Ids: options::OPT_faligned_new_EQ))
7516 CmdArgs.push_back(
7517 Elt: Args.MakeArgString(Str: Twine("-fnew-alignment=") + A->getValue()));
7518
7519 // -fconstant-cfstrings is default, and may be subject to argument translation
7520 // on Darwin.
7521 if (!Args.hasFlag(Pos: options::OPT_fconstant_cfstrings,
7522 Neg: options::OPT_fno_constant_cfstrings, Default: true) ||
7523 !Args.hasFlag(Pos: options::OPT_mconstant_cfstrings,
7524 Neg: options::OPT_mno_constant_cfstrings, Default: true))
7525 CmdArgs.push_back(Elt: "-fno-constant-cfstrings");
7526
7527 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fpascal_strings,
7528 Neg: options::OPT_fno_pascal_strings);
7529
7530 // Honor -fpack-struct= and -fpack-struct, if given. Note that
7531 // -fno-pack-struct doesn't apply to -fpack-struct=.
7532 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpack_struct_EQ)) {
7533 std::string PackStructStr = "-fpack-struct=";
7534 PackStructStr += A->getValue();
7535 CmdArgs.push_back(Elt: Args.MakeArgString(Str: PackStructStr));
7536 } else if (Args.hasFlag(Pos: options::OPT_fpack_struct,
7537 Neg: options::OPT_fno_pack_struct, Default: false)) {
7538 CmdArgs.push_back(Elt: "-fpack-struct=1");
7539 }
7540
7541 // Handle -fmax-type-align=N and -fno-type-align
7542 bool SkipMaxTypeAlign = Args.hasArg(Ids: options::OPT_fno_max_type_align);
7543 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmax_type_align_EQ)) {
7544 if (!SkipMaxTypeAlign) {
7545 std::string MaxTypeAlignStr = "-fmax-type-align=";
7546 MaxTypeAlignStr += A->getValue();
7547 CmdArgs.push_back(Elt: Args.MakeArgString(Str: MaxTypeAlignStr));
7548 }
7549 } else if (RawTriple.isOSDarwin()) {
7550 if (!SkipMaxTypeAlign) {
7551 std::string MaxTypeAlignStr = "-fmax-type-align=16";
7552 CmdArgs.push_back(Elt: Args.MakeArgString(Str: MaxTypeAlignStr));
7553 }
7554 }
7555
7556 if (!Args.hasFlag(Pos: options::OPT_Qy, Neg: options::OPT_Qn, Default: true))
7557 CmdArgs.push_back(Elt: "-Qn");
7558
7559 // -fno-common is the default, set -fcommon only when that flag is set.
7560 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcommon, Neg: options::OPT_fno_common);
7561
7562 // -fsigned-bitfields is default, and clang doesn't yet support
7563 // -funsigned-bitfields.
7564 if (!Args.hasFlag(Pos: options::OPT_fsigned_bitfields,
7565 Neg: options::OPT_funsigned_bitfields, Default: true))
7566 D.Diag(DiagID: diag::warn_drv_clang_unsupported)
7567 << Args.getLastArg(Ids: options::OPT_funsigned_bitfields)->getAsString(Args);
7568
7569 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
7570 if (!Args.hasFlag(Pos: options::OPT_ffor_scope, Neg: options::OPT_fno_for_scope, Default: true))
7571 D.Diag(DiagID: diag::err_drv_clang_unsupported)
7572 << Args.getLastArg(Ids: options::OPT_fno_for_scope)->getAsString(Args);
7573
7574 // -finput_charset=UTF-8 is default. Reject others
7575 if (Arg *inputCharset = Args.getLastArg(Ids: options::OPT_finput_charset_EQ)) {
7576 StringRef value = inputCharset->getValue();
7577 if (!value.equals_insensitive(RHS: "utf-8"))
7578 D.Diag(DiagID: diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
7579 << value;
7580 }
7581
7582 // -fexec_charset=UTF-8 is default. Reject others
7583 if (Arg *execCharset = Args.getLastArg(Ids: options::OPT_fexec_charset_EQ)) {
7584 StringRef value = execCharset->getValue();
7585 if (!value.equals_insensitive(RHS: "utf-8"))
7586 D.Diag(DiagID: diag::err_drv_invalid_value) << execCharset->getAsString(Args)
7587 << value;
7588 }
7589
7590 RenderDiagnosticsOptions(D, Args, CmdArgs);
7591
7592 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fasm_blocks,
7593 Neg: options::OPT_fno_asm_blocks);
7594
7595 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fgnu_inline_asm,
7596 Neg: options::OPT_fno_gnu_inline_asm);
7597
7598 handleVectorizeLoopsArgs(Args, CmdArgs);
7599 handleVectorizeSLPArgs(Args, CmdArgs);
7600
7601 StringRef VecWidth = parseMPreferVectorWidthOption(Diags&: D.getDiags(), Args);
7602 if (!VecWidth.empty())
7603 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mprefer-vector-width=" + VecWidth));
7604
7605 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fshow_overloads_EQ);
7606 Args.AddLastArg(Output&: CmdArgs,
7607 Ids: options::OPT_fsanitize_undefined_strip_path_components_EQ);
7608
7609 // -fdollars-in-identifiers default varies depending on platform and
7610 // language; only pass if specified.
7611 if (Arg *A = Args.getLastArg(Ids: options::OPT_fdollars_in_identifiers,
7612 Ids: options::OPT_fno_dollars_in_identifiers)) {
7613 if (A->getOption().matches(ID: options::OPT_fdollars_in_identifiers))
7614 CmdArgs.push_back(Elt: "-fdollars-in-identifiers");
7615 else
7616 CmdArgs.push_back(Elt: "-fno-dollars-in-identifiers");
7617 }
7618
7619 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fapple_pragma_pack,
7620 Neg: options::OPT_fno_apple_pragma_pack);
7621
7622 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
7623 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
7624 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
7625
7626 bool RewriteImports = Args.hasFlag(Pos: options::OPT_frewrite_imports,
7627 Neg: options::OPT_fno_rewrite_imports, Default: false);
7628 if (RewriteImports)
7629 CmdArgs.push_back(Elt: "-frewrite-imports");
7630
7631 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdirectives_only,
7632 Neg: options::OPT_fno_directives_only);
7633
7634 // Enable rewrite includes if the user's asked for it or if we're generating
7635 // diagnostics.
7636 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
7637 // nice to enable this when doing a crashdump for modules as well.
7638 if (Args.hasFlag(Pos: options::OPT_frewrite_includes,
7639 Neg: options::OPT_fno_rewrite_includes, Default: false) ||
7640 (C.isForDiagnostics() && !HaveModules))
7641 CmdArgs.push_back(Elt: "-frewrite-includes");
7642
7643 if (Args.hasFlag(Pos: options::OPT_fzos_extensions,
7644 Neg: options::OPT_fno_zos_extensions, Default: false))
7645 CmdArgs.push_back(Elt: "-fzos-extensions");
7646 else if (Args.hasArg(Ids: options::OPT_fno_zos_extensions))
7647 CmdArgs.push_back(Elt: "-fno-zos-extensions");
7648
7649 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
7650 if (Arg *A = Args.getLastArg(Ids: options::OPT_traditional,
7651 Ids: options::OPT_traditional_cpp)) {
7652 if (isa<PreprocessJobAction>(Val: JA))
7653 CmdArgs.push_back(Elt: "-traditional-cpp");
7654 else
7655 D.Diag(DiagID: diag::err_drv_clang_unsupported) << A->getAsString(Args);
7656 }
7657
7658 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dM);
7659 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dD);
7660 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dI);
7661
7662 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmax_tokens_EQ);
7663
7664 // Handle serialized diagnostics.
7665 if (Arg *A = Args.getLastArg(Ids: options::OPT__serialize_diags)) {
7666 CmdArgs.push_back(Elt: "-serialize-diagnostic-file");
7667 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getValue()));
7668 }
7669
7670 if (Args.hasArg(Ids: options::OPT_fretain_comments_from_system_headers))
7671 CmdArgs.push_back(Elt: "-fretain-comments-from-system-headers");
7672
7673 if (Arg *A = Args.getLastArg(Ids: options::OPT_fextend_variable_liveness_EQ)) {
7674 A->render(Args, Output&: CmdArgs);
7675 } else if (Arg *A = Args.getLastArg(Ids: options::OPT_O_Group);
7676 A && A->containsValue(Value: "g")) {
7677 // Set -fextend-variable-liveness=all by default at -Og.
7678 CmdArgs.push_back(Elt: "-fextend-variable-liveness=all");
7679 }
7680
7681 // Forward -fcomment-block-commands to -cc1.
7682 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fcomment_block_commands);
7683 // Forward -fparse-all-comments to -cc1.
7684 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fparse_all_comments);
7685
7686 // Turn -fplugin=name.so into -load name.so
7687 for (const Arg *A : Args.filtered(Ids: options::OPT_fplugin_EQ)) {
7688 CmdArgs.push_back(Elt: "-load");
7689 CmdArgs.push_back(Elt: A->getValue());
7690 A->claim();
7691 }
7692
7693 // Turn -fplugin-arg-pluginname-key=value into
7694 // -plugin-arg-pluginname key=value
7695 // GCC has an actual plugin_argument struct with key/value pairs that it
7696 // passes to its plugins, but we don't, so just pass it on as-is.
7697 //
7698 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
7699 // argument key are allowed to contain dashes. GCC therefore only
7700 // allows dashes in the key. We do the same.
7701 for (const Arg *A : Args.filtered(Ids: options::OPT_fplugin_arg)) {
7702 auto ArgValue = StringRef(A->getValue());
7703 auto FirstDashIndex = ArgValue.find(C: '-');
7704 StringRef PluginName = ArgValue.substr(Start: 0, N: FirstDashIndex);
7705 StringRef Arg = ArgValue.substr(Start: FirstDashIndex + 1);
7706
7707 A->claim();
7708 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
7709 if (PluginName.empty()) {
7710 D.Diag(DiagID: diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
7711 } else {
7712 D.Diag(DiagID: diag::warn_drv_missing_plugin_arg)
7713 << PluginName << A->getAsString(Args);
7714 }
7715 continue;
7716 }
7717
7718 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-plugin-arg-") + PluginName));
7719 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Arg));
7720 }
7721
7722 // Forward -fpass-plugin=name.so to -cc1.
7723 for (const Arg *A : Args.filtered(Ids: options::OPT_fpass_plugin_EQ)) {
7724 CmdArgs.push_back(
7725 Elt: Args.MakeArgString(Str: Twine("-fpass-plugin=") + A->getValue()));
7726 A->claim();
7727 }
7728
7729 // Forward --vfsoverlay to -cc1.
7730 for (const Arg *A : Args.filtered(Ids: options::OPT_vfsoverlay)) {
7731 CmdArgs.push_back(Elt: "--vfsoverlay");
7732 CmdArgs.push_back(Elt: A->getValue());
7733 A->claim();
7734 }
7735
7736 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fsafe_buffer_usage_suggestions,
7737 Neg: options::OPT_fno_safe_buffer_usage_suggestions);
7738
7739 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_late_parse_attributes,
7740 Neg: options::OPT_fno_experimental_late_parse_attributes);
7741
7742 if (Args.hasFlag(Pos: options::OPT_funique_source_file_names,
7743 Neg: options::OPT_fno_unique_source_file_names, Default: false)) {
7744 if (Arg *A = Args.getLastArg(Ids: options::OPT_unique_source_file_identifier_EQ))
7745 A->render(Args, Output&: CmdArgs);
7746 else
7747 CmdArgs.push_back(Elt: Args.MakeArgString(
7748 Str: Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
7749 }
7750
7751 if (Args.hasFlag(
7752 Pos: options::OPT_fexperimental_allow_pointer_field_protection_attr,
7753 Neg: options::OPT_fno_experimental_allow_pointer_field_protection_attr,
7754 Default: false) ||
7755 Args.hasFlag(Pos: options::OPT_fexperimental_pointer_field_protection_abi,
7756 Neg: options::OPT_fno_experimental_pointer_field_protection_abi,
7757 Default: false))
7758 CmdArgs.push_back(Elt: "-fexperimental-allow-pointer-field-protection-attr");
7759
7760 if (!IsCudaDevice) {
7761 Args.addOptInFlag(
7762 Output&: CmdArgs, Pos: options::OPT_fexperimental_pointer_field_protection_abi,
7763 Neg: options::OPT_fno_experimental_pointer_field_protection_abi);
7764 Args.addOptInFlag(
7765 Output&: CmdArgs, Pos: options::OPT_fexperimental_pointer_field_protection_tagged,
7766 Neg: options::OPT_fno_experimental_pointer_field_protection_tagged);
7767 }
7768
7769 // Setup statistics file output.
7770 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
7771 if (!StatsFile.empty()) {
7772 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-stats-file=") + StatsFile));
7773 if (D.CCPrintInternalStats)
7774 CmdArgs.push_back(Elt: "-stats-file-append");
7775 }
7776
7777 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
7778 // parser.
7779 for (auto Arg : Args.filtered(Ids: options::OPT_Xclang)) {
7780 Arg->claim();
7781 // -finclude-default-header flag is for preprocessor,
7782 // do not pass it to other cc1 commands when save-temps is enabled
7783 if (C.getDriver().isSaveTempsEnabled() &&
7784 !isa<PreprocessJobAction>(Val: JA)) {
7785 if (StringRef(Arg->getValue()) == "-finclude-default-header")
7786 continue;
7787 }
7788 CmdArgs.push_back(Elt: Arg->getValue());
7789 }
7790 for (const Arg *A : Args.filtered(Ids: options::OPT_mllvm)) {
7791 A->claim();
7792
7793 // We translate this by hand to the -cc1 argument, since nightly test uses
7794 // it and developers have been trained to spell it with -mllvm. Both
7795 // spellings are now deprecated and should be removed.
7796 if (StringRef(A->getValue(N: 0)) == "-disable-llvm-optzns") {
7797 CmdArgs.push_back(Elt: "-disable-llvm-optzns");
7798 } else {
7799 A->render(Args, Output&: CmdArgs);
7800 }
7801 }
7802
7803 // This needs to run after -Xclang argument forwarding to pick up the target
7804 // features enabled through -Xclang -target-feature flags.
7805 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
7806
7807 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_falloc_token_max_EQ);
7808
7809#if CLANG_ENABLE_CIR
7810 // Forward -mmlir arguments to to the MLIR option parser.
7811 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
7812 A->claim();
7813 A->render(Args, CmdArgs);
7814 }
7815#endif // CLANG_ENABLE_CIR
7816
7817 // With -save-temps, we want to save the unoptimized bitcode output from the
7818 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
7819 // by the frontend.
7820 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
7821 // has slightly different breakdown between stages.
7822 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
7823 // pristine IR generated by the frontend. Ideally, a new compile action should
7824 // be added so both IR can be captured.
7825 if ((C.getDriver().isSaveTempsEnabled() ||
7826 JA.isHostOffloading(OKind: Action::OFK_OpenMP)) &&
7827 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
7828 isa<CompileJobAction>(Val: JA))
7829 CmdArgs.push_back(Elt: "-disable-llvm-passes");
7830
7831 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_undef);
7832
7833 const char *Exec = D.getClangProgramPath();
7834
7835 // Optionally embed the -cc1 level arguments into the debug info or a
7836 // section, for build analysis.
7837 // Also record command line arguments into the debug info if
7838 // -grecord-gcc-switches options is set on.
7839 // By default, -gno-record-gcc-switches is set on and no recording.
7840 auto GRecordSwitches = false;
7841 auto FRecordSwitches = false;
7842 if (shouldRecordCommandLine(TC, Args, FRecordCommandLine&: FRecordSwitches, GRecordCommandLine&: GRecordSwitches)) {
7843 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
7844 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
7845 CmdArgs.push_back(Elt: "-dwarf-debug-flags");
7846 CmdArgs.push_back(Elt: FlagsArgString);
7847 }
7848 if (FRecordSwitches) {
7849 CmdArgs.push_back(Elt: "-record-command-line");
7850 CmdArgs.push_back(Elt: FlagsArgString);
7851 }
7852 }
7853
7854 // Host-side offloading compilation receives all device-side outputs. Include
7855 // them in the host compilation depending on the target. If the host inputs
7856 // are not empty we use the new-driver scheme, otherwise use the old scheme.
7857 if ((IsCuda || IsHIP) && CudaDeviceInput) {
7858 CmdArgs.push_back(Elt: "-fcuda-include-gpubinary");
7859 CmdArgs.push_back(Elt: CudaDeviceInput->getFilename());
7860 } else if (!HostOffloadingInputs.empty()) {
7861 if ((IsCuda || IsHIP) && !IsRDCMode) {
7862 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
7863 CmdArgs.push_back(Elt: "-fcuda-include-gpubinary");
7864 CmdArgs.push_back(Elt: HostOffloadingInputs.front().getFilename());
7865 } else {
7866 for (const InputInfo Input : HostOffloadingInputs)
7867 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fembed-offload-object=" +
7868 TC.getInputFilename(Input)));
7869 }
7870 }
7871
7872 if (IsCuda) {
7873 if (Args.hasFlag(Pos: options::OPT_fcuda_short_ptr,
7874 Neg: options::OPT_fno_cuda_short_ptr, Default: false))
7875 CmdArgs.push_back(Elt: "-fcuda-short-ptr");
7876 }
7877
7878 if (IsCuda || IsHIP) {
7879 // Determine the original source input.
7880 const Action *SourceAction = &JA;
7881 while (SourceAction->getKind() != Action::InputClass) {
7882 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7883 SourceAction = SourceAction->getInputs()[0];
7884 }
7885 auto CUID = cast<InputAction>(Val: SourceAction)->getId();
7886 if (!CUID.empty())
7887 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-cuid=") + Twine(CUID)));
7888
7889 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
7890 // be overriden by -fno-gpu-approx-transcendentals.
7891 bool UseApproxTranscendentals = Args.hasFlag(
7892 Pos: options::OPT_ffast_math, Neg: options::OPT_fno_fast_math, Default: false);
7893 if (Args.hasFlag(Pos: options::OPT_fgpu_approx_transcendentals,
7894 Neg: options::OPT_fno_gpu_approx_transcendentals,
7895 Default: UseApproxTranscendentals))
7896 CmdArgs.push_back(Elt: "-fgpu-approx-transcendentals");
7897 } else {
7898 Args.claimAllArgs(Ids: options::OPT_fgpu_approx_transcendentals,
7899 Ids: options::OPT_fno_gpu_approx_transcendentals);
7900 }
7901
7902 if (IsHIP) {
7903 CmdArgs.push_back(Elt: "-fcuda-allow-variadic-functions");
7904 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fgpu_default_stream_EQ);
7905 }
7906
7907 Args.AddAllArgs(Output&: CmdArgs,
7908 Id0: options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
7909
7910 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foffload_uniform_block,
7911 Ids: options::OPT_fno_offload_uniform_block);
7912
7913 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foffload_implicit_host_device_templates,
7914 Ids: options::OPT_fno_offload_implicit_host_device_templates);
7915
7916 if (IsCudaDevice || IsHIPDevice) {
7917 StringRef InlineThresh =
7918 Args.getLastArgValue(Id: options::OPT_fgpu_inline_threshold_EQ);
7919 if (!InlineThresh.empty()) {
7920 std::string ArgStr =
7921 std::string("-inline-threshold=") + InlineThresh.str();
7922 CmdArgs.append(IL: {"-mllvm", Args.MakeArgStringRef(Str: ArgStr)});
7923 }
7924 }
7925
7926 if (IsHIPDevice)
7927 Args.addOptOutFlag(Output&: CmdArgs,
7928 Pos: options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
7929 Neg: options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
7930
7931 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
7932 // to specify the result of the compile phase on the host, so the meaningful
7933 // device declarations can be identified. Also, -fopenmp-is-target-device is
7934 // passed along to tell the frontend that it is generating code for a device,
7935 // so that only the relevant declarations are emitted.
7936 if (IsOpenMPDevice) {
7937 CmdArgs.push_back(Elt: "-fopenmp-is-target-device");
7938 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
7939 if (Args.hasArg(Ids: options::OPT_foffload_via_llvm))
7940 CmdArgs.push_back(Elt: "-fcuda-is-device");
7941
7942 if (OpenMPDeviceInput) {
7943 CmdArgs.push_back(Elt: "-fopenmp-host-ir-file-path");
7944 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OpenMPDeviceInput->getFilename()));
7945 }
7946 }
7947
7948 if (Triple.isAMDGPU()) {
7949 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
7950
7951 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_munsafe_fp_atomics,
7952 Neg: options::OPT_mno_unsafe_fp_atomics);
7953 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_mamdgpu_ieee,
7954 Neg: options::OPT_mno_amdgpu_ieee);
7955 }
7956
7957 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
7958
7959 if (Args.hasFlag(Pos: options::OPT_fdevirtualize_speculatively,
7960 Neg: options::OPT_fno_devirtualize_speculatively,
7961 /*Default value*/ Default: false))
7962 CmdArgs.push_back(Elt: "-fdevirtualize-speculatively");
7963
7964 bool VirtualFunctionElimination =
7965 Args.hasFlag(Pos: options::OPT_fvirtual_function_elimination,
7966 Neg: options::OPT_fno_virtual_function_elimination, Default: false);
7967 if (VirtualFunctionElimination) {
7968 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
7969 // in the future).
7970 if (LTOMode != LTOK_Full)
7971 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
7972 << "-fvirtual-function-elimination"
7973 << "-flto=full";
7974
7975 CmdArgs.push_back(Elt: "-fvirtual-function-elimination");
7976 }
7977
7978 // VFE requires whole-program-vtables, and enables it by default.
7979 bool WholeProgramVTables = Args.hasFlag(
7980 Pos: options::OPT_fwhole_program_vtables,
7981 Neg: options::OPT_fno_whole_program_vtables, Default: VirtualFunctionElimination);
7982 if (VirtualFunctionElimination && !WholeProgramVTables) {
7983 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
7984 << "-fno-whole-program-vtables"
7985 << "-fvirtual-function-elimination";
7986 }
7987
7988 if (WholeProgramVTables) {
7989 // PS4 uses the legacy LTO API, which does not support this feature in
7990 // ThinLTO mode.
7991 bool IsPS4 = getToolChain().getTriple().isPS4();
7992
7993 // Check if we passed LTO options but they were suppressed because this is a
7994 // device offloading action, or we passed device offload LTO options which
7995 // were suppressed because this is not the device offload action.
7996 // Check if we are using PS4 in regular LTO mode.
7997 // Otherwise, issue an error.
7998
7999 auto OtherLTOMode =
8000 IsDeviceOffloadAction ? D.getLTOMode() : D.getOffloadLTOMode();
8001 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
8002
8003 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
8004 (IsPS4 && !UnifiedLTO && (D.getLTOMode() != LTOK_Full)))
8005 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
8006 << "-fwhole-program-vtables"
8007 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
8008
8009 // Propagate -fwhole-program-vtables if this is an LTO compile.
8010 if (IsUsingLTO)
8011 CmdArgs.push_back(Elt: "-fwhole-program-vtables");
8012 }
8013
8014 bool DefaultsSplitLTOUnit =
8015 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
8016 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
8017 (!Triple.isPS4() && UnifiedLTO);
8018 bool SplitLTOUnit =
8019 Args.hasFlag(Pos: options::OPT_fsplit_lto_unit,
8020 Neg: options::OPT_fno_split_lto_unit, Default: DefaultsSplitLTOUnit);
8021 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
8022 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
8023 << "-fsanitize=cfi";
8024 if (SplitLTOUnit)
8025 CmdArgs.push_back(Elt: "-fsplit-lto-unit");
8026
8027 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffat_lto_objects,
8028 Ids: options::OPT_fno_fat_lto_objects)) {
8029 if (IsUsingLTO && A->getOption().matches(ID: options::OPT_ffat_lto_objects)) {
8030 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
8031 if (!Triple.isOSBinFormatELF() && !Triple.isOSBinFormatCOFF()) {
8032 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
8033 << A->getAsString(Args) << TC.getTripleString();
8034 }
8035 CmdArgs.push_back(Elt: Args.MakeArgString(
8036 Str: Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
8037 CmdArgs.push_back(Elt: "-flto-unit");
8038 CmdArgs.push_back(Elt: "-ffat-lto-objects");
8039 A->render(Args, Output&: CmdArgs);
8040 }
8041 }
8042
8043 renderGlobalISelOptions(D, Args, CmdArgs, Triple);
8044
8045 if (Arg *A = Args.getLastArg(Ids: options::OPT_fforce_enable_int128,
8046 Ids: options::OPT_fno_force_enable_int128)) {
8047 if (A->getOption().matches(ID: options::OPT_fforce_enable_int128))
8048 CmdArgs.push_back(Elt: "-fforce-enable-int128");
8049 }
8050
8051 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_static_consts,
8052 Neg: options::OPT_fno_keep_static_consts);
8053 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_persistent_storage_variables,
8054 Neg: options::OPT_fno_keep_persistent_storage_variables);
8055 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcomplete_member_pointers,
8056 Neg: options::OPT_fno_complete_member_pointers);
8057 if (Arg *A = Args.getLastArg(Ids: options::OPT_cxx_static_destructors_EQ))
8058 A->render(Args, Output&: CmdArgs);
8059
8060 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
8061
8062 addOutlineAtomicsArgs(D, TC: getToolChain(), Args, CmdArgs, Triple);
8063
8064 if (Triple.isAArch64() &&
8065 (Args.hasArg(Ids: options::OPT_mno_fmv) ||
8066 (Triple.isAndroid() && Triple.isAndroidVersionLT(Major: 23)) ||
8067 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
8068 // Disable Function Multiversioning on AArch64 target.
8069 CmdArgs.push_back(Elt: "-target-feature");
8070 CmdArgs.push_back(Elt: "-fmv");
8071 }
8072
8073 if (Args.hasFlag(Pos: options::OPT_faddrsig, Neg: options::OPT_fno_addrsig,
8074 Default: (TC.getTriple().isOSBinFormatELF() ||
8075 TC.getTriple().isOSBinFormatCOFF()) &&
8076 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
8077 !TC.getTriple().isOSNetBSD() &&
8078 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
8079 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
8080 CmdArgs.push_back(Elt: "-faddrsig");
8081
8082 const bool HasDefaultDwarf2CFIASM =
8083 (Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
8084 (EH || UnwindTables || AsyncUnwindTables ||
8085 DebugInfoKind != llvm::codegenoptions::NoDebugInfo);
8086 if (Args.hasFlag(Pos: options::OPT_fdwarf2_cfi_asm,
8087 Neg: options::OPT_fno_dwarf2_cfi_asm, Default: HasDefaultDwarf2CFIASM))
8088 CmdArgs.push_back(Elt: "-fdwarf2-cfi-asm");
8089
8090 if (Arg *A = Args.getLastArg(Ids: options::OPT_fsymbol_partition_EQ)) {
8091 std::string Str = A->getAsString(Args);
8092 if (!TC.getTriple().isOSBinFormatELF())
8093 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
8094 << Str << TC.getTripleString();
8095 CmdArgs.push_back(Elt: Args.MakeArgString(Str));
8096 }
8097
8098 // Add the "-o out -x type src.c" flags last. This is done primarily to make
8099 // the -cc1 command easier to edit when reproducing compiler crashes.
8100 if (Output.getType() == types::TY_Dependencies) {
8101 // Handled with other dependency code.
8102 } else if (Output.isFilename()) {
8103 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
8104 Output.getType() == clang::driver::types::TY_IFS) {
8105 SmallString<128> OutputFilename(Output.getFilename());
8106 llvm::sys::path::replace_extension(path&: OutputFilename, extension: "ifs");
8107 CmdArgs.push_back(Elt: "-o");
8108 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OutputFilename));
8109 } else {
8110 CmdArgs.push_back(Elt: "-o");
8111 CmdArgs.push_back(Elt: Output.getFilename());
8112 }
8113 } else {
8114 assert(Output.isNothing() && "Invalid output.");
8115 }
8116
8117 addDashXForInput(Args, Input, CmdArgs);
8118
8119 ArrayRef<InputInfo> FrontendInputs = Input;
8120 if (IsExtractAPI)
8121 FrontendInputs = ExtractAPIInputs;
8122 else if (Input.isNothing())
8123 FrontendInputs = {};
8124
8125 for (const InputInfo &Input : FrontendInputs) {
8126 if (Input.isFilename())
8127 CmdArgs.push_back(Elt: Input.getFilename());
8128 else
8129 Input.getInputArg().renderAsInput(Args, Output&: CmdArgs);
8130 }
8131
8132 if (D.CC1Main && !D.CCGenDiagnostics) {
8133 // Invoke the CC1 directly in this process
8134 C.addCommand(C: std::make_unique<CC1Command>(
8135 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8136 args: Output, args: D.getPrependArg()));
8137 } else {
8138 C.addCommand(C: std::make_unique<Command>(
8139 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8140 args: Output, args: D.getPrependArg()));
8141 }
8142
8143 // Make the compile command echo its inputs for /showFilenames.
8144 if (Output.getType() == types::TY_Object &&
8145 Args.hasFlag(Pos: options::OPT__SLASH_showFilenames,
8146 Neg: options::OPT__SLASH_showFilenames_, Default: false)) {
8147 C.getJobs().getJobs().back()->PrintInputFilenames = true;
8148 }
8149
8150 if (Arg *A = Args.getLastArg(Ids: options::OPT_pg))
8151 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8152 !Args.hasArg(Ids: options::OPT_mfentry))
8153 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8154 << A->getAsString(Args);
8155
8156 // Claim some arguments which clang supports automatically.
8157
8158 // -fpch-preprocess is used with gcc to add a special marker in the output to
8159 // include the PCH file.
8160 Args.ClaimAllArgs(Id0: options::OPT_fpch_preprocess);
8161
8162 // Claim some arguments which clang doesn't support, but we don't
8163 // care to warn the user about.
8164 Args.ClaimAllArgs(Id0: options::OPT_clang_ignored_f_Group);
8165 Args.ClaimAllArgs(Id0: options::OPT_clang_ignored_m_Group);
8166
8167 // Disable warnings for clang -E -emit-llvm foo.c
8168 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
8169}
8170
8171Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8172 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8173 // as it is for other tools. Some operations on a Tool actually test
8174 // whether that tool is Clang based on the Tool's Name as a string.
8175 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8176
8177Clang::~Clang() {}
8178
8179/// Add options related to the Objective-C runtime/ABI.
8180///
8181/// Returns true if the runtime is non-fragile.
8182ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8183 const InputInfoList &inputs,
8184 ArgStringList &cmdArgs,
8185 RewriteKind rewriteKind) const {
8186 // Look for the controlling runtime option.
8187 Arg *runtimeArg =
8188 args.getLastArg(Ids: options::OPT_fnext_runtime, Ids: options::OPT_fgnu_runtime,
8189 Ids: options::OPT_fobjc_runtime_EQ);
8190
8191 // Just forward -fobjc-runtime= to the frontend. This supercedes
8192 // options about fragility.
8193 if (runtimeArg &&
8194 runtimeArg->getOption().matches(ID: options::OPT_fobjc_runtime_EQ)) {
8195 ObjCRuntime runtime;
8196 StringRef value = runtimeArg->getValue();
8197 if (runtime.tryParse(input: value)) {
8198 getToolChain().getDriver().Diag(DiagID: diag::err_drv_unknown_objc_runtime)
8199 << value;
8200 }
8201 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8202 (runtime.getVersion() >= VersionTuple(2, 0)))
8203 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8204 !getToolChain().getTriple().isOSBinFormatCOFF()) {
8205 getToolChain().getDriver().Diag(
8206 DiagID: diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8207 << runtime.getVersion().getMajor();
8208 }
8209
8210 runtimeArg->render(Args: args, Output&: cmdArgs);
8211 return runtime;
8212 }
8213
8214 // Otherwise, we'll need the ABI "version". Version numbers are
8215 // slightly confusing for historical reasons:
8216 // 1 - Traditional "fragile" ABI
8217 // 2 - Non-fragile ABI, version 1
8218 // 3 - Non-fragile ABI, version 2
8219 unsigned objcABIVersion = 1;
8220 // If -fobjc-abi-version= is present, use that to set the version.
8221 if (Arg *abiArg = args.getLastArg(Ids: options::OPT_fobjc_abi_version_EQ)) {
8222 StringRef value = abiArg->getValue();
8223 if (value == "1")
8224 objcABIVersion = 1;
8225 else if (value == "2")
8226 objcABIVersion = 2;
8227 else if (value == "3")
8228 objcABIVersion = 3;
8229 else
8230 getToolChain().getDriver().Diag(DiagID: diag::err_drv_clang_unsupported) << value;
8231 } else {
8232 // Otherwise, determine if we are using the non-fragile ABI.
8233 bool nonFragileABIIsDefault =
8234 (rewriteKind == RK_NonFragile ||
8235 (rewriteKind == RK_None &&
8236 getToolChain().IsObjCNonFragileABIDefault()));
8237 if (args.hasFlag(Pos: options::OPT_fobjc_nonfragile_abi,
8238 Neg: options::OPT_fno_objc_nonfragile_abi,
8239 Default: nonFragileABIIsDefault)) {
8240// Determine the non-fragile ABI version to use.
8241#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8242 unsigned nonFragileABIVersion = 1;
8243#else
8244 unsigned nonFragileABIVersion = 2;
8245#endif
8246
8247 if (Arg *abiArg =
8248 args.getLastArg(Ids: options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8249 StringRef value = abiArg->getValue();
8250 if (value == "1")
8251 nonFragileABIVersion = 1;
8252 else if (value == "2")
8253 nonFragileABIVersion = 2;
8254 else
8255 getToolChain().getDriver().Diag(DiagID: diag::err_drv_clang_unsupported)
8256 << value;
8257 }
8258
8259 objcABIVersion = 1 + nonFragileABIVersion;
8260 } else {
8261 objcABIVersion = 1;
8262 }
8263 }
8264
8265 // We don't actually care about the ABI version other than whether
8266 // it's non-fragile.
8267 bool isNonFragile = objcABIVersion != 1;
8268
8269 // If we have no runtime argument, ask the toolchain for its default runtime.
8270 // However, the rewriter only really supports the Mac runtime, so assume that.
8271 ObjCRuntime runtime;
8272 if (!runtimeArg) {
8273 switch (rewriteKind) {
8274 case RK_None:
8275 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8276 break;
8277 case RK_Fragile:
8278 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8279 break;
8280 case RK_NonFragile:
8281 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8282 break;
8283 }
8284
8285 // -fnext-runtime
8286 } else if (runtimeArg->getOption().matches(ID: options::OPT_fnext_runtime)) {
8287 // On Darwin, make this use the default behavior for the toolchain.
8288 if (getToolChain().getTriple().isOSDarwin()) {
8289 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8290
8291 // Otherwise, build for a generic macosx port.
8292 } else {
8293 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8294 }
8295
8296 // -fgnu-runtime
8297 } else {
8298 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8299 // Legacy behaviour is to target the gnustep runtime if we are in
8300 // non-fragile mode or the GCC runtime in fragile mode.
8301 if (isNonFragile)
8302 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8303 else
8304 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8305 }
8306
8307 if (llvm::any_of(Range: inputs, P: [](const InputInfo &input) {
8308 return types::isObjC(Id: input.getType());
8309 }))
8310 cmdArgs.push_back(
8311 Elt: args.MakeArgString(Str: "-fobjc-runtime=" + runtime.getAsString()));
8312 return runtime;
8313}
8314
8315static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8316 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8317 I += HaveDash;
8318 return !HaveDash;
8319}
8320
8321namespace {
8322struct EHFlags {
8323 bool Synch = false;
8324 bool Asynch = false;
8325 bool NoUnwindC = false;
8326};
8327} // end anonymous namespace
8328
8329/// /EH controls whether to run destructor cleanups when exceptions are
8330/// thrown. There are three modifiers:
8331/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8332/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8333/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8334/// - c: Assume that extern "C" functions are implicitly nounwind.
8335/// The default is /EHs-c-, meaning cleanups are disabled.
8336static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8337 bool isWindowsMSVC) {
8338 EHFlags EH;
8339
8340 std::vector<std::string> EHArgs =
8341 Args.getAllArgValues(Id: options::OPT__SLASH_EH);
8342 for (const auto &EHVal : EHArgs) {
8343 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8344 switch (EHVal[I]) {
8345 case 'a':
8346 EH.Asynch = maybeConsumeDash(EH: EHVal, I);
8347 if (EH.Asynch) {
8348 // Async exceptions are Windows MSVC only.
8349 if (!isWindowsMSVC) {
8350 EH.Asynch = false;
8351 D.Diag(DiagID: clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8352 continue;
8353 }
8354 EH.Synch = false;
8355 }
8356 continue;
8357 case 'c':
8358 EH.NoUnwindC = maybeConsumeDash(EH: EHVal, I);
8359 continue;
8360 case 's':
8361 EH.Synch = maybeConsumeDash(EH: EHVal, I);
8362 if (EH.Synch)
8363 EH.Asynch = false;
8364 continue;
8365 default:
8366 break;
8367 }
8368 D.Diag(DiagID: clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8369 break;
8370 }
8371 }
8372 // The /GX, /GX- flags are only processed if there are not /EH flags.
8373 // The default is that /GX is not specified.
8374 if (EHArgs.empty() &&
8375 Args.hasFlag(Pos: options::OPT__SLASH_GX, Neg: options::OPT__SLASH_GX_,
8376 /*Default=*/false)) {
8377 EH.Synch = true;
8378 EH.NoUnwindC = true;
8379 }
8380
8381 if (Args.hasArg(Ids: options::OPT__SLASH_kernel)) {
8382 EH.Synch = false;
8383 EH.NoUnwindC = false;
8384 EH.Asynch = false;
8385 }
8386
8387 return EH;
8388}
8389
8390void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8391 ArgStringList &CmdArgs) const {
8392 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8393
8394 ProcessVSRuntimeLibrary(TC: getToolChain(), Args, CmdArgs);
8395
8396 if (Arg *ShowIncludes =
8397 Args.getLastArg(Ids: options::OPT__SLASH_showIncludes,
8398 Ids: options::OPT__SLASH_showIncludes_user)) {
8399 CmdArgs.push_back(Elt: "--show-includes");
8400 if (ShowIncludes->getOption().matches(ID: options::OPT__SLASH_showIncludes))
8401 CmdArgs.push_back(Elt: "-sys-header-deps");
8402 }
8403
8404 // This controls whether or not we emit RTTI data for polymorphic types.
8405 if (Args.hasFlag(Pos: options::OPT__SLASH_GR_, Neg: options::OPT__SLASH_GR,
8406 /*Default=*/false))
8407 CmdArgs.push_back(Elt: "-fno-rtti-data");
8408
8409 // This controls whether or not we emit stack-protector instrumentation.
8410 // In MSVC, Buffer Security Check (/GS) is on by default.
8411 if (!isNVPTX && Args.hasFlag(Pos: options::OPT__SLASH_GS, Neg: options::OPT__SLASH_GS_,
8412 /*Default=*/true)) {
8413 CmdArgs.push_back(Elt: "-stack-protector");
8414 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(LangOptions::SSPStrong)));
8415 }
8416
8417 const Driver &D = getToolChain().getDriver();
8418
8419 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
8420 EHFlags EH = parseClangCLEHFlags(D, Args, isWindowsMSVC: IsWindowsMSVC);
8421 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
8422 if (types::isCXX(Id: InputType))
8423 CmdArgs.push_back(Elt: "-fcxx-exceptions");
8424 CmdArgs.push_back(Elt: "-fexceptions");
8425 if (EH.Asynch)
8426 CmdArgs.push_back(Elt: "-fasync-exceptions");
8427 }
8428 if (types::isCXX(Id: InputType) && EH.Synch && EH.NoUnwindC)
8429 CmdArgs.push_back(Elt: "-fexternc-nounwind");
8430
8431 // /EP should expand to -E -P.
8432 if (Args.hasArg(Ids: options::OPT__SLASH_EP)) {
8433 CmdArgs.push_back(Elt: "-E");
8434 CmdArgs.push_back(Elt: "-P");
8435 }
8436
8437 if (Args.hasFlag(Pos: options::OPT__SLASH_Zc_dllexportInlines_,
8438 Neg: options::OPT__SLASH_Zc_dllexportInlines,
8439 Default: false)) {
8440 CmdArgs.push_back(Elt: "-fno-dllexport-inlines");
8441 }
8442
8443 if (Args.hasFlag(Pos: options::OPT__SLASH_Zc_wchar_t_,
8444 Neg: options::OPT__SLASH_Zc_wchar_t, Default: false)) {
8445 CmdArgs.push_back(Elt: "-fno-wchar");
8446 }
8447
8448 if (Args.hasArg(Ids: options::OPT__SLASH_kernel)) {
8449 llvm::Triple::ArchType Arch = getToolChain().getArch();
8450 std::vector<std::string> Values =
8451 Args.getAllArgValues(Id: options::OPT__SLASH_arch);
8452 if (!Values.empty()) {
8453 llvm::SmallSet<std::string, 4> SupportedArches;
8454 if (Arch == llvm::Triple::x86)
8455 SupportedArches.insert(V: "IA32");
8456
8457 for (auto &V : Values)
8458 if (!SupportedArches.contains(V))
8459 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
8460 << std::string("/arch:").append(str: V) << "/kernel";
8461 }
8462
8463 CmdArgs.push_back(Elt: "-fno-rtti");
8464 if (Args.hasFlag(Pos: options::OPT__SLASH_GR, Neg: options::OPT__SLASH_GR_, Default: false))
8465 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "/GR"
8466 << "/kernel";
8467 }
8468
8469 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_vlen,
8470 Ids: options::OPT__SLASH_vlen_EQ_256,
8471 Ids: options::OPT__SLASH_vlen_EQ_512)) {
8472 llvm::Triple::ArchType AT = getToolChain().getArch();
8473 StringRef Default = AT == llvm::Triple::x86 ? "IA32" : "SSE2";
8474 StringRef Arch = Args.getLastArgValue(Id: options::OPT__SLASH_arch, Default);
8475 llvm::SmallSet<StringRef, 4> Arch512 = {"AVX512F", "AVX512", "AVX10.1",
8476 "AVX10.2"};
8477
8478 if (A->getOption().matches(ID: options::OPT__SLASH_vlen_EQ_512)) {
8479 if (Arch512.contains(V: Arch))
8480 CmdArgs.push_back(Elt: "-mprefer-vector-width=512");
8481 else
8482 D.Diag(DiagID: diag::warn_drv_argument_not_allowed_with)
8483 << "/vlen=512" << std::string("/arch:").append(svt: Arch);
8484 } else if (A->getOption().matches(ID: options::OPT__SLASH_vlen_EQ_256)) {
8485 if (Arch512.contains(V: Arch))
8486 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
8487 else if (Arch != "AVX" && Arch != "AVX2")
8488 D.Diag(DiagID: diag::warn_drv_argument_not_allowed_with)
8489 << "/vlen=256" << std::string("/arch:").append(svt: Arch);
8490 } else {
8491 if (Arch == "AVX10.1" || Arch == "AVX10.2")
8492 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
8493 }
8494 } else {
8495 StringRef Arch = Args.getLastArgValue(Id: options::OPT__SLASH_arch);
8496 if (Arch == "AVX10.1" || Arch == "AVX10.2")
8497 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
8498 }
8499
8500 Arg *MostGeneralArg = Args.getLastArg(Ids: options::OPT__SLASH_vmg);
8501 Arg *BestCaseArg = Args.getLastArg(Ids: options::OPT__SLASH_vmb);
8502 if (MostGeneralArg && BestCaseArg)
8503 D.Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with)
8504 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
8505
8506 if (MostGeneralArg) {
8507 Arg *SingleArg = Args.getLastArg(Ids: options::OPT__SLASH_vms);
8508 Arg *MultipleArg = Args.getLastArg(Ids: options::OPT__SLASH_vmm);
8509 Arg *VirtualArg = Args.getLastArg(Ids: options::OPT__SLASH_vmv);
8510
8511 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
8512 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
8513 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
8514 D.Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with)
8515 << FirstConflict->getAsString(Args)
8516 << SecondConflict->getAsString(Args);
8517
8518 if (SingleArg)
8519 CmdArgs.push_back(Elt: "-fms-memptr-rep=single");
8520 else if (MultipleArg)
8521 CmdArgs.push_back(Elt: "-fms-memptr-rep=multiple");
8522 else
8523 CmdArgs.push_back(Elt: "-fms-memptr-rep=virtual");
8524 }
8525
8526 if (Args.hasArg(Ids: options::OPT_regcall4))
8527 CmdArgs.push_back(Elt: "-regcall4");
8528
8529 // Parse the default calling convention options.
8530 if (Arg *CCArg =
8531 Args.getLastArg(Ids: options::OPT__SLASH_Gd, Ids: options::OPT__SLASH_Gr,
8532 Ids: options::OPT__SLASH_Gz, Ids: options::OPT__SLASH_Gv,
8533 Ids: options::OPT__SLASH_Gregcall)) {
8534 unsigned DCCOptId = CCArg->getOption().getID();
8535 const char *DCCFlag = nullptr;
8536 bool ArchSupported = !isNVPTX;
8537 llvm::Triple::ArchType Arch = getToolChain().getArch();
8538 switch (DCCOptId) {
8539 case options::OPT__SLASH_Gd:
8540 DCCFlag = "-fdefault-calling-conv=cdecl";
8541 break;
8542 case options::OPT__SLASH_Gr:
8543 ArchSupported = Arch == llvm::Triple::x86;
8544 DCCFlag = "-fdefault-calling-conv=fastcall";
8545 break;
8546 case options::OPT__SLASH_Gz:
8547 ArchSupported = Arch == llvm::Triple::x86;
8548 DCCFlag = "-fdefault-calling-conv=stdcall";
8549 break;
8550 case options::OPT__SLASH_Gv:
8551 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8552 DCCFlag = "-fdefault-calling-conv=vectorcall";
8553 break;
8554 case options::OPT__SLASH_Gregcall:
8555 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8556 DCCFlag = "-fdefault-calling-conv=regcall";
8557 break;
8558 }
8559
8560 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
8561 if (ArchSupported && DCCFlag)
8562 CmdArgs.push_back(Elt: DCCFlag);
8563 }
8564
8565 if (Args.hasArg(Ids: options::OPT__SLASH_Gregcall4))
8566 CmdArgs.push_back(Elt: "-regcall4");
8567
8568 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_vtordisp_mode_EQ);
8569
8570 if (!Args.hasArg(Ids: options::OPT_fdiagnostics_format_EQ)) {
8571 CmdArgs.push_back(Elt: "-fdiagnostics-format");
8572 CmdArgs.push_back(Elt: "msvc");
8573 }
8574
8575 if (Args.hasArg(Ids: options::OPT__SLASH_kernel))
8576 CmdArgs.push_back(Elt: "-fms-kernel");
8577
8578 // Unwind v2 (epilog) information for x64 Windows.
8579 if (Args.hasArg(Ids: options::OPT__SLASH_d2epilogunwindrequirev2))
8580 CmdArgs.push_back(Elt: "-fwinx64-eh-unwindv2=required");
8581 else if (Args.hasArg(Ids: options::OPT__SLASH_d2epilogunwind))
8582 CmdArgs.push_back(Elt: "-fwinx64-eh-unwindv2=best-effort");
8583
8584 for (const Arg *A : Args.filtered(Ids: options::OPT__SLASH_guard)) {
8585 StringRef GuardArgs = A->getValue();
8586 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
8587 // "ehcont-".
8588 if (GuardArgs.equals_insensitive(RHS: "cf")) {
8589 // Emit CFG instrumentation and the table of address-taken functions.
8590 CmdArgs.push_back(Elt: "-cfguard");
8591 } else if (GuardArgs.equals_insensitive(RHS: "cf,nochecks")) {
8592 // Emit only the table of address-taken functions.
8593 CmdArgs.push_back(Elt: "-cfguard-no-checks");
8594 } else if (GuardArgs.equals_insensitive(RHS: "ehcont")) {
8595 // Emit EH continuation table.
8596 CmdArgs.push_back(Elt: "-ehcontguard");
8597 } else if (GuardArgs.equals_insensitive(RHS: "cf-") ||
8598 GuardArgs.equals_insensitive(RHS: "ehcont-")) {
8599 // Do nothing, but we might want to emit a security warning in future.
8600 } else {
8601 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
8602 }
8603 A->claim();
8604 }
8605
8606 for (const auto &FuncOverride :
8607 Args.getAllArgValues(Id: options::OPT__SLASH_funcoverride)) {
8608 CmdArgs.push_back(Elt: Args.MakeArgString(
8609 Str: Twine("-loader-replaceable-function=") + FuncOverride));
8610 }
8611}
8612
8613const char *Clang::getBaseInputName(const ArgList &Args,
8614 const InputInfo &Input) {
8615 return Args.MakeArgString(Str: llvm::sys::path::filename(path: Input.getBaseInput()));
8616}
8617
8618const char *Clang::getBaseInputStem(const ArgList &Args,
8619 const InputInfoList &Inputs) {
8620 const char *Str = getBaseInputName(Args, Input: Inputs[0]);
8621
8622 if (const char *End = strrchr(s: Str, c: '.'))
8623 return Args.MakeArgString(Str: std::string(Str, End));
8624
8625 return Str;
8626}
8627
8628const char *Clang::getDependencyFileName(const ArgList &Args,
8629 const InputInfoList &Inputs) {
8630 // FIXME: Think about this more.
8631
8632 if (Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o)) {
8633 SmallString<128> OutputFilename(OutputOpt->getValue());
8634 llvm::sys::path::replace_extension(path&: OutputFilename, extension: llvm::Twine('d'));
8635 return Args.MakeArgString(Str: OutputFilename);
8636 }
8637
8638 return Args.MakeArgString(Str: Twine(getBaseInputStem(Args, Inputs)) + ".d");
8639}
8640
8641// Begin ClangAs
8642
8643void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
8644 ArgStringList &CmdArgs) const {
8645 StringRef CPUName;
8646 StringRef ABIName;
8647 const llvm::Triple &Triple = getToolChain().getTriple();
8648 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
8649
8650 CmdArgs.push_back(Elt: "-target-abi");
8651 CmdArgs.push_back(Elt: ABIName.data());
8652}
8653
8654void ClangAs::AddX86TargetArgs(const ArgList &Args,
8655 ArgStringList &CmdArgs) const {
8656 addX86AlignBranchArgs(D: getToolChain().getDriver(), Args, CmdArgs,
8657 /*IsLTO=*/false);
8658
8659 if (Arg *A = Args.getLastArg(Ids: options::OPT_masm_EQ)) {
8660 StringRef Value = A->getValue();
8661 if (Value == "intel" || Value == "att") {
8662 CmdArgs.push_back(Elt: "-mllvm");
8663 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
8664 } else {
8665 getToolChain().getDriver().Diag(DiagID: diag::err_drv_unsupported_option_argument)
8666 << A->getSpelling() << Value;
8667 }
8668 }
8669}
8670
8671void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
8672 ArgStringList &CmdArgs) const {
8673 CmdArgs.push_back(Elt: "-target-abi");
8674 CmdArgs.push_back(Elt: loongarch::getLoongArchABI(D: getToolChain().getDriver(), Args,
8675 Triple: getToolChain().getTriple())
8676 .data());
8677}
8678
8679void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
8680 ArgStringList &CmdArgs) const {
8681 const llvm::Triple &Triple = getToolChain().getTriple();
8682 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
8683
8684 CmdArgs.push_back(Elt: "-target-abi");
8685 CmdArgs.push_back(Elt: ABIName.data());
8686
8687 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
8688 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
8689 CmdArgs.push_back(Elt: "-mllvm");
8690 CmdArgs.push_back(Elt: "-riscv-add-build-attributes");
8691 }
8692}
8693
8694void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
8695 const InputInfo &Output, const InputInfoList &Inputs,
8696 const ArgList &Args,
8697 const char *LinkingOutput) const {
8698 ArgStringList CmdArgs;
8699
8700 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
8701 const InputInfo &Input = Inputs[0];
8702
8703 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
8704 const std::string &TripleStr = Triple.getTriple();
8705 const auto &D = getToolChain().getDriver();
8706
8707 // Don't warn about "clang -w -c foo.s"
8708 Args.ClaimAllArgs(Id0: options::OPT_w);
8709 // and "clang -emit-llvm -c foo.s"
8710 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
8711
8712 claimNoWarnArgs(Args);
8713
8714 // Invoke ourselves in -cc1as mode.
8715 //
8716 // FIXME: Implement custom jobs for internal actions.
8717 CmdArgs.push_back(Elt: "-cc1as");
8718
8719 // Add the "effective" target triple.
8720 CmdArgs.push_back(Elt: "-triple");
8721 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TripleStr));
8722
8723 getToolChain().addClangCC1ASTargetOptions(Args, CC1ASArgs&: CmdArgs);
8724
8725 // Set the output mode, we currently only expect to be used as a real
8726 // assembler.
8727 CmdArgs.push_back(Elt: "-filetype");
8728 CmdArgs.push_back(Elt: "obj");
8729
8730 // Set the main file name, so that debug info works even with
8731 // -save-temps or preprocessed assembly.
8732 CmdArgs.push_back(Elt: "-main-file-name");
8733 CmdArgs.push_back(Elt: Clang::getBaseInputName(Args, Input));
8734
8735 // Add the target cpu
8736 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ true);
8737 if (!CPU.empty()) {
8738 CmdArgs.push_back(Elt: "-target-cpu");
8739 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
8740 }
8741
8742 // Add the target features
8743 getTargetFeatures(D, Triple, Args, CmdArgs, ForAS: true);
8744
8745 // Ignore explicit -force_cpusubtype_ALL option.
8746 (void)Args.hasArg(Ids: options::OPT_force__cpusubtype__ALL);
8747
8748 // Pass along any -I options so we get proper .include search paths.
8749 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_I_Group);
8750
8751 // Pass along any --embed-dir or similar options so we get proper embed paths.
8752 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_embed_dir_EQ);
8753
8754 // Determine the original source input.
8755 auto FindSource = [](const Action *S) -> const Action * {
8756 while (S->getKind() != Action::InputClass) {
8757 assert(!S->getInputs().empty() && "unexpected root action!");
8758 S = S->getInputs()[0];
8759 }
8760 return S;
8761 };
8762 const Action *SourceAction = FindSource(&JA);
8763
8764 // Forward -g and handle debug info related flags, assuming we are dealing
8765 // with an actual assembly file.
8766 bool WantDebug = false;
8767 Args.ClaimAllArgs(Id0: options::OPT_g_Group);
8768 if (Arg *A = Args.getLastArg(Ids: options::OPT_g_Group))
8769 WantDebug = !A->getOption().matches(ID: options::OPT_g0) &&
8770 !A->getOption().matches(ID: options::OPT_ggdb0);
8771
8772 // If a -gdwarf argument appeared, remember it.
8773 bool EmitDwarf = false;
8774 if (const Arg *A = getDwarfNArg(Args))
8775 EmitDwarf = checkDebugInfoOption(A, Args, D, TC: getToolChain());
8776
8777 bool EmitCodeView = false;
8778 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcodeview))
8779 EmitCodeView = checkDebugInfoOption(A, Args, D, TC: getToolChain());
8780
8781 // If the user asked for debug info but did not explicitly specify -gcodeview
8782 // or -gdwarf, ask the toolchain for the default format.
8783 if (!EmitCodeView && !EmitDwarf && WantDebug) {
8784 switch (getToolChain().getDefaultDebugFormat()) {
8785 case llvm::codegenoptions::DIF_CodeView:
8786 EmitCodeView = true;
8787 break;
8788 case llvm::codegenoptions::DIF_DWARF:
8789 EmitDwarf = true;
8790 break;
8791 }
8792 }
8793
8794 // If the arguments don't imply DWARF, don't emit any debug info here.
8795 if (!EmitDwarf)
8796 WantDebug = false;
8797
8798 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
8799 llvm::codegenoptions::NoDebugInfo;
8800
8801 // Add the -fdebug-compilation-dir flag if needed.
8802 const char *DebugCompilationDir =
8803 addDebugCompDirArg(Args, CmdArgs, VFS: C.getDriver().getVFS());
8804
8805 if (SourceAction->getType() == types::TY_Asm ||
8806 SourceAction->getType() == types::TY_PP_Asm) {
8807 // You might think that it would be ok to set DebugInfoKind outside of
8808 // the guard for source type, however there is a test which asserts
8809 // that some assembler invocation receives no -debug-info-kind,
8810 // and it's not clear whether that test is just overly restrictive.
8811 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
8812 : llvm::codegenoptions::NoDebugInfo);
8813
8814 addDebugPrefixMapArg(D: getToolChain().getDriver(), TC: getToolChain(), Args,
8815 CmdArgs);
8816
8817 // Set the AT_producer to the clang version when using the integrated
8818 // assembler on assembly source files.
8819 CmdArgs.push_back(Elt: "-dwarf-debug-producer");
8820 CmdArgs.push_back(Elt: Args.MakeArgString(Str: getClangFullVersion()));
8821
8822 // And pass along -I options
8823 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_I);
8824 }
8825 const unsigned DwarfVersion = getDwarfVersion(TC: getToolChain(), Args);
8826 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
8827 DebuggerTuning: llvm::DebuggerKind::Default);
8828 renderDwarfFormat(D, T: Triple, Args, CmdArgs, DwarfVersion);
8829 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC: getToolChain());
8830
8831 // Handle -fPIC et al -- the relocation-model affects the assembler
8832 // for some targets.
8833 llvm::Reloc::Model RelocationModel;
8834 unsigned PICLevel;
8835 bool IsPIE;
8836 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
8837 ParsePICArgs(ToolChain: getToolChain(), Args);
8838
8839 const char *RMName = RelocationModelName(Model: RelocationModel);
8840 if (RMName) {
8841 CmdArgs.push_back(Elt: "-mrelocation-model");
8842 CmdArgs.push_back(Elt: RMName);
8843 }
8844
8845 // Optionally embed the -cc1as level arguments into the debug info, for build
8846 // analysis.
8847 if (getToolChain().UseDwarfDebugFlags()) {
8848 ArgStringList OriginalArgs;
8849 for (const auto &Arg : Args)
8850 Arg->render(Args, Output&: OriginalArgs);
8851
8852 SmallString<256> Flags;
8853 const char *Exec = getToolChain().getDriver().getClangProgramPath();
8854 escapeSpacesAndBackslashes(Arg: Exec, Res&: Flags);
8855 for (const char *OriginalArg : OriginalArgs) {
8856 SmallString<128> EscapedArg;
8857 escapeSpacesAndBackslashes(Arg: OriginalArg, Res&: EscapedArg);
8858 Flags += " ";
8859 Flags += EscapedArg;
8860 }
8861 CmdArgs.push_back(Elt: "-dwarf-debug-flags");
8862 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Flags));
8863 }
8864
8865 // FIXME: Add -static support, once we have it.
8866
8867 // Add target specific flags.
8868 switch (getToolChain().getArch()) {
8869 default:
8870 break;
8871
8872 case llvm::Triple::mips:
8873 case llvm::Triple::mipsel:
8874 case llvm::Triple::mips64:
8875 case llvm::Triple::mips64el:
8876 AddMIPSTargetArgs(Args, CmdArgs);
8877 break;
8878
8879 case llvm::Triple::x86:
8880 case llvm::Triple::x86_64:
8881 AddX86TargetArgs(Args, CmdArgs);
8882 break;
8883
8884 case llvm::Triple::arm:
8885 case llvm::Triple::armeb:
8886 case llvm::Triple::thumb:
8887 case llvm::Triple::thumbeb:
8888 // This isn't in AddARMTargetArgs because we want to do this for assembly
8889 // only, not C/C++.
8890 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
8891 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
8892 CmdArgs.push_back(Elt: "-mllvm");
8893 CmdArgs.push_back(Elt: "-arm-add-build-attributes");
8894 }
8895 break;
8896
8897 case llvm::Triple::aarch64:
8898 case llvm::Triple::aarch64_32:
8899 case llvm::Triple::aarch64_be:
8900 if (Args.hasArg(Ids: options::OPT_mmark_bti_property)) {
8901 CmdArgs.push_back(Elt: "-mllvm");
8902 CmdArgs.push_back(Elt: "-aarch64-mark-bti-property");
8903 }
8904 break;
8905
8906 case llvm::Triple::loongarch32:
8907 case llvm::Triple::loongarch64:
8908 AddLoongArchTargetArgs(Args, CmdArgs);
8909 break;
8910
8911 case llvm::Triple::riscv32:
8912 case llvm::Triple::riscv64:
8913 case llvm::Triple::riscv32be:
8914 case llvm::Triple::riscv64be:
8915 AddRISCVTargetArgs(Args, CmdArgs);
8916 break;
8917
8918 case llvm::Triple::hexagon:
8919 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
8920 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
8921 CmdArgs.push_back(Elt: "-mllvm");
8922 CmdArgs.push_back(Elt: "-hexagon-add-build-attributes");
8923 }
8924 break;
8925 }
8926
8927 // Consume all the warning flags. Usually this would be handled more
8928 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
8929 // doesn't handle that so rather than warning about unused flags that are
8930 // actually used, we'll lie by omission instead.
8931 // FIXME: Stop lying and consume only the appropriate driver flags
8932 Args.ClaimAllArgs(Id0: options::OPT_W_Group);
8933
8934 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
8935 D: getToolChain().getDriver());
8936
8937 // Forward -Xclangas arguments to -cc1as
8938 for (auto Arg : Args.filtered(Ids: options::OPT_Xclangas)) {
8939 Arg->claim();
8940 CmdArgs.push_back(Elt: Arg->getValue());
8941 }
8942
8943 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_mllvm);
8944
8945 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
8946 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
8947 OutputFileName: Output.getFilename());
8948
8949 // Fixup any previous commands that use -object-file-name because when we
8950 // generated them, the final .obj name wasn't yet known.
8951 for (Command &J : C.getJobs()) {
8952 if (SourceAction != FindSource(&J.getSource()))
8953 continue;
8954 auto &JArgs = J.getArguments();
8955 for (unsigned I = 0; I < JArgs.size(); ++I) {
8956 if (StringRef(JArgs[I]).starts_with(Prefix: "-object-file-name=") &&
8957 Output.isFilename()) {
8958 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
8959 addDebugObjectName(Args, CmdArgs&: NewArgs, DebugCompilationDir,
8960 OutputFileName: Output.getFilename());
8961 NewArgs.append(in_start: JArgs.begin() + I + 1, in_end: JArgs.end());
8962 J.replaceArguments(List: NewArgs);
8963 break;
8964 }
8965 }
8966 }
8967
8968 assert(Output.isFilename() && "Unexpected lipo output.");
8969 CmdArgs.push_back(Elt: "-o");
8970 CmdArgs.push_back(Elt: Output.getFilename());
8971
8972 const llvm::Triple &T = getToolChain().getTriple();
8973 Arg *A;
8974 if (getDebugFissionKind(D, Args, Arg&: A) == DwarfFissionKind::Split &&
8975 T.isOSBinFormatELF()) {
8976 CmdArgs.push_back(Elt: "-split-dwarf-output");
8977 CmdArgs.push_back(Elt: SplitDebugName(JA, Args, Input, Output));
8978 }
8979
8980 if (Triple.isAMDGPU())
8981 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
8982
8983 assert(Input.isFilename() && "Invalid input.");
8984 CmdArgs.push_back(Elt: Input.getFilename());
8985
8986 const char *Exec = getToolChain().getDriver().getClangProgramPath();
8987 if (D.CC1Main && !D.CCGenDiagnostics) {
8988 // Invoke cc1as directly in this process.
8989 C.addCommand(C: std::make_unique<CC1Command>(
8990 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8991 args: Output, args: D.getPrependArg()));
8992 } else {
8993 C.addCommand(C: std::make_unique<Command>(
8994 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8995 args: Output, args: D.getPrependArg()));
8996 }
8997}
8998
8999// Begin OffloadBundler
9000void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
9001 const InputInfo &Output,
9002 const InputInfoList &Inputs,
9003 const llvm::opt::ArgList &TCArgs,
9004 const char *LinkingOutput) const {
9005 // The version with only one output is expected to refer to a bundling job.
9006 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
9007
9008 // The bundling command looks like this:
9009 // clang-offload-bundler -type=bc
9010 // -targets=host-triple,openmp-triple1,openmp-triple2
9011 // -output=output_file
9012 // -input=unbundle_file_host
9013 // -input=unbundle_file_tgt1
9014 // -input=unbundle_file_tgt2
9015
9016 ArgStringList CmdArgs;
9017
9018 // Get the type.
9019 CmdArgs.push_back(Elt: TCArgs.MakeArgString(
9020 Str: Twine("-type=") + types::getTypeTempSuffix(Id: Output.getType())));
9021
9022 assert(JA.getInputs().size() == Inputs.size() &&
9023 "Not have inputs for all dependence actions??");
9024
9025 // Get the targets.
9026 SmallString<128> Triples;
9027 Triples += "-targets=";
9028 for (unsigned I = 0; I < Inputs.size(); ++I) {
9029 if (I)
9030 Triples += ',';
9031
9032 // Find ToolChain for this input.
9033 Action::OffloadKind CurKind = Action::OFK_Host;
9034 const ToolChain *CurTC = &getToolChain();
9035 const Action *CurDep = JA.getInputs()[I];
9036
9037 if (const auto *OA = dyn_cast<OffloadAction>(Val: CurDep)) {
9038 CurTC = nullptr;
9039 OA->doOnEachDependence(Work: [&](Action *A, const ToolChain *TC, const char *) {
9040 assert(CurTC == nullptr && "Expected one dependence!");
9041 CurKind = A->getOffloadingDeviceKind();
9042 CurTC = TC;
9043 });
9044 }
9045 Triples += Action::GetOffloadKindName(Kind: CurKind);
9046 Triples += '-';
9047 Triples +=
9048 CurTC->getTriple().normalize(Form: llvm::Triple::CanonicalForm::FOUR_IDENT);
9049 if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&
9050 !StringRef(CurDep->getOffloadingArch()).empty()) {
9051 Triples += '-';
9052 Triples += CurDep->getOffloadingArch();
9053 }
9054
9055 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
9056 // with each toolchain.
9057 StringRef GPUArchName;
9058 if (CurKind == Action::OFK_OpenMP) {
9059 // Extract GPUArch from -march argument in TC argument list.
9060 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
9061 auto ArchStr = StringRef(TCArgs.getArgString(Index: ArgIndex));
9062 auto Arch = ArchStr.starts_with_insensitive(Prefix: "-march=");
9063 if (Arch) {
9064 GPUArchName = ArchStr.substr(Start: 7);
9065 Triples += "-";
9066 break;
9067 }
9068 }
9069 Triples += GPUArchName.str();
9070 }
9071 }
9072 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: Triples));
9073
9074 // Get bundled file command.
9075 CmdArgs.push_back(
9076 Elt: TCArgs.MakeArgString(Str: Twine("-output=") + Output.getFilename()));
9077
9078 // Get unbundled files command.
9079 for (unsigned I = 0; I < Inputs.size(); ++I) {
9080 SmallString<128> UB;
9081 UB += "-input=";
9082
9083 // Find ToolChain for this input.
9084 const ToolChain *CurTC = &getToolChain();
9085 if (const auto *OA = dyn_cast<OffloadAction>(Val: JA.getInputs()[I])) {
9086 CurTC = nullptr;
9087 OA->doOnEachDependence(Work: [&](Action *, const ToolChain *TC, const char *) {
9088 assert(CurTC == nullptr && "Expected one dependence!");
9089 CurTC = TC;
9090 });
9091 UB += C.addTempFile(
9092 Name: C.getArgs().MakeArgString(Str: CurTC->getInputFilename(Input: Inputs[I])));
9093 } else {
9094 UB += CurTC->getInputFilename(Input: Inputs[I]);
9095 }
9096 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: UB));
9097 }
9098 addOffloadCompressArgs(TCArgs, CmdArgs);
9099 // All the inputs are encoded as commands.
9100 C.addCommand(C: std::make_unique<Command>(
9101 args: JA, args: *this, args: ResponseFileSupport::None(),
9102 args: TCArgs.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9103 args&: CmdArgs, args: ArrayRef<InputInfo>(), args: Output));
9104}
9105
9106void OffloadBundler::ConstructJobMultipleOutputs(
9107 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
9108 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
9109 const char *LinkingOutput) const {
9110 // The version with multiple outputs is expected to refer to a unbundling job.
9111 auto &UA = cast<OffloadUnbundlingJobAction>(Val: JA);
9112
9113 // The unbundling command looks like this:
9114 // clang-offload-bundler -type=bc
9115 // -targets=host-triple,openmp-triple1,openmp-triple2
9116 // -input=input_file
9117 // -output=unbundle_file_host
9118 // -output=unbundle_file_tgt1
9119 // -output=unbundle_file_tgt2
9120 // -unbundle
9121
9122 ArgStringList CmdArgs;
9123
9124 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
9125 InputInfo Input = Inputs.front();
9126
9127 // Get the type.
9128 CmdArgs.push_back(Elt: TCArgs.MakeArgString(
9129 Str: Twine("-type=") + types::getTypeTempSuffix(Id: Input.getType())));
9130
9131 // Get the targets.
9132 SmallString<128> Triples;
9133 Triples += "-targets=";
9134 auto DepInfo = UA.getDependentActionsInfo();
9135 for (unsigned I = 0; I < DepInfo.size(); ++I) {
9136 if (I)
9137 Triples += ',';
9138
9139 auto &Dep = DepInfo[I];
9140 Triples += Action::GetOffloadKindName(Kind: Dep.DependentOffloadKind);
9141 Triples += '-';
9142 Triples += Dep.DependentToolChain->getTriple().normalize(
9143 Form: llvm::Triple::CanonicalForm::FOUR_IDENT);
9144 if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
9145 Dep.DependentOffloadKind == Action::OFK_Cuda) &&
9146 !Dep.DependentBoundArch.empty()) {
9147 Triples += '-';
9148 Triples += Dep.DependentBoundArch;
9149 }
9150 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
9151 // with each toolchain.
9152 StringRef GPUArchName;
9153 if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {
9154 // Extract GPUArch from -march argument in TC argument list.
9155 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
9156 StringRef ArchStr = StringRef(TCArgs.getArgString(Index: ArgIndex));
9157 auto Arch = ArchStr.starts_with_insensitive(Prefix: "-march=");
9158 if (Arch) {
9159 GPUArchName = ArchStr.substr(Start: 7);
9160 Triples += "-";
9161 break;
9162 }
9163 }
9164 Triples += GPUArchName.str();
9165 }
9166 }
9167
9168 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: Triples));
9169
9170 // Get bundled file command.
9171 CmdArgs.push_back(
9172 Elt: TCArgs.MakeArgString(Str: Twine("-input=") + Input.getFilename()));
9173
9174 // Get unbundled files command.
9175 for (unsigned I = 0; I < Outputs.size(); ++I) {
9176 SmallString<128> UB;
9177 UB += "-output=";
9178 UB += DepInfo[I].DependentToolChain->getInputFilename(Input: Outputs[I]);
9179 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: UB));
9180 }
9181 CmdArgs.push_back(Elt: "-unbundle");
9182 CmdArgs.push_back(Elt: "-allow-missing-bundles");
9183 if (TCArgs.hasArg(Ids: options::OPT_v))
9184 CmdArgs.push_back(Elt: "-verbose");
9185
9186 // All the inputs are encoded as commands.
9187 C.addCommand(C: std::make_unique<Command>(
9188 args: JA, args: *this, args: ResponseFileSupport::None(),
9189 args: TCArgs.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9190 args&: CmdArgs, args: ArrayRef<InputInfo>(), args: Outputs));
9191}
9192
9193void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
9194 const InputInfo &Output,
9195 const InputInfoList &Inputs,
9196 const llvm::opt::ArgList &Args,
9197 const char *LinkingOutput) const {
9198 ArgStringList CmdArgs;
9199
9200 // Add the output file name.
9201 assert(Output.isFilename() && "Invalid output.");
9202 CmdArgs.push_back(Elt: "-o");
9203 CmdArgs.push_back(Elt: Output.getFilename());
9204
9205 // Create the inputs to bundle the needed metadata.
9206 for (const InputInfo &Input : Inputs) {
9207 const Action *OffloadAction = Input.getAction();
9208 const ToolChain *TC = OffloadAction->getOffloadingToolChain();
9209 const ArgList &TCArgs =
9210 C.getArgsForToolChain(TC, BoundArch: OffloadAction->getOffloadingArch(),
9211 DeviceOffloadKind: OffloadAction->getOffloadingDeviceKind());
9212 StringRef File = C.getArgs().MakeArgString(Str: TC->getInputFilename(Input));
9213 StringRef Arch = OffloadAction->getOffloadingArch()
9214 ? OffloadAction->getOffloadingArch()
9215 : TCArgs.getLastArgValue(Id: options::OPT_march_EQ);
9216 StringRef Kind =
9217 Action::GetOffloadKindName(Kind: OffloadAction->getOffloadingDeviceKind());
9218
9219 ArgStringList Features;
9220 SmallVector<StringRef> FeatureArgs;
9221 getTargetFeatures(D: TC->getDriver(), Triple: TC->getTriple(), Args: TCArgs, CmdArgs&: Features,
9222 ForAS: false);
9223 llvm::copy_if(Range&: Features, Out: std::back_inserter(x&: FeatureArgs),
9224 P: [](StringRef Arg) { return !Arg.starts_with(Prefix: "-target"); });
9225
9226 // TODO: We need to pass in the full target-id and handle it properly in the
9227 // linker wrapper.
9228 SmallVector<std::string> Parts{
9229 "file=" + File.str(),
9230 "triple=" + TC->getTripleString(),
9231 "arch=" + (Arch.empty() ? "generic" : Arch.str()),
9232 "kind=" + Kind.str(),
9233 };
9234
9235 if (TC->getDriver().isUsingOffloadLTO())
9236 for (StringRef Feature : FeatureArgs)
9237 Parts.emplace_back(Args: "feature=" + Feature.str());
9238
9239 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--image=" + llvm::join(R&: Parts, Separator: ",")));
9240 }
9241
9242 C.addCommand(C: std::make_unique<Command>(
9243 args: JA, args: *this, args: ResponseFileSupport::None(),
9244 args: Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9245 args&: CmdArgs, args: Inputs, args: Output));
9246}
9247
9248void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
9249 const InputInfo &Output,
9250 const InputInfoList &Inputs,
9251 const ArgList &Args,
9252 const char *LinkingOutput) const {
9253 using namespace options;
9254
9255 // A list of permitted options that will be forwarded to the embedded device
9256 // compilation job.
9257 const llvm::DenseSet<unsigned> CompilerOptions{
9258 OPT_v,
9259 OPT_cuda_path_EQ,
9260 OPT_rocm_path_EQ,
9261 OPT_hip_path_EQ,
9262 OPT_O_Group,
9263 OPT_g_Group,
9264 OPT_g_flags_Group,
9265 OPT_R_value_Group,
9266 OPT_R_Group,
9267 OPT_Xcuda_ptxas,
9268 OPT_ftime_report,
9269 OPT_ftime_trace,
9270 OPT_ftime_trace_EQ,
9271 OPT_ftime_trace_granularity_EQ,
9272 OPT_ftime_trace_verbose,
9273 OPT_opt_record_file,
9274 OPT_opt_record_format,
9275 OPT_opt_record_passes,
9276 OPT_fsave_optimization_record,
9277 OPT_fsave_optimization_record_EQ,
9278 OPT_fno_save_optimization_record,
9279 OPT_foptimization_record_file_EQ,
9280 OPT_foptimization_record_passes_EQ,
9281 OPT_save_temps,
9282 OPT_save_temps_EQ,
9283 OPT_mcode_object_version_EQ,
9284 OPT_load,
9285 OPT_fno_lto,
9286 OPT_flto,
9287 OPT_flto_partitions_EQ,
9288 OPT_flto_EQ,
9289 OPT_hipspv_pass_plugin_EQ,
9290 OPT_use_spirv_backend};
9291 const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9292 auto ShouldForwardForToolChain = [&](Arg *A, const ToolChain &TC) {
9293 // Don't forward -mllvm to toolchains that don't support LLVM.
9294 return TC.HasNativeLLVMSupport() || A->getOption().getID() != OPT_mllvm;
9295 };
9296 auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A,
9297 const ToolChain &TC) {
9298 // CMake hack to avoid printing verbose informatoin for HIP non-RDC mode.
9299 if (A->getOption().matches(ID: OPT_v) && JA.getType() == types::TY_HIP_FATBIN)
9300 return false;
9301 return (Set.contains(V: A->getOption().getID()) ||
9302 (A->getOption().getGroup().isValid() &&
9303 Set.contains(V: A->getOption().getGroup().getID()))) &&
9304 ShouldForwardForToolChain(A, TC);
9305 };
9306
9307 ArgStringList CmdArgs;
9308 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,
9309 Action::OFK_HIP, Action::OFK_SYCL}) {
9310 auto TCRange = C.getOffloadToolChains(Kind);
9311 for (auto &I : llvm::make_range(p: TCRange)) {
9312 const ToolChain *TC = I.second;
9313
9314 // We do not use a bound architecture here so options passed only to a
9315 // specific architecture via -Xarch_<cpu> will not be forwarded.
9316 ArgStringList CompilerArgs;
9317 ArgStringList LinkerArgs;
9318 const DerivedArgList &ToolChainArgs =
9319 C.getArgsForToolChain(TC, /*BoundArch=*/"", DeviceOffloadKind: Kind);
9320 for (Arg *A : ToolChainArgs) {
9321 if (A->getOption().matches(ID: OPT_Zlinker_input))
9322 LinkerArgs.emplace_back(Args: A->getValue());
9323 else if (ShouldForward(CompilerOptions, A, *TC))
9324 A->render(Args, Output&: CompilerArgs);
9325 else if (ShouldForward(LinkerOptions, A, *TC))
9326 A->render(Args, Output&: LinkerArgs);
9327 }
9328
9329 // If the user explicitly requested it via `--offload-arch` we should
9330 // extract it from any static libraries if present.
9331 for (StringRef Arg : ToolChainArgs.getAllArgValues(Id: OPT_offload_arch_EQ))
9332 CmdArgs.emplace_back(Args: Args.MakeArgString(Str: "--should-extract=" + Arg));
9333
9334 // If this is OpenMP the device linker will need `-lompdevice`.
9335 if (Kind == Action::OFK_OpenMP && !Args.hasArg(Ids: OPT_no_offloadlib) &&
9336 (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9337 LinkerArgs.emplace_back(Args: "-lompdevice");
9338
9339 // For SPIR-V, pass some extra flags to `spirv-link`, the out-of-tree
9340 // SPIR-V linker. `spirv-link` isn't called in LTO mode so restrict these
9341 // flags to normal compilation.
9342 if (TC->getTriple().isSPIRV() && !C.getDriver().isUsingLTO() &&
9343 !C.getDriver().isUsingOffloadLTO()) {
9344 // For SPIR-V some functions will be defined by the runtime so allow
9345 // unresolved symbols in `spirv-link`.
9346 LinkerArgs.emplace_back(Args: "--allow-partial-linkage");
9347 // Don't optimize out exported symbols.
9348 LinkerArgs.emplace_back(Args: "--create-library");
9349 }
9350
9351 // Forward all of these to the appropriate toolchain.
9352 for (StringRef Arg : CompilerArgs)
9353 CmdArgs.push_back(Elt: Args.MakeArgString(
9354 Str: "--device-compiler=" + TC->getTripleString() + "=" + Arg));
9355 for (StringRef Arg : LinkerArgs)
9356 CmdArgs.push_back(Elt: Args.MakeArgString(
9357 Str: "--device-linker=" + TC->getTripleString() + "=" + Arg));
9358
9359 // Forward the LTO mode relying on the Driver's parsing.
9360 if (C.getDriver().getOffloadLTOMode() == LTOK_Full)
9361 CmdArgs.push_back(Elt: Args.MakeArgString(
9362 Str: "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
9363 else if (C.getDriver().getOffloadLTOMode() == LTOK_Thin) {
9364 CmdArgs.push_back(Elt: Args.MakeArgString(
9365 Str: "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
9366 if (TC->getTriple().isAMDGPU()) {
9367 CmdArgs.push_back(
9368 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9369 "=-plugin-opt=-force-import-all"));
9370 CmdArgs.push_back(
9371 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9372 "=-plugin-opt=-avail-extern-to-local"));
9373 CmdArgs.push_back(Elt: Args.MakeArgString(
9374 Str: "--device-linker=" + TC->getTripleString() +
9375 "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));
9376 if (Kind == Action::OFK_OpenMP) {
9377 CmdArgs.push_back(
9378 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9379 "=-plugin-opt=-amdgpu-internalize-symbols"));
9380 }
9381 }
9382 }
9383 }
9384 }
9385
9386 CmdArgs.push_back(
9387 Elt: Args.MakeArgString(Str: "--host-triple=" + getToolChain().getTripleString()));
9388
9389 // CMake hack, suppress passing verbose arguments for the special-case HIP
9390 // non-RDC mode compilation. This confuses default CMake implicit linker
9391 // argument parsing when the language is set to HIP and the system linker is
9392 // also `ld.lld`.
9393 if (Args.hasArg(Ids: options::OPT_v) && JA.getType() != types::TY_HIP_FATBIN)
9394 CmdArgs.push_back(Elt: "--wrapper-verbose");
9395 if (Arg *A = Args.getLastArg(Ids: options::OPT_cuda_path_EQ))
9396 CmdArgs.push_back(
9397 Elt: Args.MakeArgString(Str: Twine("--cuda-path=") + A->getValue()));
9398
9399 // Construct the link job so we can wrap around it.
9400 Linker->ConstructJob(C, JA, Output, Inputs, TCArgs: Args, LinkingOutput);
9401 const auto &LinkCommand = C.getJobs().getJobs().back();
9402
9403 // Forward -Xoffload-{compiler,linker}<-triple> arguments to the linker
9404 // wrapper.
9405 for (Arg *A :
9406 Args.filtered(Ids: options::OPT_Xoffload_compiler, Ids: OPT_Xoffload_linker)) {
9407 StringRef Val = A->getValue(N: 0);
9408 bool IsLinkJob = A->getOption().getID() == OPT_Xoffload_linker;
9409 auto WrapperOption =
9410 IsLinkJob ? Twine("--device-linker=") : Twine("--device-compiler=");
9411 if (Val.empty())
9412 CmdArgs.push_back(Elt: Args.MakeArgString(Str: WrapperOption + A->getValue(N: 1)));
9413 else
9414 CmdArgs.push_back(Elt: Args.MakeArgString(
9415 Str: WrapperOption +
9416 ToolChain::getOpenMPTriple(TripleStr: Val.drop_front()).getTriple() + "=" +
9417 A->getValue(N: 1)));
9418 }
9419 Args.ClaimAllArgs(Id0: options::OPT_Xoffload_compiler);
9420 Args.ClaimAllArgs(Id0: options::OPT_Xoffload_linker);
9421
9422 // Embed bitcode instead of an object in JIT mode.
9423 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_jit,
9424 Neg: options::OPT_fno_openmp_target_jit, Default: false))
9425 CmdArgs.push_back(Elt: "--embed-bitcode");
9426
9427 // Save temporary files created by the linker wrapper.
9428 if (Args.hasArg(Ids: options::OPT_save_temps_EQ) ||
9429 Args.hasArg(Ids: options::OPT_save_temps))
9430 CmdArgs.push_back(Elt: "--save-temps");
9431
9432 // Pass in the C library for GPUs if present and not disabled.
9433 if (Args.hasFlag(Pos: options::OPT_offloadlib, Neg: OPT_no_offloadlib, Default: true) &&
9434 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_r,
9435 Ids: options::OPT_nodefaultlibs, Ids: options::OPT_nolibc,
9436 Ids: options::OPT_nogpulibc)) {
9437 forAllAssociatedToolChains(C, JA, RegularToolChain: getToolChain(), Work: [&](const ToolChain &TC) {
9438 // The device C library is only available for NVPTX and AMDGPU targets
9439 // and we only link it by default for OpenMP currently.
9440 if ((!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU()) ||
9441 !JA.isHostOffloading(OKind: Action::OFK_OpenMP))
9442 return;
9443 bool HasLibC = TC.getStdlibIncludePath().has_value();
9444 if (HasLibC) {
9445 CmdArgs.push_back(Elt: Args.MakeArgString(
9446 Str: "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
9447 CmdArgs.push_back(Elt: Args.MakeArgString(
9448 Str: "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
9449 }
9450 auto HasCompilerRT = getToolChain().getVFS().exists(
9451 Path: TC.getCompilerRT(Args, Component: "builtins", Type: ToolChain::FT_Static,
9452 /*IsFortran=*/false));
9453 if (HasCompilerRT)
9454 CmdArgs.push_back(
9455 Elt: Args.MakeArgString(Str: "--device-linker=" + TC.getTripleString() + "=" +
9456 "-lclang_rt.builtins"));
9457
9458 bool HasFlangRT = getToolChain().getVFS().exists(
9459 Path: TC.getCompilerRT(Args, Component: "runtime", Type: ToolChain::FT_Static,
9460 /*IsFortran=*/true));
9461 if (HasFlangRT && C.getDriver().IsFlangMode())
9462 CmdArgs.push_back(
9463 Elt: Args.MakeArgString(Str: "--device-linker=" + TC.getTripleString() + "=" +
9464 "-lflang_rt.runtime"));
9465 });
9466 }
9467
9468 // Add the linker arguments to be forwarded by the wrapper.
9469 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("--linker-path=") +
9470 LinkCommand->getExecutable()));
9471
9472 // We use action type to differentiate two use cases of the linker wrapper.
9473 // TY_Image for normal linker wrapper work.
9474 // TY_HIP_FATBIN for HIP fno-gpu-rdc emitting a fat binary without wrapping.
9475 assert(JA.getType() == types::TY_HIP_FATBIN ||
9476 JA.getType() == types::TY_Image);
9477 if (JA.getType() == types::TY_HIP_FATBIN) {
9478 CmdArgs.push_back(Elt: "--emit-fatbin-only");
9479 CmdArgs.append(IL: {"-o", Output.getFilename()});
9480 for (auto Input : Inputs)
9481 CmdArgs.push_back(Elt: Input.getFilename());
9482 } else
9483 for (const char *LinkArg : LinkCommand->getArguments())
9484 CmdArgs.push_back(Elt: LinkArg);
9485
9486 addOffloadCompressArgs(TCArgs: Args, CmdArgs);
9487
9488 if (Arg *A = Args.getLastArg(Ids: options::OPT_offload_jobs_EQ)) {
9489 StringRef Val = A->getValue();
9490
9491 if (Val.equals_insensitive(RHS: "jobserver"))
9492 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--wrapper-jobs=jobserver"));
9493 else {
9494 int NumThreads;
9495 if (Val.getAsInteger(Radix: 10, Result&: NumThreads) || NumThreads <= 0) {
9496 C.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
9497 << A->getAsString(Args) << Val;
9498 } else {
9499 CmdArgs.push_back(
9500 Elt: Args.MakeArgString(Str: "--wrapper-jobs=" + Twine(NumThreads)));
9501 }
9502 }
9503 }
9504
9505 const char *Exec =
9506 Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: "clang-linker-wrapper"));
9507
9508 // Replace the executable and arguments of the link job with the
9509 // wrapper.
9510 LinkCommand->replaceExecutable(Exe: Exec);
9511 LinkCommand->replaceArguments(List: CmdArgs);
9512}
9513