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/ARM.h"
11#include "Arch/LoongArch.h"
12#include "Arch/Mips.h"
13#include "Arch/PPC.h"
14#include "Arch/RISCV.h"
15#include "Arch/Sparc.h"
16#include "Arch/SystemZ.h"
17#include "Hexagon.h"
18#include "PS4CPU.h"
19#include "ToolChains/Cuda.h"
20#include "clang/Basic/CLWarnings.h"
21#include "clang/Basic/CodeGenOptions.h"
22#include "clang/Basic/HeaderInclude.h"
23#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/MakeSupport.h"
25#include "clang/Basic/ObjCRuntime.h"
26#include "clang/Basic/Version.h"
27#include "clang/Config/config.h"
28#include "clang/Driver/Action.h"
29#include "clang/Driver/CommonArgs.h"
30#include "clang/Driver/Distro.h"
31#include "clang/Driver/InputInfo.h"
32#include "clang/Driver/SanitizerArgs.h"
33#include "clang/Driver/Types.h"
34#include "clang/Driver/XRayArgs.h"
35#include "clang/Options/OptionUtils.h"
36#include "clang/Options/Options.h"
37#include "llvm/ADT/ScopeExit.h"
38#include "llvm/ADT/SmallSet.h"
39#include "llvm/ADT/StringExtras.h"
40#include "llvm/BinaryFormat/Magic.h"
41#include "llvm/Config/llvm-config.h"
42#include "llvm/Frontend/Debug/Options.h"
43#include "llvm/Object/ObjectFile.h"
44#include "llvm/Option/ArgList.h"
45#include "llvm/ProfileData/InstrProfReader.h"
46#include "llvm/Support/CodeGen.h"
47#include "llvm/Support/Compiler.h"
48#include "llvm/Support/Compression.h"
49#include "llvm/Support/Error.h"
50#include "llvm/Support/FileSystem.h"
51#include "llvm/Support/Path.h"
52#include "llvm/Support/Process.h"
53#include "llvm/Support/YAMLParser.h"
54#include "llvm/TargetParser/AArch64TargetParser.h"
55#include "llvm/TargetParser/ARMTargetParserCommon.h"
56#include "llvm/TargetParser/Host.h"
57#include "llvm/TargetParser/LoongArchTargetParser.h"
58#include "llvm/TargetParser/PPCTargetParser.h"
59#include "llvm/TargetParser/RISCVISAInfo.h"
60#include "llvm/TargetParser/RISCVTargetParser.h"
61#include <cctype>
62
63using namespace clang::driver;
64using namespace clang::driver::tools;
65using namespace clang;
66using namespace llvm::opt;
67
68static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
69 if (Arg *A = Args.getLastArg(Ids: options::OPT_C, Ids: options::OPT_CC,
70 Ids: options::OPT_fminimize_whitespace,
71 Ids: options::OPT_fno_minimize_whitespace,
72 Ids: options::OPT_fkeep_system_includes,
73 Ids: options::OPT_fno_keep_system_includes)) {
74 if (!Args.hasArg(Ids: options::OPT_E) && !Args.hasArg(Ids: options::OPT__SLASH_P) &&
75 !Args.hasArg(Ids: options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
76 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
77 << A->getBaseArg().getAsString(Args)
78 << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
79 }
80 }
81}
82
83static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
84 // In gcc, only ARM checks this, but it seems reasonable to check universally.
85 if (Args.hasArg(Ids: options::OPT_static))
86 if (const Arg *A =
87 Args.getLastArg(Ids: options::OPT_dynamic, Ids: options::OPT_mdynamic_no_pic))
88 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
89 << "-static";
90}
91
92/// Apply \a Work on the current tool chain \a RegularToolChain and any other
93/// offloading tool chain that is associated with the current action \a JA.
94static void
95forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
96 const ToolChain &RegularToolChain,
97 llvm::function_ref<void(const ToolChain &)> Work) {
98 // Apply Work on the current/regular tool chain.
99 Work(RegularToolChain);
100
101 // Apply Work on all the offloading tool chains associated with the current
102 // action.
103 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,
104 Action::OFK_HIP, Action::OFK_SYCL}) {
105 if (JA.isHostOffloading(OKind: Kind)) {
106 auto TCs = C.getOffloadToolChains(Kind);
107 for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
108 Work(*II->second);
109 } else if (JA.isDeviceOffloading(OKind: Kind))
110 Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
111 }
112}
113
114static bool
115shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
116 const llvm::Triple &Triple) {
117 // We use the zero-cost exception tables for Objective-C if the non-fragile
118 // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
119 // later.
120 if (runtime.isNonFragile())
121 return true;
122
123 if (!Triple.isMacOSX())
124 return false;
125
126 return (!Triple.isMacOSXVersionLT(Major: 10, Minor: 5) &&
127 (Triple.getArch() == llvm::Triple::x86_64 ||
128 Triple.getArch() == llvm::Triple::arm));
129}
130
131/// Adds exception related arguments to the driver command arguments. There's a
132/// main flag, -fexceptions and also language specific flags to enable/disable
133/// C++ and Objective-C exceptions. This makes it possible to for example
134/// disable C++ exceptions but enable Objective-C exceptions.
135static bool addExceptionArgs(const ArgList &Args, types::ID InputType,
136 const ToolChain &TC, bool KernelOrKext,
137 const ObjCRuntime &objcRuntime,
138 ArgStringList &CmdArgs) {
139 const llvm::Triple &Triple = TC.getTriple();
140
141 if (KernelOrKext) {
142 // -mkernel and -fapple-kext imply no exceptions, so claim exception related
143 // arguments now to avoid warnings about unused arguments.
144 Args.ClaimAllArgs(Id0: options::OPT_fexceptions);
145 Args.ClaimAllArgs(Id0: options::OPT_fno_exceptions);
146 Args.ClaimAllArgs(Id0: options::OPT_fobjc_exceptions);
147 Args.ClaimAllArgs(Id0: options::OPT_fno_objc_exceptions);
148 Args.ClaimAllArgs(Id0: options::OPT_fcxx_exceptions);
149 Args.ClaimAllArgs(Id0: options::OPT_fno_cxx_exceptions);
150 Args.ClaimAllArgs(Id0: options::OPT_fasync_exceptions);
151 Args.ClaimAllArgs(Id0: options::OPT_fno_async_exceptions);
152 return false;
153 }
154
155 // See if the user explicitly enabled exceptions.
156 bool EH = Args.hasFlag(Pos: options::OPT_fexceptions, Neg: options::OPT_fno_exceptions,
157 Default: false);
158
159 // Async exceptions are Windows MSVC only.
160 if (Triple.isWindowsMSVCEnvironment()) {
161 bool EHa = Args.hasFlag(Pos: options::OPT_fasync_exceptions,
162 Neg: options::OPT_fno_async_exceptions, Default: false);
163 if (EHa) {
164 CmdArgs.push_back(Elt: "-fasync-exceptions");
165 EH = true;
166 }
167 }
168
169 // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
170 // is not necessarily sensible, but follows GCC.
171 if (types::isObjC(Id: InputType) &&
172 Args.hasFlag(Pos: options::OPT_fobjc_exceptions,
173 Neg: options::OPT_fno_objc_exceptions, Default: true)) {
174 CmdArgs.push_back(Elt: "-fobjc-exceptions");
175
176 EH |= shouldUseExceptionTablesForObjCExceptions(runtime: objcRuntime, Triple);
177 }
178
179 if (types::isCXX(Id: InputType)) {
180 // Disable C++ EH by default on XCore and PS4/PS5.
181 bool CXXExceptionsEnabled = Triple.getArch() != llvm::Triple::xcore &&
182 !Triple.isPS() && !Triple.isDriverKit();
183 Arg *ExceptionArg = Args.getLastArg(
184 Ids: options::OPT_fcxx_exceptions, Ids: options::OPT_fno_cxx_exceptions,
185 Ids: options::OPT_fexceptions, Ids: options::OPT_fno_exceptions);
186 if (ExceptionArg)
187 CXXExceptionsEnabled =
188 ExceptionArg->getOption().matches(ID: options::OPT_fcxx_exceptions) ||
189 ExceptionArg->getOption().matches(ID: options::OPT_fexceptions);
190
191 if (CXXExceptionsEnabled) {
192 CmdArgs.push_back(Elt: "-fcxx-exceptions");
193
194 EH = true;
195 }
196 }
197
198 // OPT_fignore_exceptions means exception could still be thrown,
199 // but no clean up or catch would happen in current module.
200 // So we do not set EH to false.
201 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fignore_exceptions);
202
203 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fassume_nothrow_exception_dtor,
204 Neg: options::OPT_fno_assume_nothrow_exception_dtor);
205
206 if (EH)
207 CmdArgs.push_back(Elt: "-fexceptions");
208 return EH;
209}
210
211static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
212 const JobAction &JA) {
213 bool Default = true;
214 if (TC.getTriple().isOSDarwin()) {
215 // The native darwin assembler doesn't support the linker_option directives,
216 // so we disable them if we think the .s file will be passed to it.
217 Default = TC.useIntegratedAs();
218 }
219 // The linker_option directives are intended for host compilation.
220 if (JA.isDeviceOffloading(OKind: Action::OFK_Cuda) ||
221 JA.isDeviceOffloading(OKind: Action::OFK_HIP))
222 Default = false;
223 return Args.hasFlag(Pos: options::OPT_fautolink, Neg: options::OPT_fno_autolink,
224 Default);
225}
226
227/// Add a CC1 option to specify the debug compilation directory.
228static const char *addDebugCompDirArg(const ArgList &Args,
229 ArgStringList &CmdArgs,
230 const llvm::vfs::FileSystem &VFS) {
231 std::string DebugCompDir;
232 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffile_compilation_dir_EQ,
233 Ids: options::OPT_fdebug_compilation_dir_EQ))
234 DebugCompDir = A->getValue();
235
236 if (DebugCompDir.empty()) {
237 if (llvm::ErrorOr<std::string> CWD = VFS.getCurrentWorkingDirectory())
238 DebugCompDir = std::move(*CWD);
239 else
240 return nullptr;
241 }
242 CmdArgs.push_back(
243 Elt: Args.MakeArgString(Str: "-fdebug-compilation-dir=" + DebugCompDir));
244 StringRef Path(CmdArgs.back());
245 return Path.substr(Start: Path.find(C: '=') + 1).data();
246}
247
248static void addDebugObjectName(const ArgList &Args, ArgStringList &CmdArgs,
249 const char *DebugCompilationDir,
250 const char *OutputFileName) {
251 // No need to generate a value for -object-file-name if it was provided.
252 for (auto *Arg : Args.filtered(Ids: options::OPT_Xclang))
253 if (StringRef(Arg->getValue()).starts_with(Prefix: "-object-file-name"))
254 return;
255
256 if (Args.hasArg(Ids: options::OPT_object_file_name_EQ))
257 return;
258
259 SmallString<128> ObjFileNameForDebug(OutputFileName);
260 if (ObjFileNameForDebug != "-" &&
261 !llvm::sys::path::is_absolute(path: ObjFileNameForDebug) &&
262 (!DebugCompilationDir ||
263 llvm::sys::path::is_absolute(path: DebugCompilationDir))) {
264 // Make the path absolute in the debug infos like MSVC does.
265 llvm::sys::fs::make_absolute(path&: ObjFileNameForDebug);
266 }
267 // If the object file name is a relative path, then always use Windows
268 // backslash style as -object-file-name is used for embedding object file path
269 // in codeview and it can only be generated when targeting on Windows.
270 // Otherwise, just use native absolute path.
271 llvm::sys::path::Style Style =
272 llvm::sys::path::is_absolute(path: ObjFileNameForDebug)
273 ? llvm::sys::path::Style::native
274 : llvm::sys::path::Style::windows_backslash;
275 llvm::sys::path::remove_dots(path&: ObjFileNameForDebug, /*remove_dot_dot=*/true,
276 style: Style);
277 CmdArgs.push_back(
278 Elt: Args.MakeArgString(Str: Twine("-object-file-name=") + ObjFileNameForDebug));
279}
280
281/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
282static void addDebugPrefixMapArg(const Driver &D, const ToolChain &TC,
283 const ArgList &Args, ArgStringList &CmdArgs) {
284 auto AddOneArg = [&](StringRef Map, StringRef Name) {
285 if (!Map.contains(C: '='))
286 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option) << Map << Name;
287 else
288 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fdebug-prefix-map=" + Map));
289 };
290
291 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
292 Ids: options::OPT_fdebug_prefix_map_EQ)) {
293 AddOneArg(A->getValue(), A->getOption().getName());
294 A->claim();
295 }
296 std::string GlobalRemapEntry = TC.GetGlobalDebugPathRemapping();
297 if (GlobalRemapEntry.empty())
298 return;
299 AddOneArg(GlobalRemapEntry, "environment");
300}
301
302/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
303static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
304 ArgStringList &CmdArgs) {
305 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
306 Ids: options::OPT_fmacro_prefix_map_EQ)) {
307 StringRef Map = A->getValue();
308 if (!Map.contains(C: '='))
309 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
310 << Map << A->getOption().getName();
311 else
312 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fmacro-prefix-map=" + Map));
313 A->claim();
314 }
315}
316
317/// Add a CC1 and CC1AS option to specify the coverage file path prefix map.
318static void addCoveragePrefixMapArg(const Driver &D, const ArgList &Args,
319 ArgStringList &CmdArgs) {
320 for (const Arg *A : Args.filtered(Ids: options::OPT_ffile_prefix_map_EQ,
321 Ids: options::OPT_fcoverage_prefix_map_EQ)) {
322 StringRef Map = A->getValue();
323 if (!Map.contains(C: '='))
324 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
325 << Map << A->getOption().getName();
326 else
327 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fcoverage-prefix-map=" + Map));
328 A->claim();
329 }
330}
331
332/// Add -x lang to \p CmdArgs for \p Input.
333static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
334 ArgStringList &CmdArgs) {
335 // When using -verify-pch, we don't want to provide the type
336 // 'precompiled-header' if it was inferred from the file extension
337 if (Args.hasArg(Ids: options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
338 return;
339
340 CmdArgs.push_back(Elt: "-x");
341 if (Args.hasArg(Ids: options::OPT_rewrite_objc))
342 CmdArgs.push_back(Elt: types::getTypeName(Id: types::TY_ObjCXX));
343 else {
344 // Map the driver type to the frontend type. This is mostly an identity
345 // mapping, except that the distinction between module interface units
346 // and other source files does not exist at the frontend layer.
347 const char *ClangType;
348 switch (Input.getType()) {
349 case types::TY_CXXModule:
350 ClangType = "c++";
351 break;
352 case types::TY_PP_CXXModule:
353 ClangType = "c++-cpp-output";
354 break;
355 default:
356 ClangType = types::getTypeName(Id: Input.getType());
357 break;
358 }
359 CmdArgs.push_back(Elt: ClangType);
360 }
361}
362
363static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
364 const JobAction &JA, const InputInfo &Output,
365 const ArgList &Args, SanitizerArgs &SanArgs,
366 ArgStringList &CmdArgs) {
367 const Driver &D = TC.getDriver();
368 const llvm::Triple &T = TC.getTriple();
369 auto *PGOGenerateArg = Args.getLastArg(Ids: options::OPT_fprofile_generate,
370 Ids: options::OPT_fprofile_generate_EQ,
371 Ids: options::OPT_fno_profile_generate);
372 if (PGOGenerateArg &&
373 PGOGenerateArg->getOption().matches(ID: options::OPT_fno_profile_generate))
374 PGOGenerateArg = nullptr;
375
376 auto *CSPGOGenerateArg = getLastCSProfileGenerateArg(Args);
377
378 auto *ProfileGenerateArg = Args.getLastArg(
379 Ids: options::OPT_fprofile_instr_generate,
380 Ids: options::OPT_fprofile_instr_generate_EQ,
381 Ids: options::OPT_fno_profile_instr_generate);
382 if (ProfileGenerateArg &&
383 ProfileGenerateArg->getOption().matches(
384 ID: options::OPT_fno_profile_instr_generate))
385 ProfileGenerateArg = nullptr;
386
387 if (PGOGenerateArg && ProfileGenerateArg)
388 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
389 << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
390
391 auto *ProfileUseArg = getLastProfileUseArg(Args);
392
393 if (PGOGenerateArg && ProfileUseArg)
394 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
395 << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
396
397 if (ProfileGenerateArg && ProfileUseArg)
398 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
399 << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
400
401 if (CSPGOGenerateArg && PGOGenerateArg) {
402 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
403 << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
404 PGOGenerateArg = nullptr;
405 }
406
407 if (TC.getTriple().isOSAIX()) {
408 if (Arg *ProfileSampleUseArg = getLastProfileSampleUseArg(Args))
409 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
410 << ProfileSampleUseArg->getSpelling() << TC.getTriple().str();
411 }
412
413 if (ProfileGenerateArg) {
414 if (ProfileGenerateArg->getOption().matches(
415 ID: options::OPT_fprofile_instr_generate_EQ))
416 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-path=") +
417 ProfileGenerateArg->getValue()));
418 // The default is to use Clang Instrumentation.
419 CmdArgs.push_back(Elt: "-fprofile-instrument=clang");
420 if (TC.getTriple().isWindowsMSVCEnvironment() &&
421 Args.hasFlag(Pos: options::OPT_frtlib_defaultlib,
422 Neg: options::OPT_fno_rtlib_defaultlib, Default: true)) {
423 // Add dependent lib for clang_rt.profile
424 CmdArgs.push_back(Elt: Args.MakeArgString(
425 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "profile")));
426 }
427 }
428
429 if (auto *ColdFuncCoverageArg = Args.getLastArg(
430 Ids: options::OPT_fprofile_generate_cold_function_coverage,
431 Ids: options::OPT_fprofile_generate_cold_function_coverage_EQ)) {
432 SmallString<128> Path(
433 ColdFuncCoverageArg->getOption().matches(
434 ID: options::OPT_fprofile_generate_cold_function_coverage_EQ)
435 ? ColdFuncCoverageArg->getValue()
436 : "");
437 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
438 // FIXME: Idealy the file path should be passed through
439 // `-fprofile-instrument-path=`(InstrProfileOutput), however, this field is
440 // shared with other profile use path(see PGOOptions), we need to refactor
441 // PGOOptions to make it work.
442 CmdArgs.push_back(Elt: "-mllvm");
443 CmdArgs.push_back(Elt: Args.MakeArgString(
444 Str: Twine("--instrument-cold-function-only-path=") + Path));
445 CmdArgs.push_back(Elt: "-mllvm");
446 CmdArgs.push_back(Elt: "--pgo-instrument-cold-function-only");
447 CmdArgs.push_back(Elt: "-mllvm");
448 CmdArgs.push_back(Elt: "--pgo-function-entry-coverage");
449 CmdArgs.push_back(Elt: "-fprofile-instrument=sample-coldcov");
450 }
451
452 if (auto *A = Args.getLastArg(Ids: options::OPT_ftemporal_profile)) {
453 if (!PGOGenerateArg && !CSPGOGenerateArg)
454 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
455 << A->getSpelling() << "-fprofile-generate or -fcs-profile-generate";
456 CmdArgs.push_back(Elt: "-mllvm");
457 CmdArgs.push_back(Elt: "--pgo-temporal-instrumentation");
458 }
459
460 Arg *PGOGenArg = nullptr;
461 if (PGOGenerateArg) {
462 assert(!CSPGOGenerateArg);
463 PGOGenArg = PGOGenerateArg;
464 CmdArgs.push_back(Elt: "-fprofile-instrument=llvm");
465 }
466 if (CSPGOGenerateArg) {
467 assert(!PGOGenerateArg);
468 PGOGenArg = CSPGOGenerateArg;
469 CmdArgs.push_back(Elt: "-fprofile-instrument=csllvm");
470 }
471 if (PGOGenArg) {
472 if (TC.getTriple().isWindowsMSVCEnvironment() &&
473 Args.hasFlag(Pos: options::OPT_frtlib_defaultlib,
474 Neg: options::OPT_fno_rtlib_defaultlib, Default: true)) {
475 // Add dependent lib for clang_rt.profile
476 CmdArgs.push_back(Elt: Args.MakeArgString(
477 Str: "--dependent-lib=" + TC.getCompilerRTBasename(Args, Component: "profile")));
478 }
479 if (PGOGenArg->getOption().matches(
480 ID: PGOGenerateArg ? options::OPT_fprofile_generate_EQ
481 : options::OPT_fcs_profile_generate_EQ)) {
482 SmallString<128> Path(PGOGenArg->getValue());
483 llvm::sys::path::append(path&: Path, a: "default_%m.profraw");
484 CmdArgs.push_back(
485 Elt: Args.MakeArgString(Str: Twine("-fprofile-instrument-path=") + Path));
486 }
487 }
488
489 if (ProfileUseArg) {
490 SmallString<128> UsePathBuf;
491 StringRef UsePath;
492 if (ProfileUseArg->getOption().matches(ID: options::OPT_fprofile_instr_use_EQ))
493 UsePath = ProfileUseArg->getValue();
494 else if ((ProfileUseArg->getOption().matches(
495 ID: options::OPT_fprofile_use_EQ) ||
496 ProfileUseArg->getOption().matches(
497 ID: options::OPT_fprofile_instr_use))) {
498 UsePathBuf =
499 ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue();
500 if (UsePathBuf.empty() || llvm::sys::fs::is_directory(Path: UsePathBuf))
501 llvm::sys::path::append(path&: UsePathBuf, a: "default.profdata");
502 UsePath = UsePathBuf;
503 }
504 auto ReaderOrErr =
505 llvm::IndexedInstrProfReader::create(Path: UsePath, FS&: D.getVFS());
506 if (auto E = ReaderOrErr.takeError()) {
507 auto DiagID = D.getDiags().getCustomDiagID(
508 L: DiagnosticsEngine::Error, FormatString: "Error in reading profile %0: %1");
509 llvm::handleAllErrors(E: std::move(E), Handlers: [&](const llvm::ErrorInfoBase &EI) {
510 D.Diag(DiagID) << UsePath.str() << EI.message();
511 });
512 } else {
513 std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
514 std::move(ReaderOrErr.get());
515 StringRef UseKind;
516 // Currently memprof profiles are only added at the IR level. Mark the
517 // profile type as IR in that case as well and the subsequent matching
518 // needs to detect which is available (might be one or both).
519 if (PGOReader->isIRLevelProfile() || PGOReader->hasMemoryProfile()) {
520 if (PGOReader->hasCSIRLevelProfile())
521 UseKind = "csllvm";
522 else
523 UseKind = "llvm";
524 } else
525 UseKind = "clang";
526
527 CmdArgs.push_back(
528 Elt: Args.MakeArgString(Str: "-fprofile-instrument-use=" + UseKind));
529 CmdArgs.push_back(
530 Elt: Args.MakeArgString(Str: "-fprofile-instrument-use-path=" + UsePath));
531 }
532 }
533
534 bool EmitCovNotes = Args.hasFlag(Pos: options::OPT_ftest_coverage,
535 Neg: options::OPT_fno_test_coverage, Default: false) ||
536 Args.hasArg(Ids: options::OPT_coverage);
537 bool EmitCovData = TC.needsGCovInstrumentation(Args);
538
539 if (Args.hasFlag(Pos: options::OPT_fcoverage_mapping,
540 Neg: options::OPT_fno_coverage_mapping, Default: false)) {
541 if (!ProfileGenerateArg)
542 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
543 << "-fcoverage-mapping"
544 << "-fprofile-instr-generate";
545
546 CmdArgs.push_back(Elt: "-fcoverage-mapping");
547 }
548
549 if (Args.hasFlag(Pos: options::OPT_fmcdc_coverage, Neg: options::OPT_fno_mcdc_coverage,
550 Default: false)) {
551 if (!Args.hasFlag(Pos: options::OPT_fcoverage_mapping,
552 Neg: options::OPT_fno_coverage_mapping, Default: false))
553 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
554 << "-fcoverage-mcdc"
555 << "-fcoverage-mapping";
556
557 CmdArgs.push_back(Elt: "-fcoverage-mcdc");
558 }
559
560 StringRef CoverageCompDir;
561 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffile_compilation_dir_EQ,
562 Ids: options::OPT_fcoverage_compilation_dir_EQ))
563 CoverageCompDir = A->getValue();
564 if (CoverageCompDir.empty()) {
565 if (auto CWD = D.getVFS().getCurrentWorkingDirectory())
566 CmdArgs.push_back(
567 Elt: Args.MakeArgString(Str: Twine("-fcoverage-compilation-dir=") + *CWD));
568 } else
569 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fcoverage-compilation-dir=") +
570 CoverageCompDir));
571
572 if (Args.hasArg(Ids: options::OPT_fprofile_exclude_files_EQ)) {
573 auto *Arg = Args.getLastArg(Ids: options::OPT_fprofile_exclude_files_EQ);
574 if (!Args.hasArg(Ids: options::OPT_coverage))
575 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
576 << "-fprofile-exclude-files="
577 << "--coverage";
578
579 StringRef v = Arg->getValue();
580 CmdArgs.push_back(
581 Elt: Args.MakeArgString(Str: Twine("-fprofile-exclude-files=" + v)));
582 }
583
584 if (Args.hasArg(Ids: options::OPT_fprofile_filter_files_EQ)) {
585 auto *Arg = Args.getLastArg(Ids: options::OPT_fprofile_filter_files_EQ);
586 if (!Args.hasArg(Ids: options::OPT_coverage))
587 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
588 << "-fprofile-filter-files="
589 << "--coverage";
590
591 StringRef v = Arg->getValue();
592 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-fprofile-filter-files=" + v)));
593 }
594
595 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_update_EQ)) {
596 StringRef Val = A->getValue();
597 if (Val == "atomic" || Val == "prefer-atomic")
598 CmdArgs.push_back(Elt: "-fprofile-update=atomic");
599 else if (Val != "single")
600 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
601 << A->getSpelling() << Val;
602 }
603 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_continuous)) {
604 if (!PGOGenerateArg && !CSPGOGenerateArg && !ProfileGenerateArg)
605 D.Diag(DiagID: clang::diag::err_drv_argument_only_allowed_with)
606 << A->getSpelling()
607 << "-fprofile-generate, -fprofile-instr-generate, or "
608 "-fcs-profile-generate";
609 else {
610 CmdArgs.push_back(Elt: "-fprofile-continuous");
611 // Platforms that require a bias variable:
612 if (T.isOSBinFormatELF() || T.isOSAIX() || T.isOSWindows()) {
613 CmdArgs.push_back(Elt: "-mllvm");
614 CmdArgs.push_back(Elt: "-runtime-counter-relocation");
615 }
616 // -fprofile-instr-generate does not decide the profile file name in the
617 // FE, and so it does not define the filename symbol
618 // (__llvm_profile_filename). Instead, the runtime uses the name
619 // "default.profraw" for the profile file. When continuous mode is ON, we
620 // will create the filename symbol so that we can insert the "%c"
621 // modifier.
622 if (ProfileGenerateArg &&
623 (ProfileGenerateArg->getOption().matches(
624 ID: options::OPT_fprofile_instr_generate) ||
625 (ProfileGenerateArg->getOption().matches(
626 ID: options::OPT_fprofile_instr_generate_EQ) &&
627 strlen(s: ProfileGenerateArg->getValue()) == 0)))
628 CmdArgs.push_back(Elt: "-fprofile-instrument-path=default.profraw");
629 }
630 }
631
632 int FunctionGroups = 1;
633 int SelectedFunctionGroup = 0;
634 if (const auto *A = Args.getLastArg(Ids: options::OPT_fprofile_function_groups)) {
635 StringRef Val = A->getValue();
636 if (Val.getAsInteger(Radix: 0, Result&: FunctionGroups) || FunctionGroups < 1)
637 D.Diag(DiagID: diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
638 }
639 if (const auto *A =
640 Args.getLastArg(Ids: options::OPT_fprofile_selected_function_group)) {
641 StringRef Val = A->getValue();
642 if (Val.getAsInteger(Radix: 0, Result&: SelectedFunctionGroup) ||
643 SelectedFunctionGroup < 0 || SelectedFunctionGroup >= FunctionGroups)
644 D.Diag(DiagID: diag::err_drv_invalid_int_value) << A->getAsString(Args) << Val;
645 }
646 if (FunctionGroups != 1)
647 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-function-groups=" +
648 Twine(FunctionGroups)));
649 if (SelectedFunctionGroup != 0)
650 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-selected-function-group=" +
651 Twine(SelectedFunctionGroup)));
652
653 // Leave -fprofile-dir= an unused argument unless .gcda emission is
654 // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
655 // the flag used. There is no -fno-profile-dir, so the user has no
656 // targeted way to suppress the warning.
657 Arg *FProfileDir = nullptr;
658 if (Args.hasArg(Ids: options::OPT_fprofile_arcs) ||
659 Args.hasArg(Ids: options::OPT_coverage))
660 FProfileDir = Args.getLastArg(Ids: options::OPT_fprofile_dir);
661
662 // Put the .gcno and .gcda files (if needed) next to the primary output file,
663 // or fall back to a file in the current directory for `clang -c --coverage
664 // d/a.c` in the absence of -o.
665 if (EmitCovNotes || EmitCovData) {
666 SmallString<128> CoverageFilename;
667 if (Arg *DumpDir = Args.getLastArgNoClaim(Ids: options::OPT_dumpdir)) {
668 // Form ${dumpdir}${basename}.gcno. Note that dumpdir may not end with a
669 // path separator.
670 CoverageFilename = DumpDir->getValue();
671 CoverageFilename += llvm::sys::path::filename(path: Output.getBaseInput());
672 } else if (Arg *FinalOutput =
673 C.getArgs().getLastArg(Ids: options::OPT__SLASH_Fo)) {
674 CoverageFilename = FinalOutput->getValue();
675 } else if (Arg *FinalOutput = C.getArgs().getLastArg(Ids: options::OPT_o)) {
676 CoverageFilename = FinalOutput->getValue();
677 } else {
678 CoverageFilename = llvm::sys::path::filename(path: Output.getBaseInput());
679 }
680 if (llvm::sys::path::is_relative(path: CoverageFilename))
681 (void)D.getVFS().makeAbsolute(Path&: CoverageFilename);
682 llvm::sys::path::replace_extension(path&: CoverageFilename, extension: "gcno");
683 if (EmitCovNotes) {
684 CmdArgs.push_back(
685 Elt: Args.MakeArgString(Str: "-coverage-notes-file=" + CoverageFilename));
686 }
687
688 if (EmitCovData) {
689 if (FProfileDir) {
690 SmallString<128> Gcno = std::move(CoverageFilename);
691 CoverageFilename = FProfileDir->getValue();
692 llvm::sys::path::append(path&: CoverageFilename, a: Gcno);
693 }
694 llvm::sys::path::replace_extension(path&: CoverageFilename, extension: "gcda");
695 CmdArgs.push_back(
696 Elt: Args.MakeArgString(Str: "-coverage-data-file=" + CoverageFilename));
697 }
698 }
699}
700
701static void
702RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
703 llvm::codegenoptions::DebugInfoKind DebugInfoKind,
704 unsigned DwarfVersion,
705 llvm::DebuggerKind DebuggerTuning) {
706 addDebugInfoKind(CmdArgs, DebugInfoKind);
707 if (DwarfVersion > 0)
708 CmdArgs.push_back(
709 Elt: Args.MakeArgString(Str: "-dwarf-version=" + Twine(DwarfVersion)));
710 switch (DebuggerTuning) {
711 case llvm::DebuggerKind::GDB:
712 CmdArgs.push_back(Elt: "-debugger-tuning=gdb");
713 break;
714 case llvm::DebuggerKind::LLDB:
715 CmdArgs.push_back(Elt: "-debugger-tuning=lldb");
716 break;
717 case llvm::DebuggerKind::SCE:
718 CmdArgs.push_back(Elt: "-debugger-tuning=sce");
719 break;
720 case llvm::DebuggerKind::DBX:
721 CmdArgs.push_back(Elt: "-debugger-tuning=dbx");
722 break;
723 default:
724 break;
725 }
726}
727
728static void RenderDebugInfoCompressionArgs(const ArgList &Args,
729 ArgStringList &CmdArgs,
730 const Driver &D,
731 const ToolChain &TC) {
732 const Arg *A = Args.getLastArg(Ids: options::OPT_gz_EQ);
733 if (!A)
734 return;
735 if (checkDebugInfoOption(A, Args, D, TC)) {
736 StringRef Value = A->getValue();
737 if (Value == "none") {
738 CmdArgs.push_back(Elt: "--compress-debug-sections=none");
739 } else if (Value == "zlib") {
740 if (llvm::compression::zlib::isAvailable()) {
741 CmdArgs.push_back(
742 Elt: Args.MakeArgString(Str: "--compress-debug-sections=" + Twine(Value)));
743 } else {
744 D.Diag(DiagID: diag::warn_debug_compression_unavailable) << "zlib";
745 }
746 } else if (Value == "zstd") {
747 if (llvm::compression::zstd::isAvailable()) {
748 CmdArgs.push_back(
749 Elt: Args.MakeArgString(Str: "--compress-debug-sections=" + Twine(Value)));
750 } else {
751 D.Diag(DiagID: diag::warn_debug_compression_unavailable) << "zstd";
752 }
753 } else {
754 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
755 << A->getSpelling() << Value;
756 }
757 }
758}
759
760static void handleAMDGPUCodeObjectVersionOptions(const Driver &D,
761 const ArgList &Args,
762 ArgStringList &CmdArgs,
763 bool IsCC1As = false) {
764 // If no version was requested by the user, use the default value from the
765 // back end. This is consistent with the value returned from
766 // getAMDGPUCodeObjectVersion. This lets clang emit IR for amdgpu without
767 // requiring the corresponding llvm to have the AMDGPU target enabled,
768 // provided the user (e.g. front end tests) can use the default.
769 if (haveAMDGPUCodeObjectVersionArgument(D, Args)) {
770 unsigned CodeObjVer = getAMDGPUCodeObjectVersion(D, Args);
771 CmdArgs.insert(I: CmdArgs.begin() + 1,
772 Elt: Args.MakeArgString(Str: Twine("--amdhsa-code-object-version=") +
773 Twine(CodeObjVer)));
774 CmdArgs.insert(I: CmdArgs.begin() + 1, Elt: "-mllvm");
775 // -cc1as does not accept -mcode-object-version option.
776 if (!IsCC1As)
777 CmdArgs.insert(I: CmdArgs.begin() + 1,
778 Elt: Args.MakeArgString(Str: Twine("-mcode-object-version=") +
779 Twine(CodeObjVer)));
780 }
781}
782
783static bool maybeHasClangPchSignature(const Driver &D, StringRef Path) {
784 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> MemBuf =
785 D.getVFS().getBufferForFile(Name: Path);
786 if (!MemBuf)
787 return false;
788 llvm::file_magic Magic = llvm::identify_magic(magic: (*MemBuf)->getBuffer());
789 if (Magic == llvm::file_magic::unknown)
790 return false;
791 // Return true for both raw Clang AST files and object files which may
792 // contain a __clangast section.
793 if (Magic == llvm::file_magic::clang_ast)
794 return true;
795 Expected<std::unique_ptr<llvm::object::ObjectFile>> Obj =
796 llvm::object::ObjectFile::createObjectFile(Object: **MemBuf, Type: Magic);
797 return !Obj.takeError();
798}
799
800static bool gchProbe(const Driver &D, StringRef Path) {
801 llvm::ErrorOr<llvm::vfs::Status> Status = D.getVFS().status(Path);
802 if (!Status)
803 return false;
804
805 if (Status->isDirectory()) {
806 std::error_code EC;
807 for (llvm::vfs::directory_iterator DI = D.getVFS().dir_begin(Dir: Path, EC), DE;
808 !EC && DI != DE; DI = DI.increment(EC)) {
809 if (maybeHasClangPchSignature(D, Path: DI->path()))
810 return true;
811 }
812 D.Diag(DiagID: diag::warn_drv_pch_ignoring_gch_dir) << Path;
813 return false;
814 }
815
816 if (maybeHasClangPchSignature(D, Path))
817 return true;
818 D.Diag(DiagID: diag::warn_drv_pch_ignoring_gch_file) << Path;
819 return false;
820}
821
822void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
823 const Driver &D, const ArgList &Args,
824 ArgStringList &CmdArgs,
825 const InputInfo &Output,
826 const InputInfoList &Inputs) const {
827 const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
828
829 CheckPreprocessingOptions(D, Args);
830
831 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_C);
832 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_CC);
833
834 // Handle dependency file generation.
835 Arg *ArgM = Args.getLastArg(Ids: options::OPT_MM);
836 if (!ArgM)
837 ArgM = Args.getLastArg(Ids: options::OPT_M);
838 Arg *ArgMD = Args.getLastArg(Ids: options::OPT_MMD);
839 if (!ArgMD)
840 ArgMD = Args.getLastArg(Ids: options::OPT_MD);
841
842 // -M and -MM imply -w.
843 if (ArgM)
844 CmdArgs.push_back(Elt: "-w");
845 else
846 ArgM = ArgMD;
847
848 if (ArgM) {
849 if (!JA.isDeviceOffloading(OKind: Action::OFK_HIP)) {
850 // Determine the output location.
851 const char *DepFile;
852 if (Arg *MF = Args.getLastArg(Ids: options::OPT_MF)) {
853 DepFile = MF->getValue();
854 C.addFailureResultFile(Name: DepFile, JA: &JA);
855 } else if (Output.getType() == types::TY_Dependencies) {
856 DepFile = Output.getFilename();
857 } else if (!ArgMD) {
858 DepFile = "-";
859 } else {
860 DepFile = getDependencyFileName(Args, Inputs);
861 C.addFailureResultFile(Name: DepFile, JA: &JA);
862 }
863 CmdArgs.push_back(Elt: "-dependency-file");
864 CmdArgs.push_back(Elt: DepFile);
865 }
866 // Cmake generates dependency files using all compilation options specified
867 // by users. Claim those not used for dependency files.
868 if (JA.isOffloading(OKind: Action::OFK_HIP)) {
869 Args.ClaimAllArgs(Id0: options::OPT_offload_compress);
870 Args.ClaimAllArgs(Id0: options::OPT_no_offload_compress);
871 Args.ClaimAllArgs(Id0: options::OPT_offload_jobs_EQ);
872 }
873
874 bool HasTarget = false;
875 for (const Arg *A : Args.filtered(Ids: options::OPT_MT, Ids: options::OPT_MQ)) {
876 HasTarget = true;
877 A->claim();
878 if (A->getOption().matches(ID: options::OPT_MT)) {
879 A->render(Args, Output&: CmdArgs);
880 } else {
881 CmdArgs.push_back(Elt: "-MT");
882 SmallString<128> Quoted;
883 quoteMakeTarget(Target: A->getValue(), Res&: Quoted);
884 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Quoted));
885 }
886 }
887
888 // Add a default target if one wasn't specified.
889 if (!HasTarget) {
890 const char *DepTarget;
891
892 // If user provided -o, that is the dependency target, except
893 // when we are only generating a dependency file.
894 Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o, Ids: options::OPT__SLASH_Fo);
895 if (OutputOpt && Output.getType() != types::TY_Dependencies) {
896 DepTarget = OutputOpt->getValue();
897 } else {
898 // Otherwise derive from the base input.
899 //
900 // FIXME: This should use the computed output file location.
901 SmallString<128> P(Inputs[0].getBaseInput());
902 llvm::sys::path::replace_extension(path&: P, extension: "o");
903 DepTarget = Args.MakeArgString(Str: llvm::sys::path::filename(path: P));
904 }
905
906 CmdArgs.push_back(Elt: "-MT");
907 SmallString<128> Quoted;
908 quoteMakeTarget(Target: DepTarget, Res&: Quoted);
909 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Quoted));
910 }
911
912 if (ArgM->getOption().matches(ID: options::OPT_M) ||
913 ArgM->getOption().matches(ID: options::OPT_MD))
914 CmdArgs.push_back(Elt: "-sys-header-deps");
915 if ((isa<PrecompileJobAction>(Val: JA) &&
916 !Args.hasArg(Ids: options::OPT_fno_module_file_deps)) ||
917 Args.hasArg(Ids: options::OPT_fmodule_file_deps))
918 CmdArgs.push_back(Elt: "-module-file-deps");
919 }
920
921 if (Args.hasArg(Ids: options::OPT_MG)) {
922 if (!ArgM || ArgM->getOption().matches(ID: options::OPT_MD) ||
923 ArgM->getOption().matches(ID: options::OPT_MMD))
924 D.Diag(DiagID: diag::err_drv_mg_requires_m_or_mm);
925 CmdArgs.push_back(Elt: "-MG");
926 }
927
928 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_MP);
929 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_MV);
930
931 // Add offload include arguments specific for CUDA/HIP/SYCL. This must happen
932 // before we -I or -include anything else, because we must pick up the
933 // CUDA/HIP/SYCL headers from the particular CUDA/ROCm/SYCL installation,
934 // rather than from e.g. /usr/local/include.
935 if (JA.isOffloading(OKind: Action::OFK_Cuda))
936 getToolChain().AddCudaIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
937 if (JA.isOffloading(OKind: Action::OFK_HIP))
938 getToolChain().AddHIPIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
939 if (JA.isOffloading(OKind: Action::OFK_SYCL))
940 getToolChain().addSYCLIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
941
942 // If we are offloading to a target via OpenMP we need to include the
943 // openmp_wrappers folder which contains alternative system headers.
944 if (JA.isDeviceOffloading(OKind: Action::OFK_OpenMP) &&
945 !Args.hasArg(Ids: options::OPT_nostdinc) &&
946 Args.hasFlag(Pos: options::OPT_offload_inc, Neg: options::OPT_no_offload_inc,
947 Default: true) &&
948 getToolChain().getTriple().isGPU()) {
949 if (!Args.hasArg(Ids: options::OPT_nobuiltininc)) {
950 // Add openmp_wrappers/* to our system include path. This lets us wrap
951 // standard library headers.
952 SmallString<128> P(D.ResourceDir);
953 llvm::sys::path::append(path&: P, a: "include");
954 llvm::sys::path::append(path&: P, a: "openmp_wrappers");
955 CmdArgs.push_back(Elt: "-internal-isystem");
956 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
957 }
958
959 CmdArgs.push_back(Elt: "-include");
960 CmdArgs.push_back(Elt: "__clang_openmp_device_functions.h");
961 }
962
963 if (Args.hasArg(Ids: options::OPT_foffload_via_llvm)) {
964 // Add llvm_wrappers/* to our system include path. This lets us wrap
965 // standard library headers and other headers.
966 SmallString<128> P(D.ResourceDir);
967 llvm::sys::path::append(path&: P, a: "include", b: "llvm_offload_wrappers");
968 CmdArgs.append(IL: {"-internal-isystem", Args.MakeArgString(Str: P), "-include"});
969 if (JA.isDeviceOffloading(OKind: Action::OFK_OpenMP))
970 CmdArgs.push_back(Elt: "__llvm_offload_device.h");
971 else
972 CmdArgs.push_back(Elt: "__llvm_offload_host.h");
973 }
974
975 // Add -i* options, and automatically translate to
976 // -include-pch/-include-pth for transparent PCH support. It's
977 // wonky, but we include looking for .gch so we can support seamless
978 // replacement into a build system already set up to be generating
979 // .gch files.
980
981 if (getToolChain().getDriver().IsCLMode()) {
982 const Arg *YcArg = Args.getLastArg(Ids: options::OPT__SLASH_Yc);
983 const Arg *YuArg = Args.getLastArg(Ids: options::OPT__SLASH_Yu);
984 if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
985 JA.getKind() <= Action::AssembleJobClass) {
986 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-building-pch-with-obj"));
987 // -fpch-instantiate-templates is the default when creating
988 // precomp using /Yc
989 if (Args.hasFlag(Pos: options::OPT_fpch_instantiate_templates,
990 Neg: options::OPT_fno_pch_instantiate_templates, Default: true))
991 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fpch-instantiate-templates"));
992 }
993 if (YcArg || YuArg) {
994 StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
995 if (!isa<PrecompileJobAction>(Val: JA)) {
996 CmdArgs.push_back(Elt: "-include-pch");
997 CmdArgs.push_back(Elt: Args.MakeArgString(Str: D.GetClPchPath(
998 C, BaseName: !ThroughHeader.empty()
999 ? ThroughHeader
1000 : llvm::sys::path::filename(path: Inputs[0].getBaseInput()))));
1001 }
1002
1003 if (ThroughHeader.empty()) {
1004 CmdArgs.push_back(Elt: Args.MakeArgString(
1005 Str: Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1006 } else {
1007 CmdArgs.push_back(
1008 Elt: Args.MakeArgString(Str: Twine("-pch-through-header=") + ThroughHeader));
1009 }
1010 }
1011 }
1012
1013 bool RenderedImplicitInclude = false;
1014 for (const Arg *A : Args.filtered(Ids: options::OPT_clang_i_Group)) {
1015 if (A->getOption().matches(ID: options::OPT_include) &&
1016 D.getProbePrecompiled()) {
1017 // Handling of gcc-style gch precompiled headers.
1018 bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1019 RenderedImplicitInclude = true;
1020
1021 bool FoundPCH = false;
1022 SmallString<128> P(A->getValue());
1023 // We want the files to have a name like foo.h.pch. Add a dummy extension
1024 // so that replace_extension does the right thing.
1025 P += ".dummy";
1026 llvm::sys::path::replace_extension(path&: P, extension: "pch");
1027 if (D.getVFS().exists(Path: P))
1028 FoundPCH = true;
1029
1030 if (!FoundPCH) {
1031 // For GCC compat, probe for a file or directory ending in .gch instead.
1032 llvm::sys::path::replace_extension(path&: P, extension: "gch");
1033 FoundPCH = gchProbe(D, Path: P.str());
1034 }
1035
1036 if (FoundPCH) {
1037 if (IsFirstImplicitInclude) {
1038 A->claim();
1039 CmdArgs.push_back(Elt: "-include-pch");
1040 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1041 continue;
1042 } else {
1043 // Ignore the PCH if not first on command line and emit warning.
1044 D.Diag(DiagID: diag::warn_drv_pch_not_first_include) << P
1045 << A->getAsString(Args);
1046 }
1047 }
1048 } else if (A->getOption().matches(ID: options::OPT_isystem_after)) {
1049 // Handling of paths which must come late. These entries are handled by
1050 // the toolchain itself after the resource dir is inserted in the right
1051 // search order.
1052 // Do not claim the argument so that the use of the argument does not
1053 // silently go unnoticed on toolchains which do not honour the option.
1054 continue;
1055 } else if (A->getOption().matches(ID: options::OPT_stdlibxx_isystem)) {
1056 // Translated to -internal-isystem by the driver, no need to pass to cc1.
1057 continue;
1058 } else if (A->getOption().matches(ID: options::OPT_ibuiltininc)) {
1059 // This is used only by the driver. No need to pass to cc1.
1060 continue;
1061 }
1062
1063 // Not translated, render as usual.
1064 A->claim();
1065 A->render(Args, Output&: CmdArgs);
1066 }
1067
1068 if (C.isOffloadingHostKind(Kind: Action::OFK_Cuda) ||
1069 JA.isDeviceOffloading(OKind: Action::OFK_Cuda)) {
1070 // Collect all enabled NVPTX architectures.
1071 std::set<unsigned> ArchIDs;
1072 for (auto &I : llvm::make_range(p: C.getOffloadToolChains(Kind: Action::OFK_Cuda))) {
1073 const ToolChain *TC = I.second;
1074 for (StringRef Arch :
1075 D.getOffloadArchs(C, Args: C.getArgs(), Kind: Action::OFK_Cuda, TC: *TC)) {
1076 OffloadArch OA = StringToOffloadArch(S: Arch);
1077 if (IsNVIDIAOffloadArch(A: OA))
1078 ArchIDs.insert(x: CudaArchToID(Arch: OA));
1079 }
1080 }
1081
1082 if (!ArchIDs.empty()) {
1083 SmallString<128> List;
1084 llvm::raw_svector_ostream OS(List);
1085 llvm::interleave(c: ArchIDs, os&: OS, separator: ",");
1086 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-D__CUDA_ARCH_LIST__=" + List));
1087 }
1088 }
1089
1090 Args.addAllArgs(Output&: CmdArgs,
1091 Ids: {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1092 options::OPT_F, options::OPT_embed_dir_EQ});
1093
1094 // Add -Wp, and -Xpreprocessor if using the preprocessor.
1095
1096 // FIXME: There is a very unfortunate problem here, some troubled
1097 // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1098 // really support that we would have to parse and then translate
1099 // those options. :(
1100 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Wp_COMMA,
1101 Id1: options::OPT_Xpreprocessor);
1102
1103 // -I- is a deprecated GCC feature, reject it.
1104 if (Arg *A = Args.getLastArg(Ids: options::OPT_I_))
1105 D.Diag(DiagID: diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1106
1107 // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1108 // -isysroot to the CC1 invocation.
1109 StringRef sysroot = C.getSysRoot();
1110 if (sysroot != "") {
1111 if (!Args.hasArg(Ids: options::OPT_isysroot)) {
1112 CmdArgs.push_back(Elt: "-isysroot");
1113 CmdArgs.push_back(Elt: C.getArgs().MakeArgString(Str: sysroot));
1114 }
1115 }
1116
1117 // Parse additional include paths from environment variables.
1118 // FIXME: We should probably sink the logic for handling these from the
1119 // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1120 // CPATH - included following the user specified includes (but prior to
1121 // builtin and standard includes).
1122 addDirectoryList(Args, CmdArgs, ArgName: "-I", EnvVar: "CPATH");
1123 // C_INCLUDE_PATH - system includes enabled when compiling C.
1124 addDirectoryList(Args, CmdArgs, ArgName: "-c-isystem", EnvVar: "C_INCLUDE_PATH");
1125 // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1126 addDirectoryList(Args, CmdArgs, ArgName: "-cxx-isystem", EnvVar: "CPLUS_INCLUDE_PATH");
1127 // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1128 addDirectoryList(Args, CmdArgs, ArgName: "-objc-isystem", EnvVar: "OBJC_INCLUDE_PATH");
1129 // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1130 addDirectoryList(Args, CmdArgs, ArgName: "-objcxx-isystem", EnvVar: "OBJCPLUS_INCLUDE_PATH");
1131
1132 // While adding the include arguments, we also attempt to retrieve the
1133 // arguments of related offloading toolchains or arguments that are specific
1134 // of an offloading programming model.
1135
1136 // Add C++ include arguments, if needed.
1137 if (types::isCXX(Id: Inputs[0].getType())) {
1138 bool HasStdlibxxIsystem = Args.hasArg(Ids: options::OPT_stdlibxx_isystem);
1139 forAllAssociatedToolChains(
1140 C, JA, RegularToolChain: getToolChain(),
1141 Work: [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1142 HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(DriverArgs: Args, CC1Args&: CmdArgs)
1143 : TC.AddClangCXXStdlibIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1144 });
1145 }
1146
1147 // If we are compiling for a GPU target we want to override the system headers
1148 // with ones created by the 'libc' project if present.
1149 // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
1150 // OffloadKind as an argument.
1151 if (!Args.hasArg(Ids: options::OPT_nostdinc) &&
1152 Args.hasFlag(Pos: options::OPT_offload_inc, Neg: options::OPT_no_offload_inc,
1153 Default: true) &&
1154 !Args.hasArg(Ids: options::OPT_nobuiltininc) &&
1155 (C.getActiveOffloadKinds() == Action::OFK_OpenMP)) {
1156 // TODO: CUDA / HIP include their own headers for some common functions
1157 // implemented here. We'll need to clean those up so they do not conflict.
1158 SmallString<128> P(D.ResourceDir);
1159 llvm::sys::path::append(path&: P, a: "include");
1160 llvm::sys::path::append(path&: P, a: "llvm_libc_wrappers");
1161 CmdArgs.push_back(Elt: "-internal-isystem");
1162 CmdArgs.push_back(Elt: Args.MakeArgString(Str: P));
1163 }
1164
1165 // Add system include arguments for all targets but IAMCU.
1166 if (!IsIAMCU)
1167 forAllAssociatedToolChains(C, JA, RegularToolChain: getToolChain(),
1168 Work: [&Args, &CmdArgs](const ToolChain &TC) {
1169 TC.AddClangSystemIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1170 });
1171 else {
1172 // For IAMCU add special include arguments.
1173 getToolChain().AddIAMCUIncludeArgs(DriverArgs: Args, CC1Args&: CmdArgs);
1174 }
1175
1176 addMacroPrefixMapArg(D, Args, CmdArgs);
1177 addCoveragePrefixMapArg(D, Args, CmdArgs);
1178
1179 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffile_reproducible,
1180 Ids: options::OPT_fno_file_reproducible);
1181
1182 if (const char *Epoch = std::getenv(name: "SOURCE_DATE_EPOCH")) {
1183 CmdArgs.push_back(Elt: "-source-date-epoch");
1184 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Epoch));
1185 }
1186
1187 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdefine_target_os_macros,
1188 Neg: options::OPT_fno_define_target_os_macros);
1189}
1190
1191// FIXME: Move to target hook.
1192static bool isSignedCharDefault(const llvm::Triple &Triple) {
1193 switch (Triple.getArch()) {
1194 default:
1195 return true;
1196
1197 case llvm::Triple::aarch64:
1198 case llvm::Triple::aarch64_32:
1199 case llvm::Triple::aarch64_be:
1200 case llvm::Triple::arm:
1201 case llvm::Triple::armeb:
1202 case llvm::Triple::thumb:
1203 case llvm::Triple::thumbeb:
1204 if (Triple.isOSDarwin() || Triple.isOSWindows())
1205 return true;
1206 return false;
1207
1208 case llvm::Triple::ppc:
1209 case llvm::Triple::ppc64:
1210 if (Triple.isOSDarwin())
1211 return true;
1212 return false;
1213
1214 case llvm::Triple::csky:
1215 case llvm::Triple::hexagon:
1216 case llvm::Triple::msp430:
1217 case llvm::Triple::ppcle:
1218 case llvm::Triple::ppc64le:
1219 case llvm::Triple::riscv32:
1220 case llvm::Triple::riscv64:
1221 case llvm::Triple::systemz:
1222 case llvm::Triple::xcore:
1223 case llvm::Triple::xtensa:
1224 return false;
1225 }
1226}
1227
1228static bool hasMultipleInvocations(const llvm::Triple &Triple,
1229 const ArgList &Args) {
1230 // Supported only on Darwin where we invoke the compiler multiple times
1231 // followed by an invocation to lipo.
1232 if (!Triple.isOSDarwin())
1233 return false;
1234 // If more than one "-arch <arch>" is specified, we're targeting multiple
1235 // architectures resulting in a fat binary.
1236 return Args.getAllArgValues(Id: options::OPT_arch).size() > 1;
1237}
1238
1239static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1240 const llvm::Triple &Triple) {
1241 // When enabling remarks, we need to error if:
1242 // * The remark file is specified but we're targeting multiple architectures,
1243 // which means more than one remark file is being generated.
1244 bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1245 bool hasExplicitOutputFile =
1246 Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ);
1247 if (hasMultipleInvocations && hasExplicitOutputFile) {
1248 D.Diag(DiagID: diag::err_drv_invalid_output_with_multiple_archs)
1249 << "-foptimization-record-file";
1250 return false;
1251 }
1252 return true;
1253}
1254
1255static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1256 const llvm::Triple &Triple,
1257 const InputInfo &Input,
1258 const InputInfo &Output, const JobAction &JA) {
1259 StringRef Format = "yaml";
1260 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsave_optimization_record_EQ))
1261 Format = A->getValue();
1262
1263 CmdArgs.push_back(Elt: "-opt-record-file");
1264
1265 const Arg *A = Args.getLastArg(Ids: options::OPT_foptimization_record_file_EQ);
1266 if (A) {
1267 CmdArgs.push_back(Elt: A->getValue());
1268 } else {
1269 bool hasMultipleArchs =
1270 Triple.isOSDarwin() && // Only supported on Darwin platforms.
1271 Args.getAllArgValues(Id: options::OPT_arch).size() > 1;
1272
1273 SmallString<128> F;
1274
1275 if (Args.hasArg(Ids: options::OPT_c) || Args.hasArg(Ids: options::OPT_S)) {
1276 if (Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o))
1277 F = FinalOutput->getValue();
1278 } else {
1279 if (Format != "yaml" && // For YAML, keep the original behavior.
1280 Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1281 Output.isFilename())
1282 F = Output.getFilename();
1283 }
1284
1285 if (F.empty()) {
1286 // Use the input filename.
1287 F = llvm::sys::path::stem(path: Input.getBaseInput());
1288
1289 // If we're compiling for an offload architecture (i.e. a CUDA device),
1290 // we need to make the file name for the device compilation different
1291 // from the host compilation.
1292 if (!JA.isDeviceOffloading(OKind: Action::OFK_None) &&
1293 !JA.isDeviceOffloading(OKind: Action::OFK_Host)) {
1294 llvm::sys::path::replace_extension(path&: F, extension: "");
1295 F += Action::GetOffloadingFileNamePrefix(Kind: JA.getOffloadingDeviceKind(),
1296 NormalizedTriple: Triple.normalize());
1297 F += "-";
1298 F += JA.getOffloadingArch();
1299 }
1300 }
1301
1302 // If we're having more than one "-arch", we should name the files
1303 // differently so that every cc1 invocation writes to a different file.
1304 // We're doing that by appending "-<arch>" with "<arch>" being the arch
1305 // name from the triple.
1306 if (hasMultipleArchs) {
1307 // First, remember the extension.
1308 SmallString<64> OldExtension = llvm::sys::path::extension(path: F);
1309 // then, remove it.
1310 llvm::sys::path::replace_extension(path&: F, extension: "");
1311 // attach -<arch> to it.
1312 F += "-";
1313 F += Triple.getArchName();
1314 // put back the extension.
1315 llvm::sys::path::replace_extension(path&: F, extension: OldExtension);
1316 }
1317
1318 SmallString<32> Extension;
1319 Extension += "opt.";
1320 Extension += Format;
1321
1322 llvm::sys::path::replace_extension(path&: F, extension: Extension);
1323 CmdArgs.push_back(Elt: Args.MakeArgString(Str: F));
1324 }
1325
1326 if (const Arg *A =
1327 Args.getLastArg(Ids: options::OPT_foptimization_record_passes_EQ)) {
1328 CmdArgs.push_back(Elt: "-opt-record-passes");
1329 CmdArgs.push_back(Elt: A->getValue());
1330 }
1331
1332 if (!Format.empty()) {
1333 CmdArgs.push_back(Elt: "-opt-record-format");
1334 CmdArgs.push_back(Elt: Format.data());
1335 }
1336}
1337
1338void AddAAPCSVolatileBitfieldArgs(const ArgList &Args, ArgStringList &CmdArgs) {
1339 if (!Args.hasFlag(Pos: options::OPT_faapcs_bitfield_width,
1340 Neg: options::OPT_fno_aapcs_bitfield_width, Default: true))
1341 CmdArgs.push_back(Elt: "-fno-aapcs-bitfield-width");
1342
1343 if (Args.getLastArg(Ids: options::OPT_ForceAAPCSBitfieldLoad))
1344 CmdArgs.push_back(Elt: "-faapcs-bitfield-load");
1345}
1346
1347namespace {
1348void RenderARMABI(const Driver &D, const llvm::Triple &Triple,
1349 const ArgList &Args, ArgStringList &CmdArgs) {
1350 // Select the ABI to use.
1351 // FIXME: Support -meabi.
1352 // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1353 const char *ABIName = nullptr;
1354 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ))
1355 ABIName = A->getValue();
1356 else
1357 ABIName = llvm::ARM::computeDefaultTargetABI(TT: Triple).data();
1358
1359 CmdArgs.push_back(Elt: "-target-abi");
1360 CmdArgs.push_back(Elt: ABIName);
1361}
1362
1363void AddUnalignedAccessWarning(ArgStringList &CmdArgs) {
1364 auto StrictAlignIter =
1365 llvm::find_if(Range: llvm::reverse(C&: CmdArgs), P: [](StringRef Arg) {
1366 return Arg == "+strict-align" || Arg == "-strict-align";
1367 });
1368 if (StrictAlignIter != CmdArgs.rend() &&
1369 StringRef(*StrictAlignIter) == "+strict-align")
1370 CmdArgs.push_back(Elt: "-Wunaligned-access");
1371}
1372}
1373
1374static void CollectARMPACBTIOptions(const ToolChain &TC, const ArgList &Args,
1375 ArgStringList &CmdArgs, bool isAArch64) {
1376 const llvm::Triple &Triple = TC.getEffectiveTriple();
1377 const Arg *A = isAArch64
1378 ? Args.getLastArg(Ids: options::OPT_msign_return_address_EQ,
1379 Ids: options::OPT_mbranch_protection_EQ)
1380 : Args.getLastArg(Ids: options::OPT_mbranch_protection_EQ);
1381 if (!A) {
1382 if (Triple.isOSOpenBSD() && isAArch64) {
1383 CmdArgs.push_back(Elt: "-msign-return-address=non-leaf");
1384 CmdArgs.push_back(Elt: "-msign-return-address-key=a_key");
1385 CmdArgs.push_back(Elt: "-mbranch-target-enforce");
1386 }
1387 return;
1388 }
1389
1390 const Driver &D = TC.getDriver();
1391 if (!(isAArch64 || (Triple.isArmT32() && Triple.isArmMClass())))
1392 D.Diag(DiagID: diag::warn_incompatible_branch_protection_option)
1393 << Triple.getArchName();
1394
1395 StringRef Scope, Key;
1396 bool IndirectBranches, BranchProtectionPAuthLR, GuardedControlStack;
1397
1398 if (A->getOption().matches(ID: options::OPT_msign_return_address_EQ)) {
1399 Scope = A->getValue();
1400 if (Scope != "none" && Scope != "non-leaf" && Scope != "all")
1401 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1402 << A->getSpelling() << Scope;
1403 Key = "a_key";
1404 IndirectBranches = Triple.isOSOpenBSD() && isAArch64;
1405 BranchProtectionPAuthLR = false;
1406 GuardedControlStack = false;
1407 } else {
1408 StringRef DiagMsg;
1409 llvm::ARM::ParsedBranchProtection PBP;
1410 bool EnablePAuthLR = false;
1411
1412 // To know if we need to enable PAuth-LR As part of the standard branch
1413 // protection option, it needs to be determined if the feature has been
1414 // activated in the `march` argument. This information is stored within the
1415 // CmdArgs variable and can be found using a search.
1416 if (isAArch64) {
1417 auto isPAuthLR = [](const char *member) {
1418 llvm::AArch64::ExtensionInfo pauthlr_extension =
1419 llvm::AArch64::getExtensionByID(ExtID: llvm::AArch64::AEK_PAUTHLR);
1420 return pauthlr_extension.PosTargetFeature == member;
1421 };
1422
1423 if (llvm::any_of(Range&: CmdArgs, P: isPAuthLR))
1424 EnablePAuthLR = true;
1425 }
1426 if (!llvm::ARM::parseBranchProtection(Spec: A->getValue(), PBP, Err&: DiagMsg,
1427 EnablePAuthLR))
1428 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1429 << A->getSpelling() << DiagMsg;
1430 if (!isAArch64 && PBP.Key == "b_key")
1431 D.Diag(DiagID: diag::warn_unsupported_branch_protection)
1432 << "b-key" << A->getAsString(Args);
1433 Scope = PBP.Scope;
1434 Key = PBP.Key;
1435 BranchProtectionPAuthLR = PBP.BranchProtectionPAuthLR;
1436 IndirectBranches = PBP.BranchTargetEnforcement;
1437 GuardedControlStack = PBP.GuardedControlStack;
1438 }
1439
1440 Arg *PtrauthReturnsArg = Args.getLastArg(Ids: options::OPT_fptrauth_returns,
1441 Ids: options::OPT_fno_ptrauth_returns);
1442 bool HasPtrauthReturns =
1443 PtrauthReturnsArg &&
1444 PtrauthReturnsArg->getOption().matches(ID: options::OPT_fptrauth_returns);
1445 // GCS is currently untested with ptrauth-returns, but enabling this could be
1446 // allowed in future after testing with a suitable system.
1447 if (Scope != "none" || BranchProtectionPAuthLR || GuardedControlStack) {
1448 if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
1449 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
1450 << A->getAsString(Args) << Triple.getTriple();
1451 else if (HasPtrauthReturns)
1452 D.Diag(DiagID: diag::err_drv_incompatible_options)
1453 << A->getAsString(Args) << "-fptrauth-returns";
1454 }
1455
1456 CmdArgs.push_back(
1457 Elt: Args.MakeArgString(Str: Twine("-msign-return-address=") + Scope));
1458 if (Scope != "none")
1459 CmdArgs.push_back(
1460 Elt: Args.MakeArgString(Str: Twine("-msign-return-address-key=") + Key));
1461 if (BranchProtectionPAuthLR)
1462 CmdArgs.push_back(
1463 Elt: Args.MakeArgString(Str: Twine("-mbranch-protection-pauth-lr")));
1464 if (IndirectBranches)
1465 CmdArgs.push_back(Elt: "-mbranch-target-enforce");
1466
1467 if (GuardedControlStack)
1468 CmdArgs.push_back(Elt: "-mguarded-control-stack");
1469}
1470
1471void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1472 ArgStringList &CmdArgs, bool KernelOrKext) const {
1473 RenderARMABI(D: getToolChain().getDriver(), Triple, Args, CmdArgs);
1474
1475 // Determine floating point ABI from the options & target defaults.
1476 arm::FloatABI ABI = arm::getARMFloatABI(TC: getToolChain(), Args);
1477 if (ABI == arm::FloatABI::Soft) {
1478 // Floating point operations and argument passing are soft.
1479 // FIXME: This changes CPP defines, we need -target-soft-float.
1480 CmdArgs.push_back(Elt: "-msoft-float");
1481 CmdArgs.push_back(Elt: "-mfloat-abi");
1482 CmdArgs.push_back(Elt: "soft");
1483 } else if (ABI == arm::FloatABI::SoftFP) {
1484 // Floating point operations are hard, but argument passing is soft.
1485 CmdArgs.push_back(Elt: "-mfloat-abi");
1486 CmdArgs.push_back(Elt: "soft");
1487 } else {
1488 // Floating point operations and argument passing are hard.
1489 assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1490 CmdArgs.push_back(Elt: "-mfloat-abi");
1491 CmdArgs.push_back(Elt: "hard");
1492 }
1493
1494 // Forward the -mglobal-merge option for explicit control over the pass.
1495 if (Arg *A = Args.getLastArg(Ids: options::OPT_mglobal_merge,
1496 Ids: options::OPT_mno_global_merge)) {
1497 CmdArgs.push_back(Elt: "-mllvm");
1498 if (A->getOption().matches(ID: options::OPT_mno_global_merge))
1499 CmdArgs.push_back(Elt: "-arm-global-merge=false");
1500 else
1501 CmdArgs.push_back(Elt: "-arm-global-merge=true");
1502 }
1503
1504 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
1505 Neg: options::OPT_mno_implicit_float, Default: true))
1506 CmdArgs.push_back(Elt: "-no-implicit-float");
1507
1508 if (Args.getLastArg(Ids: options::OPT_mcmse))
1509 CmdArgs.push_back(Elt: "-mcmse");
1510
1511 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1512
1513 // Enable/disable return address signing and indirect branch targets.
1514 CollectARMPACBTIOptions(TC: getToolChain(), Args, CmdArgs, isAArch64: false /*isAArch64*/);
1515
1516 AddUnalignedAccessWarning(CmdArgs);
1517}
1518
1519void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1520 const ArgList &Args, bool KernelOrKext,
1521 ArgStringList &CmdArgs) const {
1522 const ToolChain &TC = getToolChain();
1523
1524 // Add the target features
1525 getTargetFeatures(D: TC.getDriver(), Triple: EffectiveTriple, Args, CmdArgs, ForAS: false);
1526
1527 // Add target specific flags.
1528 switch (TC.getArch()) {
1529 default:
1530 break;
1531
1532 case llvm::Triple::arm:
1533 case llvm::Triple::armeb:
1534 case llvm::Triple::thumb:
1535 case llvm::Triple::thumbeb:
1536 // Use the effective triple, which takes into account the deployment target.
1537 AddARMTargetArgs(Triple: EffectiveTriple, Args, CmdArgs, KernelOrKext);
1538 break;
1539
1540 case llvm::Triple::aarch64:
1541 case llvm::Triple::aarch64_32:
1542 case llvm::Triple::aarch64_be:
1543 AddAArch64TargetArgs(Args, CmdArgs);
1544 break;
1545
1546 case llvm::Triple::loongarch32:
1547 case llvm::Triple::loongarch64:
1548 AddLoongArchTargetArgs(Args, CmdArgs);
1549 break;
1550
1551 case llvm::Triple::mips:
1552 case llvm::Triple::mipsel:
1553 case llvm::Triple::mips64:
1554 case llvm::Triple::mips64el:
1555 AddMIPSTargetArgs(Args, CmdArgs);
1556 break;
1557
1558 case llvm::Triple::ppc:
1559 case llvm::Triple::ppcle:
1560 case llvm::Triple::ppc64:
1561 case llvm::Triple::ppc64le:
1562 AddPPCTargetArgs(Args, CmdArgs);
1563 break;
1564
1565 case llvm::Triple::riscv32:
1566 case llvm::Triple::riscv64:
1567 AddRISCVTargetArgs(Args, CmdArgs);
1568 break;
1569
1570 case llvm::Triple::sparc:
1571 case llvm::Triple::sparcel:
1572 case llvm::Triple::sparcv9:
1573 AddSparcTargetArgs(Args, CmdArgs);
1574 break;
1575
1576 case llvm::Triple::systemz:
1577 AddSystemZTargetArgs(Args, CmdArgs);
1578 break;
1579
1580 case llvm::Triple::x86:
1581 case llvm::Triple::x86_64:
1582 AddX86TargetArgs(Args, CmdArgs);
1583 break;
1584
1585 case llvm::Triple::lanai:
1586 AddLanaiTargetArgs(Args, CmdArgs);
1587 break;
1588
1589 case llvm::Triple::hexagon:
1590 AddHexagonTargetArgs(Args, CmdArgs);
1591 break;
1592
1593 case llvm::Triple::wasm32:
1594 case llvm::Triple::wasm64:
1595 AddWebAssemblyTargetArgs(Args, CmdArgs);
1596 break;
1597
1598 case llvm::Triple::ve:
1599 AddVETargetArgs(Args, CmdArgs);
1600 break;
1601 }
1602}
1603
1604namespace {
1605void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1606 ArgStringList &CmdArgs) {
1607 const char *ABIName = nullptr;
1608 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ))
1609 ABIName = A->getValue();
1610 else if (Triple.isOSDarwin())
1611 ABIName = "darwinpcs";
1612 // TODO: we probably want to have some target hook here.
1613 else if (Triple.isOSLinux() &&
1614 Triple.getEnvironment() == llvm::Triple::PAuthTest)
1615 ABIName = "pauthtest";
1616 else
1617 ABIName = "aapcs";
1618
1619 CmdArgs.push_back(Elt: "-target-abi");
1620 CmdArgs.push_back(Elt: ABIName);
1621}
1622}
1623
1624void Clang::AddAArch64TargetArgs(const ArgList &Args,
1625 ArgStringList &CmdArgs) const {
1626 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1627
1628 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true) ||
1629 Args.hasArg(Ids: options::OPT_mkernel) ||
1630 Args.hasArg(Ids: options::OPT_fapple_kext))
1631 CmdArgs.push_back(Elt: "-disable-red-zone");
1632
1633 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
1634 Neg: options::OPT_mno_implicit_float, Default: true))
1635 CmdArgs.push_back(Elt: "-no-implicit-float");
1636
1637 RenderAArch64ABI(Triple, Args, CmdArgs);
1638
1639 // Forward the -mglobal-merge option for explicit control over the pass.
1640 if (Arg *A = Args.getLastArg(Ids: options::OPT_mglobal_merge,
1641 Ids: options::OPT_mno_global_merge)) {
1642 CmdArgs.push_back(Elt: "-mllvm");
1643 if (A->getOption().matches(ID: options::OPT_mno_global_merge))
1644 CmdArgs.push_back(Elt: "-aarch64-enable-global-merge=false");
1645 else
1646 CmdArgs.push_back(Elt: "-aarch64-enable-global-merge=true");
1647 }
1648
1649 // Handle -msve_vector_bits=<bits>
1650 auto HandleVectorBits = [&](Arg *A, StringRef VScaleMin,
1651 StringRef VScaleMax) {
1652 StringRef Val = A->getValue();
1653 const Driver &D = getToolChain().getDriver();
1654 if (Val == "128" || Val == "256" || Val == "512" || Val == "1024" ||
1655 Val == "2048" || Val == "128+" || Val == "256+" || Val == "512+" ||
1656 Val == "1024+" || Val == "2048+") {
1657 unsigned Bits = 0;
1658 if (!Val.consume_back(Suffix: "+")) {
1659 bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits);
1660 (void)Invalid;
1661 assert(!Invalid && "Failed to parse value");
1662 CmdArgs.push_back(
1663 Elt: Args.MakeArgString(Str: VScaleMax + llvm::Twine(Bits / 128)));
1664 }
1665
1666 bool Invalid = Val.getAsInteger(Radix: 10, Result&: Bits);
1667 (void)Invalid;
1668 assert(!Invalid && "Failed to parse value");
1669
1670 CmdArgs.push_back(
1671 Elt: Args.MakeArgString(Str: VScaleMin + llvm::Twine(Bits / 128)));
1672 } else if (Val == "scalable") {
1673 // Silently drop requests for vector-length agnostic code as it's implied.
1674 } else {
1675 // Handle the unsupported values passed to msve-vector-bits.
1676 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1677 << A->getSpelling() << Val;
1678 }
1679 };
1680 if (Arg *A = Args.getLastArg(Ids: options::OPT_msve_vector_bits_EQ))
1681 HandleVectorBits(A, "-mvscale-min=", "-mvscale-max=");
1682 if (Arg *A = Args.getLastArg(Ids: options::OPT_msve_streaming_vector_bits_EQ))
1683 HandleVectorBits(A, "-mvscale-streaming-min=", "-mvscale-streaming-max=");
1684
1685 AddAAPCSVolatileBitfieldArgs(Args, CmdArgs);
1686
1687 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
1688 CmdArgs.push_back(Elt: "-tune-cpu");
1689 if (strcmp(s1: A->getValue(), s2: "native") == 0)
1690 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::getHostCPUName()));
1691 else
1692 CmdArgs.push_back(Elt: A->getValue());
1693 }
1694
1695 AddUnalignedAccessWarning(CmdArgs);
1696
1697 if (Triple.isOSDarwin() ||
1698 (Triple.isOSLinux() &&
1699 Triple.getEnvironment() == llvm::Triple::PAuthTest)) {
1700 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_intrinsics,
1701 Neg: options::OPT_fno_ptrauth_intrinsics);
1702 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_calls,
1703 Neg: options::OPT_fno_ptrauth_calls);
1704 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_returns,
1705 Neg: options::OPT_fno_ptrauth_returns);
1706 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_auth_traps,
1707 Neg: options::OPT_fno_ptrauth_auth_traps);
1708 Args.addOptInFlag(
1709 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtable_pointer_address_discrimination,
1710 Neg: options::OPT_fno_ptrauth_vtable_pointer_address_discrimination);
1711 Args.addOptInFlag(
1712 Output&: CmdArgs, Pos: options::OPT_fptrauth_vtable_pointer_type_discrimination,
1713 Neg: options::OPT_fno_ptrauth_vtable_pointer_type_discrimination);
1714 Args.addOptInFlag(
1715 Output&: CmdArgs, Pos: options::OPT_fptrauth_type_info_vtable_pointer_discrimination,
1716 Neg: options::OPT_fno_ptrauth_type_info_vtable_pointer_discrimination);
1717 Args.addOptInFlag(
1718 Output&: CmdArgs, Pos: options::OPT_fptrauth_function_pointer_type_discrimination,
1719 Neg: options::OPT_fno_ptrauth_function_pointer_type_discrimination);
1720 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_indirect_gotos,
1721 Neg: options::OPT_fno_ptrauth_indirect_gotos);
1722 }
1723 if (Triple.isOSLinux() &&
1724 Triple.getEnvironment() == llvm::Triple::PAuthTest) {
1725 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_init_fini,
1726 Neg: options::OPT_fno_ptrauth_init_fini);
1727 Args.addOptInFlag(
1728 Output&: CmdArgs, Pos: options::OPT_fptrauth_init_fini_address_discrimination,
1729 Neg: options::OPT_fno_ptrauth_init_fini_address_discrimination);
1730 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_elf_got,
1731 Neg: options::OPT_fno_ptrauth_elf_got);
1732 }
1733 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_faarch64_jump_table_hardening,
1734 Neg: options::OPT_fno_aarch64_jump_table_hardening);
1735
1736 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_isa,
1737 Neg: options::OPT_fno_ptrauth_objc_isa);
1738 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_interface_sel,
1739 Neg: options::OPT_fno_ptrauth_objc_interface_sel);
1740 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fptrauth_objc_class_ro,
1741 Neg: options::OPT_fno_ptrauth_objc_class_ro);
1742
1743 // Enable/disable return address signing and indirect branch targets.
1744 CollectARMPACBTIOptions(TC: getToolChain(), Args, CmdArgs, isAArch64: true /*isAArch64*/);
1745}
1746
1747void Clang::AddLoongArchTargetArgs(const ArgList &Args,
1748 ArgStringList &CmdArgs) const {
1749 const llvm::Triple &Triple = getToolChain().getTriple();
1750
1751 CmdArgs.push_back(Elt: "-target-abi");
1752 CmdArgs.push_back(
1753 Elt: loongarch::getLoongArchABI(D: getToolChain().getDriver(), Args, Triple)
1754 .data());
1755
1756 // Handle -mtune.
1757 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
1758 std::string TuneCPU = A->getValue();
1759 TuneCPU = loongarch::postProcessTargetCPUString(CPU: TuneCPU, Triple);
1760 CmdArgs.push_back(Elt: "-tune-cpu");
1761 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
1762 }
1763
1764 if (Arg *A = Args.getLastArg(Ids: options::OPT_mannotate_tablejump,
1765 Ids: options::OPT_mno_annotate_tablejump)) {
1766 if (A->getOption().matches(ID: options::OPT_mannotate_tablejump)) {
1767 CmdArgs.push_back(Elt: "-mllvm");
1768 CmdArgs.push_back(Elt: "-loongarch-annotate-tablejump");
1769 }
1770 }
1771}
1772
1773void Clang::AddMIPSTargetArgs(const ArgList &Args,
1774 ArgStringList &CmdArgs) const {
1775 const Driver &D = getToolChain().getDriver();
1776 StringRef CPUName;
1777 StringRef ABIName;
1778 const llvm::Triple &Triple = getToolChain().getTriple();
1779 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1780
1781 CmdArgs.push_back(Elt: "-target-abi");
1782 CmdArgs.push_back(Elt: ABIName.data());
1783
1784 mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1785 if (ABI == mips::FloatABI::Soft) {
1786 // Floating point operations and argument passing are soft.
1787 CmdArgs.push_back(Elt: "-msoft-float");
1788 CmdArgs.push_back(Elt: "-mfloat-abi");
1789 CmdArgs.push_back(Elt: "soft");
1790 } else {
1791 // Floating point operations and argument passing are hard.
1792 assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1793 CmdArgs.push_back(Elt: "-mfloat-abi");
1794 CmdArgs.push_back(Elt: "hard");
1795 }
1796
1797 if (Arg *A = Args.getLastArg(Ids: options::OPT_mldc1_sdc1,
1798 Ids: options::OPT_mno_ldc1_sdc1)) {
1799 if (A->getOption().matches(ID: options::OPT_mno_ldc1_sdc1)) {
1800 CmdArgs.push_back(Elt: "-mllvm");
1801 CmdArgs.push_back(Elt: "-mno-ldc1-sdc1");
1802 }
1803 }
1804
1805 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcheck_zero_division,
1806 Ids: options::OPT_mno_check_zero_division)) {
1807 if (A->getOption().matches(ID: options::OPT_mno_check_zero_division)) {
1808 CmdArgs.push_back(Elt: "-mllvm");
1809 CmdArgs.push_back(Elt: "-mno-check-zero-division");
1810 }
1811 }
1812
1813 if (Args.getLastArg(Ids: options::OPT_mfix4300)) {
1814 CmdArgs.push_back(Elt: "-mllvm");
1815 CmdArgs.push_back(Elt: "-mfix4300");
1816 }
1817
1818 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
1819 StringRef v = A->getValue();
1820 CmdArgs.push_back(Elt: "-mllvm");
1821 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mips-ssection-threshold=" + v));
1822 A->claim();
1823 }
1824
1825 Arg *GPOpt = Args.getLastArg(Ids: options::OPT_mgpopt, Ids: options::OPT_mno_gpopt);
1826 Arg *ABICalls =
1827 Args.getLastArg(Ids: options::OPT_mabicalls, Ids: options::OPT_mno_abicalls);
1828
1829 // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1830 // -mgpopt is the default for static, -fno-pic environments but these two
1831 // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1832 // the only case where -mllvm -mgpopt is passed.
1833 // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1834 // passed explicitly when compiling something with -mabicalls
1835 // (implictly) in affect. Currently the warning is in the backend.
1836 //
1837 // When the ABI in use is N64, we also need to determine the PIC mode that
1838 // is in use, as -fno-pic for N64 implies -mno-abicalls.
1839 bool NoABICalls =
1840 ABICalls && ABICalls->getOption().matches(ID: options::OPT_mno_abicalls);
1841
1842 llvm::Reloc::Model RelocationModel;
1843 unsigned PICLevel;
1844 bool IsPIE;
1845 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
1846 ParsePICArgs(ToolChain: getToolChain(), Args);
1847
1848 NoABICalls = NoABICalls ||
1849 (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1850
1851 bool WantGPOpt = GPOpt && GPOpt->getOption().matches(ID: options::OPT_mgpopt);
1852 // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1853 if (NoABICalls && (!GPOpt || WantGPOpt)) {
1854 CmdArgs.push_back(Elt: "-mllvm");
1855 CmdArgs.push_back(Elt: "-mgpopt");
1856
1857 Arg *LocalSData = Args.getLastArg(Ids: options::OPT_mlocal_sdata,
1858 Ids: options::OPT_mno_local_sdata);
1859 Arg *ExternSData = Args.getLastArg(Ids: options::OPT_mextern_sdata,
1860 Ids: options::OPT_mno_extern_sdata);
1861 Arg *EmbeddedData = Args.getLastArg(Ids: options::OPT_membedded_data,
1862 Ids: options::OPT_mno_embedded_data);
1863 if (LocalSData) {
1864 CmdArgs.push_back(Elt: "-mllvm");
1865 if (LocalSData->getOption().matches(ID: options::OPT_mlocal_sdata)) {
1866 CmdArgs.push_back(Elt: "-mlocal-sdata=1");
1867 } else {
1868 CmdArgs.push_back(Elt: "-mlocal-sdata=0");
1869 }
1870 LocalSData->claim();
1871 }
1872
1873 if (ExternSData) {
1874 CmdArgs.push_back(Elt: "-mllvm");
1875 if (ExternSData->getOption().matches(ID: options::OPT_mextern_sdata)) {
1876 CmdArgs.push_back(Elt: "-mextern-sdata=1");
1877 } else {
1878 CmdArgs.push_back(Elt: "-mextern-sdata=0");
1879 }
1880 ExternSData->claim();
1881 }
1882
1883 if (EmbeddedData) {
1884 CmdArgs.push_back(Elt: "-mllvm");
1885 if (EmbeddedData->getOption().matches(ID: options::OPT_membedded_data)) {
1886 CmdArgs.push_back(Elt: "-membedded-data=1");
1887 } else {
1888 CmdArgs.push_back(Elt: "-membedded-data=0");
1889 }
1890 EmbeddedData->claim();
1891 }
1892
1893 } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1894 D.Diag(DiagID: diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1895
1896 if (GPOpt)
1897 GPOpt->claim();
1898
1899 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcompact_branches_EQ)) {
1900 StringRef Val = StringRef(A->getValue());
1901 if (mips::hasCompactBranches(CPU&: CPUName)) {
1902 if (Val == "never" || Val == "always" || Val == "optimal") {
1903 CmdArgs.push_back(Elt: "-mllvm");
1904 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mips-compact-branches=" + Val));
1905 } else
1906 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
1907 << A->getSpelling() << Val;
1908 } else
1909 D.Diag(DiagID: diag::warn_target_unsupported_compact_branches) << CPUName;
1910 }
1911
1912 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrelax_pic_calls,
1913 Ids: options::OPT_mno_relax_pic_calls)) {
1914 if (A->getOption().matches(ID: options::OPT_mno_relax_pic_calls)) {
1915 CmdArgs.push_back(Elt: "-mllvm");
1916 CmdArgs.push_back(Elt: "-mips-jalr-reloc=0");
1917 }
1918 }
1919}
1920
1921void Clang::AddPPCTargetArgs(const ArgList &Args,
1922 ArgStringList &CmdArgs) const {
1923 const Driver &D = getToolChain().getDriver();
1924 const llvm::Triple &T = getToolChain().getTriple();
1925 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
1926 CmdArgs.push_back(Elt: "-tune-cpu");
1927 StringRef CPU = llvm::PPC::getNormalizedPPCTuneCPU(T, CPUName: A->getValue());
1928 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU.str()));
1929 }
1930
1931 // Select the ABI to use.
1932 const char *ABIName = nullptr;
1933 if (T.isOSBinFormatELF()) {
1934 switch (getToolChain().getArch()) {
1935 case llvm::Triple::ppc64: {
1936 if (T.isPPC64ELFv2ABI())
1937 ABIName = "elfv2";
1938 else
1939 ABIName = "elfv1";
1940 break;
1941 }
1942 case llvm::Triple::ppc64le:
1943 ABIName = "elfv2";
1944 break;
1945 default:
1946 break;
1947 }
1948 }
1949
1950 bool IEEELongDouble = getToolChain().defaultToIEEELongDouble();
1951 bool VecExtabi = false;
1952 for (const Arg *A : Args.filtered(Ids: options::OPT_mabi_EQ)) {
1953 StringRef V = A->getValue();
1954 if (V == "ieeelongdouble") {
1955 IEEELongDouble = true;
1956 A->claim();
1957 } else if (V == "ibmlongdouble") {
1958 IEEELongDouble = false;
1959 A->claim();
1960 } else if (V == "vec-default") {
1961 VecExtabi = false;
1962 A->claim();
1963 } else if (V == "vec-extabi") {
1964 VecExtabi = true;
1965 A->claim();
1966 } else if (V == "elfv1") {
1967 ABIName = "elfv1";
1968 A->claim();
1969 } else if (V == "elfv2") {
1970 ABIName = "elfv2";
1971 A->claim();
1972 } else if (V != "altivec")
1973 // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1974 // the option if given as we don't have backend support for any targets
1975 // that don't use the altivec abi.
1976 ABIName = A->getValue();
1977 }
1978 if (IEEELongDouble)
1979 CmdArgs.push_back(Elt: "-mabi=ieeelongdouble");
1980 if (VecExtabi) {
1981 if (!T.isOSAIX())
1982 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
1983 << "-mabi=vec-extabi" << T.str();
1984 CmdArgs.push_back(Elt: "-mabi=vec-extabi");
1985 }
1986
1987 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true))
1988 CmdArgs.push_back(Elt: "-disable-red-zone");
1989
1990 ppc::FloatABI FloatABI = ppc::getPPCFloatABI(D, Args);
1991 if (FloatABI == ppc::FloatABI::Soft) {
1992 // Floating point operations and argument passing are soft.
1993 CmdArgs.push_back(Elt: "-msoft-float");
1994 CmdArgs.push_back(Elt: "-mfloat-abi");
1995 CmdArgs.push_back(Elt: "soft");
1996 } else {
1997 // Floating point operations and argument passing are hard.
1998 assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1999 CmdArgs.push_back(Elt: "-mfloat-abi");
2000 CmdArgs.push_back(Elt: "hard");
2001 }
2002
2003 if (ABIName) {
2004 CmdArgs.push_back(Elt: "-target-abi");
2005 CmdArgs.push_back(Elt: ABIName);
2006 }
2007}
2008
2009void Clang::AddRISCVTargetArgs(const ArgList &Args,
2010 ArgStringList &CmdArgs) const {
2011 const llvm::Triple &Triple = getToolChain().getTriple();
2012 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
2013
2014 CmdArgs.push_back(Elt: "-target-abi");
2015 CmdArgs.push_back(Elt: ABIName.data());
2016
2017 if (Arg *A = Args.getLastArg(Ids: options::OPT_G)) {
2018 CmdArgs.push_back(Elt: "-msmall-data-limit");
2019 CmdArgs.push_back(Elt: A->getValue());
2020 }
2021
2022 if (!Args.hasFlag(Pos: options::OPT_mimplicit_float,
2023 Neg: options::OPT_mno_implicit_float, Default: true))
2024 CmdArgs.push_back(Elt: "-no-implicit-float");
2025
2026 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2027 CmdArgs.push_back(Elt: "-tune-cpu");
2028 if (strcmp(s1: A->getValue(), s2: "native") == 0)
2029 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::getHostCPUName()));
2030 else
2031 CmdArgs.push_back(Elt: A->getValue());
2032 }
2033
2034 // Handle -mrvv-vector-bits=<bits>
2035 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrvv_vector_bits_EQ)) {
2036 StringRef Val = A->getValue();
2037 const Driver &D = getToolChain().getDriver();
2038
2039 // Get minimum VLen from march.
2040 unsigned MinVLen = 0;
2041 std::string Arch = riscv::getRISCVArch(Args, Triple);
2042 auto ISAInfo = llvm::RISCVISAInfo::parseArchString(
2043 Arch, /*EnableExperimentalExtensions*/ EnableExperimentalExtension: true);
2044 // Ignore parsing error.
2045 if (!errorToBool(Err: ISAInfo.takeError()))
2046 MinVLen = (*ISAInfo)->getMinVLen();
2047
2048 // If the value is "zvl", use MinVLen from march. Otherwise, try to parse
2049 // as integer as long as we have a MinVLen.
2050 unsigned Bits = 0;
2051 if (Val == "zvl" && MinVLen >= llvm::RISCV::RVVBitsPerBlock) {
2052 Bits = MinVLen;
2053 } else if (!Val.getAsInteger(Radix: 10, Result&: Bits)) {
2054 // Only accept power of 2 values beteen RVVBitsPerBlock and 65536 that
2055 // at least MinVLen.
2056 if (Bits < MinVLen || Bits < llvm::RISCV::RVVBitsPerBlock ||
2057 Bits > 65536 || !llvm::isPowerOf2_32(Value: Bits))
2058 Bits = 0;
2059 }
2060
2061 // If we got a valid value try to use it.
2062 if (Bits != 0) {
2063 unsigned VScaleMin = Bits / llvm::RISCV::RVVBitsPerBlock;
2064 CmdArgs.push_back(
2065 Elt: Args.MakeArgString(Str: "-mvscale-max=" + llvm::Twine(VScaleMin)));
2066 CmdArgs.push_back(
2067 Elt: Args.MakeArgString(Str: "-mvscale-min=" + llvm::Twine(VScaleMin)));
2068 } else if (Val != "scalable") {
2069 // Handle the unsupported values passed to mrvv-vector-bits.
2070 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2071 << A->getSpelling() << Val;
2072 }
2073 }
2074}
2075
2076void Clang::AddSparcTargetArgs(const ArgList &Args,
2077 ArgStringList &CmdArgs) const {
2078 sparc::FloatABI FloatABI =
2079 sparc::getSparcFloatABI(D: getToolChain().getDriver(), Args);
2080
2081 if (FloatABI == sparc::FloatABI::Soft) {
2082 // Floating point operations and argument passing are soft.
2083 CmdArgs.push_back(Elt: "-msoft-float");
2084 CmdArgs.push_back(Elt: "-mfloat-abi");
2085 CmdArgs.push_back(Elt: "soft");
2086 } else {
2087 // Floating point operations and argument passing are hard.
2088 assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
2089 CmdArgs.push_back(Elt: "-mfloat-abi");
2090 CmdArgs.push_back(Elt: "hard");
2091 }
2092
2093 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2094 StringRef Name = A->getValue();
2095 std::string TuneCPU;
2096 if (Name == "native")
2097 TuneCPU = std::string(llvm::sys::getHostCPUName());
2098 else
2099 TuneCPU = std::string(Name);
2100
2101 CmdArgs.push_back(Elt: "-tune-cpu");
2102 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
2103 }
2104}
2105
2106void Clang::AddSystemZTargetArgs(const ArgList &Args,
2107 ArgStringList &CmdArgs) const {
2108 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2109 CmdArgs.push_back(Elt: "-tune-cpu");
2110 if (strcmp(s1: A->getValue(), s2: "native") == 0)
2111 CmdArgs.push_back(Elt: Args.MakeArgString(Str: llvm::sys::getHostCPUName()));
2112 else
2113 CmdArgs.push_back(Elt: A->getValue());
2114 }
2115
2116 bool HasBackchain =
2117 Args.hasFlag(Pos: options::OPT_mbackchain, Neg: options::OPT_mno_backchain, Default: false);
2118 bool HasPackedStack = Args.hasFlag(Pos: options::OPT_mpacked_stack,
2119 Neg: options::OPT_mno_packed_stack, Default: false);
2120 systemz::FloatABI FloatABI =
2121 systemz::getSystemZFloatABI(D: getToolChain().getDriver(), Args);
2122 bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2123 if (HasBackchain && HasPackedStack && !HasSoftFloat) {
2124 const Driver &D = getToolChain().getDriver();
2125 D.Diag(DiagID: diag::err_drv_unsupported_opt)
2126 << "-mpacked-stack -mbackchain -mhard-float";
2127 }
2128 if (HasBackchain)
2129 CmdArgs.push_back(Elt: "-mbackchain");
2130 if (HasPackedStack)
2131 CmdArgs.push_back(Elt: "-mpacked-stack");
2132 if (HasSoftFloat) {
2133 // Floating point operations and argument passing are soft.
2134 CmdArgs.push_back(Elt: "-msoft-float");
2135 CmdArgs.push_back(Elt: "-mfloat-abi");
2136 CmdArgs.push_back(Elt: "soft");
2137 }
2138}
2139
2140void Clang::AddX86TargetArgs(const ArgList &Args,
2141 ArgStringList &CmdArgs) const {
2142 const Driver &D = getToolChain().getDriver();
2143 addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2144
2145 if (!Args.hasFlag(Pos: options::OPT_mred_zone, Neg: options::OPT_mno_red_zone, Default: true) ||
2146 Args.hasArg(Ids: options::OPT_mkernel) ||
2147 Args.hasArg(Ids: options::OPT_fapple_kext))
2148 CmdArgs.push_back(Elt: "-disable-red-zone");
2149
2150 if (!Args.hasFlag(Pos: options::OPT_mtls_direct_seg_refs,
2151 Neg: options::OPT_mno_tls_direct_seg_refs, Default: true))
2152 CmdArgs.push_back(Elt: "-mno-tls-direct-seg-refs");
2153
2154 // Default to avoid implicit floating-point for kernel/kext code, but allow
2155 // that to be overridden with -mno-soft-float.
2156 bool NoImplicitFloat = (Args.hasArg(Ids: options::OPT_mkernel) ||
2157 Args.hasArg(Ids: options::OPT_fapple_kext));
2158 if (Arg *A = Args.getLastArg(
2159 Ids: options::OPT_msoft_float, Ids: options::OPT_mno_soft_float,
2160 Ids: options::OPT_mimplicit_float, Ids: options::OPT_mno_implicit_float)) {
2161 const Option &O = A->getOption();
2162 NoImplicitFloat = (O.matches(ID: options::OPT_mno_implicit_float) ||
2163 O.matches(ID: options::OPT_msoft_float));
2164 }
2165 if (NoImplicitFloat)
2166 CmdArgs.push_back(Elt: "-no-implicit-float");
2167
2168 if (Arg *A = Args.getLastArg(Ids: options::OPT_masm_EQ)) {
2169 StringRef Value = A->getValue();
2170 if (Value == "intel" || Value == "att") {
2171 CmdArgs.push_back(Elt: "-mllvm");
2172 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
2173 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-inline-asm=" + Value));
2174 } else {
2175 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2176 << A->getSpelling() << Value;
2177 }
2178 } else if (D.IsCLMode()) {
2179 CmdArgs.push_back(Elt: "-mllvm");
2180 CmdArgs.push_back(Elt: "-x86-asm-syntax=intel");
2181 }
2182
2183 if (Arg *A = Args.getLastArg(Ids: options::OPT_mskip_rax_setup,
2184 Ids: options::OPT_mno_skip_rax_setup))
2185 if (A->getOption().matches(ID: options::OPT_mskip_rax_setup))
2186 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mskip-rax-setup"));
2187
2188 // Set flags to support MCU ABI.
2189 if (Args.hasFlag(Pos: options::OPT_miamcu, Neg: options::OPT_mno_iamcu, Default: false)) {
2190 CmdArgs.push_back(Elt: "-mfloat-abi");
2191 CmdArgs.push_back(Elt: "soft");
2192 CmdArgs.push_back(Elt: "-mstack-alignment=4");
2193 }
2194
2195 // Handle -mtune.
2196
2197 // Default to "generic" unless -march is present or targetting the PS4/PS5.
2198 std::string TuneCPU;
2199 if (!Args.hasArg(Ids: options::OPT_march_EQ) && !getToolChain().getTriple().isPS())
2200 TuneCPU = "generic";
2201
2202 // Override based on -mtune.
2203 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mtune_EQ)) {
2204 StringRef Name = A->getValue();
2205
2206 if (Name == "native") {
2207 Name = llvm::sys::getHostCPUName();
2208 if (!Name.empty())
2209 TuneCPU = std::string(Name);
2210 } else
2211 TuneCPU = std::string(Name);
2212 }
2213
2214 if (!TuneCPU.empty()) {
2215 CmdArgs.push_back(Elt: "-tune-cpu");
2216 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TuneCPU));
2217 }
2218}
2219
2220void Clang::AddHexagonTargetArgs(const ArgList &Args,
2221 ArgStringList &CmdArgs) const {
2222 CmdArgs.push_back(Elt: "-mqdsp6-compat");
2223 CmdArgs.push_back(Elt: "-Wreturn-type");
2224
2225 if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2226 CmdArgs.push_back(Elt: "-mllvm");
2227 CmdArgs.push_back(
2228 Elt: Args.MakeArgString(Str: "-hexagon-small-data-threshold=" + Twine(*G)));
2229 }
2230
2231 if (!Args.hasArg(Ids: options::OPT_fno_short_enums))
2232 CmdArgs.push_back(Elt: "-fshort-enums");
2233 if (Args.getLastArg(Ids: options::OPT_mieee_rnd_near)) {
2234 CmdArgs.push_back(Elt: "-mllvm");
2235 CmdArgs.push_back(Elt: "-enable-hexagon-ieee-rnd-near");
2236 }
2237 CmdArgs.push_back(Elt: "-mllvm");
2238 CmdArgs.push_back(Elt: "-machine-sink-split=0");
2239}
2240
2241void Clang::AddLanaiTargetArgs(const ArgList &Args,
2242 ArgStringList &CmdArgs) const {
2243 if (Arg *A = Args.getLastArg(Ids: options::OPT_mcpu_EQ)) {
2244 StringRef CPUName = A->getValue();
2245
2246 CmdArgs.push_back(Elt: "-target-cpu");
2247 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPUName));
2248 }
2249 if (Arg *A = Args.getLastArg(Ids: options::OPT_mregparm_EQ)) {
2250 StringRef Value = A->getValue();
2251 // Only support mregparm=4 to support old usage. Report error for all other
2252 // cases.
2253 int Mregparm;
2254 if (Value.getAsInteger(Radix: 10, Result&: Mregparm)) {
2255 if (Mregparm != 4) {
2256 getToolChain().getDriver().Diag(
2257 DiagID: diag::err_drv_unsupported_option_argument)
2258 << A->getSpelling() << Value;
2259 }
2260 }
2261 }
2262}
2263
2264void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2265 ArgStringList &CmdArgs) const {
2266 // Default to "hidden" visibility.
2267 if (!Args.hasArg(Ids: options::OPT_fvisibility_EQ,
2268 Ids: options::OPT_fvisibility_ms_compat))
2269 CmdArgs.push_back(Elt: "-fvisibility=hidden");
2270}
2271
2272void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2273 // Floating point operations and argument passing are hard.
2274 CmdArgs.push_back(Elt: "-mfloat-abi");
2275 CmdArgs.push_back(Elt: "hard");
2276}
2277
2278void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2279 StringRef Target, const InputInfo &Output,
2280 const InputInfo &Input, const ArgList &Args) const {
2281 // If this is a dry run, do not create the compilation database file.
2282 if (C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH))
2283 return;
2284
2285 using llvm::yaml::escape;
2286 const Driver &D = getToolChain().getDriver();
2287
2288 if (!CompilationDatabase) {
2289 std::error_code EC;
2290 auto File = std::make_unique<llvm::raw_fd_ostream>(
2291 args&: Filename, args&: EC,
2292 args: llvm::sys::fs::OF_TextWithCRLF | llvm::sys::fs::OF_Append);
2293 if (EC) {
2294 D.Diag(DiagID: clang::diag::err_drv_compilationdatabase) << Filename
2295 << EC.message();
2296 return;
2297 }
2298 CompilationDatabase = std::move(File);
2299 }
2300 auto &CDB = *CompilationDatabase;
2301 auto CWD = D.getVFS().getCurrentWorkingDirectory();
2302 if (!CWD)
2303 CWD = ".";
2304 CDB << "{ \"directory\": \"" << escape(Input: *CWD) << "\"";
2305 CDB << ", \"file\": \"" << escape(Input: Input.getFilename()) << "\"";
2306 if (Output.isFilename())
2307 CDB << ", \"output\": \"" << escape(Input: Output.getFilename()) << "\"";
2308 CDB << ", \"arguments\": [\"" << escape(Input: D.ClangExecutable) << "\"";
2309 SmallString<128> Buf;
2310 Buf = "-x";
2311 Buf += types::getTypeName(Id: Input.getType());
2312 CDB << ", \"" << escape(Input: Buf) << "\"";
2313 if (!D.SysRoot.empty() && !Args.hasArg(Ids: options::OPT__sysroot_EQ)) {
2314 Buf = "--sysroot=";
2315 Buf += D.SysRoot;
2316 CDB << ", \"" << escape(Input: Buf) << "\"";
2317 }
2318 CDB << ", \"" << escape(Input: Input.getFilename()) << "\"";
2319 if (Output.isFilename())
2320 CDB << ", \"-o\", \"" << escape(Input: Output.getFilename()) << "\"";
2321 for (auto &A: Args) {
2322 auto &O = A->getOption();
2323 // Skip language selection, which is positional.
2324 if (O.getID() == options::OPT_x)
2325 continue;
2326 // Skip writing dependency output and the compilation database itself.
2327 if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
2328 continue;
2329 if (O.getID() == options::OPT_gen_cdb_fragment_path)
2330 continue;
2331 // Skip inputs.
2332 if (O.getKind() == Option::InputClass)
2333 continue;
2334 // Skip output.
2335 if (O.getID() == options::OPT_o)
2336 continue;
2337 // All other arguments are quoted and appended.
2338 ArgStringList ASL;
2339 A->render(Args, Output&: ASL);
2340 for (auto &it: ASL)
2341 CDB << ", \"" << escape(Input: it) << "\"";
2342 }
2343 Buf = "--target=";
2344 Buf += Target;
2345 CDB << ", \"" << escape(Input: Buf) << "\"]},\n";
2346}
2347
2348void Clang::DumpCompilationDatabaseFragmentToDir(
2349 StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2350 const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2351 // If this is a dry run, do not create the compilation database file.
2352 if (C.getArgs().hasArg(Ids: options::OPT__HASH_HASH_HASH))
2353 return;
2354
2355 if (CompilationDatabase)
2356 DumpCompilationDatabase(C, Filename: "", Target, Output, Input, Args);
2357
2358 SmallString<256> Path = Dir;
2359 const auto &Driver = C.getDriver();
2360 Driver.getVFS().makeAbsolute(Path);
2361 auto Err = llvm::sys::fs::create_directory(path: Path, /*IgnoreExisting=*/true);
2362 if (Err) {
2363 Driver.Diag(DiagID: diag::err_drv_compilationdatabase) << Dir << Err.message();
2364 return;
2365 }
2366
2367 llvm::sys::path::append(
2368 path&: Path,
2369 a: Twine(llvm::sys::path::filename(path: Input.getFilename())) + ".%%%%.json");
2370 int FD;
2371 SmallString<256> TempPath;
2372 Err = llvm::sys::fs::createUniqueFile(Model: Path, ResultFD&: FD, ResultPath&: TempPath,
2373 Flags: llvm::sys::fs::OF_Text);
2374 if (Err) {
2375 Driver.Diag(DiagID: diag::err_drv_compilationdatabase) << Path << Err.message();
2376 return;
2377 }
2378 CompilationDatabase =
2379 std::make_unique<llvm::raw_fd_ostream>(args&: FD, /*shouldClose=*/args: true);
2380 DumpCompilationDatabase(C, Filename: "", Target, Output, Input, Args);
2381}
2382
2383static bool CheckARMImplicitITArg(StringRef Value) {
2384 return Value == "always" || Value == "never" || Value == "arm" ||
2385 Value == "thumb";
2386}
2387
2388static void AddARMImplicitITArgs(const ArgList &Args, ArgStringList &CmdArgs,
2389 StringRef Value) {
2390 CmdArgs.push_back(Elt: "-mllvm");
2391 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-arm-implicit-it=" + Value));
2392}
2393
2394static void CollectArgsForIntegratedAssembler(Compilation &C,
2395 const ArgList &Args,
2396 ArgStringList &CmdArgs,
2397 const Driver &D) {
2398 // Default to -mno-relax-all.
2399 //
2400 // Note: RISC-V requires an indirect jump for offsets larger than 1MiB. This
2401 // cannot be done by assembler branch relaxation as it needs a free temporary
2402 // register. Because of this, branch relaxation is handled by a MachineIR pass
2403 // before the assembler. Forcing assembler branch relaxation for -O0 makes the
2404 // MachineIR branch relaxation inaccurate and it will miss cases where an
2405 // indirect branch is necessary.
2406 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mrelax_all,
2407 Neg: options::OPT_mno_relax_all);
2408
2409 // Only default to -mincremental-linker-compatible if we think we are
2410 // targeting the MSVC linker.
2411 bool DefaultIncrementalLinkerCompatible =
2412 C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2413 if (Args.hasFlag(Pos: options::OPT_mincremental_linker_compatible,
2414 Neg: options::OPT_mno_incremental_linker_compatible,
2415 Default: DefaultIncrementalLinkerCompatible))
2416 CmdArgs.push_back(Elt: "-mincremental-linker-compatible");
2417
2418 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_femit_dwarf_unwind_EQ);
2419
2420 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_femit_compact_unwind_non_canonical,
2421 Neg: options::OPT_fno_emit_compact_unwind_non_canonical);
2422
2423 // If you add more args here, also add them to the block below that
2424 // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2425
2426 // When passing -I arguments to the assembler we sometimes need to
2427 // unconditionally take the next argument. For example, when parsing
2428 // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2429 // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2430 // arg after parsing the '-I' arg.
2431 bool TakeNextArg = false;
2432
2433 const llvm::Triple &Triple = C.getDefaultToolChain().getTriple();
2434 bool IsELF = Triple.isOSBinFormatELF();
2435 bool Crel = false, ExperimentalCrel = false;
2436 bool SFrame = false, ExperimentalSFrame = false;
2437 bool ImplicitMapSyms = false;
2438 bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2439 bool UseNoExecStack = false;
2440 bool Msa = false;
2441 const char *MipsTargetFeature = nullptr;
2442 llvm::SmallVector<const char *> SparcTargetFeatures;
2443 StringRef ImplicitIt;
2444 for (const Arg *A :
2445 Args.filtered(Ids: options::OPT_Wa_COMMA, Ids: options::OPT_Xassembler,
2446 Ids: options::OPT_mimplicit_it_EQ)) {
2447 A->claim();
2448
2449 if (A->getOption().getID() == options::OPT_mimplicit_it_EQ) {
2450 switch (C.getDefaultToolChain().getArch()) {
2451 case llvm::Triple::arm:
2452 case llvm::Triple::armeb:
2453 case llvm::Triple::thumb:
2454 case llvm::Triple::thumbeb:
2455 // Only store the value; the last value set takes effect.
2456 ImplicitIt = A->getValue();
2457 if (!CheckARMImplicitITArg(Value: ImplicitIt))
2458 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2459 << A->getSpelling() << ImplicitIt;
2460 continue;
2461 default:
2462 break;
2463 }
2464 }
2465
2466 for (StringRef Value : A->getValues()) {
2467 if (TakeNextArg) {
2468 CmdArgs.push_back(Elt: Value.data());
2469 TakeNextArg = false;
2470 continue;
2471 }
2472
2473 if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2474 Value == "-mbig-obj")
2475 continue; // LLVM handles bigobj automatically
2476
2477 auto Equal = Value.split(Separator: '=');
2478 auto checkArg = [&](bool ValidTarget,
2479 std::initializer_list<const char *> Set) {
2480 if (!ValidTarget) {
2481 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2482 << (Twine("-Wa,") + Equal.first + "=").str()
2483 << Triple.getTriple();
2484 } else if (!llvm::is_contained(Set, Element: Equal.second)) {
2485 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2486 << (Twine("-Wa,") + Equal.first + "=").str() << Equal.second;
2487 }
2488 };
2489 switch (C.getDefaultToolChain().getArch()) {
2490 default:
2491 break;
2492 case llvm::Triple::x86:
2493 case llvm::Triple::x86_64:
2494 if (Equal.first == "-mrelax-relocations" ||
2495 Equal.first == "--mrelax-relocations") {
2496 UseRelaxRelocations = Equal.second == "yes";
2497 checkArg(IsELF, {"yes", "no"});
2498 continue;
2499 }
2500 if (Value == "-msse2avx") {
2501 CmdArgs.push_back(Elt: "-msse2avx");
2502 continue;
2503 }
2504 break;
2505 case llvm::Triple::wasm32:
2506 case llvm::Triple::wasm64:
2507 if (Value == "--no-type-check") {
2508 CmdArgs.push_back(Elt: "-mno-type-check");
2509 continue;
2510 }
2511 break;
2512 case llvm::Triple::thumb:
2513 case llvm::Triple::thumbeb:
2514 case llvm::Triple::arm:
2515 case llvm::Triple::armeb:
2516 if (Equal.first == "-mimplicit-it") {
2517 // Only store the value; the last value set takes effect.
2518 ImplicitIt = Equal.second;
2519 checkArg(true, {"always", "never", "arm", "thumb"});
2520 continue;
2521 }
2522 if (Value == "-mthumb")
2523 // -mthumb has already been processed in ComputeLLVMTriple()
2524 // recognize but skip over here.
2525 continue;
2526 break;
2527 case llvm::Triple::aarch64:
2528 case llvm::Triple::aarch64_be:
2529 case llvm::Triple::aarch64_32:
2530 if (Equal.first == "-mmapsyms") {
2531 ImplicitMapSyms = Equal.second == "implicit";
2532 checkArg(IsELF, {"default", "implicit"});
2533 continue;
2534 }
2535 break;
2536 case llvm::Triple::mips:
2537 case llvm::Triple::mipsel:
2538 case llvm::Triple::mips64:
2539 case llvm::Triple::mips64el:
2540 if (Value == "--trap") {
2541 CmdArgs.push_back(Elt: "-target-feature");
2542 CmdArgs.push_back(Elt: "+use-tcc-in-div");
2543 continue;
2544 }
2545 if (Value == "--break") {
2546 CmdArgs.push_back(Elt: "-target-feature");
2547 CmdArgs.push_back(Elt: "-use-tcc-in-div");
2548 continue;
2549 }
2550 if (Value.starts_with(Prefix: "-msoft-float")) {
2551 CmdArgs.push_back(Elt: "-target-feature");
2552 CmdArgs.push_back(Elt: "+soft-float");
2553 continue;
2554 }
2555 if (Value.starts_with(Prefix: "-mhard-float")) {
2556 CmdArgs.push_back(Elt: "-target-feature");
2557 CmdArgs.push_back(Elt: "-soft-float");
2558 continue;
2559 }
2560 if (Value == "-mmsa") {
2561 Msa = true;
2562 continue;
2563 }
2564 if (Value == "-mno-msa") {
2565 Msa = false;
2566 continue;
2567 }
2568 MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2569 .Case(S: "-mips1", Value: "+mips1")
2570 .Case(S: "-mips2", Value: "+mips2")
2571 .Case(S: "-mips3", Value: "+mips3")
2572 .Case(S: "-mips4", Value: "+mips4")
2573 .Case(S: "-mips5", Value: "+mips5")
2574 .Case(S: "-mips32", Value: "+mips32")
2575 .Case(S: "-mips32r2", Value: "+mips32r2")
2576 .Case(S: "-mips32r3", Value: "+mips32r3")
2577 .Case(S: "-mips32r5", Value: "+mips32r5")
2578 .Case(S: "-mips32r6", Value: "+mips32r6")
2579 .Case(S: "-mips64", Value: "+mips64")
2580 .Case(S: "-mips64r2", Value: "+mips64r2")
2581 .Case(S: "-mips64r3", Value: "+mips64r3")
2582 .Case(S: "-mips64r5", Value: "+mips64r5")
2583 .Case(S: "-mips64r6", Value: "+mips64r6")
2584 .Default(Value: nullptr);
2585 if (MipsTargetFeature)
2586 continue;
2587 break;
2588
2589 case llvm::Triple::sparc:
2590 case llvm::Triple::sparcel:
2591 case llvm::Triple::sparcv9:
2592 if (Value == "--undeclared-regs") {
2593 // LLVM already allows undeclared use of G registers, so this option
2594 // becomes a no-op. This solely exists for GNU compatibility.
2595 // TODO implement --no-undeclared-regs
2596 continue;
2597 }
2598 SparcTargetFeatures =
2599 llvm::StringSwitch<llvm::SmallVector<const char *>>(Value)
2600 .Case(S: "-Av8", Value: {"-v8plus"})
2601 .Case(S: "-Av8plus", Value: {"+v8plus", "+v9"})
2602 .Case(S: "-Av8plusa", Value: {"+v8plus", "+v9", "+vis"})
2603 .Case(S: "-Av8plusb", Value: {"+v8plus", "+v9", "+vis", "+vis2"})
2604 .Case(S: "-Av8plusd", Value: {"+v8plus", "+v9", "+vis", "+vis2", "+vis3"})
2605 .Case(S: "-Av9", Value: {"+v9"})
2606 .Case(S: "-Av9a", Value: {"+v9", "+vis"})
2607 .Case(S: "-Av9b", Value: {"+v9", "+vis", "+vis2"})
2608 .Case(S: "-Av9d", Value: {"+v9", "+vis", "+vis2", "+vis3"})
2609 .Default(Value: {});
2610 if (!SparcTargetFeatures.empty())
2611 continue;
2612 break;
2613 }
2614
2615 if (Value == "-force_cpusubtype_ALL") {
2616 // Do nothing, this is the default and we don't support anything else.
2617 } else if (Value == "-L") {
2618 CmdArgs.push_back(Elt: "-msave-temp-labels");
2619 } else if (Value == "--fatal-warnings") {
2620 CmdArgs.push_back(Elt: "-massembler-fatal-warnings");
2621 } else if (Value == "--no-warn" || Value == "-W") {
2622 CmdArgs.push_back(Elt: "-massembler-no-warn");
2623 } else if (Value == "--noexecstack") {
2624 UseNoExecStack = true;
2625 } else if (Value.starts_with(Prefix: "-compress-debug-sections") ||
2626 Value.starts_with(Prefix: "--compress-debug-sections") ||
2627 Value == "-nocompress-debug-sections" ||
2628 Value == "--nocompress-debug-sections") {
2629 CmdArgs.push_back(Elt: Value.data());
2630 } else if (Value == "--crel") {
2631 Crel = true;
2632 } else if (Value == "--no-crel") {
2633 Crel = false;
2634 } else if (Value == "--allow-experimental-crel") {
2635 ExperimentalCrel = true;
2636 } else if (Value.starts_with(Prefix: "-I")) {
2637 CmdArgs.push_back(Elt: Value.data());
2638 // We need to consume the next argument if the current arg is a plain
2639 // -I. The next arg will be the include directory.
2640 if (Value == "-I")
2641 TakeNextArg = true;
2642 } else if (Value.starts_with(Prefix: "-gdwarf-")) {
2643 // "-gdwarf-N" options are not cc1as options.
2644 unsigned DwarfVersion = DwarfVersionNum(ArgValue: Value);
2645 if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2646 CmdArgs.push_back(Elt: Value.data());
2647 } else {
2648 RenderDebugEnablingArgs(Args, CmdArgs,
2649 DebugInfoKind: llvm::codegenoptions::DebugInfoConstructor,
2650 DwarfVersion, DebuggerTuning: llvm::DebuggerKind::Default);
2651 }
2652 } else if (Value == "--gsframe") {
2653 SFrame = true;
2654 } else if (Value == "--allow-experimental-sframe") {
2655 ExperimentalSFrame = true;
2656 } else if (Value.starts_with(Prefix: "-mcpu") || Value.starts_with(Prefix: "-mfpu") ||
2657 Value.starts_with(Prefix: "-mhwdiv") || Value.starts_with(Prefix: "-march")) {
2658 // Do nothing, we'll validate it later.
2659 } else if (Value == "-defsym" || Value == "--defsym") {
2660 if (A->getNumValues() != 2) {
2661 D.Diag(DiagID: diag::err_drv_defsym_invalid_format) << Value;
2662 break;
2663 }
2664 const char *S = A->getValue(N: 1);
2665 auto Pair = StringRef(S).split(Separator: '=');
2666 auto Sym = Pair.first;
2667 auto SVal = Pair.second;
2668
2669 if (Sym.empty() || SVal.empty()) {
2670 D.Diag(DiagID: diag::err_drv_defsym_invalid_format) << S;
2671 break;
2672 }
2673 int64_t IVal;
2674 if (SVal.getAsInteger(Radix: 0, Result&: IVal)) {
2675 D.Diag(DiagID: diag::err_drv_defsym_invalid_symval) << SVal;
2676 break;
2677 }
2678 CmdArgs.push_back(Elt: "--defsym");
2679 TakeNextArg = true;
2680 } else if (Value == "-fdebug-compilation-dir") {
2681 CmdArgs.push_back(Elt: "-fdebug-compilation-dir");
2682 TakeNextArg = true;
2683 } else if (Value.consume_front(Prefix: "-fdebug-compilation-dir=")) {
2684 // The flag is a -Wa / -Xassembler argument and Options doesn't
2685 // parse the argument, so this isn't automatically aliased to
2686 // -fdebug-compilation-dir (without '=') here.
2687 CmdArgs.push_back(Elt: "-fdebug-compilation-dir");
2688 CmdArgs.push_back(Elt: Value.data());
2689 } else if (Value == "--version") {
2690 D.PrintVersion(C, OS&: llvm::outs());
2691 } else {
2692 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2693 << A->getSpelling() << Value;
2694 }
2695 }
2696 }
2697 if (ImplicitIt.size())
2698 AddARMImplicitITArgs(Args, CmdArgs, Value: ImplicitIt);
2699 if (Crel) {
2700 if (!ExperimentalCrel)
2701 D.Diag(DiagID: diag::err_drv_experimental_crel);
2702 if (Triple.isOSBinFormatELF() && !Triple.isMIPS()) {
2703 CmdArgs.push_back(Elt: "--crel");
2704 } else {
2705 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2706 << "-Wa,--crel" << D.getTargetTriple();
2707 }
2708 }
2709 if (SFrame) {
2710 if (Triple.isOSBinFormatELF() && Triple.isX86()) {
2711 if (!ExperimentalSFrame)
2712 D.Diag(DiagID: diag::err_drv_experimental_sframe);
2713 else
2714 CmdArgs.push_back(Elt: "--gsframe");
2715 } else {
2716 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
2717 << "-Wa,--gsframe" << D.getTargetTriple();
2718 }
2719 }
2720 if (ImplicitMapSyms)
2721 CmdArgs.push_back(Elt: "-mmapsyms=implicit");
2722 if (Msa)
2723 CmdArgs.push_back(Elt: "-mmsa");
2724 if (!UseRelaxRelocations)
2725 CmdArgs.push_back(Elt: "-mrelax-relocations=no");
2726 if (UseNoExecStack)
2727 CmdArgs.push_back(Elt: "-mnoexecstack");
2728 if (MipsTargetFeature != nullptr) {
2729 CmdArgs.push_back(Elt: "-target-feature");
2730 CmdArgs.push_back(Elt: MipsTargetFeature);
2731 }
2732
2733 for (const char *Feature : SparcTargetFeatures) {
2734 CmdArgs.push_back(Elt: "-target-feature");
2735 CmdArgs.push_back(Elt: Feature);
2736 }
2737
2738 // forward -fembed-bitcode to assmebler
2739 if (C.getDriver().embedBitcodeEnabled() ||
2740 C.getDriver().embedBitcodeMarkerOnly())
2741 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fembed_bitcode_EQ);
2742
2743 if (const char *AsSecureLogFile = getenv(name: "AS_SECURE_LOG_FILE")) {
2744 CmdArgs.push_back(Elt: "-as-secure-log-file");
2745 CmdArgs.push_back(Elt: Args.MakeArgString(Str: AsSecureLogFile));
2746 }
2747}
2748
2749static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2750 bool OFastEnabled, const ArgList &Args,
2751 ArgStringList &CmdArgs,
2752 const JobAction &JA) {
2753 // List of veclibs which when used with -fveclib imply -fno-math-errno.
2754 constexpr std::array VecLibImpliesNoMathErrno{llvm::StringLiteral("ArmPL"),
2755 llvm::StringLiteral("SLEEF")};
2756 bool NoMathErrnoWasImpliedByVecLib = false;
2757 const Arg *VecLibArg = nullptr;
2758 // Track the arg (if any) that enabled errno after -fveclib for diagnostics.
2759 const Arg *ArgThatEnabledMathErrnoAfterVecLib = nullptr;
2760
2761 // Handle various floating point optimization flags, mapping them to the
2762 // appropriate LLVM code generation flags. This is complicated by several
2763 // "umbrella" flags, so we do this by stepping through the flags incrementally
2764 // adjusting what we think is enabled/disabled, then at the end setting the
2765 // LLVM flags based on the final state.
2766 bool HonorINFs = true;
2767 bool HonorNaNs = true;
2768 bool ApproxFunc = false;
2769 // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2770 bool MathErrno = TC.IsMathErrnoDefault();
2771 bool AssociativeMath = false;
2772 bool ReciprocalMath = false;
2773 bool SignedZeros = true;
2774 bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2775 bool TrappingMathPresent = false; // Is trapping-math in args, and not
2776 // overriden by ffp-exception-behavior?
2777 bool RoundingFPMath = false;
2778 // -ffp-model values: strict, fast, precise
2779 StringRef FPModel = "";
2780 // -ffp-exception-behavior options: strict, maytrap, ignore
2781 StringRef FPExceptionBehavior = "";
2782 // -ffp-eval-method options: double, extended, source
2783 StringRef FPEvalMethod = "";
2784 llvm::DenormalMode DenormalFPMath =
2785 TC.getDefaultDenormalModeForType(DriverArgs: Args, JA);
2786 llvm::DenormalMode DenormalFP32Math =
2787 TC.getDefaultDenormalModeForType(DriverArgs: Args, JA, FPType: &llvm::APFloat::IEEEsingle());
2788
2789 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2790 // If one wasn't given by the user, don't pass it here.
2791 StringRef FPContract;
2792 StringRef LastSeenFfpContractOption;
2793 StringRef LastFpContractOverrideOption;
2794 bool SeenUnsafeMathModeOption = false;
2795 if (!JA.isDeviceOffloading(OKind: Action::OFK_Cuda) &&
2796 !JA.isOffloading(OKind: Action::OFK_HIP))
2797 FPContract = "on";
2798 bool StrictFPModel = false;
2799 StringRef Float16ExcessPrecision = "";
2800 StringRef BFloat16ExcessPrecision = "";
2801 LangOptions::ComplexRangeKind Range = LangOptions::ComplexRangeKind::CX_None;
2802 std::string ComplexRangeStr;
2803 StringRef LastComplexRangeOption;
2804
2805 // Lambda to set fast-math options. This is also used by -ffp-model=fast
2806 auto applyFastMath = [&](bool Aggressive, StringRef CallerOption) {
2807 if (Aggressive) {
2808 HonorINFs = false;
2809 HonorNaNs = false;
2810 setComplexRange(D, NewOpt: CallerOption, NewRange: LangOptions::ComplexRangeKind::CX_Basic,
2811 LastOpt&: LastComplexRangeOption, Range);
2812 } else {
2813 HonorINFs = true;
2814 HonorNaNs = true;
2815 setComplexRange(D, NewOpt: CallerOption,
2816 NewRange: LangOptions::ComplexRangeKind::CX_Promoted,
2817 LastOpt&: LastComplexRangeOption, Range);
2818 }
2819 MathErrno = false;
2820 AssociativeMath = true;
2821 ReciprocalMath = true;
2822 ApproxFunc = true;
2823 SignedZeros = false;
2824 TrappingMath = false;
2825 RoundingFPMath = false;
2826 FPExceptionBehavior = "";
2827 FPContract = "fast";
2828 SeenUnsafeMathModeOption = true;
2829 };
2830
2831 // Lambda to consolidate common handling for fp-contract
2832 auto restoreFPContractState = [&]() {
2833 // CUDA and HIP don't rely on the frontend to pass an ffp-contract option.
2834 // For other targets, if the state has been changed by one of the
2835 // unsafe-math umbrella options a subsequent -fno-fast-math or
2836 // -fno-unsafe-math-optimizations option reverts to the last value seen for
2837 // the -ffp-contract option or "on" if we have not seen the -ffp-contract
2838 // option. If we have not seen an unsafe-math option or -ffp-contract,
2839 // we leave the FPContract state unchanged.
2840 if (!JA.isDeviceOffloading(OKind: Action::OFK_Cuda) &&
2841 !JA.isOffloading(OKind: Action::OFK_HIP)) {
2842 if (LastSeenFfpContractOption != "")
2843 FPContract = LastSeenFfpContractOption;
2844 else if (SeenUnsafeMathModeOption)
2845 FPContract = "on";
2846 }
2847 // In this case, we're reverting to the last explicit fp-contract option
2848 // or the platform default
2849 LastFpContractOverrideOption = "";
2850 };
2851
2852 if (const Arg *A = Args.getLastArg(Ids: options::OPT_flimited_precision_EQ)) {
2853 CmdArgs.push_back(Elt: "-mlimit-float-precision");
2854 CmdArgs.push_back(Elt: A->getValue());
2855 }
2856
2857 for (const Arg *A : Args) {
2858 llvm::scope_exit CheckMathErrnoForVecLib(
2859 [&, MathErrnoBeforeArg = MathErrno] {
2860 if (NoMathErrnoWasImpliedByVecLib && !MathErrnoBeforeArg && MathErrno)
2861 ArgThatEnabledMathErrnoAfterVecLib = A;
2862 });
2863
2864 switch (A->getOption().getID()) {
2865 // If this isn't an FP option skip the claim below
2866 default: continue;
2867
2868 case options::OPT_fcx_limited_range:
2869 setComplexRange(D, NewOpt: A->getSpelling(),
2870 NewRange: LangOptions::ComplexRangeKind::CX_Basic,
2871 LastOpt&: LastComplexRangeOption, Range);
2872 break;
2873 case options::OPT_fno_cx_limited_range:
2874 setComplexRange(D, NewOpt: A->getSpelling(),
2875 NewRange: LangOptions::ComplexRangeKind::CX_Full,
2876 LastOpt&: LastComplexRangeOption, Range);
2877 break;
2878 case options::OPT_fcx_fortran_rules:
2879 setComplexRange(D, NewOpt: A->getSpelling(),
2880 NewRange: LangOptions::ComplexRangeKind::CX_Improved,
2881 LastOpt&: LastComplexRangeOption, Range);
2882 break;
2883 case options::OPT_fno_cx_fortran_rules:
2884 setComplexRange(D, NewOpt: A->getSpelling(),
2885 NewRange: LangOptions::ComplexRangeKind::CX_Full,
2886 LastOpt&: LastComplexRangeOption, Range);
2887 break;
2888 case options::OPT_fcomplex_arithmetic_EQ: {
2889 LangOptions::ComplexRangeKind RangeVal;
2890 StringRef Val = A->getValue();
2891 if (Val == "full")
2892 RangeVal = LangOptions::ComplexRangeKind::CX_Full;
2893 else if (Val == "improved")
2894 RangeVal = LangOptions::ComplexRangeKind::CX_Improved;
2895 else if (Val == "promoted")
2896 RangeVal = LangOptions::ComplexRangeKind::CX_Promoted;
2897 else if (Val == "basic")
2898 RangeVal = LangOptions::ComplexRangeKind::CX_Basic;
2899 else {
2900 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2901 << A->getSpelling() << Val;
2902 break;
2903 }
2904 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val), NewRange: RangeVal,
2905 LastOpt&: LastComplexRangeOption, Range);
2906 break;
2907 }
2908 case options::OPT_ffp_model_EQ: {
2909 // If -ffp-model= is seen, reset to fno-fast-math
2910 HonorINFs = true;
2911 HonorNaNs = true;
2912 ApproxFunc = false;
2913 // Turning *off* -ffast-math restores the toolchain default.
2914 MathErrno = TC.IsMathErrnoDefault();
2915 AssociativeMath = false;
2916 ReciprocalMath = false;
2917 SignedZeros = true;
2918
2919 StringRef Val = A->getValue();
2920 if (OFastEnabled && Val != "aggressive") {
2921 // Only -ffp-model=aggressive is compatible with -OFast, ignore.
2922 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
2923 << Args.MakeArgString(Str: "-ffp-model=" + Val) << "-Ofast";
2924 break;
2925 }
2926 StrictFPModel = false;
2927 if (!FPModel.empty() && FPModel != Val)
2928 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
2929 << Args.MakeArgString(Str: "-ffp-model=" + FPModel)
2930 << Args.MakeArgString(Str: "-ffp-model=" + Val);
2931 if (Val == "fast") {
2932 FPModel = Val;
2933 applyFastMath(false, Args.MakeArgString(Str: A->getSpelling() + Val));
2934 // applyFastMath sets fp-contract="fast"
2935 LastFpContractOverrideOption = "-ffp-model=fast";
2936 } else if (Val == "aggressive") {
2937 FPModel = Val;
2938 applyFastMath(true, Args.MakeArgString(Str: A->getSpelling() + Val));
2939 // applyFastMath sets fp-contract="fast"
2940 LastFpContractOverrideOption = "-ffp-model=aggressive";
2941 } else if (Val == "precise") {
2942 FPModel = Val;
2943 FPContract = "on";
2944 LastFpContractOverrideOption = "-ffp-model=precise";
2945 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val),
2946 NewRange: LangOptions::ComplexRangeKind::CX_Full,
2947 LastOpt&: LastComplexRangeOption, Range);
2948 } else if (Val == "strict") {
2949 StrictFPModel = true;
2950 FPExceptionBehavior = "strict";
2951 FPModel = Val;
2952 FPContract = "off";
2953 LastFpContractOverrideOption = "-ffp-model=strict";
2954 TrappingMath = true;
2955 RoundingFPMath = true;
2956 setComplexRange(D, NewOpt: Args.MakeArgString(Str: A->getSpelling() + Val),
2957 NewRange: LangOptions::ComplexRangeKind::CX_Full,
2958 LastOpt&: LastComplexRangeOption, Range);
2959 } else
2960 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
2961 << A->getSpelling() << Val;
2962 break;
2963 }
2964
2965 // Options controlling individual features
2966 case options::OPT_fhonor_infinities: HonorINFs = true; break;
2967 case options::OPT_fno_honor_infinities: HonorINFs = false; break;
2968 case options::OPT_fhonor_nans: HonorNaNs = true; break;
2969 case options::OPT_fno_honor_nans: HonorNaNs = false; break;
2970 case options::OPT_fapprox_func: ApproxFunc = true; break;
2971 case options::OPT_fno_approx_func: ApproxFunc = false; break;
2972 case options::OPT_fmath_errno: MathErrno = true; break;
2973 case options::OPT_fno_math_errno: MathErrno = false; break;
2974 case options::OPT_fassociative_math: AssociativeMath = true; break;
2975 case options::OPT_fno_associative_math: AssociativeMath = false; break;
2976 case options::OPT_freciprocal_math: ReciprocalMath = true; break;
2977 case options::OPT_fno_reciprocal_math: ReciprocalMath = false; break;
2978 case options::OPT_fsigned_zeros: SignedZeros = true; break;
2979 case options::OPT_fno_signed_zeros: SignedZeros = false; break;
2980 case options::OPT_ftrapping_math:
2981 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
2982 FPExceptionBehavior != "strict")
2983 // Warn that previous value of option is overridden.
2984 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
2985 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
2986 FPExceptionBehavior)
2987 << "-ftrapping-math";
2988 TrappingMath = true;
2989 TrappingMathPresent = true;
2990 FPExceptionBehavior = "strict";
2991 break;
2992 case options::OPT_fveclib:
2993 VecLibArg = A;
2994 NoMathErrnoWasImpliedByVecLib =
2995 llvm::is_contained(Range: VecLibImpliesNoMathErrno, Element: A->getValue());
2996 if (NoMathErrnoWasImpliedByVecLib)
2997 MathErrno = false;
2998 break;
2999 case options::OPT_fno_trapping_math:
3000 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3001 FPExceptionBehavior != "ignore")
3002 // Warn that previous value of option is overridden.
3003 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3004 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3005 FPExceptionBehavior)
3006 << "-fno-trapping-math";
3007 TrappingMath = false;
3008 TrappingMathPresent = true;
3009 FPExceptionBehavior = "ignore";
3010 break;
3011
3012 case options::OPT_frounding_math:
3013 RoundingFPMath = true;
3014 break;
3015
3016 case options::OPT_fno_rounding_math:
3017 RoundingFPMath = false;
3018 break;
3019
3020 case options::OPT_fdenormal_fp_math_EQ:
3021 DenormalFPMath = llvm::parseDenormalFPAttribute(Str: A->getValue());
3022 DenormalFP32Math = DenormalFPMath;
3023 if (!DenormalFPMath.isValid()) {
3024 D.Diag(DiagID: diag::err_drv_invalid_value)
3025 << A->getAsString(Args) << A->getValue();
3026 }
3027 break;
3028
3029 case options::OPT_fdenormal_fp_math_f32_EQ:
3030 DenormalFP32Math = llvm::parseDenormalFPAttribute(Str: A->getValue());
3031 if (!DenormalFP32Math.isValid()) {
3032 D.Diag(DiagID: diag::err_drv_invalid_value)
3033 << A->getAsString(Args) << A->getValue();
3034 }
3035 break;
3036
3037 // Validate and pass through -ffp-contract option.
3038 case options::OPT_ffp_contract: {
3039 StringRef Val = A->getValue();
3040 if (Val == "fast" || Val == "on" || Val == "off" ||
3041 Val == "fast-honor-pragmas") {
3042 if (Val != FPContract && LastFpContractOverrideOption != "") {
3043 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3044 << LastFpContractOverrideOption
3045 << Args.MakeArgString(Str: "-ffp-contract=" + Val);
3046 }
3047
3048 FPContract = Val;
3049 LastSeenFfpContractOption = Val;
3050 LastFpContractOverrideOption = "";
3051 } else
3052 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3053 << A->getSpelling() << Val;
3054 break;
3055 }
3056
3057 // Validate and pass through -ffp-exception-behavior option.
3058 case options::OPT_ffp_exception_behavior_EQ: {
3059 StringRef Val = A->getValue();
3060 if (!TrappingMathPresent && !FPExceptionBehavior.empty() &&
3061 FPExceptionBehavior != Val)
3062 // Warn that previous value of option is overridden.
3063 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3064 << Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3065 FPExceptionBehavior)
3066 << Args.MakeArgString(Str: "-ffp-exception-behavior=" + Val);
3067 TrappingMath = TrappingMathPresent = false;
3068 if (Val == "ignore" || Val == "maytrap")
3069 FPExceptionBehavior = Val;
3070 else if (Val == "strict") {
3071 FPExceptionBehavior = Val;
3072 TrappingMath = TrappingMathPresent = true;
3073 } else
3074 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3075 << A->getSpelling() << Val;
3076 break;
3077 }
3078
3079 // Validate and pass through -ffp-eval-method option.
3080 case options::OPT_ffp_eval_method_EQ: {
3081 StringRef Val = A->getValue();
3082 if (Val == "double" || Val == "extended" || Val == "source")
3083 FPEvalMethod = Val;
3084 else
3085 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3086 << A->getSpelling() << Val;
3087 break;
3088 }
3089
3090 case options::OPT_fexcess_precision_EQ: {
3091 StringRef Val = A->getValue();
3092 const llvm::Triple::ArchType Arch = TC.getArch();
3093 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
3094 if (Val == "standard" || Val == "fast")
3095 Float16ExcessPrecision = Val;
3096 // To make it GCC compatible, allow the value of "16" which
3097 // means disable excess precision, the same meaning than clang's
3098 // equivalent value "none".
3099 else if (Val == "16")
3100 Float16ExcessPrecision = "none";
3101 else
3102 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3103 << A->getSpelling() << Val;
3104 } else {
3105 if (!(Val == "standard" || Val == "fast"))
3106 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3107 << A->getSpelling() << Val;
3108 }
3109 BFloat16ExcessPrecision = Float16ExcessPrecision;
3110 break;
3111 }
3112 case options::OPT_ffinite_math_only:
3113 HonorINFs = false;
3114 HonorNaNs = false;
3115 break;
3116 case options::OPT_fno_finite_math_only:
3117 HonorINFs = true;
3118 HonorNaNs = true;
3119 break;
3120
3121 case options::OPT_funsafe_math_optimizations:
3122 AssociativeMath = true;
3123 ReciprocalMath = true;
3124 SignedZeros = false;
3125 ApproxFunc = true;
3126 TrappingMath = false;
3127 FPExceptionBehavior = "";
3128 FPContract = "fast";
3129 LastFpContractOverrideOption = "-funsafe-math-optimizations";
3130 SeenUnsafeMathModeOption = true;
3131 break;
3132 case options::OPT_fno_unsafe_math_optimizations:
3133 AssociativeMath = false;
3134 ReciprocalMath = false;
3135 SignedZeros = true;
3136 ApproxFunc = false;
3137 restoreFPContractState();
3138 break;
3139
3140 case options::OPT_Ofast:
3141 // If -Ofast is the optimization level, then -ffast-math should be enabled
3142 if (!OFastEnabled)
3143 continue;
3144 [[fallthrough]];
3145 case options::OPT_ffast_math:
3146 applyFastMath(true, A->getSpelling());
3147 if (A->getOption().getID() == options::OPT_Ofast)
3148 LastFpContractOverrideOption = "-Ofast";
3149 else
3150 LastFpContractOverrideOption = "-ffast-math";
3151 break;
3152 case options::OPT_fno_fast_math:
3153 HonorINFs = true;
3154 HonorNaNs = true;
3155 // Turning on -ffast-math (with either flag) removes the need for
3156 // MathErrno. However, turning *off* -ffast-math merely restores the
3157 // toolchain default (which may be false).
3158 MathErrno = TC.IsMathErrnoDefault();
3159 AssociativeMath = false;
3160 ReciprocalMath = false;
3161 ApproxFunc = false;
3162 SignedZeros = true;
3163 restoreFPContractState();
3164 if (Range != LangOptions::ComplexRangeKind::CX_Full)
3165 setComplexRange(D, NewOpt: A->getSpelling(),
3166 NewRange: LangOptions::ComplexRangeKind::CX_None,
3167 LastOpt&: LastComplexRangeOption, Range);
3168 else
3169 Range = LangOptions::ComplexRangeKind::CX_None;
3170 LastComplexRangeOption = "";
3171 LastFpContractOverrideOption = "";
3172 break;
3173 } // End switch (A->getOption().getID())
3174
3175 // The StrictFPModel local variable is needed to report warnings
3176 // in the way we intend. If -ffp-model=strict has been used, we
3177 // want to report a warning for the next option encountered that
3178 // takes us out of the settings described by fp-model=strict, but
3179 // we don't want to continue issuing warnings for other conflicting
3180 // options after that.
3181 if (StrictFPModel) {
3182 // If -ffp-model=strict has been specified on command line but
3183 // subsequent options conflict then emit warning diagnostic.
3184 if (HonorINFs && HonorNaNs && !AssociativeMath && !ReciprocalMath &&
3185 SignedZeros && TrappingMath && RoundingFPMath && !ApproxFunc &&
3186 FPContract == "off")
3187 // OK: Current Arg doesn't conflict with -ffp-model=strict
3188 ;
3189 else {
3190 StrictFPModel = false;
3191 FPModel = "";
3192 // The warning for -ffp-contract would have been reported by the
3193 // OPT_ffp_contract_EQ handler above. A special check here is needed
3194 // to avoid duplicating the warning.
3195 auto RHS = (A->getNumValues() == 0)
3196 ? A->getSpelling()
3197 : Args.MakeArgString(Str: A->getSpelling() + A->getValue());
3198 if (A->getSpelling() != "-ffp-contract=") {
3199 if (RHS != "-ffp-model=strict")
3200 D.Diag(DiagID: clang::diag::warn_drv_overriding_option)
3201 << "-ffp-model=strict" << RHS;
3202 }
3203 }
3204 }
3205
3206 // If we handled this option claim it
3207 A->claim();
3208 }
3209
3210 if (!HonorINFs)
3211 CmdArgs.push_back(Elt: "-menable-no-infs");
3212
3213 if (!HonorNaNs)
3214 CmdArgs.push_back(Elt: "-menable-no-nans");
3215
3216 if (ApproxFunc)
3217 CmdArgs.push_back(Elt: "-fapprox-func");
3218
3219 if (MathErrno) {
3220 CmdArgs.push_back(Elt: "-fmath-errno");
3221 if (NoMathErrnoWasImpliedByVecLib)
3222 D.Diag(DiagID: clang::diag::warn_drv_math_errno_enabled_after_veclib)
3223 << ArgThatEnabledMathErrnoAfterVecLib->getAsString(Args)
3224 << VecLibArg->getAsString(Args);
3225 }
3226
3227 if (AssociativeMath && ReciprocalMath && !SignedZeros && ApproxFunc &&
3228 !TrappingMath)
3229 CmdArgs.push_back(Elt: "-funsafe-math-optimizations");
3230
3231 if (!SignedZeros)
3232 CmdArgs.push_back(Elt: "-fno-signed-zeros");
3233
3234 if (AssociativeMath && !SignedZeros && !TrappingMath)
3235 CmdArgs.push_back(Elt: "-mreassociate");
3236
3237 if (ReciprocalMath)
3238 CmdArgs.push_back(Elt: "-freciprocal-math");
3239
3240 if (TrappingMath) {
3241 // FP Exception Behavior is also set to strict
3242 assert(FPExceptionBehavior == "strict");
3243 }
3244
3245 // The default is IEEE.
3246 if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
3247 llvm::SmallString<64> DenormFlag;
3248 llvm::raw_svector_ostream ArgStr(DenormFlag);
3249 ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
3250 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArgStr.str()));
3251 }
3252
3253 // Add f32 specific denormal mode flag if it's different.
3254 if (DenormalFP32Math != DenormalFPMath) {
3255 llvm::SmallString<64> DenormFlag;
3256 llvm::raw_svector_ostream ArgStr(DenormFlag);
3257 ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
3258 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ArgStr.str()));
3259 }
3260
3261 if (!FPContract.empty())
3262 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-contract=" + FPContract));
3263
3264 if (RoundingFPMath)
3265 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-frounding-math"));
3266 else
3267 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fno-rounding-math"));
3268
3269 if (!FPExceptionBehavior.empty())
3270 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-exception-behavior=" +
3271 FPExceptionBehavior));
3272
3273 if (!FPEvalMethod.empty())
3274 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffp-eval-method=" + FPEvalMethod));
3275
3276 if (!Float16ExcessPrecision.empty())
3277 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ffloat16-excess-precision=" +
3278 Float16ExcessPrecision));
3279 if (!BFloat16ExcessPrecision.empty())
3280 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fbfloat16-excess-precision=" +
3281 BFloat16ExcessPrecision));
3282
3283 StringRef Recip = parseMRecipOption(Diags&: D.getDiags(), Args);
3284 if (!Recip.empty())
3285 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mrecip=" + Recip));
3286
3287 // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
3288 // individual features enabled by -ffast-math instead of the option itself as
3289 // that's consistent with gcc's behaviour.
3290 if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath && ApproxFunc &&
3291 ReciprocalMath && !SignedZeros && !TrappingMath && !RoundingFPMath)
3292 CmdArgs.push_back(Elt: "-ffast-math");
3293
3294 // Handle __FINITE_MATH_ONLY__ similarly.
3295 // The -ffinite-math-only is added to CmdArgs when !HonorINFs && !HonorNaNs.
3296 // Otherwise process the Xclang arguments to determine if -menable-no-infs and
3297 // -menable-no-nans are set by the user.
3298 bool shouldAddFiniteMathOnly = false;
3299 if (!HonorINFs && !HonorNaNs) {
3300 shouldAddFiniteMathOnly = true;
3301 } else {
3302 bool InfValues = true;
3303 bool NanValues = true;
3304 for (const auto *Arg : Args.filtered(Ids: options::OPT_Xclang)) {
3305 StringRef ArgValue = Arg->getValue();
3306 if (ArgValue == "-menable-no-nans")
3307 NanValues = false;
3308 else if (ArgValue == "-menable-no-infs")
3309 InfValues = false;
3310 }
3311 if (!NanValues && !InfValues)
3312 shouldAddFiniteMathOnly = true;
3313 }
3314 if (shouldAddFiniteMathOnly) {
3315 CmdArgs.push_back(Elt: "-ffinite-math-only");
3316 }
3317 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mfpmath_EQ)) {
3318 CmdArgs.push_back(Elt: "-mfpmath");
3319 CmdArgs.push_back(Elt: A->getValue());
3320 }
3321
3322 // Disable a codegen optimization for floating-point casts.
3323 if (Args.hasFlag(Pos: options::OPT_fno_strict_float_cast_overflow,
3324 Neg: options::OPT_fstrict_float_cast_overflow, Default: false))
3325 CmdArgs.push_back(Elt: "-fno-strict-float-cast-overflow");
3326
3327 if (Range != LangOptions::ComplexRangeKind::CX_None)
3328 ComplexRangeStr = renderComplexRangeOption(Range);
3329 if (!ComplexRangeStr.empty()) {
3330 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ComplexRangeStr));
3331 if (Args.hasArg(Ids: options::OPT_fcomplex_arithmetic_EQ))
3332 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fcomplex-arithmetic=" +
3333 complexRangeKindToStr(Range)));
3334 }
3335 if (Args.hasArg(Ids: options::OPT_fcx_limited_range))
3336 CmdArgs.push_back(Elt: "-fcx-limited-range");
3337 if (Args.hasArg(Ids: options::OPT_fcx_fortran_rules))
3338 CmdArgs.push_back(Elt: "-fcx-fortran-rules");
3339 if (Args.hasArg(Ids: options::OPT_fno_cx_limited_range))
3340 CmdArgs.push_back(Elt: "-fno-cx-limited-range");
3341 if (Args.hasArg(Ids: options::OPT_fno_cx_fortran_rules))
3342 CmdArgs.push_back(Elt: "-fno-cx-fortran-rules");
3343}
3344
3345static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
3346 const llvm::Triple &Triple,
3347 const InputInfo &Input) {
3348 // Add default argument set.
3349 if (!Args.hasArg(Ids: options::OPT__analyzer_no_default_checks)) {
3350 CmdArgs.push_back(Elt: "-analyzer-checker=core");
3351 CmdArgs.push_back(Elt: "-analyzer-checker=apiModeling");
3352
3353 if (!Triple.isWindowsMSVCEnvironment()) {
3354 CmdArgs.push_back(Elt: "-analyzer-checker=unix");
3355 } else {
3356 // Enable "unix" checkers that also work on Windows.
3357 CmdArgs.push_back(Elt: "-analyzer-checker=unix.API");
3358 CmdArgs.push_back(Elt: "-analyzer-checker=unix.Malloc");
3359 CmdArgs.push_back(Elt: "-analyzer-checker=unix.MallocSizeof");
3360 CmdArgs.push_back(Elt: "-analyzer-checker=unix.MismatchedDeallocator");
3361 CmdArgs.push_back(Elt: "-analyzer-checker=unix.cstring.BadSizeArg");
3362 CmdArgs.push_back(Elt: "-analyzer-checker=unix.cstring.NullArg");
3363 }
3364
3365 // Disable some unix checkers for PS4/PS5.
3366 if (Triple.isPS()) {
3367 CmdArgs.push_back(Elt: "-analyzer-disable-checker=unix.API");
3368 CmdArgs.push_back(Elt: "-analyzer-disable-checker=unix.Vfork");
3369 }
3370
3371 if (Triple.isOSDarwin()) {
3372 CmdArgs.push_back(Elt: "-analyzer-checker=osx");
3373 CmdArgs.push_back(
3374 Elt: "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
3375 }
3376 else if (Triple.isOSFuchsia())
3377 CmdArgs.push_back(Elt: "-analyzer-checker=fuchsia");
3378
3379 CmdArgs.push_back(Elt: "-analyzer-checker=deadcode");
3380
3381 if (types::isCXX(Id: Input.getType()))
3382 CmdArgs.push_back(Elt: "-analyzer-checker=cplusplus");
3383
3384 if (!Triple.isPS()) {
3385 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.UncheckedReturn");
3386 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.getpw");
3387 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.gets");
3388 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.mktemp");
3389 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.mkstemp");
3390 CmdArgs.push_back(Elt: "-analyzer-checker=security.insecureAPI.vfork");
3391 }
3392
3393 // Default nullability checks.
3394 CmdArgs.push_back(Elt: "-analyzer-checker=nullability.NullPassedToNonnull");
3395 CmdArgs.push_back(Elt: "-analyzer-checker=nullability.NullReturnedFromNonnull");
3396 }
3397
3398 // Set the output format. The default is plist, for (lame) historical reasons.
3399 CmdArgs.push_back(Elt: "-analyzer-output");
3400 if (Arg *A = Args.getLastArg(Ids: options::OPT__analyzer_output))
3401 CmdArgs.push_back(Elt: A->getValue());
3402 else
3403 CmdArgs.push_back(Elt: "plist");
3404
3405 // Disable the presentation of standard compiler warnings when using
3406 // --analyze. We only want to show static analyzer diagnostics or frontend
3407 // errors.
3408 CmdArgs.push_back(Elt: "-w");
3409
3410 // Add -Xanalyzer arguments when running as analyzer.
3411 Args.AddAllArgValues(Output&: CmdArgs, Id0: options::OPT_Xanalyzer);
3412}
3413
3414static bool isValidSymbolName(StringRef S) {
3415 if (S.empty())
3416 return false;
3417
3418 if (std::isdigit(S[0]))
3419 return false;
3420
3421 return llvm::all_of(Range&: S, P: [](char C) { return std::isalnum(C) || C == '_'; });
3422}
3423
3424static void RenderSSPOptions(const Driver &D, const ToolChain &TC,
3425 const ArgList &Args, ArgStringList &CmdArgs,
3426 bool KernelOrKext) {
3427 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3428
3429 // NVPTX doesn't support stack protectors; from the compiler's perspective, it
3430 // doesn't even have a stack!
3431 if (EffectiveTriple.isNVPTX())
3432 return;
3433
3434 // -stack-protector=0 is default.
3435 LangOptions::StackProtectorMode StackProtectorLevel = LangOptions::SSPOff;
3436 LangOptions::StackProtectorMode DefaultStackProtectorLevel =
3437 TC.GetDefaultStackProtectorLevel(KernelOrKext);
3438
3439 if (Arg *A = Args.getLastArg(Ids: options::OPT_fno_stack_protector,
3440 Ids: options::OPT_fstack_protector_all,
3441 Ids: options::OPT_fstack_protector_strong,
3442 Ids: options::OPT_fstack_protector)) {
3443 if (A->getOption().matches(ID: options::OPT_fstack_protector))
3444 StackProtectorLevel =
3445 std::max<>(a: LangOptions::SSPOn, b: DefaultStackProtectorLevel);
3446 else if (A->getOption().matches(ID: options::OPT_fstack_protector_strong))
3447 StackProtectorLevel = LangOptions::SSPStrong;
3448 else if (A->getOption().matches(ID: options::OPT_fstack_protector_all))
3449 StackProtectorLevel = LangOptions::SSPReq;
3450
3451 if (EffectiveTriple.isBPF() && StackProtectorLevel != LangOptions::SSPOff) {
3452 D.Diag(DiagID: diag::warn_drv_unsupported_option_for_target)
3453 << A->getSpelling() << EffectiveTriple.getTriple();
3454 StackProtectorLevel = DefaultStackProtectorLevel;
3455 }
3456 } else {
3457 StackProtectorLevel = DefaultStackProtectorLevel;
3458 }
3459
3460 if (StackProtectorLevel) {
3461 CmdArgs.push_back(Elt: "-stack-protector");
3462 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(StackProtectorLevel)));
3463 }
3464
3465 // --param ssp-buffer-size=
3466 for (const Arg *A : Args.filtered(Ids: options::OPT__param)) {
3467 StringRef Str(A->getValue());
3468 if (Str.consume_front(Prefix: "ssp-buffer-size=")) {
3469 if (StackProtectorLevel) {
3470 CmdArgs.push_back(Elt: "-stack-protector-buffer-size");
3471 // FIXME: Verify the argument is a valid integer.
3472 CmdArgs.push_back(Elt: Args.MakeArgString(Str));
3473 }
3474 A->claim();
3475 }
3476 }
3477
3478 const std::string &TripleStr = EffectiveTriple.getTriple();
3479 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_EQ)) {
3480 StringRef Value = A->getValue();
3481 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3482 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3483 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3484 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3485 << A->getAsString(Args) << TripleStr;
3486 if ((EffectiveTriple.isX86() || EffectiveTriple.isARM() ||
3487 EffectiveTriple.isThumb()) &&
3488 Value != "tls" && Value != "global") {
3489 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3490 << A->getOption().getName() << Value << "tls global";
3491 return;
3492 }
3493 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3494 Value == "tls") {
3495 if (!Args.hasArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3496 D.Diag(DiagID: diag::err_drv_ssp_missing_offset_argument)
3497 << A->getAsString(Args);
3498 return;
3499 }
3500 // Check whether the target subarch supports the hardware TLS register
3501 if (!arm::isHardTPSupported(Triple: EffectiveTriple)) {
3502 D.Diag(DiagID: diag::err_target_unsupported_tp_hard)
3503 << EffectiveTriple.getArchName();
3504 return;
3505 }
3506 // Check whether the user asked for something other than -mtp=cp15
3507 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtp_mode_EQ)) {
3508 StringRef Value = A->getValue();
3509 if (Value != "cp15") {
3510 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
3511 << A->getAsString(Args) << "-mstack-protector-guard=tls";
3512 return;
3513 }
3514 }
3515 CmdArgs.push_back(Elt: "-target-feature");
3516 CmdArgs.push_back(Elt: "+read-tp-tpidruro");
3517 }
3518 if (EffectiveTriple.isAArch64() && Value != "sysreg" && Value != "global") {
3519 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3520 << A->getOption().getName() << Value << "sysreg global";
3521 return;
3522 }
3523 if (EffectiveTriple.isRISCV() || EffectiveTriple.isPPC()) {
3524 if (Value != "tls" && Value != "global") {
3525 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3526 << A->getOption().getName() << Value << "tls global";
3527 return;
3528 }
3529 if (Value == "tls") {
3530 if (!Args.hasArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3531 D.Diag(DiagID: diag::err_drv_ssp_missing_offset_argument)
3532 << A->getAsString(Args);
3533 return;
3534 }
3535 }
3536 }
3537 A->render(Args, Output&: CmdArgs);
3538 }
3539
3540 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_offset_EQ)) {
3541 StringRef Value = A->getValue();
3542 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3543 !EffectiveTriple.isARM() && !EffectiveTriple.isThumb() &&
3544 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3545 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3546 << A->getAsString(Args) << TripleStr;
3547 int Offset;
3548 if (Value.getAsInteger(Radix: 10, Result&: Offset)) {
3549 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3550 return;
3551 }
3552 if ((EffectiveTriple.isARM() || EffectiveTriple.isThumb()) &&
3553 (Offset < 0 || Offset > 0xfffff)) {
3554 D.Diag(DiagID: diag::err_drv_invalid_int_value)
3555 << A->getOption().getName() << Value;
3556 return;
3557 }
3558 A->render(Args, Output&: CmdArgs);
3559 }
3560
3561 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_reg_EQ)) {
3562 StringRef Value = A->getValue();
3563 if (!EffectiveTriple.isX86() && !EffectiveTriple.isAArch64() &&
3564 !EffectiveTriple.isRISCV() && !EffectiveTriple.isPPC())
3565 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
3566 << A->getAsString(Args) << TripleStr;
3567 if (EffectiveTriple.isX86() && (Value != "fs" && Value != "gs")) {
3568 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3569 << A->getOption().getName() << Value << "fs gs";
3570 return;
3571 }
3572 if (EffectiveTriple.isAArch64() && Value != "sp_el0") {
3573 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getOption().getName() << Value;
3574 return;
3575 }
3576 if (EffectiveTriple.isRISCV() && Value != "tp") {
3577 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3578 << A->getOption().getName() << Value << "tp";
3579 return;
3580 }
3581 if (EffectiveTriple.isPPC64() && Value != "r13") {
3582 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3583 << A->getOption().getName() << Value << "r13";
3584 return;
3585 }
3586 if (EffectiveTriple.isPPC32() && Value != "r2") {
3587 D.Diag(DiagID: diag::err_drv_invalid_value_with_suggestion)
3588 << A->getOption().getName() << Value << "r2";
3589 return;
3590 }
3591 A->render(Args, Output&: CmdArgs);
3592 }
3593
3594 if (Arg *A = Args.getLastArg(Ids: options::OPT_mstack_protector_guard_symbol_EQ)) {
3595 StringRef Value = A->getValue();
3596 if (!isValidSymbolName(S: Value)) {
3597 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
3598 << A->getOption().getName() << "legal symbol name";
3599 return;
3600 }
3601 A->render(Args, Output&: CmdArgs);
3602 }
3603}
3604
3605static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
3606 ArgStringList &CmdArgs) {
3607 const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
3608
3609 if (!EffectiveTriple.isOSFreeBSD() && !EffectiveTriple.isOSLinux() &&
3610 !EffectiveTriple.isOSFuchsia())
3611 return;
3612
3613 if (!EffectiveTriple.isX86() && !EffectiveTriple.isSystemZ() &&
3614 !EffectiveTriple.isPPC64() && !EffectiveTriple.isAArch64() &&
3615 !EffectiveTriple.isRISCV())
3616 return;
3617
3618 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstack_clash_protection,
3619 Neg: options::OPT_fno_stack_clash_protection);
3620}
3621
3622static void RenderTrivialAutoVarInitOptions(const Driver &D,
3623 const ToolChain &TC,
3624 const ArgList &Args,
3625 ArgStringList &CmdArgs) {
3626 auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3627 StringRef TrivialAutoVarInit = "";
3628
3629 for (const Arg *A : Args) {
3630 switch (A->getOption().getID()) {
3631 default:
3632 continue;
3633 case options::OPT_ftrivial_auto_var_init: {
3634 A->claim();
3635 StringRef Val = A->getValue();
3636 if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
3637 TrivialAutoVarInit = Val;
3638 else
3639 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
3640 << A->getSpelling() << Val;
3641 break;
3642 }
3643 }
3644 }
3645
3646 if (TrivialAutoVarInit.empty())
3647 switch (DefaultTrivialAutoVarInit) {
3648 case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3649 break;
3650 case LangOptions::TrivialAutoVarInitKind::Pattern:
3651 TrivialAutoVarInit = "pattern";
3652 break;
3653 case LangOptions::TrivialAutoVarInitKind::Zero:
3654 TrivialAutoVarInit = "zero";
3655 break;
3656 }
3657
3658 if (!TrivialAutoVarInit.empty()) {
3659 CmdArgs.push_back(
3660 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3661 }
3662
3663 if (Arg *A =
3664 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init_stop_after)) {
3665 if (!Args.hasArg(Ids: options::OPT_ftrivial_auto_var_init) ||
3666 StringRef(
3667 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init)->getValue()) ==
3668 "uninitialized")
3669 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3670 A->claim();
3671 StringRef Val = A->getValue();
3672 if (std::stoi(str: Val.str()) <= 0)
3673 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3674 CmdArgs.push_back(
3675 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init-stop-after=" + Val));
3676 }
3677
3678 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init_max_size)) {
3679 if (!Args.hasArg(Ids: options::OPT_ftrivial_auto_var_init) ||
3680 StringRef(
3681 Args.getLastArg(Ids: options::OPT_ftrivial_auto_var_init)->getValue()) ==
3682 "uninitialized")
3683 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_max_size_missing_dependency);
3684 A->claim();
3685 StringRef Val = A->getValue();
3686 if (std::stoi(str: Val.str()) <= 0)
3687 D.Diag(DiagID: diag::err_drv_trivial_auto_var_init_max_size_invalid_value);
3688 CmdArgs.push_back(
3689 Elt: Args.MakeArgString(Str: "-ftrivial-auto-var-init-max-size=" + Val));
3690 }
3691}
3692
3693static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3694 types::ID InputType) {
3695 // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3696 // for denormal flushing handling based on the target.
3697 const unsigned ForwardedArguments[] = {
3698 options::OPT_cl_opt_disable,
3699 options::OPT_cl_strict_aliasing,
3700 options::OPT_cl_single_precision_constant,
3701 options::OPT_cl_finite_math_only,
3702 options::OPT_cl_kernel_arg_info,
3703 options::OPT_cl_unsafe_math_optimizations,
3704 options::OPT_cl_fast_relaxed_math,
3705 options::OPT_cl_mad_enable,
3706 options::OPT_cl_no_signed_zeros,
3707 options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3708 options::OPT_cl_uniform_work_group_size
3709 };
3710
3711 if (Arg *A = Args.getLastArg(Ids: options::OPT_cl_std_EQ)) {
3712 std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3713 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CLStdStr));
3714 } else if (Arg *A = Args.getLastArg(Ids: options::OPT_cl_ext_EQ)) {
3715 std::string CLExtStr = std::string("-cl-ext=") + A->getValue();
3716 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CLExtStr));
3717 }
3718
3719 if (Args.hasArg(Ids: options::OPT_cl_finite_math_only)) {
3720 CmdArgs.push_back(Elt: "-menable-no-infs");
3721 CmdArgs.push_back(Elt: "-menable-no-nans");
3722 }
3723
3724 for (const auto &Arg : ForwardedArguments)
3725 if (const auto *A = Args.getLastArg(Ids: Arg))
3726 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getOption().getPrefixedName()));
3727
3728 // Only add the default headers if we are compiling OpenCL sources.
3729 if ((types::isOpenCL(Id: InputType) ||
3730 (Args.hasArg(Ids: options::OPT_cl_std_EQ) && types::isSrcFile(Id: InputType))) &&
3731 !Args.hasArg(Ids: options::OPT_cl_no_stdinc)) {
3732 CmdArgs.push_back(Elt: "-finclude-default-header");
3733 CmdArgs.push_back(Elt: "-fdeclare-opencl-builtins");
3734 }
3735}
3736
3737static void RenderHLSLOptions(const ArgList &Args, ArgStringList &CmdArgs,
3738 types::ID InputType) {
3739 const unsigned ForwardedArguments[] = {
3740 options::OPT_hlsl_all_resources_bound,
3741 options::OPT_dxil_validator_version,
3742 options::OPT_res_may_alias,
3743 options::OPT_D,
3744 options::OPT_I,
3745 options::OPT_O,
3746 options::OPT_emit_llvm,
3747 options::OPT_emit_obj,
3748 options::OPT_disable_llvm_passes,
3749 options::OPT_fnative_half_type,
3750 options::OPT_fnative_int16_type,
3751 options::OPT_fmatrix_memory_layout_EQ,
3752 options::OPT_hlsl_entrypoint,
3753 options::OPT_fdx_rootsignature_define,
3754 options::OPT_fdx_rootsignature_version,
3755 options::OPT_fhlsl_spv_use_unknown_image_format,
3756 options::OPT_fhlsl_spv_enable_maximal_reconvergence};
3757 if (!types::isHLSL(Id: InputType))
3758 return;
3759 for (const auto &Arg : ForwardedArguments)
3760 if (const auto *A = Args.getLastArg(Ids: Arg))
3761 A->renderAsInput(Args, Output&: CmdArgs);
3762 // Add the default headers if dxc_no_stdinc is not set.
3763 if (!Args.hasArg(Ids: options::OPT_dxc_no_stdinc) &&
3764 !Args.hasArg(Ids: options::OPT_nostdinc))
3765 CmdArgs.push_back(Elt: "-finclude-default-header");
3766}
3767
3768static void RenderOpenACCOptions(const Driver &D, const ArgList &Args,
3769 ArgStringList &CmdArgs, types::ID InputType) {
3770 if (!Args.hasArg(Ids: options::OPT_fopenacc))
3771 return;
3772
3773 CmdArgs.push_back(Elt: "-fopenacc");
3774}
3775
3776static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3777 const ArgList &Args, ArgStringList &CmdArgs) {
3778 // -fbuiltin is default unless -mkernel is used.
3779 bool UseBuiltins =
3780 Args.hasFlag(Pos: options::OPT_fbuiltin, Neg: options::OPT_fno_builtin,
3781 Default: !Args.hasArg(Ids: options::OPT_mkernel));
3782 if (!UseBuiltins)
3783 CmdArgs.push_back(Elt: "-fno-builtin");
3784
3785 // -ffreestanding implies -fno-builtin.
3786 if (Args.hasArg(Ids: options::OPT_ffreestanding))
3787 UseBuiltins = false;
3788
3789 // Process the -fno-builtin-* options.
3790 for (const Arg *A : Args.filtered(Ids: options::OPT_fno_builtin_)) {
3791 A->claim();
3792
3793 // If -fno-builtin is specified, then there's no need to pass the option to
3794 // the frontend.
3795 if (UseBuiltins)
3796 A->render(Args, Output&: CmdArgs);
3797 }
3798}
3799
3800bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
3801 if (const char *Str = std::getenv(name: "CLANG_MODULE_CACHE_PATH")) {
3802 Twine Path{Str};
3803 Path.toVector(Out&: Result);
3804 return Path.getSingleStringRef() != "";
3805 }
3806 if (llvm::sys::path::cache_directory(result&: Result)) {
3807 llvm::sys::path::append(path&: Result, a: "clang");
3808 llvm::sys::path::append(path&: Result, a: "ModuleCache");
3809 return true;
3810 }
3811 return false;
3812}
3813
3814llvm::SmallString<256>
3815clang::driver::tools::getCXX20NamedModuleOutputPath(const ArgList &Args,
3816 const char *BaseInput) {
3817 if (Arg *ModuleOutputEQ = Args.getLastArg(Ids: options::OPT_fmodule_output_EQ))
3818 return StringRef(ModuleOutputEQ->getValue());
3819
3820 SmallString<256> OutputPath;
3821 if (Arg *FinalOutput = Args.getLastArg(Ids: options::OPT_o);
3822 FinalOutput && Args.hasArg(Ids: options::OPT_c))
3823 OutputPath = FinalOutput->getValue();
3824 else {
3825 llvm::sys::fs::current_path(result&: OutputPath);
3826 llvm::sys::path::append(path&: OutputPath, a: llvm::sys::path::filename(path: BaseInput));
3827 }
3828
3829 const char *Extension = types::getTypeTempSuffix(Id: types::TY_ModuleFile);
3830 llvm::sys::path::replace_extension(path&: OutputPath, extension: Extension);
3831 return OutputPath;
3832}
3833
3834static bool RenderModulesOptions(Compilation &C, const Driver &D,
3835 const ArgList &Args, const InputInfo &Input,
3836 const InputInfo &Output, bool HaveStd20,
3837 ArgStringList &CmdArgs) {
3838 const bool IsCXX = types::isCXX(Id: Input.getType());
3839 const bool HaveStdCXXModules = IsCXX && HaveStd20;
3840 bool HaveModules = HaveStdCXXModules;
3841
3842 // -fmodules enables the use of precompiled modules (off by default).
3843 // Users can pass -fno-cxx-modules to turn off modules support for
3844 // C++/Objective-C++ programs.
3845 const bool AllowedInCXX = Args.hasFlag(Pos: options::OPT_fcxx_modules,
3846 Neg: options::OPT_fno_cxx_modules, Default: true);
3847 bool HaveClangModules = false;
3848 if (Args.hasFlag(Pos: options::OPT_fmodules, Neg: options::OPT_fno_modules, Default: false)) {
3849 if (AllowedInCXX || !IsCXX) {
3850 CmdArgs.push_back(Elt: "-fmodules");
3851 HaveClangModules = true;
3852 }
3853 }
3854
3855 HaveModules |= HaveClangModules;
3856
3857 if (HaveModules && !AllowedInCXX)
3858 CmdArgs.push_back(Elt: "-fno-cxx-modules");
3859
3860 // -fmodule-maps enables implicit reading of module map files. By default,
3861 // this is enabled if we are using Clang's flavor of precompiled modules.
3862 if (Args.hasFlag(Pos: options::OPT_fimplicit_module_maps,
3863 Neg: options::OPT_fno_implicit_module_maps, Default: HaveClangModules))
3864 CmdArgs.push_back(Elt: "-fimplicit-module-maps");
3865
3866 // -fmodules-decluse checks that modules used are declared so (off by default)
3867 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fmodules_decluse,
3868 Neg: options::OPT_fno_modules_decluse);
3869
3870 // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3871 // all #included headers are part of modules.
3872 if (Args.hasFlag(Pos: options::OPT_fmodules_strict_decluse,
3873 Neg: options::OPT_fno_modules_strict_decluse, Default: false))
3874 CmdArgs.push_back(Elt: "-fmodules-strict-decluse");
3875
3876 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fmodulemap_allow_subdirectory_search,
3877 Neg: options::OPT_fno_modulemap_allow_subdirectory_search);
3878
3879 // -fno-implicit-modules turns off implicitly compiling modules on demand.
3880 bool ImplicitModules = false;
3881 if (!Args.hasFlag(Pos: options::OPT_fimplicit_modules,
3882 Neg: options::OPT_fno_implicit_modules, Default: HaveClangModules)) {
3883 if (HaveModules)
3884 CmdArgs.push_back(Elt: "-fno-implicit-modules");
3885 } else if (HaveModules) {
3886 ImplicitModules = true;
3887 // -fmodule-cache-path specifies where our implicitly-built module files
3888 // should be written.
3889 SmallString<128> Path;
3890 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmodules_cache_path))
3891 Path = A->getValue();
3892
3893 bool HasPath = true;
3894 if (C.isForDiagnostics()) {
3895 // When generating crash reports, we want to emit the modules along with
3896 // the reproduction sources, so we ignore any provided module path.
3897 Path = Output.getFilename();
3898 llvm::sys::path::replace_extension(path&: Path, extension: ".cache");
3899 llvm::sys::path::append(path&: Path, a: "modules");
3900 } else if (Path.empty()) {
3901 // No module path was provided: use the default.
3902 HasPath = Driver::getDefaultModuleCachePath(Result&: Path);
3903 }
3904
3905 // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3906 // That being said, that failure is unlikely and not caching is harmless.
3907 if (HasPath) {
3908 const char Arg[] = "-fmodules-cache-path=";
3909 Path.insert(I: Path.begin(), From: Arg, To: Arg + strlen(s: Arg));
3910 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Path));
3911 }
3912 }
3913
3914 if (HaveModules) {
3915 if (Args.hasFlag(Pos: options::OPT_fprebuilt_implicit_modules,
3916 Neg: options::OPT_fno_prebuilt_implicit_modules, Default: false))
3917 CmdArgs.push_back(Elt: "-fprebuilt-implicit-modules");
3918 if (Args.hasFlag(Pos: options::OPT_fmodules_validate_input_files_content,
3919 Neg: options::OPT_fno_modules_validate_input_files_content,
3920 Default: false))
3921 CmdArgs.push_back(Elt: "-fvalidate-ast-input-files-content");
3922 }
3923
3924 // -fmodule-name specifies the module that is currently being built (or
3925 // used for header checking by -fmodule-maps).
3926 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodule_name_EQ);
3927
3928 // -fmodule-map-file can be used to specify files containing module
3929 // definitions.
3930 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodule_map_file);
3931
3932 // -fbuiltin-module-map can be used to load the clang
3933 // builtin headers modulemap file.
3934 if (Args.hasArg(Ids: options::OPT_fbuiltin_module_map)) {
3935 SmallString<128> BuiltinModuleMap(D.ResourceDir);
3936 llvm::sys::path::append(path&: BuiltinModuleMap, a: "include");
3937 llvm::sys::path::append(path&: BuiltinModuleMap, a: "module.modulemap");
3938 if (llvm::sys::fs::exists(Path: BuiltinModuleMap))
3939 CmdArgs.push_back(
3940 Elt: Args.MakeArgString(Str: "-fmodule-map-file=" + BuiltinModuleMap));
3941 }
3942
3943 // The -fmodule-file=<name>=<file> form specifies the mapping of module
3944 // names to precompiled module files (the module is loaded only if used).
3945 // The -fmodule-file=<file> form can be used to unconditionally load
3946 // precompiled module files (whether used or not).
3947 if (HaveModules || Input.getType() == clang::driver::types::TY_ModuleFile) {
3948 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodule_file);
3949
3950 // -fprebuilt-module-path specifies where to load the prebuilt module files.
3951 for (const Arg *A : Args.filtered(Ids: options::OPT_fprebuilt_module_path)) {
3952 CmdArgs.push_back(Elt: Args.MakeArgString(
3953 Str: std::string("-fprebuilt-module-path=") + A->getValue()));
3954 A->claim();
3955 }
3956 } else
3957 Args.ClaimAllArgs(Id0: options::OPT_fmodule_file);
3958
3959 // When building modules and generating crashdumps, we need to dump a module
3960 // dependency VFS alongside the output.
3961 if (HaveClangModules && C.isForDiagnostics()) {
3962 SmallString<128> VFSDir(Output.getFilename());
3963 llvm::sys::path::replace_extension(path&: VFSDir, extension: ".cache");
3964 // Add the cache directory as a temp so the crash diagnostics pick it up.
3965 C.addTempFile(Name: Args.MakeArgString(Str: VFSDir));
3966
3967 llvm::sys::path::append(path&: VFSDir, a: "vfs");
3968 CmdArgs.push_back(Elt: "-module-dependency-dir");
3969 CmdArgs.push_back(Elt: Args.MakeArgString(Str: VFSDir));
3970 }
3971
3972 if (HaveClangModules)
3973 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_user_build_path);
3974
3975 // Pass through all -fmodules-ignore-macro arguments.
3976 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fmodules_ignore_macro);
3977 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_prune_interval);
3978 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodules_prune_after);
3979
3980 if (HaveClangModules) {
3981 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fbuild_session_timestamp);
3982
3983 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbuild_session_file)) {
3984 if (Args.hasArg(Ids: options::OPT_fbuild_session_timestamp))
3985 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
3986 << A->getAsString(Args) << "-fbuild-session-timestamp";
3987
3988 llvm::sys::fs::file_status Status;
3989 if (llvm::sys::fs::status(path: A->getValue(), result&: Status))
3990 D.Diag(DiagID: diag::err_drv_no_such_file) << A->getValue();
3991 CmdArgs.push_back(Elt: Args.MakeArgString(
3992 Str: "-fbuild-session-timestamp=" +
3993 Twine((uint64_t)std::chrono::duration_cast<std::chrono::seconds>(
3994 d: Status.getLastModificationTime().time_since_epoch())
3995 .count())));
3996 }
3997
3998 if (Args.getLastArg(
3999 Ids: options::OPT_fmodules_validate_once_per_build_session)) {
4000 if (!Args.getLastArg(Ids: options::OPT_fbuild_session_timestamp,
4001 Ids: options::OPT_fbuild_session_file))
4002 D.Diag(DiagID: diag::err_drv_modules_validate_once_requires_timestamp);
4003
4004 Args.AddLastArg(Output&: CmdArgs,
4005 Ids: options::OPT_fmodules_validate_once_per_build_session);
4006 }
4007
4008 if (Args.hasFlag(Pos: options::OPT_fmodules_validate_system_headers,
4009 Neg: options::OPT_fno_modules_validate_system_headers,
4010 Default: ImplicitModules))
4011 CmdArgs.push_back(Elt: "-fmodules-validate-system-headers");
4012
4013 Args.AddLastArg(Output&: CmdArgs,
4014 Ids: options::OPT_fmodules_disable_diagnostic_validation);
4015 } else {
4016 Args.ClaimAllArgs(Id0: options::OPT_fbuild_session_timestamp);
4017 Args.ClaimAllArgs(Id0: options::OPT_fbuild_session_file);
4018 Args.ClaimAllArgs(Id0: options::OPT_fmodules_validate_once_per_build_session);
4019 Args.ClaimAllArgs(Id0: options::OPT_fmodules_validate_system_headers);
4020 Args.ClaimAllArgs(Id0: options::OPT_fno_modules_validate_system_headers);
4021 Args.ClaimAllArgs(Id0: options::OPT_fmodules_disable_diagnostic_validation);
4022 }
4023
4024 // FIXME: We provisionally don't check ODR violations for decls in the global
4025 // module fragment.
4026 CmdArgs.push_back(Elt: "-fskip-odr-check-in-gmf");
4027
4028 if (Input.getType() == driver::types::TY_CXXModule ||
4029 Input.getType() == driver::types::TY_PP_CXXModule) {
4030 if (!Args.hasArg(Ids: options::OPT_fno_modules_reduced_bmi))
4031 CmdArgs.push_back(Elt: "-fmodules-reduced-bmi");
4032
4033 if (Args.hasArg(Ids: options::OPT_fmodule_output_EQ))
4034 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmodule_output_EQ);
4035 else if (!Args.hasArg(Ids: options::OPT__precompile) ||
4036 Args.hasArg(Ids: options::OPT_fmodule_output))
4037 // If --precompile is specified, we will always generate a module file if
4038 // we're compiling an importable module unit. This is fine even if the
4039 // compilation process won't reach the point of generating the module file
4040 // (e.g., in the preprocessing mode), since the attached flag
4041 // '-fmodule-output' is useless.
4042 //
4043 // But if '--precompile' is specified, it might be annoying to always
4044 // generate the module file as '--precompile' will generate the module
4045 // file anyway.
4046 CmdArgs.push_back(Elt: Args.MakeArgString(
4047 Str: "-fmodule-output=" +
4048 getCXX20NamedModuleOutputPath(Args, BaseInput: Input.getBaseInput())));
4049 }
4050
4051 if (Args.hasArg(Ids: options::OPT_fmodules_reduced_bmi) &&
4052 Args.hasArg(Ids: options::OPT__precompile) &&
4053 (!Args.hasArg(Ids: options::OPT_o) ||
4054 Args.getLastArg(Ids: options::OPT_o)->getValue() ==
4055 getCXX20NamedModuleOutputPath(Args, BaseInput: Input.getBaseInput()))) {
4056 D.Diag(DiagID: diag::err_drv_reduced_module_output_overrided);
4057 }
4058
4059 // Noop if we see '-fmodules-reduced-bmi' or `-fno-modules-reduced-bmi` with
4060 // other translation units than module units. This is more user friendly to
4061 // allow end uers to enable this feature without asking for help from build
4062 // systems.
4063 Args.ClaimAllArgs(Id0: options::OPT_fmodules_reduced_bmi);
4064 Args.ClaimAllArgs(Id0: options::OPT_fno_modules_reduced_bmi);
4065
4066 // We need to include the case the input file is a module file here.
4067 // Since the default compilation model for C++ module interface unit will
4068 // create temporary module file and compile the temporary module file
4069 // to get the object file. Then the `-fmodule-output` flag will be
4070 // brought to the second compilation process. So we have to claim it for
4071 // the case too.
4072 if (Input.getType() == driver::types::TY_CXXModule ||
4073 Input.getType() == driver::types::TY_PP_CXXModule ||
4074 Input.getType() == driver::types::TY_ModuleFile) {
4075 Args.ClaimAllArgs(Id0: options::OPT_fmodule_output);
4076 Args.ClaimAllArgs(Id0: options::OPT_fmodule_output_EQ);
4077 }
4078
4079 if (Args.hasArg(Ids: options::OPT_fmodules_embed_all_files))
4080 CmdArgs.push_back(Elt: "-fmodules-embed-all-files");
4081
4082 return HaveModules;
4083}
4084
4085static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
4086 ArgStringList &CmdArgs) {
4087 // -fsigned-char is default.
4088 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fsigned_char,
4089 Ids: options::OPT_fno_signed_char,
4090 Ids: options::OPT_funsigned_char,
4091 Ids: options::OPT_fno_unsigned_char)) {
4092 if (A->getOption().matches(ID: options::OPT_funsigned_char) ||
4093 A->getOption().matches(ID: options::OPT_fno_signed_char)) {
4094 CmdArgs.push_back(Elt: "-fno-signed-char");
4095 }
4096 } else if (!isSignedCharDefault(Triple: T)) {
4097 CmdArgs.push_back(Elt: "-fno-signed-char");
4098 }
4099
4100 // The default depends on the language standard.
4101 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fchar8__t, Ids: options::OPT_fno_char8__t);
4102
4103 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fshort_wchar,
4104 Ids: options::OPT_fno_short_wchar)) {
4105 if (A->getOption().matches(ID: options::OPT_fshort_wchar)) {
4106 CmdArgs.push_back(Elt: "-fwchar-type=short");
4107 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4108 } else {
4109 bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
4110 CmdArgs.push_back(Elt: "-fwchar-type=int");
4111 if (T.isOSzOS() ||
4112 (IsARM && !(T.isOSWindows() || T.isOSNetBSD() || T.isOSOpenBSD())))
4113 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4114 else
4115 CmdArgs.push_back(Elt: "-fsigned-wchar");
4116 }
4117 } else if (T.isOSzOS())
4118 CmdArgs.push_back(Elt: "-fno-signed-wchar");
4119}
4120
4121static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
4122 const llvm::Triple &T, const ArgList &Args,
4123 ObjCRuntime &Runtime, bool InferCovariantReturns,
4124 const InputInfo &Input, ArgStringList &CmdArgs) {
4125 const llvm::Triple::ArchType Arch = TC.getArch();
4126
4127 // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
4128 // is the default. Except for deployment target of 10.5, next runtime is
4129 // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
4130 if (Runtime.isNonFragile()) {
4131 if (!Args.hasFlag(Pos: options::OPT_fobjc_legacy_dispatch,
4132 Neg: options::OPT_fno_objc_legacy_dispatch,
4133 Default: Runtime.isLegacyDispatchDefaultForArch(Arch))) {
4134 if (TC.UseObjCMixedDispatch())
4135 CmdArgs.push_back(Elt: "-fobjc-dispatch-method=mixed");
4136 else
4137 CmdArgs.push_back(Elt: "-fobjc-dispatch-method=non-legacy");
4138 }
4139 }
4140
4141 // Forward -fobjc-direct-precondition-thunk to cc1
4142 // Defaults to false and needs explict turn on for now
4143 // TODO: switch to default true and needs explict turn off in the future.
4144 // TODO: add support for other runtimes
4145 if (Args.hasFlag(Pos: options::OPT_fobjc_direct_precondition_thunk,
4146 Neg: options::OPT_fno_objc_direct_precondition_thunk, Default: false)) {
4147 if (Runtime.isNeXTFamily()) {
4148 CmdArgs.push_back(Elt: "-fobjc-direct-precondition-thunk");
4149 } else {
4150 D.Diag(DiagID: diag::warn_drv_unsupported_option_for_runtime)
4151 << "-fobjc-direct-precondition-thunk" << Runtime.getAsString();
4152 }
4153 }
4154 // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
4155 // to do Array/Dictionary subscripting by default.
4156 if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
4157 Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
4158 CmdArgs.push_back(Elt: "-fobjc-subscripting-legacy-runtime");
4159
4160 // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
4161 // NOTE: This logic is duplicated in ToolChains.cpp.
4162 if (isObjCAutoRefCount(Args)) {
4163 TC.CheckObjCARC();
4164
4165 CmdArgs.push_back(Elt: "-fobjc-arc");
4166
4167 // FIXME: It seems like this entire block, and several around it should be
4168 // wrapped in isObjC, but for now we just use it here as this is where it
4169 // was being used previously.
4170 if (types::isCXX(Id: Input.getType()) && types::isObjC(Id: Input.getType())) {
4171 if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
4172 CmdArgs.push_back(Elt: "-fobjc-arc-cxxlib=libc++");
4173 else
4174 CmdArgs.push_back(Elt: "-fobjc-arc-cxxlib=libstdc++");
4175 }
4176
4177 // Allow the user to enable full exceptions code emission.
4178 // We default off for Objective-C, on for Objective-C++.
4179 if (Args.hasFlag(Pos: options::OPT_fobjc_arc_exceptions,
4180 Neg: options::OPT_fno_objc_arc_exceptions,
4181 /*Default=*/types::isCXX(Id: Input.getType())))
4182 CmdArgs.push_back(Elt: "-fobjc-arc-exceptions");
4183 }
4184
4185 // Silence warning for full exception code emission options when explicitly
4186 // set to use no ARC.
4187 if (Args.hasArg(Ids: options::OPT_fno_objc_arc)) {
4188 Args.ClaimAllArgs(Id0: options::OPT_fobjc_arc_exceptions);
4189 Args.ClaimAllArgs(Id0: options::OPT_fno_objc_arc_exceptions);
4190 }
4191
4192 // Allow the user to control whether messages can be converted to runtime
4193 // functions.
4194 if (types::isObjC(Id: Input.getType())) {
4195 auto *Arg = Args.getLastArg(
4196 Ids: options::OPT_fobjc_convert_messages_to_runtime_calls,
4197 Ids: options::OPT_fno_objc_convert_messages_to_runtime_calls);
4198 if (Arg &&
4199 Arg->getOption().matches(
4200 ID: options::OPT_fno_objc_convert_messages_to_runtime_calls))
4201 CmdArgs.push_back(Elt: "-fno-objc-convert-messages-to-runtime-calls");
4202 }
4203
4204 // -fobjc-infer-related-result-type is the default, except in the Objective-C
4205 // rewriter.
4206 if (InferCovariantReturns)
4207 CmdArgs.push_back(Elt: "-fno-objc-infer-related-result-type");
4208
4209 // Pass down -fobjc-weak or -fno-objc-weak if present.
4210 if (types::isObjC(Id: Input.getType())) {
4211 auto WeakArg =
4212 Args.getLastArg(Ids: options::OPT_fobjc_weak, Ids: options::OPT_fno_objc_weak);
4213 if (!WeakArg) {
4214 // nothing to do
4215 } else if (!Runtime.allowsWeak()) {
4216 if (WeakArg->getOption().matches(ID: options::OPT_fobjc_weak))
4217 D.Diag(DiagID: diag::err_objc_weak_unsupported);
4218 } else {
4219 WeakArg->render(Args, Output&: CmdArgs);
4220 }
4221 }
4222
4223 if (Args.hasArg(Ids: options::OPT_fobjc_disable_direct_methods_for_testing))
4224 CmdArgs.push_back(Elt: "-fobjc-disable-direct-methods-for-testing");
4225}
4226
4227static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
4228 ArgStringList &CmdArgs) {
4229 bool CaretDefault = true;
4230 bool ColumnDefault = true;
4231
4232 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_diagnostics_classic,
4233 Ids: options::OPT__SLASH_diagnostics_column,
4234 Ids: options::OPT__SLASH_diagnostics_caret)) {
4235 switch (A->getOption().getID()) {
4236 case options::OPT__SLASH_diagnostics_caret:
4237 CaretDefault = true;
4238 ColumnDefault = true;
4239 break;
4240 case options::OPT__SLASH_diagnostics_column:
4241 CaretDefault = false;
4242 ColumnDefault = true;
4243 break;
4244 case options::OPT__SLASH_diagnostics_classic:
4245 CaretDefault = false;
4246 ColumnDefault = false;
4247 break;
4248 }
4249 }
4250
4251 // -fcaret-diagnostics is default.
4252 if (!Args.hasFlag(Pos: options::OPT_fcaret_diagnostics,
4253 Neg: options::OPT_fno_caret_diagnostics, Default: CaretDefault))
4254 CmdArgs.push_back(Elt: "-fno-caret-diagnostics");
4255
4256 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_fixit_info,
4257 Neg: options::OPT_fno_diagnostics_fixit_info);
4258 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_option,
4259 Neg: options::OPT_fno_diagnostics_show_option);
4260
4261 if (const Arg *A =
4262 Args.getLastArg(Ids: options::OPT_fdiagnostics_show_category_EQ)) {
4263 CmdArgs.push_back(Elt: "-fdiagnostics-show-category");
4264 CmdArgs.push_back(Elt: A->getValue());
4265 }
4266
4267 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_hotness,
4268 Neg: options::OPT_fno_diagnostics_show_hotness);
4269
4270 if (const Arg *A =
4271 Args.getLastArg(Ids: options::OPT_fdiagnostics_hotness_threshold_EQ)) {
4272 std::string Opt =
4273 std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
4274 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
4275 }
4276
4277 if (const Arg *A =
4278 Args.getLastArg(Ids: options::OPT_fdiagnostics_misexpect_tolerance_EQ)) {
4279 std::string Opt =
4280 std::string("-fdiagnostics-misexpect-tolerance=") + A->getValue();
4281 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Opt));
4282 }
4283
4284 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fdiagnostics_format_EQ)) {
4285 CmdArgs.push_back(Elt: "-fdiagnostics-format");
4286 CmdArgs.push_back(Elt: A->getValue());
4287 if (StringRef(A->getValue()) == "sarif" ||
4288 StringRef(A->getValue()) == "SARIF")
4289 D.Diag(DiagID: diag::warn_drv_sarif_format_unstable);
4290 }
4291
4292 if (const Arg *A = Args.getLastArg(
4293 Ids: options::OPT_fdiagnostics_show_note_include_stack,
4294 Ids: options::OPT_fno_diagnostics_show_note_include_stack)) {
4295 const Option &O = A->getOption();
4296 if (O.matches(ID: options::OPT_fdiagnostics_show_note_include_stack))
4297 CmdArgs.push_back(Elt: "-fdiagnostics-show-note-include-stack");
4298 else
4299 CmdArgs.push_back(Elt: "-fno-diagnostics-show-note-include-stack");
4300 }
4301
4302 handleColorDiagnosticsArgs(D, Args, CmdArgs);
4303
4304 if (Args.hasArg(Ids: options::OPT_fansi_escape_codes))
4305 CmdArgs.push_back(Elt: "-fansi-escape-codes");
4306
4307 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fshow_source_location,
4308 Neg: options::OPT_fno_show_source_location);
4309
4310 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdiagnostics_show_line_numbers,
4311 Neg: options::OPT_fno_diagnostics_show_line_numbers);
4312
4313 if (Args.hasArg(Ids: options::OPT_fdiagnostics_absolute_paths))
4314 CmdArgs.push_back(Elt: "-fdiagnostics-absolute-paths");
4315
4316 if (!Args.hasFlag(Pos: options::OPT_fshow_column, Neg: options::OPT_fno_show_column,
4317 Default: ColumnDefault))
4318 CmdArgs.push_back(Elt: "-fno-show-column");
4319
4320 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fspell_checking,
4321 Neg: options::OPT_fno_spell_checking);
4322
4323 Args.addLastArg(Output&: CmdArgs, Ids: options::OPT_warning_suppression_mappings_EQ);
4324}
4325
4326static void renderDwarfFormat(const Driver &D, const llvm::Triple &T,
4327 const ArgList &Args, ArgStringList &CmdArgs,
4328 unsigned DwarfVersion) {
4329 auto *DwarfFormatArg =
4330 Args.getLastArg(Ids: options::OPT_gdwarf64, Ids: options::OPT_gdwarf32);
4331 if (!DwarfFormatArg)
4332 return;
4333
4334 if (DwarfFormatArg->getOption().matches(ID: options::OPT_gdwarf64)) {
4335 if (DwarfVersion < 3)
4336 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4337 << DwarfFormatArg->getAsString(Args) << "DWARFv3 or greater";
4338 else if (!T.isArch64Bit())
4339 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4340 << DwarfFormatArg->getAsString(Args) << "64 bit architecture";
4341 else if (!T.isOSBinFormatELF())
4342 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4343 << DwarfFormatArg->getAsString(Args) << "ELF platforms";
4344 }
4345
4346 DwarfFormatArg->render(Args, Output&: CmdArgs);
4347}
4348
4349static void
4350renderDebugOptions(const ToolChain &TC, const Driver &D, const llvm::Triple &T,
4351 const ArgList &Args, types::ID InputType,
4352 ArgStringList &CmdArgs, const InputInfo &Output,
4353 llvm::codegenoptions::DebugInfoKind &DebugInfoKind,
4354 DwarfFissionKind &DwarfFission) {
4355 bool IRInput = isLLVMIR(Id: InputType);
4356 bool PlainCOrCXX = isDerivedFromC(Id: InputType) && !isCuda(Id: InputType) &&
4357 !isHIP(Id: InputType) && !isObjC(Id: InputType) &&
4358 !isOpenCL(Id: InputType);
4359
4360 if (Args.hasFlag(Pos: options::OPT_fdebug_info_for_profiling,
4361 Neg: options::OPT_fno_debug_info_for_profiling, Default: false) &&
4362 checkDebugInfoOption(
4363 A: Args.getLastArg(Ids: options::OPT_fdebug_info_for_profiling), Args, D, TC))
4364 CmdArgs.push_back(Elt: "-fdebug-info-for-profiling");
4365
4366 // The 'g' groups options involve a somewhat intricate sequence of decisions
4367 // about what to pass from the driver to the frontend, but by the time they
4368 // reach cc1 they've been factored into three well-defined orthogonal choices:
4369 // * what level of debug info to generate
4370 // * what dwarf version to write
4371 // * what debugger tuning to use
4372 // This avoids having to monkey around further in cc1 other than to disable
4373 // codeview if not running in a Windows environment. Perhaps even that
4374 // decision should be made in the driver as well though.
4375 llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
4376
4377 bool SplitDWARFInlining =
4378 Args.hasFlag(Pos: options::OPT_fsplit_dwarf_inlining,
4379 Neg: options::OPT_fno_split_dwarf_inlining, Default: false);
4380
4381 // Normally -gsplit-dwarf is only useful with -gN. For IR input, Clang does
4382 // object file generation and no IR generation, -gN should not be needed. So
4383 // allow -gsplit-dwarf with either -gN or IR input.
4384 if (IRInput || Args.hasArg(Ids: options::OPT_g_Group)) {
4385 // FIXME: -gsplit-dwarf on AIX is currently unimplemented.
4386 if (TC.getTriple().isOSAIX() && Args.hasArg(Ids: options::OPT_gsplit_dwarf)) {
4387 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
4388 << Args.getLastArg(Ids: options::OPT_gsplit_dwarf)->getSpelling()
4389 << TC.getTriple().str();
4390 return;
4391 }
4392 Arg *SplitDWARFArg;
4393 DwarfFission = getDebugFissionKind(D, Args, Arg&: SplitDWARFArg);
4394 if (DwarfFission != DwarfFissionKind::None &&
4395 !checkDebugInfoOption(A: SplitDWARFArg, Args, D, TC)) {
4396 DwarfFission = DwarfFissionKind::None;
4397 SplitDWARFInlining = false;
4398 }
4399 }
4400 if (const Arg *A = Args.getLastArg(Ids: options::OPT_g_Group)) {
4401 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4402
4403 // If the last option explicitly specified a debug-info level, use it.
4404 if (checkDebugInfoOption(A, Args, D, TC) &&
4405 A->getOption().matches(ID: options::OPT_gN_Group)) {
4406 DebugInfoKind = debugLevelToInfoKind(A: *A);
4407 // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
4408 // complicated if you've disabled inline info in the skeleton CUs
4409 // (SplitDWARFInlining) - then there's value in composing split-dwarf and
4410 // line-tables-only, so let those compose naturally in that case.
4411 if (DebugInfoKind == llvm::codegenoptions::NoDebugInfo ||
4412 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly ||
4413 (DebugInfoKind == llvm::codegenoptions::DebugLineTablesOnly &&
4414 SplitDWARFInlining))
4415 DwarfFission = DwarfFissionKind::None;
4416 }
4417 }
4418
4419 // If a debugger tuning argument appeared, remember it.
4420 bool HasDebuggerTuning = false;
4421 if (const Arg *A =
4422 Args.getLastArg(Ids: options::OPT_gTune_Group, Ids: options::OPT_ggdbN_Group)) {
4423 HasDebuggerTuning = true;
4424 if (checkDebugInfoOption(A, Args, D, TC)) {
4425 if (A->getOption().matches(ID: options::OPT_glldb))
4426 DebuggerTuning = llvm::DebuggerKind::LLDB;
4427 else if (A->getOption().matches(ID: options::OPT_gsce))
4428 DebuggerTuning = llvm::DebuggerKind::SCE;
4429 else if (A->getOption().matches(ID: options::OPT_gdbx))
4430 DebuggerTuning = llvm::DebuggerKind::DBX;
4431 else
4432 DebuggerTuning = llvm::DebuggerKind::GDB;
4433 }
4434 }
4435
4436 // If a -gdwarf argument appeared, remember it.
4437 bool EmitDwarf = false;
4438 if (const Arg *A = getDwarfNArg(Args))
4439 EmitDwarf = checkDebugInfoOption(A, Args, D, TC);
4440
4441 bool EmitCodeView = false;
4442 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcodeview))
4443 EmitCodeView = checkDebugInfoOption(A, Args, D, TC);
4444
4445 // If the user asked for debug info but did not explicitly specify -gcodeview
4446 // or -gdwarf, ask the toolchain for the default format.
4447 if (!EmitCodeView && !EmitDwarf &&
4448 DebugInfoKind != llvm::codegenoptions::NoDebugInfo) {
4449 switch (TC.getDefaultDebugFormat()) {
4450 case llvm::codegenoptions::DIF_CodeView:
4451 EmitCodeView = true;
4452 break;
4453 case llvm::codegenoptions::DIF_DWARF:
4454 EmitDwarf = true;
4455 break;
4456 }
4457 }
4458
4459 unsigned RequestedDWARFVersion = 0; // DWARF version requested by the user
4460 unsigned EffectiveDWARFVersion = 0; // DWARF version TC can generate. It may
4461 // be lower than what the user wanted.
4462 if (EmitDwarf) {
4463 RequestedDWARFVersion = getDwarfVersion(TC, Args);
4464 // Clamp effective DWARF version to the max supported by the toolchain.
4465 EffectiveDWARFVersion =
4466 std::min(a: RequestedDWARFVersion, b: TC.getMaxDwarfVersion());
4467 } else {
4468 Args.ClaimAllArgs(Id0: options::OPT_fdebug_default_version);
4469 }
4470
4471 // -gline-directives-only supported only for the DWARF debug info.
4472 if (RequestedDWARFVersion == 0 &&
4473 DebugInfoKind == llvm::codegenoptions::DebugDirectivesOnly)
4474 DebugInfoKind = llvm::codegenoptions::NoDebugInfo;
4475
4476 // strict DWARF is set to false by default. But for DBX, we need it to be set
4477 // as true by default.
4478 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gstrict_dwarf))
4479 (void)checkDebugInfoOption(A, Args, D, TC);
4480 if (Args.hasFlag(Pos: options::OPT_gstrict_dwarf, Neg: options::OPT_gno_strict_dwarf,
4481 Default: DebuggerTuning == llvm::DebuggerKind::DBX))
4482 CmdArgs.push_back(Elt: "-gstrict-dwarf");
4483
4484 // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
4485 Args.ClaimAllArgs(Id0: options::OPT_g_flags_Group);
4486
4487 // Column info is included by default for everything except SCE and
4488 // CodeView if not use sampling PGO. Clang doesn't track end columns, just
4489 // starting columns, which, in theory, is fine for CodeView (and PDB). In
4490 // practice, however, the Microsoft debuggers don't handle missing end columns
4491 // well, and the AIX debugger DBX also doesn't handle the columns well, so
4492 // it's better not to include any column info.
4493 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcolumn_info))
4494 (void)checkDebugInfoOption(A, Args, D, TC);
4495 if (!Args.hasFlag(Pos: options::OPT_gcolumn_info, Neg: options::OPT_gno_column_info,
4496 Default: !(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
4497 (DebuggerTuning != llvm::DebuggerKind::SCE &&
4498 DebuggerTuning != llvm::DebuggerKind::DBX)))
4499 CmdArgs.push_back(Elt: "-gno-column-info");
4500
4501 if (!Args.hasFlag(Pos: options::OPT_gcall_site_info,
4502 Neg: options::OPT_gno_call_site_info, Default: true))
4503 CmdArgs.push_back(Elt: "-gno-call-site-info");
4504
4505 // FIXME: Move backend command line options to the module.
4506 if (Args.hasFlag(Pos: options::OPT_gmodules, Neg: options::OPT_gno_modules, Default: false)) {
4507 // If -gline-tables-only or -gline-directives-only is the last option it
4508 // wins.
4509 if (checkDebugInfoOption(A: Args.getLastArg(Ids: options::OPT_gmodules), Args, D,
4510 TC)) {
4511 if (DebugInfoKind != llvm::codegenoptions::DebugLineTablesOnly &&
4512 DebugInfoKind != llvm::codegenoptions::DebugDirectivesOnly) {
4513 DebugInfoKind = llvm::codegenoptions::DebugInfoConstructor;
4514 CmdArgs.push_back(Elt: "-dwarf-ext-refs");
4515 CmdArgs.push_back(Elt: "-fmodule-format=obj");
4516 }
4517 }
4518 }
4519
4520 if (T.isOSBinFormatELF() && SplitDWARFInlining)
4521 CmdArgs.push_back(Elt: "-fsplit-dwarf-inlining");
4522
4523 // After we've dealt with all combinations of things that could
4524 // make DebugInfoKind be other than None or DebugLineTablesOnly,
4525 // figure out if we need to "upgrade" it to standalone debug info.
4526 // We parse these two '-f' options whether or not they will be used,
4527 // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
4528 bool NeedFullDebug = Args.hasFlag(
4529 Pos: options::OPT_fstandalone_debug, Neg: options::OPT_fno_standalone_debug,
4530 Default: DebuggerTuning == llvm::DebuggerKind::LLDB ||
4531 TC.GetDefaultStandaloneDebug());
4532 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fstandalone_debug))
4533 (void)checkDebugInfoOption(A, Args, D, TC);
4534
4535 if (DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo ||
4536 DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor) {
4537 if (Args.hasFlag(Pos: options::OPT_fno_eliminate_unused_debug_types,
4538 Neg: options::OPT_feliminate_unused_debug_types, Default: false))
4539 DebugInfoKind = llvm::codegenoptions::UnusedTypeInfo;
4540 else if (NeedFullDebug)
4541 DebugInfoKind = llvm::codegenoptions::FullDebugInfo;
4542 }
4543
4544 if (Args.hasFlag(Pos: options::OPT_gembed_source, Neg: options::OPT_gno_embed_source,
4545 Default: false)) {
4546 // Source embedding is a vendor extension to DWARF v5. By now we have
4547 // checked if a DWARF version was stated explicitly, and have otherwise
4548 // fallen back to the target default, so if this is still not at least 5
4549 // we emit an error.
4550 const Arg *A = Args.getLastArg(Ids: options::OPT_gembed_source);
4551 if (RequestedDWARFVersion < 5)
4552 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
4553 << A->getAsString(Args) << "-gdwarf-5";
4554 else if (EffectiveDWARFVersion < 5)
4555 // The toolchain has reduced allowed dwarf version, so we can't enable
4556 // -gembed-source.
4557 D.Diag(DiagID: diag::warn_drv_dwarf_version_limited_by_target)
4558 << A->getAsString(Args) << TC.getTripleString() << 5
4559 << EffectiveDWARFVersion;
4560 else if (checkDebugInfoOption(A, Args, D, TC))
4561 CmdArgs.push_back(Elt: "-gembed-source");
4562 }
4563
4564 // Enable Key Instructions by default if we're emitting DWARF, the language is
4565 // plain C or C++, and optimisations are enabled.
4566 Arg *OptLevel = Args.getLastArg(Ids: options::OPT_O_Group);
4567 bool KeyInstructionsOnByDefault =
4568 EmitDwarf && PlainCOrCXX && OptLevel &&
4569 !OptLevel->getOption().matches(ID: options::OPT_O0);
4570 if (Args.hasFlag(Pos: options::OPT_gkey_instructions,
4571 Neg: options::OPT_gno_key_instructions,
4572 Default: KeyInstructionsOnByDefault))
4573 CmdArgs.push_back(Elt: "-gkey-instructions");
4574
4575 if (!Args.hasFlag(Pos: options::OPT_gstructor_decl_linkage_names,
4576 Neg: options::OPT_gno_structor_decl_linkage_names, Default: true))
4577 CmdArgs.push_back(Elt: "-gno-structor-decl-linkage-names");
4578
4579 if (EmitCodeView) {
4580 CmdArgs.push_back(Elt: "-gcodeview");
4581
4582 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_gcodeview_ghash,
4583 Neg: options::OPT_gno_codeview_ghash);
4584
4585 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_gcodeview_command_line,
4586 Neg: options::OPT_gno_codeview_command_line);
4587 }
4588
4589 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_ginline_line_tables,
4590 Neg: options::OPT_gno_inline_line_tables);
4591
4592 // When emitting remarks, we need at least debug lines in the output.
4593 if (willEmitRemarks(Args) &&
4594 DebugInfoKind <= llvm::codegenoptions::DebugDirectivesOnly)
4595 DebugInfoKind = llvm::codegenoptions::DebugLineTablesOnly;
4596
4597 // Adjust the debug info kind for the given toolchain.
4598 TC.adjustDebugInfoKind(DebugInfoKind, Args);
4599
4600 // On AIX, the debugger tuning option can be omitted if it is not explicitly
4601 // set.
4602 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion: EffectiveDWARFVersion,
4603 DebuggerTuning: T.isOSAIX() && !HasDebuggerTuning
4604 ? llvm::DebuggerKind::Default
4605 : DebuggerTuning);
4606
4607 // -fdebug-macro turns on macro debug info generation.
4608 if (Args.hasFlag(Pos: options::OPT_fdebug_macro, Neg: options::OPT_fno_debug_macro,
4609 Default: false))
4610 if (checkDebugInfoOption(A: Args.getLastArg(Ids: options::OPT_fdebug_macro), Args,
4611 D, TC))
4612 CmdArgs.push_back(Elt: "-debug-info-macro");
4613
4614 // -ggnu-pubnames turns on gnu style pubnames in the backend.
4615 const auto *PubnamesArg =
4616 Args.getLastArg(Ids: options::OPT_ggnu_pubnames, Ids: options::OPT_gno_gnu_pubnames,
4617 Ids: options::OPT_gpubnames, Ids: options::OPT_gno_pubnames);
4618 if (DwarfFission != DwarfFissionKind::None ||
4619 (PubnamesArg && checkDebugInfoOption(A: PubnamesArg, Args, D, TC))) {
4620 const bool OptionSet =
4621 (PubnamesArg &&
4622 (PubnamesArg->getOption().matches(ID: options::OPT_gpubnames) ||
4623 PubnamesArg->getOption().matches(ID: options::OPT_ggnu_pubnames)));
4624 if ((DebuggerTuning != llvm::DebuggerKind::LLDB || OptionSet) &&
4625 (!PubnamesArg ||
4626 (!PubnamesArg->getOption().matches(ID: options::OPT_gno_gnu_pubnames) &&
4627 !PubnamesArg->getOption().matches(ID: options::OPT_gno_pubnames))))
4628 CmdArgs.push_back(Elt: PubnamesArg && PubnamesArg->getOption().matches(
4629 ID: options::OPT_gpubnames)
4630 ? "-gpubnames"
4631 : "-ggnu-pubnames");
4632 }
4633 const auto *SimpleTemplateNamesArg =
4634 Args.getLastArg(Ids: options::OPT_gsimple_template_names,
4635 Ids: options::OPT_gno_simple_template_names);
4636 bool ForwardTemplateParams = DebuggerTuning == llvm::DebuggerKind::SCE;
4637 if (SimpleTemplateNamesArg &&
4638 checkDebugInfoOption(A: SimpleTemplateNamesArg, Args, D, TC)) {
4639 const auto &Opt = SimpleTemplateNamesArg->getOption();
4640 if (Opt.matches(ID: options::OPT_gsimple_template_names)) {
4641 ForwardTemplateParams = true;
4642 CmdArgs.push_back(Elt: "-gsimple-template-names=simple");
4643 }
4644 }
4645
4646 // Emit DW_TAG_template_alias for template aliases? True by default for SCE.
4647 bool UseDebugTemplateAlias =
4648 DebuggerTuning == llvm::DebuggerKind::SCE && RequestedDWARFVersion >= 4;
4649 if (const auto *DebugTemplateAlias = Args.getLastArg(
4650 Ids: options::OPT_gtemplate_alias, Ids: options::OPT_gno_template_alias)) {
4651 // DW_TAG_template_alias is only supported from DWARFv5 but if a user
4652 // asks for it we should let them have it (if the target supports it).
4653 if (checkDebugInfoOption(A: DebugTemplateAlias, Args, D, TC)) {
4654 const auto &Opt = DebugTemplateAlias->getOption();
4655 UseDebugTemplateAlias = Opt.matches(ID: options::OPT_gtemplate_alias);
4656 }
4657 }
4658 if (UseDebugTemplateAlias)
4659 CmdArgs.push_back(Elt: "-gtemplate-alias");
4660
4661 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gsrc_hash_EQ)) {
4662 StringRef v = A->getValue();
4663 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-gsrc-hash=" + v));
4664 }
4665
4666 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdebug_ranges_base_address,
4667 Neg: options::OPT_fno_debug_ranges_base_address);
4668
4669 // -gdwarf-aranges turns on the emission of the aranges section in the
4670 // backend.
4671 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gdwarf_aranges);
4672 A && checkDebugInfoOption(A, Args, D, TC)) {
4673 CmdArgs.push_back(Elt: "-mllvm");
4674 CmdArgs.push_back(Elt: "-generate-arange-section");
4675 }
4676
4677 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fforce_dwarf_frame,
4678 Neg: options::OPT_fno_force_dwarf_frame);
4679
4680 bool EnableTypeUnits = false;
4681 if (Args.hasFlag(Pos: options::OPT_fdebug_types_section,
4682 Neg: options::OPT_fno_debug_types_section, Default: false)) {
4683 if (!(T.isOSBinFormatELF() || T.isOSBinFormatWasm())) {
4684 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
4685 << Args.getLastArg(Ids: options::OPT_fdebug_types_section)
4686 ->getAsString(Args)
4687 << T.getTriple();
4688 } else if (checkDebugInfoOption(
4689 A: Args.getLastArg(Ids: options::OPT_fdebug_types_section), Args, D,
4690 TC)) {
4691 EnableTypeUnits = true;
4692 CmdArgs.push_back(Elt: "-mllvm");
4693 CmdArgs.push_back(Elt: "-generate-type-units");
4694 }
4695 }
4696
4697 if (const Arg *A =
4698 Args.getLastArg(Ids: options::OPT_gomit_unreferenced_methods,
4699 Ids: options::OPT_gno_omit_unreferenced_methods))
4700 (void)checkDebugInfoOption(A, Args, D, TC);
4701 if (Args.hasFlag(Pos: options::OPT_gomit_unreferenced_methods,
4702 Neg: options::OPT_gno_omit_unreferenced_methods, Default: false) &&
4703 (DebugInfoKind == llvm::codegenoptions::DebugInfoConstructor ||
4704 DebugInfoKind == llvm::codegenoptions::LimitedDebugInfo) &&
4705 !EnableTypeUnits) {
4706 CmdArgs.push_back(Elt: "-gomit-unreferenced-methods");
4707 }
4708
4709 // To avoid join/split of directory+filename, the integrated assembler prefers
4710 // the directory form of .file on all DWARF versions. GNU as doesn't allow the
4711 // form before DWARF v5.
4712 if (!Args.hasFlag(Pos: options::OPT_fdwarf_directory_asm,
4713 Neg: options::OPT_fno_dwarf_directory_asm,
4714 Default: TC.useIntegratedAs() || EffectiveDWARFVersion >= 5))
4715 CmdArgs.push_back(Elt: "-fno-dwarf-directory-asm");
4716
4717 // Decide how to render forward declarations of template instantiations.
4718 // SCE wants full descriptions, others just get them in the name.
4719 if (ForwardTemplateParams)
4720 CmdArgs.push_back(Elt: "-debug-forward-template-params");
4721
4722 // Do we need to explicitly import anonymous namespaces into the parent
4723 // scope?
4724 if (DebuggerTuning == llvm::DebuggerKind::SCE)
4725 CmdArgs.push_back(Elt: "-dwarf-explicit-import");
4726
4727 renderDwarfFormat(D, T, Args, CmdArgs, DwarfVersion: EffectiveDWARFVersion);
4728 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
4729
4730 // This controls whether or not we perform JustMyCode instrumentation.
4731 if (Args.hasFlag(Pos: options::OPT_fjmc, Neg: options::OPT_fno_jmc, Default: false)) {
4732 if (TC.getTriple().isOSBinFormatELF() ||
4733 TC.getTriple().isWindowsMSVCEnvironment()) {
4734 if (DebugInfoKind >= llvm::codegenoptions::DebugInfoConstructor)
4735 CmdArgs.push_back(Elt: "-fjmc");
4736 else if (D.IsCLMode())
4737 D.Diag(DiagID: clang::diag::warn_drv_jmc_requires_debuginfo) << "/JMC"
4738 << "'/Zi', '/Z7'";
4739 else
4740 D.Diag(DiagID: clang::diag::warn_drv_jmc_requires_debuginfo) << "-fjmc"
4741 << "-g";
4742 } else {
4743 D.Diag(DiagID: clang::diag::warn_drv_fjmc_for_elf_only);
4744 }
4745 }
4746
4747 // Add in -fdebug-compilation-dir if necessary.
4748 const char *DebugCompilationDir =
4749 addDebugCompDirArg(Args, CmdArgs, VFS: D.getVFS());
4750
4751 addDebugPrefixMapArg(D, TC, Args, CmdArgs);
4752
4753 // Add the output path to the object file for CodeView debug infos.
4754 if (EmitCodeView && Output.isFilename())
4755 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
4756 OutputFileName: Output.getFilename());
4757}
4758
4759static void ProcessVSRuntimeLibrary(const ToolChain &TC, const ArgList &Args,
4760 ArgStringList &CmdArgs) {
4761 unsigned RTOptionID = options::OPT__SLASH_MT;
4762
4763 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
4764 // The /LDd option implies /MTd. The dependent lib part can be overridden,
4765 // but defining _DEBUG is sticky.
4766 RTOptionID = options::OPT__SLASH_MTd;
4767
4768 if (Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_M_Group))
4769 RTOptionID = A->getOption().getID();
4770
4771 if (Arg *A = Args.getLastArg(Ids: options::OPT_fms_runtime_lib_EQ)) {
4772 RTOptionID = llvm::StringSwitch<unsigned>(A->getValue())
4773 .Case(S: "static", Value: options::OPT__SLASH_MT)
4774 .Case(S: "static_dbg", Value: options::OPT__SLASH_MTd)
4775 .Case(S: "dll", Value: options::OPT__SLASH_MD)
4776 .Case(S: "dll_dbg", Value: options::OPT__SLASH_MDd)
4777 .Default(Value: options::OPT__SLASH_MT);
4778 }
4779
4780 StringRef FlagForCRT;
4781 switch (RTOptionID) {
4782 case options::OPT__SLASH_MD:
4783 if (Args.hasArg(Ids: options::OPT__SLASH_LDd))
4784 CmdArgs.push_back(Elt: "-D_DEBUG");
4785 CmdArgs.push_back(Elt: "-D_MT");
4786 CmdArgs.push_back(Elt: "-D_DLL");
4787 FlagForCRT = "--dependent-lib=msvcrt";
4788 break;
4789 case options::OPT__SLASH_MDd:
4790 CmdArgs.push_back(Elt: "-D_DEBUG");
4791 CmdArgs.push_back(Elt: "-D_MT");
4792 CmdArgs.push_back(Elt: "-D_DLL");
4793 FlagForCRT = "--dependent-lib=msvcrtd";
4794 break;
4795 case options::OPT__SLASH_MT:
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: "-flto-visibility-public-std");
4800 FlagForCRT = "--dependent-lib=libcmt";
4801 break;
4802 case options::OPT__SLASH_MTd:
4803 CmdArgs.push_back(Elt: "-D_DEBUG");
4804 CmdArgs.push_back(Elt: "-D_MT");
4805 CmdArgs.push_back(Elt: "-flto-visibility-public-std");
4806 FlagForCRT = "--dependent-lib=libcmtd";
4807 break;
4808 default:
4809 llvm_unreachable("Unexpected option ID.");
4810 }
4811
4812 if (Args.hasArg(Ids: options::OPT_fms_omit_default_lib)) {
4813 CmdArgs.push_back(Elt: "-D_VC_NODEFAULTLIB");
4814 } else {
4815 CmdArgs.push_back(Elt: FlagForCRT.data());
4816
4817 // This provides POSIX compatibility (maps 'open' to '_open'), which most
4818 // users want. The /Za flag to cl.exe turns this off, but it's not
4819 // implemented in clang.
4820 CmdArgs.push_back(Elt: "--dependent-lib=oldnames");
4821 }
4822
4823 // All Arm64EC object files implicitly add softintrin.lib. This is necessary
4824 // even if the file doesn't actually refer to any of the routines because
4825 // the CRT itself has incomplete dependency markings.
4826 if (TC.getTriple().isWindowsArm64EC())
4827 CmdArgs.push_back(Elt: "--dependent-lib=softintrin");
4828}
4829
4830void Clang::ConstructJob(Compilation &C, const JobAction &JA,
4831 const InputInfo &Output, const InputInfoList &Inputs,
4832 const ArgList &Args, const char *LinkingOutput) const {
4833 const auto &TC = getToolChain();
4834 const llvm::Triple &RawTriple = TC.getTriple();
4835 const llvm::Triple &Triple = TC.getEffectiveTriple();
4836 const std::string &TripleStr = Triple.getTriple();
4837
4838 bool KernelOrKext =
4839 Args.hasArg(Ids: options::OPT_mkernel, Ids: options::OPT_fapple_kext);
4840 const Driver &D = TC.getDriver();
4841 ArgStringList CmdArgs;
4842
4843 assert(Inputs.size() >= 1 && "Must have at least one input.");
4844 // CUDA/HIP compilation may have multiple inputs (source file + results of
4845 // device-side compilations). OpenMP device jobs also take the host IR as a
4846 // second input. Module precompilation accepts a list of header files to
4847 // include as part of the module. API extraction accepts a list of header
4848 // files whose API information is emitted in the output. All other jobs are
4849 // expected to have exactly one input. SYCL compilation only expects a
4850 // single input.
4851 bool IsCuda = JA.isOffloading(OKind: Action::OFK_Cuda);
4852 bool IsCudaDevice = JA.isDeviceOffloading(OKind: Action::OFK_Cuda);
4853 bool IsHIP = JA.isOffloading(OKind: Action::OFK_HIP);
4854 bool IsHIPDevice = JA.isDeviceOffloading(OKind: Action::OFK_HIP);
4855 bool IsSYCL = JA.isOffloading(OKind: Action::OFK_SYCL);
4856 bool IsSYCLDevice = JA.isDeviceOffloading(OKind: Action::OFK_SYCL);
4857 bool IsOpenMPDevice = JA.isDeviceOffloading(OKind: Action::OFK_OpenMP);
4858 bool IsExtractAPI = isa<ExtractAPIJobAction>(Val: JA);
4859 bool IsDeviceOffloadAction = !(JA.isDeviceOffloading(OKind: Action::OFK_None) ||
4860 JA.isDeviceOffloading(OKind: Action::OFK_Host));
4861 bool IsHostOffloadingAction =
4862 JA.isHostOffloading(OKind: Action::OFK_OpenMP) ||
4863 JA.isHostOffloading(OKind: Action::OFK_SYCL) ||
4864 (JA.isHostOffloading(OKind: C.getActiveOffloadKinds()) &&
4865 Args.hasFlag(Pos: options::OPT_offload_new_driver,
4866 Neg: options::OPT_no_offload_new_driver,
4867 Default: C.isOffloadingHostKind(Kind: Action::OFK_Cuda)));
4868
4869 bool IsRDCMode =
4870 Args.hasFlag(Pos: options::OPT_fgpu_rdc, Neg: options::OPT_fno_gpu_rdc, Default: false);
4871
4872 auto LTOMode = IsDeviceOffloadAction ? D.getOffloadLTOMode() : D.getLTOMode();
4873 bool IsUsingLTO = LTOMode != LTOK_None;
4874
4875 // Extract API doesn't have a main input file, so invent a fake one as a
4876 // placeholder.
4877 InputInfo ExtractAPIPlaceholderInput(Inputs[0].getType(), "extract-api",
4878 "extract-api");
4879
4880 const InputInfo &Input =
4881 IsExtractAPI ? ExtractAPIPlaceholderInput : Inputs[0];
4882
4883 InputInfoList ExtractAPIInputs;
4884 InputInfoList HostOffloadingInputs;
4885 const InputInfo *CudaDeviceInput = nullptr;
4886 const InputInfo *OpenMPDeviceInput = nullptr;
4887 for (const InputInfo &I : Inputs) {
4888 if (&I == &Input || I.getType() == types::TY_Nothing) {
4889 // This is the primary input or contains nothing.
4890 } else if (IsExtractAPI) {
4891 auto ExpectedInputType = ExtractAPIPlaceholderInput.getType();
4892 if (I.getType() != ExpectedInputType) {
4893 D.Diag(DiagID: diag::err_drv_extract_api_wrong_kind)
4894 << I.getFilename() << types::getTypeName(Id: I.getType())
4895 << types::getTypeName(Id: ExpectedInputType);
4896 }
4897 ExtractAPIInputs.push_back(Elt: I);
4898 } else if (IsHostOffloadingAction) {
4899 HostOffloadingInputs.push_back(Elt: I);
4900 } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
4901 CudaDeviceInput = &I;
4902 } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
4903 OpenMPDeviceInput = &I;
4904 } else {
4905 llvm_unreachable("unexpectedly given multiple inputs");
4906 }
4907 }
4908
4909 const llvm::Triple *AuxTriple =
4910 (IsCuda || IsHIP) ? TC.getAuxTriple() : nullptr;
4911 bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
4912 bool IsUEFI = RawTriple.isUEFI();
4913 bool IsIAMCU = RawTriple.isOSIAMCU();
4914
4915 // Adjust IsWindowsXYZ for CUDA/HIP/SYCL compilations. Even when compiling in
4916 // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
4917 // Windows), we need to pass Windows-specific flags to cc1.
4918 if (IsCuda || IsHIP || IsSYCL)
4919 IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
4920
4921 // C++ is not supported for IAMCU.
4922 if (IsIAMCU && types::isCXX(Id: Input.getType()))
4923 D.Diag(DiagID: diag::err_drv_clang_unsupported) << "C++ for IAMCU";
4924
4925 // Invoke ourselves in -cc1 mode.
4926 //
4927 // FIXME: Implement custom jobs for internal actions.
4928 CmdArgs.push_back(Elt: "-cc1");
4929
4930 // Add the "effective" target triple.
4931 CmdArgs.push_back(Elt: "-triple");
4932 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TripleStr));
4933
4934 if (const Arg *MJ = Args.getLastArg(Ids: options::OPT_MJ)) {
4935 DumpCompilationDatabase(C, Filename: MJ->getValue(), Target: TripleStr, Output, Input, Args);
4936 Args.ClaimAllArgs(Id0: options::OPT_MJ);
4937 } else if (const Arg *GenCDBFragment =
4938 Args.getLastArg(Ids: options::OPT_gen_cdb_fragment_path)) {
4939 DumpCompilationDatabaseFragmentToDir(Dir: GenCDBFragment->getValue(), C,
4940 Target: TripleStr, Output, Input, Args);
4941 Args.ClaimAllArgs(Id0: options::OPT_gen_cdb_fragment_path);
4942 }
4943
4944 if (IsCuda || IsHIP) {
4945 // We have to pass the triple of the host if compiling for a CUDA/HIP device
4946 // and vice-versa.
4947 std::string NormalizedTriple;
4948 if (JA.isDeviceOffloading(OKind: Action::OFK_Cuda) ||
4949 JA.isDeviceOffloading(OKind: Action::OFK_HIP))
4950 NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
4951 ->getTriple()
4952 .normalize();
4953 else {
4954 // Host-side compilation.
4955 NormalizedTriple =
4956 (IsCuda ? C.getOffloadToolChains(Kind: Action::OFK_Cuda).first->second
4957 : C.getOffloadToolChains(Kind: Action::OFK_HIP).first->second)
4958 ->getTriple()
4959 .normalize();
4960 if (IsCuda) {
4961 // We need to figure out which CUDA version we're compiling for, as that
4962 // determines how we load and launch GPU kernels.
4963 auto *CTC = static_cast<const toolchains::CudaToolChain *>(
4964 C.getSingleOffloadToolChain<Action::OFK_Cuda>());
4965 assert(CTC && "Expected valid CUDA Toolchain.");
4966 if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
4967 CmdArgs.push_back(Elt: Args.MakeArgString(
4968 Str: Twine("-target-sdk-version=") +
4969 CudaVersionToString(V: CTC->CudaInstallation.version())));
4970 // Unsized function arguments used for variadics were introduced in
4971 // CUDA-9.0. We still do not support generating code that actually uses
4972 // variadic arguments yet, but we do need to allow parsing them as
4973 // recent CUDA headers rely on that.
4974 // https://github.com/llvm/llvm-project/issues/58410
4975 if (CTC->CudaInstallation.version() >= CudaVersion::CUDA_90)
4976 CmdArgs.push_back(Elt: "-fcuda-allow-variadic-functions");
4977 }
4978 }
4979 CmdArgs.push_back(Elt: "-aux-triple");
4980 CmdArgs.push_back(Elt: Args.MakeArgString(Str: NormalizedTriple));
4981
4982 if (JA.isDeviceOffloading(OKind: Action::OFK_HIP) &&
4983 (getToolChain().getTriple().isAMDGPU() ||
4984 (getToolChain().getTriple().isSPIRV() &&
4985 getToolChain().getTriple().getVendor() == llvm::Triple::AMD))) {
4986 // Device side compilation printf
4987 if (Args.getLastArg(Ids: options::OPT_mprintf_kind_EQ)) {
4988 CmdArgs.push_back(Elt: Args.MakeArgString(
4989 Str: "-mprintf-kind=" +
4990 Args.getLastArgValue(Id: options::OPT_mprintf_kind_EQ)));
4991 // Force compiler error on invalid conversion specifiers
4992 CmdArgs.push_back(
4993 Elt: Args.MakeArgString(Str: "-Werror=format-invalid-specifier"));
4994 }
4995 }
4996 }
4997
4998 // Optimization level for CodeGen.
4999 if (const Arg *A = Args.getLastArg(Ids: options::OPT_O_Group)) {
5000 if (A->getOption().matches(ID: options::OPT_O4)) {
5001 CmdArgs.push_back(Elt: "-O3");
5002 D.Diag(DiagID: diag::warn_O4_is_O3);
5003 } else {
5004 A->render(Args, Output&: CmdArgs);
5005 }
5006 }
5007
5008 // Unconditionally claim the printf option now to avoid unused diagnostic.
5009 if (const Arg *PF = Args.getLastArg(Ids: options::OPT_mprintf_kind_EQ))
5010 PF->claim();
5011
5012 if (IsSYCL) {
5013 if (IsSYCLDevice) {
5014 // Host triple is needed when doing SYCL device compilations.
5015 llvm::Triple AuxT = C.getDefaultToolChain().getTriple();
5016 std::string NormalizedTriple = AuxT.normalize();
5017 CmdArgs.push_back(Elt: "-aux-triple");
5018 CmdArgs.push_back(Elt: Args.MakeArgString(Str: NormalizedTriple));
5019
5020 // We want to compile sycl kernels.
5021 CmdArgs.push_back(Elt: "-fsycl-is-device");
5022
5023 // Set O2 optimization level by default
5024 if (!Args.getLastArg(Ids: options::OPT_O_Group))
5025 CmdArgs.push_back(Elt: "-O2");
5026 } else {
5027 // Add any options that are needed specific to SYCL offload while
5028 // performing the host side compilation.
5029
5030 // Let the front-end host compilation flow know about SYCL offload
5031 // compilation.
5032 CmdArgs.push_back(Elt: "-fsycl-is-host");
5033 }
5034
5035 // Set options for both host and device.
5036 Arg *SYCLStdArg = Args.getLastArg(Ids: options::OPT_sycl_std_EQ);
5037 if (SYCLStdArg) {
5038 SYCLStdArg->render(Args, Output&: CmdArgs);
5039 } else {
5040 // Ensure the default version in SYCL mode is 2020.
5041 CmdArgs.push_back(Elt: "-sycl-std=2020");
5042 }
5043 }
5044
5045 if (Args.hasArg(Ids: options::OPT_fclangir))
5046 CmdArgs.push_back(Elt: "-fclangir");
5047
5048 if (IsOpenMPDevice) {
5049 // We have to pass the triple of the host if compiling for an OpenMP device.
5050 std::string NormalizedTriple =
5051 C.getSingleOffloadToolChain<Action::OFK_Host>()
5052 ->getTriple()
5053 .normalize();
5054 CmdArgs.push_back(Elt: "-aux-triple");
5055 CmdArgs.push_back(Elt: Args.MakeArgString(Str: NormalizedTriple));
5056 }
5057
5058 if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
5059 Triple.getArch() == llvm::Triple::thumb)) {
5060 unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5061 unsigned Version = 0;
5062 bool Failure =
5063 Triple.getArchName().substr(Start: Offset).consumeInteger(Radix: 10, Result&: Version);
5064 if (Failure || Version < 7)
5065 D.Diag(DiagID: diag::err_target_unsupported_arch) << Triple.getArchName()
5066 << TripleStr;
5067 }
5068
5069 // Push all default warning arguments that are specific to
5070 // the given target. These come before user provided warning options
5071 // are provided.
5072 TC.addClangWarningOptions(CC1Args&: CmdArgs);
5073
5074 // FIXME: Subclass ToolChain for SPIR and move this to addClangWarningOptions.
5075 if (Triple.isSPIR() || Triple.isSPIRV())
5076 CmdArgs.push_back(Elt: "-Wspir-compat");
5077
5078 // Select the appropriate action.
5079 RewriteKind rewriteKind = RK_None;
5080
5081 bool UnifiedLTO = false;
5082 if (IsUsingLTO) {
5083 UnifiedLTO = Args.hasFlag(Pos: options::OPT_funified_lto,
5084 Neg: options::OPT_fno_unified_lto, Default: Triple.isPS());
5085 if (UnifiedLTO)
5086 CmdArgs.push_back(Elt: "-funified-lto");
5087 }
5088
5089 // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
5090 // it claims when not running an assembler. Otherwise, clang would emit
5091 // "argument unused" warnings for assembler flags when e.g. adding "-E" to
5092 // flags while debugging something. That'd be somewhat inconvenient, and it's
5093 // also inconsistent with most other flags -- we don't warn on
5094 // -ffunction-sections not being used in -E mode either for example, even
5095 // though it's not really used either.
5096 if (!isa<AssembleJobAction>(Val: JA)) {
5097 // The args claimed here should match the args used in
5098 // CollectArgsForIntegratedAssembler().
5099 if (TC.useIntegratedAs()) {
5100 Args.ClaimAllArgs(Id0: options::OPT_mrelax_all);
5101 Args.ClaimAllArgs(Id0: options::OPT_mno_relax_all);
5102 Args.ClaimAllArgs(Id0: options::OPT_mincremental_linker_compatible);
5103 Args.ClaimAllArgs(Id0: options::OPT_mno_incremental_linker_compatible);
5104 switch (C.getDefaultToolChain().getArch()) {
5105 case llvm::Triple::arm:
5106 case llvm::Triple::armeb:
5107 case llvm::Triple::thumb:
5108 case llvm::Triple::thumbeb:
5109 Args.ClaimAllArgs(Id0: options::OPT_mimplicit_it_EQ);
5110 break;
5111 default:
5112 break;
5113 }
5114 }
5115 Args.ClaimAllArgs(Id0: options::OPT_Wa_COMMA);
5116 Args.ClaimAllArgs(Id0: options::OPT_Xassembler);
5117 Args.ClaimAllArgs(Id0: options::OPT_femit_dwarf_unwind_EQ);
5118 }
5119
5120 bool IsAMDSPIRVForHIPDevice =
5121 IsHIPDevice && getToolChain().getTriple().isSPIRV() &&
5122 getToolChain().getTriple().getVendor() == llvm::Triple::AMD;
5123
5124 if (isa<AnalyzeJobAction>(Val: JA)) {
5125 assert(JA.getType() == types::TY_Plist && "Invalid output type.");
5126 CmdArgs.push_back(Elt: "-analyze");
5127 } else if (isa<PreprocessJobAction>(Val: JA)) {
5128 if (Output.getType() == types::TY_Dependencies)
5129 CmdArgs.push_back(Elt: "-Eonly");
5130 else {
5131 CmdArgs.push_back(Elt: "-E");
5132 if (Args.hasArg(Ids: options::OPT_rewrite_objc) &&
5133 !Args.hasArg(Ids: options::OPT_g_Group))
5134 CmdArgs.push_back(Elt: "-P");
5135 else if (JA.getType() == types::TY_PP_CXXHeaderUnit)
5136 CmdArgs.push_back(Elt: "-fdirectives-only");
5137 }
5138 } else if (isa<AssembleJobAction>(Val: JA)) {
5139 CmdArgs.push_back(Elt: "-emit-obj");
5140
5141 CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
5142
5143 // Also ignore explicit -force_cpusubtype_ALL option.
5144 (void)Args.hasArg(Ids: options::OPT_force__cpusubtype__ALL);
5145 } else if (isa<PrecompileJobAction>(Val: JA)) {
5146 if (JA.getType() == types::TY_Nothing)
5147 CmdArgs.push_back(Elt: "-fsyntax-only");
5148 else if (JA.getType() == types::TY_ModuleFile)
5149 CmdArgs.push_back(Elt: "-emit-module-interface");
5150 else if (JA.getType() == types::TY_HeaderUnit)
5151 CmdArgs.push_back(Elt: "-emit-header-unit");
5152 else if (!Args.hasArg(Ids: options::OPT_ignore_pch))
5153 CmdArgs.push_back(Elt: "-emit-pch");
5154 } else if (isa<VerifyPCHJobAction>(Val: JA)) {
5155 CmdArgs.push_back(Elt: "-verify-pch");
5156 } else if (isa<ExtractAPIJobAction>(Val: JA)) {
5157 assert(JA.getType() == types::TY_API_INFO &&
5158 "Extract API actions must generate a API information.");
5159 CmdArgs.push_back(Elt: "-extract-api");
5160
5161 if (Arg *PrettySGFArg = Args.getLastArg(Ids: options::OPT_emit_pretty_sgf))
5162 PrettySGFArg->render(Args, Output&: CmdArgs);
5163
5164 Arg *SymbolGraphDirArg = Args.getLastArg(Ids: options::OPT_symbol_graph_dir_EQ);
5165
5166 if (Arg *ProductNameArg = Args.getLastArg(Ids: options::OPT_product_name_EQ))
5167 ProductNameArg->render(Args, Output&: CmdArgs);
5168 if (Arg *ExtractAPIIgnoresFileArg =
5169 Args.getLastArg(Ids: options::OPT_extract_api_ignores_EQ))
5170 ExtractAPIIgnoresFileArg->render(Args, Output&: CmdArgs);
5171 if (Arg *EmitExtensionSymbolGraphs =
5172 Args.getLastArg(Ids: options::OPT_emit_extension_symbol_graphs)) {
5173 if (!SymbolGraphDirArg)
5174 D.Diag(DiagID: diag::err_drv_missing_symbol_graph_dir);
5175
5176 EmitExtensionSymbolGraphs->render(Args, Output&: CmdArgs);
5177 }
5178 if (SymbolGraphDirArg)
5179 SymbolGraphDirArg->render(Args, Output&: CmdArgs);
5180 } else {
5181 assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
5182 "Invalid action for clang tool.");
5183 if (JA.getType() == types::TY_Nothing) {
5184 CmdArgs.push_back(Elt: "-fsyntax-only");
5185 } else if (JA.getType() == types::TY_LLVM_IR ||
5186 JA.getType() == types::TY_LTO_IR) {
5187 CmdArgs.push_back(Elt: "-emit-llvm");
5188 } else if (JA.getType() == types::TY_LLVM_BC ||
5189 JA.getType() == types::TY_LTO_BC) {
5190 // Emit textual llvm IR for AMDGPU offloading for -emit-llvm -S
5191 if (Triple.isAMDGCN() && IsOpenMPDevice && Args.hasArg(Ids: options::OPT_S) &&
5192 Args.hasArg(Ids: options::OPT_emit_llvm)) {
5193 CmdArgs.push_back(Elt: "-emit-llvm");
5194 } else {
5195 CmdArgs.push_back(Elt: "-emit-llvm-bc");
5196 }
5197 } else if (JA.getType() == types::TY_IFS ||
5198 JA.getType() == types::TY_IFS_CPP) {
5199 StringRef ArgStr =
5200 Args.hasArg(Ids: options::OPT_interface_stub_version_EQ)
5201 ? Args.getLastArgValue(Id: options::OPT_interface_stub_version_EQ)
5202 : "ifs-v1";
5203 CmdArgs.push_back(Elt: "-emit-interface-stubs");
5204 CmdArgs.push_back(
5205 Elt: Args.MakeArgString(Str: Twine("-interface-stub-version=") + ArgStr.str()));
5206 } else if (JA.getType() == types::TY_PP_Asm) {
5207 CmdArgs.push_back(Elt: "-S");
5208 } else if (JA.getType() == types::TY_AST) {
5209 if (!Args.hasArg(Ids: options::OPT_ignore_pch))
5210 CmdArgs.push_back(Elt: "-emit-pch");
5211 } else if (JA.getType() == types::TY_ModuleFile) {
5212 CmdArgs.push_back(Elt: "-module-file-info");
5213 } else if (JA.getType() == types::TY_RewrittenObjC) {
5214 CmdArgs.push_back(Elt: "-rewrite-objc");
5215 rewriteKind = RK_NonFragile;
5216 } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
5217 CmdArgs.push_back(Elt: "-rewrite-objc");
5218 rewriteKind = RK_Fragile;
5219 } else if (JA.getType() == types::TY_CIR) {
5220 CmdArgs.push_back(Elt: "-emit-cir");
5221 } else if (JA.getType() == types::TY_Image && IsAMDSPIRVForHIPDevice) {
5222 CmdArgs.push_back(Elt: "-emit-obj");
5223 } else {
5224 assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
5225 }
5226
5227 // Preserve use-list order by default when emitting bitcode, so that
5228 // loading the bitcode up in 'opt' or 'llc' and running passes gives the
5229 // same result as running passes here. For LTO, we don't need to preserve
5230 // the use-list order, since serialization to bitcode is part of the flow.
5231 if (JA.getType() == types::TY_LLVM_BC)
5232 CmdArgs.push_back(Elt: "-emit-llvm-uselists");
5233
5234 if (IsUsingLTO) {
5235 if (IsDeviceOffloadAction && !JA.isDeviceOffloading(OKind: Action::OFK_OpenMP) &&
5236 !Args.hasFlag(Pos: options::OPT_offload_new_driver,
5237 Neg: options::OPT_no_offload_new_driver,
5238 Default: C.isOffloadingHostKind(Kind: Action::OFK_Cuda)) &&
5239 !Triple.isAMDGPU()) {
5240 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5241 << Args.getLastArg(Ids: options::OPT_foffload_lto,
5242 Ids: options::OPT_foffload_lto_EQ)
5243 ->getAsString(Args)
5244 << Triple.getTriple();
5245 } else if (Triple.isNVPTX() && !IsRDCMode &&
5246 JA.isDeviceOffloading(OKind: Action::OFK_Cuda)) {
5247 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_language_mode)
5248 << Args.getLastArg(Ids: options::OPT_foffload_lto,
5249 Ids: options::OPT_foffload_lto_EQ)
5250 ->getAsString(Args)
5251 << "-fno-gpu-rdc";
5252 } else {
5253 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
5254 CmdArgs.push_back(Elt: Args.MakeArgString(
5255 Str: Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
5256 // PS4 uses the legacy LTO API, which does not support some of the
5257 // features enabled by -flto-unit.
5258 if (!RawTriple.isPS4() ||
5259 (D.getLTOMode() == LTOK_Full) || !UnifiedLTO)
5260 CmdArgs.push_back(Elt: "-flto-unit");
5261 }
5262 }
5263 }
5264
5265 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dumpdir);
5266
5267 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fthinlto_index_EQ)) {
5268 if (!types::isLLVMIR(Id: Input.getType()))
5269 D.Diag(DiagID: diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
5270 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fthinlto_index_EQ);
5271 }
5272
5273 if (Triple.isPPC())
5274 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mregnames,
5275 Neg: options::OPT_mno_regnames);
5276
5277 if (Args.getLastArg(Ids: options::OPT_fthin_link_bitcode_EQ))
5278 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fthin_link_bitcode_EQ);
5279
5280 if (Args.getLastArg(Ids: options::OPT_save_temps_EQ))
5281 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_save_temps_EQ);
5282
5283 auto *MemProfArg = Args.getLastArg(Ids: options::OPT_fmemory_profile,
5284 Ids: options::OPT_fmemory_profile_EQ,
5285 Ids: options::OPT_fno_memory_profile);
5286 if (MemProfArg &&
5287 !MemProfArg->getOption().matches(ID: options::OPT_fno_memory_profile))
5288 MemProfArg->render(Args, Output&: CmdArgs);
5289
5290 if (auto *MemProfUseArg =
5291 Args.getLastArg(Ids: options::OPT_fmemory_profile_use_EQ)) {
5292 if (MemProfArg)
5293 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
5294 << MemProfUseArg->getAsString(Args) << MemProfArg->getAsString(Args);
5295 if (auto *PGOInstrArg = Args.getLastArg(Ids: options::OPT_fprofile_generate,
5296 Ids: options::OPT_fprofile_generate_EQ))
5297 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
5298 << MemProfUseArg->getAsString(Args) << PGOInstrArg->getAsString(Args);
5299 MemProfUseArg->render(Args, Output&: CmdArgs);
5300 }
5301
5302 // Embed-bitcode option.
5303 // Only white-listed flags below are allowed to be embedded.
5304 if (C.getDriver().embedBitcodeInObject() && !IsUsingLTO &&
5305 (isa<BackendJobAction>(Val: JA) || isa<AssembleJobAction>(Val: JA))) {
5306 // Add flags implied by -fembed-bitcode.
5307 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fembed_bitcode_EQ);
5308 // Disable all llvm IR level optimizations.
5309 CmdArgs.push_back(Elt: "-disable-llvm-passes");
5310
5311 // Render target options.
5312 TC.addClangTargetOptions(DriverArgs: Args, CC1Args&: CmdArgs, DeviceOffloadKind: JA.getOffloadingDeviceKind());
5313
5314 // reject options that shouldn't be supported in bitcode
5315 // also reject kernel/kext
5316 static const constexpr unsigned kBitcodeOptionIgnorelist[] = {
5317 options::OPT_mkernel,
5318 options::OPT_fapple_kext,
5319 options::OPT_ffunction_sections,
5320 options::OPT_fno_function_sections,
5321 options::OPT_fdata_sections,
5322 options::OPT_fno_data_sections,
5323 options::OPT_fbasic_block_sections_EQ,
5324 options::OPT_funique_internal_linkage_names,
5325 options::OPT_fno_unique_internal_linkage_names,
5326 options::OPT_funique_section_names,
5327 options::OPT_fno_unique_section_names,
5328 options::OPT_funique_basic_block_section_names,
5329 options::OPT_fno_unique_basic_block_section_names,
5330 options::OPT_mrestrict_it,
5331 options::OPT_mno_restrict_it,
5332 options::OPT_mstackrealign,
5333 options::OPT_mno_stackrealign,
5334 options::OPT_mstack_alignment,
5335 options::OPT_mcmodel_EQ,
5336 options::OPT_mlong_calls,
5337 options::OPT_mno_long_calls,
5338 options::OPT_ggnu_pubnames,
5339 options::OPT_gdwarf_aranges,
5340 options::OPT_fdebug_types_section,
5341 options::OPT_fno_debug_types_section,
5342 options::OPT_fdwarf_directory_asm,
5343 options::OPT_fno_dwarf_directory_asm,
5344 options::OPT_mrelax_all,
5345 options::OPT_mno_relax_all,
5346 options::OPT_ftrap_function_EQ,
5347 options::OPT_ffixed_r9,
5348 options::OPT_mfix_cortex_a53_835769,
5349 options::OPT_mno_fix_cortex_a53_835769,
5350 options::OPT_ffixed_x18,
5351 options::OPT_mglobal_merge,
5352 options::OPT_mno_global_merge,
5353 options::OPT_mred_zone,
5354 options::OPT_mno_red_zone,
5355 options::OPT_Wa_COMMA,
5356 options::OPT_Xassembler,
5357 options::OPT_mllvm,
5358 options::OPT_mmlir,
5359 };
5360 for (const auto &A : Args)
5361 if (llvm::is_contained(Range: kBitcodeOptionIgnorelist, Element: A->getOption().getID()))
5362 D.Diag(DiagID: diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
5363
5364 // Render the CodeGen options that need to be passed.
5365 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_foptimize_sibling_calls,
5366 Neg: options::OPT_fno_optimize_sibling_calls);
5367
5368 RenderFloatingPointOptions(TC, D, OFastEnabled: isOptimizationLevelFast(Args), Args,
5369 CmdArgs, JA);
5370
5371 // Render ABI arguments
5372 switch (TC.getArch()) {
5373 default: break;
5374 case llvm::Triple::arm:
5375 case llvm::Triple::armeb:
5376 case llvm::Triple::thumbeb:
5377 RenderARMABI(D, Triple, Args, CmdArgs);
5378 break;
5379 case llvm::Triple::aarch64:
5380 case llvm::Triple::aarch64_32:
5381 case llvm::Triple::aarch64_be:
5382 RenderAArch64ABI(Triple, Args, CmdArgs);
5383 break;
5384 }
5385
5386 // Input/Output file.
5387 if (Output.getType() == types::TY_Dependencies) {
5388 // Handled with other dependency code.
5389 } else if (Output.isFilename()) {
5390 CmdArgs.push_back(Elt: "-o");
5391 CmdArgs.push_back(Elt: Output.getFilename());
5392 } else {
5393 assert(Output.isNothing() && "Input output.");
5394 }
5395
5396 for (const auto &II : Inputs) {
5397 addDashXForInput(Args, Input: II, CmdArgs);
5398 if (II.isFilename())
5399 CmdArgs.push_back(Elt: II.getFilename());
5400 else
5401 II.getInputArg().renderAsInput(Args, Output&: CmdArgs);
5402 }
5403
5404 C.addCommand(C: std::make_unique<Command>(
5405 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args: D.getClangProgramPath(),
5406 args&: CmdArgs, args: Inputs, args: Output, args: D.getPrependArg()));
5407 return;
5408 }
5409
5410 if (C.getDriver().embedBitcodeMarkerOnly() && !IsUsingLTO)
5411 CmdArgs.push_back(Elt: "-fembed-bitcode=marker");
5412
5413 // We normally speed up the clang process a bit by skipping destructors at
5414 // exit, but when we're generating diagnostics we can rely on some of the
5415 // cleanup.
5416 if (!C.isForDiagnostics())
5417 CmdArgs.push_back(Elt: "-disable-free");
5418 CmdArgs.push_back(Elt: "-clear-ast-before-backend");
5419
5420#ifdef NDEBUG
5421 const bool IsAssertBuild = false;
5422#else
5423 const bool IsAssertBuild = true;
5424#endif
5425
5426 // Disable the verification pass in no-asserts builds unless otherwise
5427 // specified.
5428 if (Args.hasFlag(Pos: options::OPT_fno_verify_intermediate_code,
5429 Neg: options::OPT_fverify_intermediate_code, Default: !IsAssertBuild)) {
5430 CmdArgs.push_back(Elt: "-disable-llvm-verifier");
5431 }
5432
5433 // Discard value names in no-asserts builds unless otherwise specified.
5434 if (Args.hasFlag(Pos: options::OPT_fdiscard_value_names,
5435 Neg: options::OPT_fno_discard_value_names, Default: !IsAssertBuild)) {
5436 if (Args.hasArg(Ids: options::OPT_fdiscard_value_names) &&
5437 llvm::any_of(Range: Inputs, P: [](const clang::driver::InputInfo &II) {
5438 return types::isLLVMIR(Id: II.getType());
5439 })) {
5440 D.Diag(DiagID: diag::warn_ignoring_fdiscard_for_bitcode);
5441 }
5442 CmdArgs.push_back(Elt: "-discard-value-names");
5443 }
5444
5445 // Set the main file name, so that debug info works even with
5446 // -save-temps.
5447 CmdArgs.push_back(Elt: "-main-file-name");
5448 CmdArgs.push_back(Elt: getBaseInputName(Args, Input));
5449
5450 // Some flags which affect the language (via preprocessor
5451 // defines).
5452 if (Args.hasArg(Ids: options::OPT_static))
5453 CmdArgs.push_back(Elt: "-static-define");
5454
5455 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_static_libclosure);
5456
5457 if (Args.hasArg(Ids: options::OPT_municode))
5458 CmdArgs.push_back(Elt: "-DUNICODE");
5459
5460 if (isa<AnalyzeJobAction>(Val: JA))
5461 RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
5462
5463 if (isa<AnalyzeJobAction>(Val: JA) ||
5464 (isa<PreprocessJobAction>(Val: JA) && Args.hasArg(Ids: options::OPT__analyze)))
5465 CmdArgs.push_back(Elt: "-setup-static-analyzer");
5466
5467 // Enable compatilibily mode to avoid analyzer-config related errors.
5468 // Since we can't access frontend flags through hasArg, let's manually iterate
5469 // through them.
5470 bool FoundAnalyzerConfig = false;
5471 for (auto *Arg : Args.filtered(Ids: options::OPT_Xclang))
5472 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5473 FoundAnalyzerConfig = true;
5474 break;
5475 }
5476 if (!FoundAnalyzerConfig)
5477 for (auto *Arg : Args.filtered(Ids: options::OPT_Xanalyzer))
5478 if (StringRef(Arg->getValue()) == "-analyzer-config") {
5479 FoundAnalyzerConfig = true;
5480 break;
5481 }
5482 if (FoundAnalyzerConfig)
5483 CmdArgs.push_back(Elt: "-analyzer-config-compatibility-mode=true");
5484
5485 CheckCodeGenerationOptions(D, Args);
5486
5487 unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
5488 assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
5489 if (FunctionAlignment) {
5490 CmdArgs.push_back(Elt: "-function-alignment");
5491 CmdArgs.push_back(Elt: Args.MakeArgString(Str: std::to_string(val: FunctionAlignment)));
5492 }
5493
5494 // We support -falign-loops=N where N is a power of 2. GCC supports more
5495 // forms.
5496 if (const Arg *A = Args.getLastArg(Ids: options::OPT_falign_loops_EQ)) {
5497 unsigned Value = 0;
5498 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: Value) || Value > 65536)
5499 TC.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
5500 << A->getAsString(Args) << A->getValue();
5501 else if (Value & (Value - 1))
5502 TC.getDriver().Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
5503 << A->getAsString(Args) << A->getValue();
5504 // Treat =0 as unspecified (use the target preference).
5505 if (Value)
5506 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-falign-loops=" +
5507 Twine(std::min(a: Value, b: 65536u))));
5508 }
5509
5510 if (Triple.isOSzOS()) {
5511 // On z/OS some of the system header feature macros need to
5512 // be defined to enable most cross platform projects to build
5513 // successfully. Ths include the libc++ library. A
5514 // complicating factor is that users can define these
5515 // macros to the same or different values. We need to add
5516 // the definition for these macros to the compilation command
5517 // if the user hasn't already defined them.
5518
5519 auto findMacroDefinition = [&](const std::string &Macro) {
5520 auto MacroDefs = Args.getAllArgValues(Id: options::OPT_D);
5521 return llvm::any_of(Range&: MacroDefs, P: [&](const std::string &M) {
5522 return M == Macro || M.find(str: Macro + '=') != std::string::npos;
5523 });
5524 };
5525
5526 // _UNIX03_WITHDRAWN is required for libcxx & porting.
5527 if (!findMacroDefinition("_UNIX03_WITHDRAWN"))
5528 CmdArgs.push_back(Elt: "-D_UNIX03_WITHDRAWN");
5529 // _OPEN_DEFAULT is required for XL compat
5530 if (!findMacroDefinition("_OPEN_DEFAULT"))
5531 CmdArgs.push_back(Elt: "-D_OPEN_DEFAULT");
5532 if (D.CCCIsCXX() || types::isCXX(Id: Input.getType())) {
5533 // _XOPEN_SOURCE=600 is required for libcxx.
5534 if (!findMacroDefinition("_XOPEN_SOURCE"))
5535 CmdArgs.push_back(Elt: "-D_XOPEN_SOURCE=600");
5536 }
5537 }
5538
5539 llvm::Reloc::Model RelocationModel;
5540 unsigned PICLevel;
5541 bool IsPIE;
5542 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) = ParsePICArgs(ToolChain: TC, Args);
5543 Arg *LastPICDataRelArg =
5544 Args.getLastArg(Ids: options::OPT_mno_pic_data_is_text_relative,
5545 Ids: options::OPT_mpic_data_is_text_relative);
5546 bool NoPICDataIsTextRelative = false;
5547 if (LastPICDataRelArg) {
5548 if (LastPICDataRelArg->getOption().matches(
5549 ID: options::OPT_mno_pic_data_is_text_relative)) {
5550 NoPICDataIsTextRelative = true;
5551 if (!PICLevel)
5552 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
5553 << "-mno-pic-data-is-text-relative"
5554 << "-fpic/-fpie";
5555 }
5556 if (!Triple.isSystemZ())
5557 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5558 << (NoPICDataIsTextRelative ? "-mno-pic-data-is-text-relative"
5559 : "-mpic-data-is-text-relative")
5560 << RawTriple.str();
5561 }
5562
5563 bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
5564 RelocationModel == llvm::Reloc::ROPI_RWPI;
5565 bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
5566 RelocationModel == llvm::Reloc::ROPI_RWPI;
5567
5568 if (Args.hasArg(Ids: options::OPT_mcmse) &&
5569 !Args.hasArg(Ids: options::OPT_fallow_unsupported)) {
5570 if (IsROPI)
5571 D.Diag(DiagID: diag::err_cmse_pi_are_incompatible) << IsROPI;
5572 if (IsRWPI)
5573 D.Diag(DiagID: diag::err_cmse_pi_are_incompatible) << !IsRWPI;
5574 }
5575
5576 if (IsROPI && types::isCXX(Id: Input.getType()) &&
5577 !Args.hasArg(Ids: options::OPT_fallow_unsupported))
5578 D.Diag(DiagID: diag::err_drv_ropi_incompatible_with_cxx);
5579
5580 const char *RMName = RelocationModelName(Model: RelocationModel);
5581 if (RMName) {
5582 CmdArgs.push_back(Elt: "-mrelocation-model");
5583 CmdArgs.push_back(Elt: RMName);
5584 }
5585 if (PICLevel > 0) {
5586 CmdArgs.push_back(Elt: "-pic-level");
5587 CmdArgs.push_back(Elt: PICLevel == 1 ? "1" : "2");
5588 if (IsPIE)
5589 CmdArgs.push_back(Elt: "-pic-is-pie");
5590 if (NoPICDataIsTextRelative)
5591 CmdArgs.push_back(Elt: "-mcmodel=medium");
5592 }
5593
5594 if (RelocationModel == llvm::Reloc::ROPI ||
5595 RelocationModel == llvm::Reloc::ROPI_RWPI)
5596 CmdArgs.push_back(Elt: "-fropi");
5597 if (RelocationModel == llvm::Reloc::RWPI ||
5598 RelocationModel == llvm::Reloc::ROPI_RWPI)
5599 CmdArgs.push_back(Elt: "-frwpi");
5600
5601 if (Arg *A = Args.getLastArg(Ids: options::OPT_meabi)) {
5602 CmdArgs.push_back(Elt: "-meabi");
5603 CmdArgs.push_back(Elt: A->getValue());
5604 }
5605
5606 // -fsemantic-interposition is forwarded to CC1: set the
5607 // "SemanticInterposition" metadata to 1 (make some linkages interposable) and
5608 // make default visibility external linkage definitions dso_preemptable.
5609 //
5610 // -fno-semantic-interposition: if the target supports .Lfoo$local local
5611 // aliases (make default visibility external linkage definitions dso_local).
5612 // This is the CC1 default for ELF to match COFF/Mach-O.
5613 //
5614 // Otherwise use Clang's traditional behavior: like
5615 // -fno-semantic-interposition but local aliases are not used. So references
5616 // can be interposed if not optimized out.
5617 if (Triple.isOSBinFormatELF()) {
5618 Arg *A = Args.getLastArg(Ids: options::OPT_fsemantic_interposition,
5619 Ids: options::OPT_fno_semantic_interposition);
5620 if (RelocationModel != llvm::Reloc::Static && !IsPIE) {
5621 // The supported targets need to call AsmPrinter::getSymbolPreferLocal.
5622 bool SupportsLocalAlias =
5623 Triple.isAArch64() || Triple.isRISCV() || Triple.isX86();
5624 if (!A)
5625 CmdArgs.push_back(Elt: "-fhalf-no-semantic-interposition");
5626 else if (A->getOption().matches(ID: options::OPT_fsemantic_interposition))
5627 A->render(Args, Output&: CmdArgs);
5628 else if (!SupportsLocalAlias)
5629 CmdArgs.push_back(Elt: "-fhalf-no-semantic-interposition");
5630 }
5631 }
5632
5633 {
5634 std::string Model;
5635 if (Arg *A = Args.getLastArg(Ids: options::OPT_mthread_model)) {
5636 if (!TC.isThreadModelSupported(Model: A->getValue()))
5637 D.Diag(DiagID: diag::err_drv_invalid_thread_model_for_target)
5638 << A->getValue() << A->getAsString(Args);
5639 Model = A->getValue();
5640 } else
5641 Model = TC.getThreadModel();
5642 if (Model != "posix") {
5643 CmdArgs.push_back(Elt: "-mthread-model");
5644 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Model));
5645 }
5646 }
5647
5648 if (Arg *A = Args.getLastArg(Ids: options::OPT_fveclib)) {
5649 StringRef Name = A->getValue();
5650 if (Name == "SVML") {
5651 if (Triple.getArch() != llvm::Triple::x86 &&
5652 Triple.getArch() != llvm::Triple::x86_64)
5653 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5654 << Name << Triple.getArchName();
5655 } else if (Name == "AMDLIBM") {
5656 if (Triple.getArch() != llvm::Triple::x86 &&
5657 Triple.getArch() != llvm::Triple::x86_64)
5658 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5659 << Name << Triple.getArchName();
5660 } else if (Name == "libmvec") {
5661 if (Triple.getArch() != llvm::Triple::x86 &&
5662 Triple.getArch() != llvm::Triple::x86_64 &&
5663 Triple.getArch() != llvm::Triple::aarch64 &&
5664 Triple.getArch() != llvm::Triple::aarch64_be)
5665 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5666 << Name << Triple.getArchName();
5667 } else if (Name == "SLEEF" || Name == "ArmPL") {
5668 if (Triple.getArch() != llvm::Triple::aarch64 &&
5669 Triple.getArch() != llvm::Triple::aarch64_be &&
5670 Triple.getArch() != llvm::Triple::riscv64)
5671 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5672 << Name << Triple.getArchName();
5673 }
5674 A->render(Args, Output&: CmdArgs);
5675 }
5676
5677 if (Args.hasFlag(Pos: options::OPT_fmerge_all_constants,
5678 Neg: options::OPT_fno_merge_all_constants, Default: false))
5679 CmdArgs.push_back(Elt: "-fmerge-all-constants");
5680
5681 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fdelete_null_pointer_checks,
5682 Neg: options::OPT_fno_delete_null_pointer_checks);
5683
5684 // LLVM Code Generator Options.
5685
5686 if (Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ_quadword_atomics)) {
5687 if (!Triple.isOSAIX() || Triple.isPPC32())
5688 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5689 << A->getSpelling() << RawTriple.str();
5690 CmdArgs.push_back(Elt: "-mabi=quadword-atomics");
5691 }
5692
5693 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlong_double_128)) {
5694 // Emit the unsupported option error until the Clang's library integration
5695 // support for 128-bit long double is available for AIX.
5696 if (Triple.isOSAIX())
5697 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5698 << A->getSpelling() << RawTriple.str();
5699 }
5700
5701 if (Arg *A = Args.getLastArg(Ids: options::OPT_Wframe_larger_than_EQ)) {
5702 StringRef V = A->getValue(), V1 = V;
5703 unsigned Size;
5704 if (V1.consumeInteger(Radix: 10, Result&: Size) || !V1.empty())
5705 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
5706 << V << A->getOption().getName();
5707 else
5708 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fwarn-stack-size=" + V));
5709 }
5710
5711 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fjump_tables,
5712 Neg: options::OPT_fno_jump_tables);
5713 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fprofile_sample_accurate,
5714 Neg: options::OPT_fno_profile_sample_accurate);
5715 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fpreserve_as_comments,
5716 Neg: options::OPT_fno_preserve_as_comments);
5717
5718 if (Arg *A = Args.getLastArg(Ids: options::OPT_mregparm_EQ)) {
5719 CmdArgs.push_back(Elt: "-mregparm");
5720 CmdArgs.push_back(Elt: A->getValue());
5721 }
5722
5723 if (Arg *A = Args.getLastArg(Ids: options::OPT_maix_struct_return,
5724 Ids: options::OPT_msvr4_struct_return)) {
5725 if (!TC.getTriple().isPPC32()) {
5726 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5727 << A->getSpelling() << RawTriple.str();
5728 } else if (A->getOption().matches(ID: options::OPT_maix_struct_return)) {
5729 CmdArgs.push_back(Elt: "-maix-struct-return");
5730 } else {
5731 assert(A->getOption().matches(options::OPT_msvr4_struct_return));
5732 CmdArgs.push_back(Elt: "-msvr4-struct-return");
5733 }
5734 }
5735
5736 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpcc_struct_return,
5737 Ids: options::OPT_freg_struct_return)) {
5738 if (TC.getArch() != llvm::Triple::x86) {
5739 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5740 << A->getSpelling() << RawTriple.str();
5741 } else if (A->getOption().matches(ID: options::OPT_fpcc_struct_return)) {
5742 CmdArgs.push_back(Elt: "-fpcc-struct-return");
5743 } else {
5744 assert(A->getOption().matches(options::OPT_freg_struct_return));
5745 CmdArgs.push_back(Elt: "-freg-struct-return");
5746 }
5747 }
5748
5749 if (Args.hasFlag(Pos: options::OPT_mrtd, Neg: options::OPT_mno_rtd, Default: false)) {
5750 if (Triple.getArch() == llvm::Triple::m68k)
5751 CmdArgs.push_back(Elt: "-fdefault-calling-conv=rtdcall");
5752 else
5753 CmdArgs.push_back(Elt: "-fdefault-calling-conv=stdcall");
5754 }
5755
5756 if (Args.hasArg(Ids: options::OPT_fenable_matrix)) {
5757 // enable-matrix is needed by both the LangOpts and by LLVM.
5758 CmdArgs.push_back(Elt: "-fenable-matrix");
5759 CmdArgs.push_back(Elt: "-mllvm");
5760 CmdArgs.push_back(Elt: "-enable-matrix");
5761 // Only handle default layout if matrix is enabled
5762 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fmatrix_memory_layout_EQ)) {
5763 StringRef Val = A->getValue();
5764 if (Val == "row-major" || Val == "column-major") {
5765 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fmatrix-memory-layout=" + Val));
5766 CmdArgs.push_back(Elt: "-mllvm");
5767 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-matrix-default-layout=" + Val));
5768
5769 } else {
5770 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
5771 }
5772 }
5773 }
5774
5775 CodeGenOptions::FramePointerKind FPKeepKind =
5776 getFramePointerKind(Args, Triple: RawTriple);
5777 const char *FPKeepKindStr = nullptr;
5778 switch (FPKeepKind) {
5779 case CodeGenOptions::FramePointerKind::None:
5780 FPKeepKindStr = "-mframe-pointer=none";
5781 break;
5782 case CodeGenOptions::FramePointerKind::Reserved:
5783 FPKeepKindStr = "-mframe-pointer=reserved";
5784 break;
5785 case CodeGenOptions::FramePointerKind::NonLeafNoReserve:
5786 FPKeepKindStr = "-mframe-pointer=non-leaf-no-reserve";
5787 break;
5788 case CodeGenOptions::FramePointerKind::NonLeaf:
5789 FPKeepKindStr = "-mframe-pointer=non-leaf";
5790 break;
5791 case CodeGenOptions::FramePointerKind::All:
5792 FPKeepKindStr = "-mframe-pointer=all";
5793 break;
5794 }
5795 assert(FPKeepKindStr && "unknown FramePointerKind");
5796 CmdArgs.push_back(Elt: FPKeepKindStr);
5797
5798 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fzero_initialized_in_bss,
5799 Neg: options::OPT_fno_zero_initialized_in_bss);
5800
5801 bool OFastEnabled = isOptimizationLevelFast(Args);
5802 if (OFastEnabled)
5803 D.Diag(DiagID: diag::warn_drv_deprecated_arg_ofast);
5804 // If -Ofast is the optimization level, then -fstrict-aliasing should be
5805 // enabled. This alias option is being used to simplify the hasFlag logic.
5806 OptSpecifier StrictAliasingAliasOption =
5807 OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
5808 // We turn strict aliasing off by default if we're Windows MSVC since MSVC
5809 // doesn't do any TBAA.
5810 if (!Args.hasFlag(Pos: options::OPT_fstrict_aliasing, PosAlias: StrictAliasingAliasOption,
5811 Neg: options::OPT_fno_strict_aliasing,
5812 Default: !IsWindowsMSVC && !IsUEFI))
5813 CmdArgs.push_back(Elt: "-relaxed-aliasing");
5814 if (Args.hasFlag(Pos: options::OPT_fno_pointer_tbaa, Neg: options::OPT_fpointer_tbaa,
5815 Default: false))
5816 CmdArgs.push_back(Elt: "-no-pointer-tbaa");
5817 if (!Args.hasFlag(Pos: options::OPT_fstruct_path_tbaa,
5818 Neg: options::OPT_fno_struct_path_tbaa, Default: true))
5819 CmdArgs.push_back(Elt: "-no-struct-path-tbaa");
5820 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_enums,
5821 Neg: options::OPT_fno_strict_enums);
5822 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_return,
5823 Neg: options::OPT_fno_strict_return);
5824 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fallow_editor_placeholders,
5825 Neg: options::OPT_fno_allow_editor_placeholders);
5826 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstrict_vtable_pointers,
5827 Neg: options::OPT_fno_strict_vtable_pointers);
5828 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fforce_emit_vtables,
5829 Neg: options::OPT_fno_force_emit_vtables);
5830 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_foptimize_sibling_calls,
5831 Neg: options::OPT_fno_optimize_sibling_calls);
5832 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fescaping_block_tail_calls,
5833 Neg: options::OPT_fno_escaping_block_tail_calls);
5834
5835 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffine_grained_bitfield_accesses,
5836 Ids: options::OPT_fno_fine_grained_bitfield_accesses);
5837
5838 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_relative_cxx_abi_vtables,
5839 Ids: options::OPT_fno_experimental_relative_cxx_abi_vtables);
5840
5841 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_omit_vtable_rtti,
5842 Ids: options::OPT_fno_experimental_omit_vtable_rtti);
5843
5844 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdisable_block_signature_string,
5845 Ids: options::OPT_fno_disable_block_signature_string);
5846
5847 // Handle segmented stacks.
5848 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fsplit_stack,
5849 Neg: options::OPT_fno_split_stack);
5850
5851 // -fprotect-parens=0 is default.
5852 if (Args.hasFlag(Pos: options::OPT_fprotect_parens,
5853 Neg: options::OPT_fno_protect_parens, Default: false))
5854 CmdArgs.push_back(Elt: "-fprotect-parens");
5855
5856 RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
5857
5858 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_remote_memory,
5859 Neg: options::OPT_fno_atomic_remote_memory);
5860 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_fine_grained_memory,
5861 Neg: options::OPT_fno_atomic_fine_grained_memory);
5862 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fatomic_ignore_denormal_mode,
5863 Neg: options::OPT_fno_atomic_ignore_denormal_mode);
5864
5865 if (Arg *A = Args.getLastArg(Ids: options::OPT_fextend_args_EQ)) {
5866 const llvm::Triple::ArchType Arch = TC.getArch();
5867 if (Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) {
5868 StringRef V = A->getValue();
5869 if (V == "64")
5870 CmdArgs.push_back(Elt: "-fextend-arguments=64");
5871 else if (V != "32")
5872 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
5873 << A->getValue() << A->getOption().getName();
5874 } else
5875 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5876 << A->getOption().getName() << TripleStr;
5877 }
5878
5879 if (Arg *A = Args.getLastArg(Ids: options::OPT_mdouble_EQ)) {
5880 if (TC.getArch() == llvm::Triple::avr)
5881 A->render(Args, Output&: CmdArgs);
5882 else
5883 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
5884 << A->getAsString(Args) << TripleStr;
5885 }
5886
5887 if (Arg *A = Args.getLastArg(Ids: options::OPT_LongDouble_Group)) {
5888 if (TC.getTriple().isX86())
5889 A->render(Args, Output&: CmdArgs);
5890 else if (TC.getTriple().isPPC() &&
5891 (A->getOption().getID() != options::OPT_mlong_double_80))
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 // Decide whether to use verbose asm. Verbose assembly is the default on
5899 // toolchains which have the integrated assembler on by default.
5900 bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
5901 if (!Args.hasFlag(Pos: options::OPT_fverbose_asm, Neg: options::OPT_fno_verbose_asm,
5902 Default: IsIntegratedAssemblerDefault))
5903 CmdArgs.push_back(Elt: "-fno-verbose-asm");
5904
5905 // Parse 'none' or '$major.$minor'. Disallow -fbinutils-version=0 because we
5906 // use that to indicate the MC default in the backend.
5907 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbinutils_version_EQ)) {
5908 StringRef V = A->getValue();
5909 unsigned Num;
5910 if (V == "none")
5911 A->render(Args, Output&: CmdArgs);
5912 else if (!V.consumeInteger(Radix: 10, Result&: Num) && Num > 0 &&
5913 (V.empty() || (V.consume_front(Prefix: ".") &&
5914 !V.consumeInteger(Radix: 10, Result&: Num) && V.empty())))
5915 A->render(Args, Output&: CmdArgs);
5916 else
5917 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
5918 << A->getValue() << A->getOption().getName();
5919 }
5920
5921 // If toolchain choose to use MCAsmParser for inline asm don't pass the
5922 // option to disable integrated-as explicitly.
5923 if (!TC.useIntegratedAs() && !TC.parseInlineAsmUsingAsmParser())
5924 CmdArgs.push_back(Elt: "-no-integrated-as");
5925
5926 if (Args.hasArg(Ids: options::OPT_fdebug_pass_structure)) {
5927 CmdArgs.push_back(Elt: "-mdebug-pass");
5928 CmdArgs.push_back(Elt: "Structure");
5929 }
5930 if (Args.hasArg(Ids: options::OPT_fdebug_pass_arguments)) {
5931 CmdArgs.push_back(Elt: "-mdebug-pass");
5932 CmdArgs.push_back(Elt: "Arguments");
5933 }
5934
5935 // Enable -mconstructor-aliases except on darwin, where we have to work around
5936 // a linker bug (see https://openradar.appspot.com/7198997), and CUDA device
5937 // code, where aliases aren't supported.
5938 if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
5939 CmdArgs.push_back(Elt: "-mconstructor-aliases");
5940
5941 // Darwin's kernel doesn't support guard variables; just die if we
5942 // try to use them.
5943 if (KernelOrKext && RawTriple.isOSDarwin())
5944 CmdArgs.push_back(Elt: "-fforbid-guard-variables");
5945
5946 if (Arg *A = Args.getLastArg(Ids: options::OPT_mms_bitfields,
5947 Ids: options::OPT_mno_ms_bitfields)) {
5948 if (A->getOption().matches(ID: options::OPT_mms_bitfields))
5949 CmdArgs.push_back(Elt: "-fms-layout-compatibility=microsoft");
5950 else
5951 CmdArgs.push_back(Elt: "-fms-layout-compatibility=itanium");
5952 }
5953
5954 if (Triple.isOSCygMing()) {
5955 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fauto_import,
5956 Neg: options::OPT_fno_auto_import);
5957 }
5958
5959 if (Args.hasFlag(Pos: options::OPT_fms_volatile, Neg: options::OPT_fno_ms_volatile,
5960 Default: Triple.isX86() && IsWindowsMSVC))
5961 CmdArgs.push_back(Elt: "-fms-volatile");
5962
5963 // Non-PIC code defaults to -fdirect-access-external-data while PIC code
5964 // defaults to -fno-direct-access-external-data. Pass the option if different
5965 // from the default.
5966 if (Arg *A = Args.getLastArg(Ids: options::OPT_fdirect_access_external_data,
5967 Ids: options::OPT_fno_direct_access_external_data)) {
5968 if (A->getOption().matches(ID: options::OPT_fdirect_access_external_data) !=
5969 (PICLevel == 0))
5970 A->render(Args, Output&: CmdArgs);
5971 } else if (PICLevel == 0 && Triple.isLoongArch()) {
5972 // Some targets default to -fno-direct-access-external-data even for
5973 // -fno-pic.
5974 CmdArgs.push_back(Elt: "-fno-direct-access-external-data");
5975 }
5976
5977 if (Triple.isOSBinFormatELF() && (Triple.isAArch64() || Triple.isX86()))
5978 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fplt, Neg: options::OPT_fno_plt);
5979
5980 // -fhosted is default.
5981 // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
5982 // use Freestanding.
5983 bool Freestanding =
5984 Args.hasFlag(Pos: options::OPT_ffreestanding, Neg: options::OPT_fhosted, Default: false) ||
5985 KernelOrKext;
5986 if (Freestanding)
5987 CmdArgs.push_back(Elt: "-ffreestanding");
5988
5989 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_knr_functions);
5990
5991 auto SanitizeArgs = TC.getSanitizerArgs(JobArgs: Args);
5992 Args.AddLastArg(Output&: CmdArgs,
5993 Ids: options::OPT_fallow_runtime_check_skip_hot_cutoff_EQ);
5994
5995 // This is a coarse approximation of what llvm-gcc actually does, both
5996 // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
5997 // complicated ways.
5998 bool IsAsyncUnwindTablesDefault =
5999 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Asynchronous;
6000 bool IsSyncUnwindTablesDefault =
6001 TC.getDefaultUnwindTableLevel(Args) == ToolChain::UnwindTableLevel::Synchronous;
6002
6003 bool AsyncUnwindTables = Args.hasFlag(
6004 Pos: options::OPT_fasynchronous_unwind_tables,
6005 Neg: options::OPT_fno_asynchronous_unwind_tables,
6006 Default: (IsAsyncUnwindTablesDefault || SanitizeArgs.needsUnwindTables()) &&
6007 !Freestanding);
6008 bool UnwindTables =
6009 Args.hasFlag(Pos: options::OPT_funwind_tables, Neg: options::OPT_fno_unwind_tables,
6010 Default: IsSyncUnwindTablesDefault && !Freestanding);
6011 if (AsyncUnwindTables)
6012 CmdArgs.push_back(Elt: "-funwind-tables=2");
6013 else if (UnwindTables)
6014 CmdArgs.push_back(Elt: "-funwind-tables=1");
6015
6016 // Sframe unwind tables are independent of the other types. Although also
6017 // defined for aarch64, only x86_64 support is implemented at the moment.
6018 if (Arg *A = Args.getLastArg(Ids: options::OPT_gsframe)) {
6019 if (Triple.isOSBinFormatELF() && Triple.isX86())
6020 CmdArgs.push_back(Elt: "--gsframe");
6021 else
6022 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6023 << A->getOption().getName() << TripleStr;
6024 }
6025
6026 // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
6027 // `--gpu-use-aux-triple-only` is specified.
6028 if (!Args.getLastArg(Ids: options::OPT_gpu_use_aux_triple_only) &&
6029 (IsCudaDevice || IsHIPDevice || IsSYCLDevice)) {
6030 const ArgList &HostArgs =
6031 C.getArgsForToolChain(TC: nullptr, BoundArch: StringRef(), DeviceOffloadKind: Action::OFK_None);
6032 std::string HostCPU =
6033 getCPUName(D, Args: HostArgs, T: *TC.getAuxTriple(), /*FromAs*/ false);
6034 if (!HostCPU.empty()) {
6035 CmdArgs.push_back(Elt: "-aux-target-cpu");
6036 CmdArgs.push_back(Elt: Args.MakeArgString(Str: HostCPU));
6037 }
6038 getTargetFeatures(D, Triple: *TC.getAuxTriple(), Args: HostArgs, CmdArgs,
6039 /*ForAS*/ false, /*IsAux*/ true);
6040 }
6041
6042 TC.addClangTargetOptions(DriverArgs: Args, CC1Args&: CmdArgs, DeviceOffloadKind: JA.getOffloadingDeviceKind());
6043
6044 addMCModel(D, Args, Triple, RelocationModel, CmdArgs);
6045
6046 if (Arg *A = Args.getLastArg(Ids: options::OPT_mtls_size_EQ)) {
6047 StringRef Value = A->getValue();
6048 unsigned TLSSize = 0;
6049 Value.getAsInteger(Radix: 10, Result&: TLSSize);
6050 if (!Triple.isAArch64() || !Triple.isOSBinFormatELF())
6051 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6052 << A->getOption().getName() << TripleStr;
6053 if (TLSSize != 12 && TLSSize != 24 && TLSSize != 32 && TLSSize != 48)
6054 D.Diag(DiagID: diag::err_drv_invalid_int_value)
6055 << A->getOption().getName() << Value;
6056 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mtls_size_EQ);
6057 }
6058
6059 if (isTLSDESCEnabled(TC, Args))
6060 CmdArgs.push_back(Elt: "-enable-tlsdesc");
6061
6062 // Add the target cpu
6063 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ false);
6064 if (!CPU.empty()) {
6065 CmdArgs.push_back(Elt: "-target-cpu");
6066 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
6067 }
6068
6069 RenderTargetOptions(EffectiveTriple: Triple, Args, KernelOrKext, CmdArgs);
6070
6071 // Add clang-cl arguments.
6072 types::ID InputType = Input.getType();
6073 if (D.IsCLMode())
6074 AddClangCLArgs(Args, InputType, CmdArgs);
6075
6076 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
6077 llvm::codegenoptions::NoDebugInfo;
6078 DwarfFissionKind DwarfFission = DwarfFissionKind::None;
6079 renderDebugOptions(TC, D, T: RawTriple, Args, InputType, CmdArgs, Output,
6080 DebugInfoKind, DwarfFission);
6081
6082 // Add the split debug info name to the command lines here so we
6083 // can propagate it to the backend.
6084 bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
6085 (TC.getTriple().isOSBinFormatELF() ||
6086 TC.getTriple().isOSBinFormatWasm() ||
6087 TC.getTriple().isOSBinFormatCOFF()) &&
6088 (isa<AssembleJobAction>(Val: JA) || isa<CompileJobAction>(Val: JA) ||
6089 isa<BackendJobAction>(Val: JA));
6090 if (SplitDWARF) {
6091 const char *SplitDWARFOut = SplitDebugName(JA, Args, Input, Output);
6092 CmdArgs.push_back(Elt: "-split-dwarf-file");
6093 CmdArgs.push_back(Elt: SplitDWARFOut);
6094 if (DwarfFission == DwarfFissionKind::Split) {
6095 CmdArgs.push_back(Elt: "-split-dwarf-output");
6096 CmdArgs.push_back(Elt: SplitDWARFOut);
6097 }
6098 }
6099
6100 // Pass the linker version in use.
6101 if (Arg *A = Args.getLastArg(Ids: options::OPT_mlinker_version_EQ)) {
6102 CmdArgs.push_back(Elt: "-target-linker-version");
6103 CmdArgs.push_back(Elt: A->getValue());
6104 }
6105
6106 // Explicitly error on some things we know we don't support and can't just
6107 // ignore.
6108 if (!Args.hasArg(Ids: options::OPT_fallow_unsupported)) {
6109 Arg *Unsupported;
6110 if (types::isCXX(Id: InputType) && RawTriple.isOSDarwin() &&
6111 TC.getArch() == llvm::Triple::x86) {
6112 if ((Unsupported = Args.getLastArg(Ids: options::OPT_fapple_kext)) ||
6113 (Unsupported = Args.getLastArg(Ids: options::OPT_mkernel)))
6114 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
6115 << Unsupported->getOption().getName();
6116 }
6117 // The faltivec option has been superseded by the maltivec option.
6118 if ((Unsupported = Args.getLastArg(Ids: options::OPT_faltivec)))
6119 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_faltivec)
6120 << Unsupported->getOption().getName()
6121 << "please use -maltivec and include altivec.h explicitly";
6122 if ((Unsupported = Args.getLastArg(Ids: options::OPT_fno_altivec)))
6123 D.Diag(DiagID: diag::err_drv_clang_unsupported_opt_faltivec)
6124 << Unsupported->getOption().getName() << "please use -mno-altivec";
6125 }
6126
6127 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_v);
6128
6129 if (Args.getLastArg(Ids: options::OPT_H)) {
6130 CmdArgs.push_back(Elt: "-H");
6131 CmdArgs.push_back(Elt: "-sys-header-deps");
6132 }
6133 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fshow_skipped_includes);
6134
6135 if (D.CCPrintHeadersFormat && !D.CCGenDiagnostics) {
6136 CmdArgs.push_back(Elt: "-header-include-file");
6137 CmdArgs.push_back(Elt: !D.CCPrintHeadersFilename.empty()
6138 ? D.CCPrintHeadersFilename.c_str()
6139 : "-");
6140 CmdArgs.push_back(Elt: "-sys-header-deps");
6141 CmdArgs.push_back(Elt: Args.MakeArgString(
6142 Str: "-header-include-format=" +
6143 std::string(headerIncludeFormatKindToString(K: D.CCPrintHeadersFormat))));
6144 CmdArgs.push_back(
6145 Elt: Args.MakeArgString(Str: "-header-include-filtering=" +
6146 std::string(headerIncludeFilteringKindToString(
6147 K: D.CCPrintHeadersFiltering))));
6148 }
6149 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_P);
6150 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_print_ivar_layout);
6151
6152 if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
6153 CmdArgs.push_back(Elt: "-diagnostic-log-file");
6154 CmdArgs.push_back(Elt: !D.CCLogDiagnosticsFilename.empty()
6155 ? D.CCLogDiagnosticsFilename.c_str()
6156 : "-");
6157 }
6158
6159 // Give the gen diagnostics more chances to succeed, by avoiding intentional
6160 // crashes.
6161 if (D.CCGenDiagnostics)
6162 CmdArgs.push_back(Elt: "-disable-pragma-debug-crash");
6163
6164 // Allow backend to put its diagnostic files in the same place as frontend
6165 // crash diagnostics files.
6166 if (Args.hasArg(Ids: options::OPT_fcrash_diagnostics_dir)) {
6167 StringRef Dir = Args.getLastArgValue(Id: options::OPT_fcrash_diagnostics_dir);
6168 CmdArgs.push_back(Elt: "-mllvm");
6169 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-crash-diagnostics-dir=" + Dir));
6170 }
6171
6172 bool UseSeparateSections = isUseSeparateSections(Triple);
6173
6174 if (Args.hasFlag(Pos: options::OPT_ffunction_sections,
6175 Neg: options::OPT_fno_function_sections, Default: UseSeparateSections)) {
6176 CmdArgs.push_back(Elt: "-ffunction-sections");
6177 }
6178
6179 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbasic_block_address_map,
6180 Ids: options::OPT_fno_basic_block_address_map)) {
6181 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6182 if (A->getOption().matches(ID: options::OPT_fbasic_block_address_map))
6183 A->render(Args, Output&: CmdArgs);
6184 } else {
6185 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6186 << A->getAsString(Args) << TripleStr;
6187 }
6188 }
6189
6190 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbasic_block_sections_EQ)) {
6191 StringRef Val = A->getValue();
6192 if (Val == "labels") {
6193 D.Diag(DiagID: diag::warn_drv_deprecated_arg)
6194 << A->getAsString(Args) << /*hasReplacement=*/true
6195 << "-fbasic-block-address-map";
6196 CmdArgs.push_back(Elt: "-fbasic-block-address-map");
6197 } else if (Triple.isX86() && Triple.isOSBinFormatELF()) {
6198 if (Val != "all" && Val != "none" && !Val.starts_with(Prefix: "list="))
6199 D.Diag(DiagID: diag::err_drv_invalid_value)
6200 << A->getAsString(Args) << A->getValue();
6201 else
6202 A->render(Args, Output&: CmdArgs);
6203 } else if (Triple.isAArch64() && Triple.isOSBinFormatELF()) {
6204 // "all" is not supported on AArch64 since branch relaxation creates new
6205 // basic blocks for some cross-section branches.
6206 if (Val != "labels" && Val != "none" && !Val.starts_with(Prefix: "list="))
6207 D.Diag(DiagID: diag::err_drv_invalid_value)
6208 << A->getAsString(Args) << A->getValue();
6209 else
6210 A->render(Args, Output&: CmdArgs);
6211 } else if (Triple.isNVPTX()) {
6212 // Do not pass the option to the GPU compilation. We still want it enabled
6213 // for the host-side compilation, so seeing it here is not an error.
6214 } else if (Val != "none") {
6215 // =none is allowed everywhere. It's useful for overriding the option
6216 // and is the same as not specifying the option.
6217 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6218 << A->getAsString(Args) << TripleStr;
6219 }
6220 }
6221
6222 bool HasDefaultDataSections = Triple.isOSBinFormatXCOFF();
6223 if (Args.hasFlag(Pos: options::OPT_fdata_sections, Neg: options::OPT_fno_data_sections,
6224 Default: UseSeparateSections || HasDefaultDataSections)) {
6225 CmdArgs.push_back(Elt: "-fdata-sections");
6226 }
6227
6228 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_funique_section_names,
6229 Neg: options::OPT_fno_unique_section_names);
6230 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fseparate_named_sections,
6231 Neg: options::OPT_fno_separate_named_sections);
6232 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_funique_internal_linkage_names,
6233 Neg: options::OPT_fno_unique_internal_linkage_names);
6234 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_funique_basic_block_section_names,
6235 Neg: options::OPT_fno_unique_basic_block_section_names);
6236
6237 if (Arg *A = Args.getLastArg(Ids: options::OPT_fsplit_machine_functions,
6238 Ids: options::OPT_fno_split_machine_functions)) {
6239 if (!A->getOption().matches(ID: options::OPT_fno_split_machine_functions)) {
6240 // This codegen pass is only available on x86 and AArch64 ELF targets.
6241 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF())
6242 A->render(Args, Output&: CmdArgs);
6243 else
6244 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6245 << A->getAsString(Args) << TripleStr;
6246 }
6247 }
6248
6249 if (Arg *A =
6250 Args.getLastArg(Ids: options::OPT_fpartition_static_data_sections,
6251 Ids: options::OPT_fno_partition_static_data_sections)) {
6252 if (!A->getOption().matches(
6253 ID: options::OPT_fno_partition_static_data_sections)) {
6254 // This codegen pass is only available on x86 and AArch64 ELF targets.
6255 if ((Triple.isX86() || Triple.isAArch64()) && Triple.isOSBinFormatELF()) {
6256 A->render(Args, Output&: CmdArgs);
6257 CmdArgs.push_back(Elt: "-mllvm");
6258 CmdArgs.push_back(Elt: "-memprof-annotate-static-data-prefix");
6259 } else
6260 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6261 << A->getAsString(Args) << TripleStr;
6262 }
6263 }
6264
6265 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_finstrument_functions,
6266 Ids: options::OPT_finstrument_functions_after_inlining,
6267 Ids: options::OPT_finstrument_function_entry_bare);
6268 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconvergent_functions,
6269 Ids: options::OPT_fno_convergent_functions);
6270
6271 // NVPTX doesn't support PGO or coverage
6272 if (!Triple.isNVPTX())
6273 addPGOAndCoverageFlags(TC, C, JA, Output, Args, SanArgs&: SanitizeArgs, CmdArgs);
6274
6275 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fclang_abi_compat_EQ);
6276
6277 if (getLastProfileSampleUseArg(Args) &&
6278 Args.hasFlag(Pos: options::OPT_fsample_profile_use_profi,
6279 Neg: options::OPT_fno_sample_profile_use_profi, Default: true)) {
6280 CmdArgs.push_back(Elt: "-mllvm");
6281 CmdArgs.push_back(Elt: "-sample-profile-use-profi");
6282 }
6283
6284 // Add runtime flag for PS4/PS5 when PGO, coverage, or sanitizers are enabled.
6285 if (RawTriple.isPS() &&
6286 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs)) {
6287 PScpu::addProfileRTArgs(TC, Args, CmdArgs);
6288 PScpu::addSanitizerArgs(TC, Args, CmdArgs);
6289 }
6290
6291 // Pass options for controlling the default header search paths.
6292 if (Args.hasArg(Ids: options::OPT_nostdinc)) {
6293 CmdArgs.push_back(Elt: "-nostdsysteminc");
6294 CmdArgs.push_back(Elt: "-nobuiltininc");
6295 } else {
6296 if (Args.hasArg(Ids: options::OPT_nostdlibinc))
6297 CmdArgs.push_back(Elt: "-nostdsysteminc");
6298 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_nostdincxx);
6299 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_nobuiltininc);
6300 }
6301
6302 // Pass the path to compiler resource files.
6303 CmdArgs.push_back(Elt: "-resource-dir");
6304 CmdArgs.push_back(Elt: D.ResourceDir.c_str());
6305
6306 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_working_directory);
6307
6308 // Add preprocessing options like -I, -D, etc. if we are using the
6309 // preprocessor.
6310 //
6311 // FIXME: Support -fpreprocessed
6312 if (types::getPreprocessedType(Id: InputType) != types::TY_INVALID)
6313 AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
6314
6315 // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
6316 // that "The compiler can only warn and ignore the option if not recognized".
6317 // When building with ccache, it will pass -D options to clang even on
6318 // preprocessed inputs and configure concludes that -fPIC is not supported.
6319 Args.ClaimAllArgs(Id0: options::OPT_D);
6320
6321 // Warn about ignored options to clang.
6322 for (const Arg *A :
6323 Args.filtered(Ids: options::OPT_clang_ignored_gcc_optimization_f_Group)) {
6324 D.Diag(DiagID: diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
6325 A->claim();
6326 }
6327
6328 for (const Arg *A :
6329 Args.filtered(Ids: options::OPT_clang_ignored_legacy_options_Group)) {
6330 D.Diag(DiagID: diag::warn_ignored_clang_option) << A->getAsString(Args);
6331 A->claim();
6332 }
6333
6334 claimNoWarnArgs(Args);
6335
6336 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_R_Group);
6337
6338 for (const Arg *A :
6339 Args.filtered(Ids: options::OPT_W_Group, Ids: options::OPT__SLASH_wd)) {
6340 A->claim();
6341 if (A->getOption().getID() == options::OPT__SLASH_wd) {
6342 unsigned WarningNumber;
6343 if (StringRef(A->getValue()).getAsInteger(Radix: 10, Result&: WarningNumber)) {
6344 D.Diag(DiagID: diag::err_drv_invalid_int_value)
6345 << A->getAsString(Args) << A->getValue();
6346 continue;
6347 }
6348
6349 if (auto Group = diagGroupFromCLWarningID(WarningNumber)) {
6350 CmdArgs.push_back(Elt: Args.MakeArgString(
6351 Str: "-Wno-" + DiagnosticIDs::getWarningOptionForGroup(*Group)));
6352 }
6353 continue;
6354 }
6355 A->render(Args, Output&: CmdArgs);
6356 }
6357
6358 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_Wsystem_headers_in_module_EQ);
6359
6360 if (Args.hasFlag(Pos: options::OPT_pedantic, Neg: options::OPT_no_pedantic, Default: false))
6361 CmdArgs.push_back(Elt: "-pedantic");
6362 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pedantic_errors);
6363 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_w);
6364
6365 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_ffixed_point,
6366 Neg: options::OPT_fno_fixed_point);
6367
6368 if (Arg *A = Args.getLastArg(Ids: options::OPT_fcxx_abi_EQ))
6369 A->render(Args, Output&: CmdArgs);
6370
6371 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_relative_cxx_abi_vtables,
6372 Ids: options::OPT_fno_experimental_relative_cxx_abi_vtables);
6373
6374 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_omit_vtable_rtti,
6375 Ids: options::OPT_fno_experimental_omit_vtable_rtti);
6376
6377 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffuchsia_api_level_EQ))
6378 A->render(Args, Output&: CmdArgs);
6379
6380 // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
6381 // (-ansi is equivalent to -std=c89 or -std=c++98).
6382 //
6383 // If a std is supplied, only add -trigraphs if it follows the
6384 // option.
6385 bool ImplyVCPPCVer = false;
6386 bool ImplyVCPPCXXVer = false;
6387 const Arg *Std = Args.getLastArg(Ids: options::OPT_std_EQ, Ids: options::OPT_ansi);
6388 if (Std) {
6389 if (Std->getOption().matches(ID: options::OPT_ansi))
6390 if (types::isCXX(Id: InputType))
6391 CmdArgs.push_back(Elt: "-std=c++98");
6392 else
6393 CmdArgs.push_back(Elt: "-std=c89");
6394 else
6395 Std->render(Args, Output&: CmdArgs);
6396
6397 // If -f(no-)trigraphs appears after the language standard flag, honor it.
6398 if (Arg *A = Args.getLastArg(Ids: options::OPT_std_EQ, Ids: options::OPT_ansi,
6399 Ids: options::OPT_ftrigraphs,
6400 Ids: options::OPT_fno_trigraphs))
6401 if (A != Std)
6402 A->render(Args, Output&: CmdArgs);
6403 } else {
6404 // Honor -std-default.
6405 //
6406 // FIXME: Clang doesn't correctly handle -std= when the input language
6407 // doesn't match. For the time being just ignore this for C++ inputs;
6408 // eventually we want to do all the standard defaulting here instead of
6409 // splitting it between the driver and clang -cc1.
6410 if (!types::isCXX(Id: InputType)) {
6411 if (!Args.hasArg(Ids: options::OPT__SLASH_std)) {
6412 Args.AddAllArgsTranslated(Output&: CmdArgs, Id0: options::OPT_std_default_EQ, Translation: "-std=",
6413 /*Joined=*/true);
6414 } else
6415 ImplyVCPPCVer = true;
6416 }
6417 else if (IsWindowsMSVC)
6418 ImplyVCPPCXXVer = true;
6419
6420 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrigraphs,
6421 Ids: options::OPT_fno_trigraphs);
6422 }
6423
6424 // GCC's behavior for -Wwrite-strings is a bit strange:
6425 // * In C, this "warning flag" changes the types of string literals from
6426 // 'char[N]' to 'const char[N]', and thus triggers an unrelated warning
6427 // for the discarded qualifier.
6428 // * In C++, this is just a normal warning flag.
6429 //
6430 // Implementing this warning correctly in C is hard, so we follow GCC's
6431 // behavior for now. FIXME: Directly diagnose uses of a string literal as
6432 // a non-const char* in C, rather than using this crude hack.
6433 if (!types::isCXX(Id: InputType)) {
6434 // FIXME: This should behave just like a warning flag, and thus should also
6435 // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
6436 Arg *WriteStrings =
6437 Args.getLastArg(Ids: options::OPT_Wwrite_strings,
6438 Ids: options::OPT_Wno_write_strings, Ids: options::OPT_w);
6439 if (WriteStrings &&
6440 WriteStrings->getOption().matches(ID: options::OPT_Wwrite_strings))
6441 CmdArgs.push_back(Elt: "-fconst-strings");
6442 }
6443
6444 // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
6445 // during C++ compilation, which it is by default. GCC keeps this define even
6446 // in the presence of '-w', match this behavior bug-for-bug.
6447 if (types::isCXX(Id: InputType) &&
6448 Args.hasFlag(Pos: options::OPT_Wdeprecated, Neg: options::OPT_Wno_deprecated,
6449 Default: true)) {
6450 CmdArgs.push_back(Elt: "-fdeprecated-macro");
6451 }
6452
6453 // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
6454 if (Arg *Asm = Args.getLastArg(Ids: options::OPT_fasm, Ids: options::OPT_fno_asm)) {
6455 if (Asm->getOption().matches(ID: options::OPT_fasm))
6456 CmdArgs.push_back(Elt: "-fgnu-keywords");
6457 else
6458 CmdArgs.push_back(Elt: "-fno-gnu-keywords");
6459 }
6460
6461 if (!ShouldEnableAutolink(Args, TC, JA))
6462 CmdArgs.push_back(Elt: "-fno-autolink");
6463
6464 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftemplate_depth_EQ);
6465 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foperator_arrow_depth_EQ);
6466 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_depth_EQ);
6467 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_steps_EQ);
6468
6469 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fexperimental_library);
6470
6471 if (Args.hasArg(Ids: options::OPT_fexperimental_new_constant_interpreter))
6472 CmdArgs.push_back(Elt: "-fexperimental-new-constant-interpreter");
6473
6474 if (Arg *A = Args.getLastArg(Ids: options::OPT_fbracket_depth_EQ)) {
6475 CmdArgs.push_back(Elt: "-fbracket-depth");
6476 CmdArgs.push_back(Elt: A->getValue());
6477 }
6478
6479 if (Arg *A = Args.getLastArg(Ids: options::OPT_Wlarge_by_value_copy_EQ,
6480 Ids: options::OPT_Wlarge_by_value_copy_def)) {
6481 if (A->getNumValues()) {
6482 StringRef bytes = A->getValue();
6483 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-Wlarge-by-value-copy=" + bytes));
6484 } else
6485 CmdArgs.push_back(Elt: "-Wlarge-by-value-copy=64"); // default value
6486 }
6487
6488 if (Args.hasArg(Ids: options::OPT_relocatable_pch))
6489 CmdArgs.push_back(Elt: "-relocatable-pch");
6490
6491 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fcf_runtime_abi_EQ)) {
6492 static const char *kCFABIs[] = {
6493 "standalone", "objc", "swift", "swift-5.0", "swift-4.2", "swift-4.1",
6494 };
6495
6496 if (!llvm::is_contained(Range&: kCFABIs, Element: StringRef(A->getValue())))
6497 D.Diag(DiagID: diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
6498 else
6499 A->render(Args, Output&: CmdArgs);
6500 }
6501
6502 if (Arg *A = Args.getLastArg(Ids: options::OPT_fconstant_string_class_EQ)) {
6503 CmdArgs.push_back(Elt: "-fconstant-string-class");
6504 CmdArgs.push_back(Elt: A->getValue());
6505 }
6506
6507 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftabstop_EQ)) {
6508 CmdArgs.push_back(Elt: "-ftabstop");
6509 CmdArgs.push_back(Elt: A->getValue());
6510 }
6511
6512 if (Args.hasFlag(Pos: options::OPT_fexperimental_call_graph_section,
6513 Neg: options::OPT_fno_experimental_call_graph_section, Default: false))
6514 CmdArgs.push_back(Elt: "-fexperimental-call-graph-section");
6515
6516 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fstack_size_section,
6517 Neg: options::OPT_fno_stack_size_section);
6518
6519 if (Args.hasArg(Ids: options::OPT_fstack_usage)) {
6520 CmdArgs.push_back(Elt: "-stack-usage-file");
6521
6522 if (Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o)) {
6523 SmallString<128> OutputFilename(OutputOpt->getValue());
6524 llvm::sys::path::replace_extension(path&: OutputFilename, extension: "su");
6525 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OutputFilename));
6526 } else
6527 CmdArgs.push_back(
6528 Elt: Args.MakeArgString(Str: Twine(getBaseInputStem(Args, Inputs)) + ".su"));
6529 }
6530
6531 CmdArgs.push_back(Elt: "-ferror-limit");
6532 if (Arg *A = Args.getLastArg(Ids: options::OPT_ferror_limit_EQ))
6533 CmdArgs.push_back(Elt: A->getValue());
6534 else
6535 CmdArgs.push_back(Elt: "19");
6536
6537 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fconstexpr_backtrace_limit_EQ);
6538 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmacro_backtrace_limit_EQ);
6539 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftemplate_backtrace_limit_EQ);
6540 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fspell_checking_limit_EQ);
6541 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fcaret_diagnostics_max_lines_EQ);
6542
6543 // Pass -fmessage-length=.
6544 unsigned MessageLength = 0;
6545 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmessage_length_EQ)) {
6546 StringRef V(A->getValue());
6547 if (V.getAsInteger(Radix: 0, Result&: MessageLength))
6548 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6549 << V << A->getOption().getName();
6550 } else {
6551 // If -fmessage-length=N was not specified, determine whether this is a
6552 // terminal and, if so, implicitly define -fmessage-length appropriately.
6553 MessageLength = llvm::sys::Process::StandardErrColumns();
6554 }
6555 if (MessageLength != 0)
6556 CmdArgs.push_back(
6557 Elt: Args.MakeArgString(Str: "-fmessage-length=" + Twine(MessageLength)));
6558
6559 if (Arg *A = Args.getLastArg(Ids: options::OPT_frandomize_layout_seed_EQ))
6560 CmdArgs.push_back(
6561 Elt: Args.MakeArgString(Str: "-frandomize-layout-seed=" + Twine(A->getValue(N: 0))));
6562
6563 if (Arg *A = Args.getLastArg(Ids: options::OPT_frandomize_layout_seed_file_EQ))
6564 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-frandomize-layout-seed-file=" +
6565 Twine(A->getValue(N: 0))));
6566
6567 // -fvisibility= and -fvisibility-ms-compat are of a piece.
6568 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fvisibility_EQ,
6569 Ids: options::OPT_fvisibility_ms_compat)) {
6570 if (A->getOption().matches(ID: options::OPT_fvisibility_EQ)) {
6571 A->render(Args, Output&: CmdArgs);
6572 } else {
6573 assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
6574 CmdArgs.push_back(Elt: "-fvisibility=hidden");
6575 CmdArgs.push_back(Elt: "-ftype-visibility=default");
6576 }
6577 } else if (IsOpenMPDevice) {
6578 // When compiling for the OpenMP device we want protected visibility by
6579 // default. This prevents the device from accidentally preempting code on
6580 // the host, makes the system more robust, and improves performance.
6581 CmdArgs.push_back(Elt: "-fvisibility=protected");
6582 }
6583
6584 // PS4/PS5 process these options in addClangTargetOptions.
6585 if (!RawTriple.isPS()) {
6586 if (const Arg *A =
6587 Args.getLastArg(Ids: options::OPT_fvisibility_from_dllstorageclass,
6588 Ids: options::OPT_fno_visibility_from_dllstorageclass)) {
6589 if (A->getOption().matches(
6590 ID: options::OPT_fvisibility_from_dllstorageclass)) {
6591 CmdArgs.push_back(Elt: "-fvisibility-from-dllstorageclass");
6592 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_dllexport_EQ);
6593 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_nodllstorageclass_EQ);
6594 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_externs_dllimport_EQ);
6595 Args.AddLastArg(Output&: CmdArgs,
6596 Ids: options::OPT_fvisibility_externs_nodllstorageclass_EQ);
6597 }
6598 }
6599 }
6600
6601 if (Args.hasFlag(Pos: options::OPT_fvisibility_inlines_hidden,
6602 Neg: options::OPT_fno_visibility_inlines_hidden, Default: false))
6603 CmdArgs.push_back(Elt: "-fvisibility-inlines-hidden");
6604
6605 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fvisibility_inlines_hidden_static_local_var,
6606 Ids: options::OPT_fno_visibility_inlines_hidden_static_local_var);
6607
6608 // -fvisibility-global-new-delete-hidden is a deprecated spelling of
6609 // -fvisibility-global-new-delete=force-hidden.
6610 if (const Arg *A =
6611 Args.getLastArg(Ids: options::OPT_fvisibility_global_new_delete_hidden)) {
6612 D.Diag(DiagID: diag::warn_drv_deprecated_arg)
6613 << A->getAsString(Args) << /*hasReplacement=*/true
6614 << "-fvisibility-global-new-delete=force-hidden";
6615 }
6616
6617 if (const Arg *A =
6618 Args.getLastArg(Ids: options::OPT_fvisibility_global_new_delete_EQ,
6619 Ids: options::OPT_fvisibility_global_new_delete_hidden)) {
6620 if (A->getOption().matches(ID: options::OPT_fvisibility_global_new_delete_EQ)) {
6621 A->render(Args, Output&: CmdArgs);
6622 } else {
6623 assert(A->getOption().matches(
6624 options::OPT_fvisibility_global_new_delete_hidden));
6625 CmdArgs.push_back(Elt: "-fvisibility-global-new-delete=force-hidden");
6626 }
6627 }
6628
6629 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftlsmodel_EQ);
6630
6631 if (Args.hasFlag(Pos: options::OPT_fnew_infallible,
6632 Neg: options::OPT_fno_new_infallible, Default: false))
6633 CmdArgs.push_back(Elt: "-fnew-infallible");
6634
6635 if (Args.hasFlag(Pos: options::OPT_fno_operator_names,
6636 Neg: options::OPT_foperator_names, Default: false))
6637 CmdArgs.push_back(Elt: "-fno-operator-names");
6638
6639 // Forward -f (flag) options which we can pass directly.
6640 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_femit_all_decls);
6641 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fheinous_gnu_extensions);
6642 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdigraphs, Ids: options::OPT_fno_digraphs);
6643 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fzero_call_used_regs_EQ);
6644 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fraw_string_literals,
6645 Ids: options::OPT_fno_raw_string_literals);
6646
6647 if (Args.hasFlag(Pos: options::OPT_femulated_tls, Neg: options::OPT_fno_emulated_tls,
6648 Default: Triple.hasDefaultEmulatedTLS()))
6649 CmdArgs.push_back(Elt: "-femulated-tls");
6650
6651 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcheck_new,
6652 Neg: options::OPT_fno_check_new);
6653
6654 if (Arg *A = Args.getLastArg(Ids: options::OPT_fzero_call_used_regs_EQ)) {
6655 // FIXME: There's no reason for this to be restricted to X86. The backend
6656 // code needs to be changed to include the appropriate function calls
6657 // automatically.
6658 if (!Triple.isX86() && !Triple.isAArch64())
6659 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6660 << A->getAsString(Args) << TripleStr;
6661 }
6662
6663 // AltiVec-like language extensions aren't relevant for assembling.
6664 if (!isa<PreprocessJobAction>(Val: JA) || Output.getType() != types::TY_PP_Asm)
6665 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fzvector);
6666
6667 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_show_template_tree);
6668 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_elide_type);
6669
6670 // Forward flags for OpenMP. We don't do this if the current action is an
6671 // device offloading action other than OpenMP.
6672 if (Args.hasFlag(Pos: options::OPT_fopenmp, PosAlias: options::OPT_fopenmp_EQ,
6673 Neg: options::OPT_fno_openmp, Default: false) &&
6674 !Args.hasFlag(Pos: options::OPT_foffload_via_llvm,
6675 Neg: options::OPT_fno_offload_via_llvm, Default: false) &&
6676 (JA.isDeviceOffloading(OKind: Action::OFK_None) ||
6677 JA.isDeviceOffloading(OKind: Action::OFK_OpenMP))) {
6678 switch (D.getOpenMPRuntime(Args)) {
6679 case Driver::OMPRT_OMP:
6680 case Driver::OMPRT_IOMP5:
6681 // Clang can generate useful OpenMP code for these two runtime libraries.
6682 CmdArgs.push_back(Elt: "-fopenmp");
6683
6684 // If no option regarding the use of TLS in OpenMP codegeneration is
6685 // given, decide a default based on the target. Otherwise rely on the
6686 // options and pass the right information to the frontend.
6687 if (!Args.hasFlag(Pos: options::OPT_fopenmp_use_tls,
6688 Neg: options::OPT_fnoopenmp_use_tls, /*Default=*/true))
6689 CmdArgs.push_back(Elt: "-fnoopenmp-use-tls");
6690 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fopenmp_simd,
6691 Ids: options::OPT_fno_openmp_simd);
6692 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_enable_irbuilder);
6693 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_version_EQ);
6694 if (!Args.hasFlag(Pos: options::OPT_fopenmp_extensions,
6695 Neg: options::OPT_fno_openmp_extensions, /*Default=*/true))
6696 CmdArgs.push_back(Elt: "-fno-openmp-extensions");
6697 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_cuda_number_of_sm_EQ);
6698 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
6699 Args.AddAllArgs(Output&: CmdArgs,
6700 Id0: options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
6701 if (Args.hasFlag(Pos: options::OPT_fopenmp_optimistic_collapse,
6702 Neg: options::OPT_fno_openmp_optimistic_collapse,
6703 /*Default=*/false))
6704 CmdArgs.push_back(Elt: "-fopenmp-optimistic-collapse");
6705
6706 // When in OpenMP offloading mode with NVPTX target, forward
6707 // cuda-mode flag
6708 if (Args.hasFlag(Pos: options::OPT_fopenmp_cuda_mode,
6709 Neg: options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
6710 CmdArgs.push_back(Elt: "-fopenmp-cuda-mode");
6711
6712 // When in OpenMP offloading mode, enable debugging on the device.
6713 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_target_debug_EQ);
6714 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_debug,
6715 Neg: options::OPT_fno_openmp_target_debug, /*Default=*/false))
6716 CmdArgs.push_back(Elt: "-fopenmp-target-debug");
6717
6718 // When in OpenMP offloading mode, forward assumptions information about
6719 // thread and team counts in the device.
6720 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_teams_oversubscription,
6721 Neg: options::OPT_fno_openmp_assume_teams_oversubscription,
6722 /*Default=*/false))
6723 CmdArgs.push_back(Elt: "-fopenmp-assume-teams-oversubscription");
6724 if (Args.hasFlag(Pos: options::OPT_fopenmp_assume_threads_oversubscription,
6725 Neg: options::OPT_fno_openmp_assume_threads_oversubscription,
6726 /*Default=*/false))
6727 CmdArgs.push_back(Elt: "-fopenmp-assume-threads-oversubscription");
6728 if (Args.hasArg(Ids: options::OPT_fopenmp_assume_no_thread_state))
6729 CmdArgs.push_back(Elt: "-fopenmp-assume-no-thread-state");
6730 if (Args.hasArg(Ids: options::OPT_fopenmp_assume_no_nested_parallelism))
6731 CmdArgs.push_back(Elt: "-fopenmp-assume-no-nested-parallelism");
6732 if (Args.hasArg(Ids: options::OPT_fopenmp_offload_mandatory))
6733 CmdArgs.push_back(Elt: "-fopenmp-offload-mandatory");
6734 if (Args.hasArg(Ids: options::OPT_fopenmp_force_usm))
6735 CmdArgs.push_back(Elt: "-fopenmp-force-usm");
6736 break;
6737 default:
6738 // By default, if Clang doesn't know how to generate useful OpenMP code
6739 // for a specific runtime library, we just don't pass the '-fopenmp' flag
6740 // down to the actual compilation.
6741 // FIXME: It would be better to have a mode which *only* omits IR
6742 // generation based on the OpenMP support so that we get consistent
6743 // semantic analysis, etc.
6744 break;
6745 }
6746 } else {
6747 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fopenmp_simd,
6748 Ids: options::OPT_fno_openmp_simd);
6749 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fopenmp_version_EQ);
6750 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fopenmp_extensions,
6751 Neg: options::OPT_fno_openmp_extensions);
6752 }
6753 // Forward the offload runtime change to code generation, liboffload implies
6754 // new driver. Otherwise, check if we should forward the new driver to change
6755 // offloading code generation.
6756 if (Args.hasFlag(Pos: options::OPT_foffload_via_llvm,
6757 Neg: options::OPT_fno_offload_via_llvm, Default: false)) {
6758 CmdArgs.append(IL: {"--offload-new-driver", "-foffload-via-llvm"});
6759 } else if (Args.hasFlag(Pos: options::OPT_offload_new_driver,
6760 Neg: options::OPT_no_offload_new_driver,
6761 Default: C.isOffloadingHostKind(Kind: Action::OFK_Cuda))) {
6762 CmdArgs.push_back(Elt: "--offload-new-driver");
6763 }
6764
6765 const XRayArgs &XRay = TC.getXRayArgs(Args);
6766 XRay.addArgs(TC, Args, CmdArgs, InputType);
6767
6768 for (const auto &Filename :
6769 Args.getAllArgValues(Id: options::OPT_fprofile_list_EQ)) {
6770 if (D.getVFS().exists(Path: Filename))
6771 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fprofile-list=" + Filename));
6772 else
6773 D.Diag(DiagID: clang::diag::err_drv_no_such_file) << Filename;
6774 }
6775
6776 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpatchable_function_entry_EQ)) {
6777 StringRef S0 = A->getValue(), S = S0;
6778 unsigned Size, Offset = 0;
6779 if (!Triple.isAArch64() && !Triple.isLoongArch() && !Triple.isRISCV() &&
6780 !Triple.isX86() && !Triple.isSystemZ() &&
6781 !(!Triple.isOSAIX() && (Triple.getArch() == llvm::Triple::ppc ||
6782 Triple.getArch() == llvm::Triple::ppc64 ||
6783 Triple.getArch() == llvm::Triple::ppc64le)))
6784 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6785 << A->getAsString(Args) << TripleStr;
6786 else if (S.consumeInteger(Radix: 10, Result&: Size) ||
6787 (!S.empty() &&
6788 (!S.consume_front(Prefix: ",") || S.consumeInteger(Radix: 10, Result&: Offset))) ||
6789 (!S.empty() && (!S.consume_front(Prefix: ",") || S.empty())))
6790 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6791 << S0 << A->getOption().getName();
6792 else if (Size < Offset)
6793 D.Diag(DiagID: diag::err_drv_unsupported_fpatchable_function_entry_argument);
6794 else {
6795 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getSpelling() + Twine(Size)));
6796 CmdArgs.push_back(Elt: Args.MakeArgString(
6797 Str: "-fpatchable-function-entry-offset=" + Twine(Offset)));
6798 if (!S.empty())
6799 CmdArgs.push_back(
6800 Elt: Args.MakeArgString(Str: "-fpatchable-function-entry-section=" + S));
6801 }
6802 }
6803
6804 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fms_hotpatch);
6805
6806 if (Args.hasArg(Ids: options::OPT_fms_secure_hotpatch_functions_file))
6807 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fms_secure_hotpatch_functions_file);
6808
6809 for (const auto &A :
6810 Args.getAllArgValues(Id: options::OPT_fms_secure_hotpatch_functions_list))
6811 CmdArgs.push_back(
6812 Elt: Args.MakeArgString(Str: "-fms-secure-hotpatch-functions-list=" + Twine(A)));
6813
6814 if (TC.SupportsProfiling()) {
6815 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pg);
6816
6817 llvm::Triple::ArchType Arch = TC.getArch();
6818 if (Arg *A = Args.getLastArg(Ids: options::OPT_mfentry)) {
6819 if (Arch == llvm::Triple::systemz || TC.getTriple().isX86())
6820 A->render(Args, Output&: CmdArgs);
6821 else
6822 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6823 << A->getAsString(Args) << TripleStr;
6824 }
6825 if (Arg *A = Args.getLastArg(Ids: options::OPT_mnop_mcount)) {
6826 if (Arch == llvm::Triple::systemz)
6827 A->render(Args, Output&: CmdArgs);
6828 else
6829 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6830 << A->getAsString(Args) << TripleStr;
6831 }
6832 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrecord_mcount)) {
6833 if (Arch == llvm::Triple::systemz)
6834 A->render(Args, Output&: CmdArgs);
6835 else
6836 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6837 << A->getAsString(Args) << TripleStr;
6838 }
6839 }
6840
6841 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_pg)) {
6842 if (TC.getTriple().isOSzOS()) {
6843 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6844 << A->getAsString(Args) << TripleStr;
6845 }
6846 }
6847 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_p)) {
6848 if (!(TC.getTriple().isOSAIX() || TC.getTriple().isOSOpenBSD())) {
6849 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6850 << A->getAsString(Args) << TripleStr;
6851 }
6852 }
6853 if (Arg *A = Args.getLastArgNoClaim(Ids: options::OPT_p, Ids: options::OPT_pg)) {
6854 if (A->getOption().matches(ID: options::OPT_p)) {
6855 A->claim();
6856 if (TC.getTriple().isOSAIX() && !Args.hasArgNoClaim(Ids: options::OPT_pg))
6857 CmdArgs.push_back(Elt: "-pg");
6858 }
6859 }
6860
6861 // Reject AIX-specific link options on other targets.
6862 if (!TC.getTriple().isOSAIX()) {
6863 for (const Arg *A : Args.filtered(Ids: options::OPT_b, Ids: options::OPT_K,
6864 Ids: options::OPT_mxcoff_build_id_EQ)) {
6865 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
6866 << A->getSpelling() << TripleStr;
6867 }
6868 }
6869
6870 if (Args.getLastArg(Ids: options::OPT_fapple_kext) ||
6871 (Args.hasArg(Ids: options::OPT_mkernel) && types::isCXX(Id: InputType)))
6872 CmdArgs.push_back(Elt: "-fapple-kext");
6873
6874 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_altivec_src_compat);
6875 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_flax_vector_conversions_EQ);
6876 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fobjc_sender_dependent_dispatch);
6877 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_print_source_range_info);
6878 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdiagnostics_parseable_fixits);
6879 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report);
6880 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report_EQ);
6881 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_report_json);
6882 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrapv);
6883 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_malign_double);
6884 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fno_temp_file);
6885
6886 if (const char *Name = C.getTimeTraceFile(JA: &JA)) {
6887 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-ftime-trace=" + Twine(Name)));
6888 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_trace_granularity_EQ);
6889 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftime_trace_verbose);
6890 }
6891
6892 if (Arg *A = Args.getLastArg(Ids: options::OPT_ftrapv_handler_EQ)) {
6893 CmdArgs.push_back(Elt: "-ftrapv-handler");
6894 CmdArgs.push_back(Elt: A->getValue());
6895 }
6896
6897 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ftrap_function_EQ);
6898
6899 // Handle -f[no-]wrapv and -f[no-]strict-overflow, which are used by both
6900 // clang and flang.
6901 renderCommonIntegerOverflowOptions(Args, CmdArgs);
6902
6903 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_ffinite_loops,
6904 Ids: options::OPT_fno_finite_loops);
6905
6906 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fwritable_strings);
6907 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_funroll_loops,
6908 Ids: options::OPT_fno_unroll_loops);
6909 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_floop_interchange,
6910 Ids: options::OPT_fno_loop_interchange);
6911 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_loop_fusion,
6912 Neg: options::OPT_fno_experimental_loop_fusion);
6913
6914 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fstrict_flex_arrays_EQ);
6915
6916 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_pthread);
6917
6918 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mspeculative_load_hardening,
6919 Neg: options::OPT_mno_speculative_load_hardening);
6920
6921 RenderSSPOptions(D, TC, Args, CmdArgs, KernelOrKext);
6922 RenderSCPOptions(TC, Args, CmdArgs);
6923 RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
6924
6925 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fswift_async_fp_EQ);
6926
6927 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_mstackrealign,
6928 Neg: options::OPT_mno_stackrealign);
6929
6930 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mstack_alignment)) {
6931 StringRef Value = A->getValue();
6932 int64_t Alignment = 0;
6933 if (Value.getAsInteger(Radix: 10, Result&: Alignment) || Alignment < 0)
6934 D.Diag(DiagID: diag::err_drv_invalid_argument_to_option)
6935 << Value << A->getOption().getName();
6936 else if (Alignment & (Alignment - 1))
6937 D.Diag(DiagID: diag::err_drv_alignment_not_power_of_two)
6938 << A->getAsString(Args) << Value;
6939 else
6940 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mstack-alignment=" + Value));
6941 }
6942
6943 if (Args.hasArg(Ids: options::OPT_mstack_probe_size)) {
6944 StringRef Size = Args.getLastArgValue(Id: options::OPT_mstack_probe_size);
6945
6946 if (!Size.empty())
6947 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mstack-probe-size=" + Size));
6948 else
6949 CmdArgs.push_back(Elt: "-mstack-probe-size=0");
6950 }
6951
6952 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_mstack_arg_probe,
6953 Neg: options::OPT_mno_stack_arg_probe);
6954
6955 if (Arg *A = Args.getLastArg(Ids: options::OPT_mrestrict_it,
6956 Ids: options::OPT_mno_restrict_it)) {
6957 if (A->getOption().matches(ID: options::OPT_mrestrict_it)) {
6958 CmdArgs.push_back(Elt: "-mllvm");
6959 CmdArgs.push_back(Elt: "-arm-restrict-it");
6960 } else {
6961 CmdArgs.push_back(Elt: "-mllvm");
6962 CmdArgs.push_back(Elt: "-arm-default-it");
6963 }
6964 }
6965
6966 // Forward -cl options to -cc1
6967 RenderOpenCLOptions(Args, CmdArgs, InputType);
6968
6969 // Forward hlsl options to -cc1
6970 RenderHLSLOptions(Args, CmdArgs, InputType);
6971
6972 // Forward OpenACC options to -cc1
6973 RenderOpenACCOptions(D, Args, CmdArgs, InputType);
6974
6975 if (IsHIP) {
6976 if (Args.hasFlag(Pos: options::OPT_fhip_new_launch_api,
6977 Neg: options::OPT_fno_hip_new_launch_api, Default: true))
6978 CmdArgs.push_back(Elt: "-fhip-new-launch-api");
6979 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgpu_allow_device_init,
6980 Neg: options::OPT_fno_gpu_allow_device_init);
6981 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_hipstdpar);
6982 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_hipstdpar_interpose_alloc);
6983 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fhip_kernel_arg_name,
6984 Neg: options::OPT_fno_hip_kernel_arg_name);
6985 }
6986
6987 if (IsCuda || IsHIP) {
6988 if (IsRDCMode)
6989 CmdArgs.push_back(Elt: "-fgpu-rdc");
6990 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgpu_defer_diag,
6991 Neg: options::OPT_fno_gpu_defer_diag);
6992 if (Args.hasFlag(Pos: options::OPT_fgpu_exclude_wrong_side_overloads,
6993 Neg: options::OPT_fno_gpu_exclude_wrong_side_overloads,
6994 Default: false)) {
6995 CmdArgs.push_back(Elt: "-fgpu-exclude-wrong-side-overloads");
6996 CmdArgs.push_back(Elt: "-fgpu-defer-diag");
6997 }
6998 }
6999
7000 // Forward --no-offloadlib to -cc1.
7001 if (!Args.hasFlag(Pos: options::OPT_offloadlib, Neg: options::OPT_no_offloadlib, Default: true))
7002 CmdArgs.push_back(Elt: "--no-offloadlib");
7003
7004 if (Arg *A = Args.getLastArg(Ids: options::OPT_fcf_protection_EQ)) {
7005 CmdArgs.push_back(
7006 Elt: Args.MakeArgString(Str: Twine("-fcf-protection=") + A->getValue()));
7007
7008 if (Arg *SA = Args.getLastArg(Ids: options::OPT_mcf_branch_label_scheme_EQ))
7009 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-mcf-branch-label-scheme=") +
7010 SA->getValue()));
7011 } else if (Triple.isOSOpenBSD() && Triple.getArch() == llvm::Triple::x86_64) {
7012 // Emit IBT endbr64 instructions by default
7013 CmdArgs.push_back(Elt: "-fcf-protection=branch");
7014 // jump-table can generate indirect jumps, which are not permitted
7015 CmdArgs.push_back(Elt: "-fno-jump-tables");
7016 }
7017
7018 if (Arg *A = Args.getLastArg(Ids: options::OPT_mfunction_return_EQ))
7019 CmdArgs.push_back(
7020 Elt: Args.MakeArgString(Str: Twine("-mfunction-return=") + A->getValue()));
7021
7022 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_mindirect_branch_cs_prefix);
7023
7024 // Forward -f options with positive and negative forms; we translate these by
7025 // hand. Do not propagate PGO options to the GPU-side compilations as the
7026 // profile info is for the host-side compilation only.
7027 if (!(IsCudaDevice || IsHIPDevice)) {
7028 if (Arg *A = getLastProfileSampleUseArg(Args)) {
7029 auto *PGOArg = Args.getLastArg(
7030 Ids: options::OPT_fprofile_generate, Ids: options::OPT_fprofile_generate_EQ,
7031 Ids: options::OPT_fcs_profile_generate,
7032 Ids: options::OPT_fcs_profile_generate_EQ, Ids: options::OPT_fprofile_use,
7033 Ids: options::OPT_fprofile_use_EQ);
7034 if (PGOArg)
7035 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
7036 << "SampleUse with PGO options";
7037
7038 StringRef fname = A->getValue();
7039 if (!llvm::sys::fs::exists(Path: fname))
7040 D.Diag(DiagID: diag::err_drv_no_such_file) << fname;
7041 else
7042 A->render(Args, Output&: CmdArgs);
7043 }
7044 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fprofile_remapping_file_EQ);
7045
7046 if (Args.hasFlag(Pos: options::OPT_fpseudo_probe_for_profiling,
7047 Neg: options::OPT_fno_pseudo_probe_for_profiling, Default: false)) {
7048 CmdArgs.push_back(Elt: "-fpseudo-probe-for-profiling");
7049 // Enforce -funique-internal-linkage-names if it's not explicitly turned
7050 // off.
7051 if (Args.hasFlag(Pos: options::OPT_funique_internal_linkage_names,
7052 Neg: options::OPT_fno_unique_internal_linkage_names, Default: true))
7053 CmdArgs.push_back(Elt: "-funique-internal-linkage-names");
7054 }
7055 }
7056 RenderBuiltinOptions(TC, T: RawTriple, Args, CmdArgs);
7057
7058 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_sane_operator_new,
7059 Neg: options::OPT_fno_assume_sane_operator_new);
7060
7061 if (Args.hasFlag(Pos: options::OPT_fapinotes, Neg: options::OPT_fno_apinotes, Default: false))
7062 CmdArgs.push_back(Elt: "-fapinotes");
7063 if (Args.hasFlag(Pos: options::OPT_fapinotes_modules,
7064 Neg: options::OPT_fno_apinotes_modules, Default: false))
7065 CmdArgs.push_back(Elt: "-fapinotes-modules");
7066 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fapinotes_swift_version);
7067
7068 if (Args.hasFlag(Pos: options::OPT_fswift_version_independent_apinotes,
7069 Neg: options::OPT_fno_swift_version_independent_apinotes, Default: false))
7070 CmdArgs.push_back(Elt: "-fswift-version-independent-apinotes");
7071
7072 // -fblocks=0 is default.
7073 if (Args.hasFlag(Pos: options::OPT_fblocks, Neg: options::OPT_fno_blocks,
7074 Default: TC.IsBlocksDefault()) ||
7075 (Args.hasArg(Ids: options::OPT_fgnu_runtime) &&
7076 Args.hasArg(Ids: options::OPT_fobjc_nonfragile_abi) &&
7077 !Args.hasArg(Ids: options::OPT_fno_blocks))) {
7078 CmdArgs.push_back(Elt: "-fblocks");
7079
7080 if (!Args.hasArg(Ids: options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
7081 CmdArgs.push_back(Elt: "-fblocks-runtime-optional");
7082 }
7083
7084 // -fencode-extended-block-signature=1 is default.
7085 if (TC.IsEncodeExtendedBlockSignatureDefault())
7086 CmdArgs.push_back(Elt: "-fencode-extended-block-signature");
7087
7088 if (Args.hasFlag(Pos: options::OPT_fcoro_aligned_allocation,
7089 Neg: options::OPT_fno_coro_aligned_allocation, Default: false) &&
7090 types::isCXX(Id: InputType))
7091 CmdArgs.push_back(Elt: "-fcoro-aligned-allocation");
7092
7093 if (Args.hasFlag(Pos: options::OPT_fdefer_ts, Neg: options::OPT_fno_defer_ts,
7094 /*Default=*/false))
7095 CmdArgs.push_back(Elt: "-fdefer-ts");
7096
7097 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fdouble_square_bracket_attributes,
7098 Ids: options::OPT_fno_double_square_bracket_attributes);
7099
7100 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_faccess_control,
7101 Neg: options::OPT_fno_access_control);
7102 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_felide_constructors,
7103 Neg: options::OPT_fno_elide_constructors);
7104
7105 ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
7106
7107 if (KernelOrKext || (types::isCXX(Id: InputType) &&
7108 (RTTIMode == ToolChain::RM_Disabled)))
7109 CmdArgs.push_back(Elt: "-fno-rtti");
7110
7111 // -fshort-enums=0 is default for all architectures except Hexagon and z/OS.
7112 if (Args.hasFlag(Pos: options::OPT_fshort_enums, Neg: options::OPT_fno_short_enums,
7113 Default: TC.getArch() == llvm::Triple::hexagon || Triple.isOSzOS()))
7114 CmdArgs.push_back(Elt: "-fshort-enums");
7115
7116 RenderCharacterOptions(Args, T: AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
7117
7118 // -fuse-cxa-atexit is default.
7119 if (!Args.hasFlag(
7120 Pos: options::OPT_fuse_cxa_atexit, Neg: options::OPT_fno_use_cxa_atexit,
7121 Default: !RawTriple.isOSAIX() &&
7122 (!RawTriple.isOSWindows() ||
7123 RawTriple.isWindowsCygwinEnvironment()) &&
7124 ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
7125 RawTriple.hasEnvironment())) ||
7126 KernelOrKext)
7127 CmdArgs.push_back(Elt: "-fno-use-cxa-atexit");
7128
7129 if (Args.hasFlag(Pos: options::OPT_fregister_global_dtors_with_atexit,
7130 Neg: options::OPT_fno_register_global_dtors_with_atexit,
7131 Default: RawTriple.isOSDarwin() && !KernelOrKext))
7132 CmdArgs.push_back(Elt: "-fregister-global-dtors-with-atexit");
7133
7134 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fuse_line_directives,
7135 Neg: options::OPT_fno_use_line_directives);
7136
7137 // -fno-minimize-whitespace is default.
7138 if (Args.hasFlag(Pos: options::OPT_fminimize_whitespace,
7139 Neg: options::OPT_fno_minimize_whitespace, Default: false)) {
7140 types::ID InputType = Inputs[0].getType();
7141 if (!isDerivedFromC(Id: InputType))
7142 D.Diag(DiagID: diag::err_drv_opt_unsupported_input_type)
7143 << "-fminimize-whitespace" << types::getTypeName(Id: InputType);
7144 CmdArgs.push_back(Elt: "-fminimize-whitespace");
7145 }
7146
7147 // -fno-keep-system-includes is default.
7148 if (Args.hasFlag(Pos: options::OPT_fkeep_system_includes,
7149 Neg: options::OPT_fno_keep_system_includes, Default: false)) {
7150 types::ID InputType = Inputs[0].getType();
7151 if (!isDerivedFromC(Id: InputType))
7152 D.Diag(DiagID: diag::err_drv_opt_unsupported_input_type)
7153 << "-fkeep-system-includes" << types::getTypeName(Id: InputType);
7154 CmdArgs.push_back(Elt: "-fkeep-system-includes");
7155 }
7156
7157 // -fms-extensions=0 is default.
7158 if (Args.hasFlag(Pos: options::OPT_fms_extensions, Neg: options::OPT_fno_ms_extensions,
7159 Default: IsWindowsMSVC || IsUEFI))
7160 CmdArgs.push_back(Elt: "-fms-extensions");
7161
7162 // -fms-compatibility=0 is default.
7163 bool IsMSVCCompat = Args.hasFlag(
7164 Pos: options::OPT_fms_compatibility, Neg: options::OPT_fno_ms_compatibility,
7165 Default: (IsWindowsMSVC && Args.hasFlag(Pos: options::OPT_fms_extensions,
7166 Neg: options::OPT_fno_ms_extensions, Default: true)));
7167 if (IsMSVCCompat) {
7168 CmdArgs.push_back(Elt: "-fms-compatibility");
7169 if (!types::isCXX(Id: Input.getType()) &&
7170 Args.hasArg(Ids: options::OPT_fms_define_stdc))
7171 CmdArgs.push_back(Elt: "-fms-define-stdc");
7172 }
7173
7174 // -fms-anonymous-structs is disabled by default.
7175 // Determine whether to enable Microsoft named anonymous struct/union support.
7176 // This implements "last flag wins" semantics for -fms-anonymous-structs,
7177 // where the feature can be:
7178 // - Explicitly enabled via -fms-anonymous-structs.
7179 // - Explicitly disabled via fno-ms-anonymous-structs
7180 // - Implicitly enabled via -fms-extensions or -fms-compatibility
7181 // - Implicitly disabled via -fno-ms-extensions or -fno-ms-compatibility
7182 //
7183 // When multiple relevent options are present, the last option on the command
7184 // line takes precedence. This allows users to selectively override implicit
7185 // enablement. Examples:
7186 // -fms-extensions -fno-ms-anonymous-structs -> disabled (explicit override)
7187 // -fno-ms-anonymous-structs -fms-extensions -> enabled (last flag wins)
7188 auto MSAnonymousStructsOptionToUseOrNull =
7189 [](const ArgList &Args) -> const char * {
7190 const char *Option = nullptr;
7191 constexpr const char *Enable = "-fms-anonymous-structs";
7192 constexpr const char *Disable = "-fno-ms-anonymous-structs";
7193
7194 // Iterate through all arguments in order to implement "last flag wins".
7195 for (const Arg *A : Args) {
7196 switch (A->getOption().getID()) {
7197 case options::OPT_fms_anonymous_structs:
7198 A->claim();
7199 Option = Enable;
7200 break;
7201 case options::OPT_fno_ms_anonymous_structs:
7202 A->claim();
7203 Option = Disable;
7204 break;
7205 // Each of -fms-extensions and -fms-compatibility implicitly enables the
7206 // feature.
7207 case options::OPT_fms_extensions:
7208 case options::OPT_fms_compatibility:
7209 Option = Enable;
7210 break;
7211 // Each of -fno-ms-extensions and -fno-ms-compatibility implicitly
7212 // disables the feature.
7213 case options::OPT_fno_ms_extensions:
7214 case options::OPT_fno_ms_compatibility:
7215 Option = Disable;
7216 break;
7217 default:
7218 break;
7219 }
7220 }
7221 return Option;
7222 };
7223
7224 // Only pass a flag to CC1 if a relevant option was seen
7225 if (auto MSAnonOpt = MSAnonymousStructsOptionToUseOrNull(Args))
7226 CmdArgs.push_back(Elt: MSAnonOpt);
7227
7228 if (Triple.isWindowsMSVCEnvironment() && !D.IsCLMode() &&
7229 Args.hasArg(Ids: options::OPT_fms_runtime_lib_EQ))
7230 ProcessVSRuntimeLibrary(TC: getToolChain(), Args, CmdArgs);
7231
7232 // Handle -fgcc-version, if present.
7233 VersionTuple GNUCVer;
7234 if (Arg *A = Args.getLastArg(Ids: options::OPT_fgnuc_version_EQ)) {
7235 // Check that the version has 1 to 3 components and the minor and patch
7236 // versions fit in two decimal digits.
7237 StringRef Val = A->getValue();
7238 Val = Val.empty() ? "0" : Val; // Treat "" as 0 or disable.
7239 bool Invalid = GNUCVer.tryParse(string: Val);
7240 unsigned Minor = GNUCVer.getMinor().value_or(u: 0);
7241 unsigned Patch = GNUCVer.getSubminor().value_or(u: 0);
7242 if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
7243 D.Diag(DiagID: diag::err_drv_invalid_value)
7244 << A->getAsString(Args) << A->getValue();
7245 }
7246 } else if (!IsMSVCCompat) {
7247 // Imitate GCC 4.2.1 by default if -fms-compatibility is not in effect.
7248 GNUCVer = VersionTuple(4, 2, 1);
7249 }
7250 if (!GNUCVer.empty()) {
7251 CmdArgs.push_back(
7252 Elt: Args.MakeArgString(Str: "-fgnuc-version=" + GNUCVer.getAsString()));
7253 }
7254
7255 VersionTuple MSVT = TC.computeMSVCVersion(D: &D, Args);
7256 if (!MSVT.empty())
7257 CmdArgs.push_back(
7258 Elt: Args.MakeArgString(Str: "-fms-compatibility-version=" + MSVT.getAsString()));
7259
7260 bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
7261 if (ImplyVCPPCVer) {
7262 StringRef LanguageStandard;
7263 if (const Arg *StdArg = Args.getLastArg(Ids: options::OPT__SLASH_std)) {
7264 Std = StdArg;
7265 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7266 .Case(S: "c11", Value: "-std=c11")
7267 .Case(S: "c17", Value: "-std=c17")
7268 // If you add cases below for spellings that are
7269 // not in LangStandards.def, update
7270 // TransferableCommand::tryParseStdArg() in
7271 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7272 // to match.
7273 // TODO: add c23 when MSVC supports it.
7274 .Case(S: "clatest", Value: "-std=c23")
7275 .Default(Value: "");
7276 if (LanguageStandard.empty())
7277 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
7278 << StdArg->getAsString(Args);
7279 }
7280 CmdArgs.push_back(Elt: LanguageStandard.data());
7281 }
7282 if (ImplyVCPPCXXVer) {
7283 StringRef LanguageStandard;
7284 if (const Arg *StdArg = Args.getLastArg(Ids: options::OPT__SLASH_std)) {
7285 Std = StdArg;
7286 LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
7287 .Case(S: "c++14", Value: "-std=c++14")
7288 .Case(S: "c++17", Value: "-std=c++17")
7289 .Case(S: "c++20", Value: "-std=c++20")
7290 // If you add cases below for spellings that are
7291 // not in LangStandards.def, update
7292 // TransferableCommand::tryParseStdArg() in
7293 // lib/Tooling/InterpolatingCompilationDatabase.cpp
7294 // to match.
7295 // TODO add c++23 and c++26 when MSVC supports it.
7296 .Case(S: "c++23preview", Value: "-std=c++23")
7297 .Case(S: "c++latest", Value: "-std=c++26")
7298 .Default(Value: "");
7299 if (LanguageStandard.empty())
7300 D.Diag(DiagID: clang::diag::warn_drv_unused_argument)
7301 << StdArg->getAsString(Args);
7302 }
7303
7304 if (LanguageStandard.empty()) {
7305 if (IsMSVC2015Compatible)
7306 LanguageStandard = "-std=c++14";
7307 else
7308 LanguageStandard = "-std=c++11";
7309 }
7310
7311 CmdArgs.push_back(Elt: LanguageStandard.data());
7312 }
7313
7314 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fborland_extensions,
7315 Neg: options::OPT_fno_borland_extensions);
7316
7317 // -fno-declspec is default, except for PS4/PS5.
7318 if (Args.hasFlag(Pos: options::OPT_fdeclspec, Neg: options::OPT_fno_declspec,
7319 Default: RawTriple.isPS()))
7320 CmdArgs.push_back(Elt: "-fdeclspec");
7321 else if (Args.hasArg(Ids: options::OPT_fno_declspec))
7322 CmdArgs.push_back(Elt: "-fno-declspec"); // Explicitly disabling __declspec.
7323
7324 // -fthreadsafe-static is default, except for MSVC compatibility versions less
7325 // than 19.
7326 if (!Args.hasFlag(Pos: options::OPT_fthreadsafe_statics,
7327 Neg: options::OPT_fno_threadsafe_statics,
7328 Default: !types::isOpenCL(Id: InputType) &&
7329 (!IsWindowsMSVC || IsMSVC2015Compatible)))
7330 CmdArgs.push_back(Elt: "-fno-threadsafe-statics");
7331
7332 if (!Args.hasFlag(Pos: options::OPT_fms_tls_guards, Neg: options::OPT_fno_ms_tls_guards,
7333 Default: true))
7334 CmdArgs.push_back(Elt: "-fno-ms-tls-guards");
7335
7336 // Add -fno-assumptions, if it was specified.
7337 if (!Args.hasFlag(Pos: options::OPT_fassumptions, Neg: options::OPT_fno_assumptions,
7338 Default: true))
7339 CmdArgs.push_back(Elt: "-fno-assumptions");
7340
7341 // -fgnu-keywords default varies depending on language; only pass if
7342 // specified.
7343 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fgnu_keywords,
7344 Ids: options::OPT_fno_gnu_keywords);
7345
7346 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fgnu89_inline,
7347 Neg: options::OPT_fno_gnu89_inline);
7348
7349 const Arg *InlineArg = Args.getLastArg(Ids: options::OPT_finline_functions,
7350 Ids: options::OPT_finline_hint_functions,
7351 Ids: options::OPT_fno_inline_functions);
7352 if (Arg *A = Args.getLastArg(Ids: options::OPT_finline, Ids: options::OPT_fno_inline)) {
7353 if (A->getOption().matches(ID: options::OPT_fno_inline))
7354 A->render(Args, Output&: CmdArgs);
7355 } else if (InlineArg) {
7356 InlineArg->render(Args, Output&: CmdArgs);
7357 }
7358
7359 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_finline_max_stacksize_EQ);
7360
7361 // FIXME: Find a better way to determine whether we are in C++20.
7362 bool HaveCxx20 =
7363 Std &&
7364 (Std->containsValue(Value: "c++2a") || Std->containsValue(Value: "gnu++2a") ||
7365 Std->containsValue(Value: "c++20") || Std->containsValue(Value: "gnu++20") ||
7366 Std->containsValue(Value: "c++2b") || Std->containsValue(Value: "gnu++2b") ||
7367 Std->containsValue(Value: "c++23") || Std->containsValue(Value: "gnu++23") ||
7368 Std->containsValue(Value: "c++23preview") || Std->containsValue(Value: "c++2c") ||
7369 Std->containsValue(Value: "gnu++2c") || Std->containsValue(Value: "c++26") ||
7370 Std->containsValue(Value: "gnu++26") || Std->containsValue(Value: "c++latest") ||
7371 Std->containsValue(Value: "gnu++latest"));
7372 bool HaveModules =
7373 RenderModulesOptions(C, D, Args, Input, Output, HaveStd20: HaveCxx20, CmdArgs);
7374
7375 // -fdelayed-template-parsing is default when targeting MSVC.
7376 // Many old Windows SDK versions require this to parse.
7377 //
7378 // According to
7379 // https://learn.microsoft.com/en-us/cpp/build/reference/permissive-standards-conformance?view=msvc-170,
7380 // MSVC actually defaults to -fno-delayed-template-parsing (/Zc:twoPhase-
7381 // with MSVC CLI) if using C++20. So we match the behavior with MSVC here to
7382 // not enable -fdelayed-template-parsing by default after C++20.
7383 //
7384 // FIXME: Given -fdelayed-template-parsing is a source of bugs, we should be
7385 // able to disable this by default at some point.
7386 if (Args.hasFlag(Pos: options::OPT_fdelayed_template_parsing,
7387 Neg: options::OPT_fno_delayed_template_parsing,
7388 Default: IsWindowsMSVC && !HaveCxx20)) {
7389 if (HaveCxx20)
7390 D.Diag(DiagID: clang::diag::warn_drv_delayed_template_parsing_after_cxx20);
7391
7392 CmdArgs.push_back(Elt: "-fdelayed-template-parsing");
7393 }
7394
7395 if (Args.hasFlag(Pos: options::OPT_fpch_validate_input_files_content,
7396 Neg: options::OPT_fno_pch_validate_input_files_content, Default: false))
7397 CmdArgs.push_back(Elt: "-fvalidate-ast-input-files-content");
7398 if (Args.hasFlag(Pos: options::OPT_fpch_instantiate_templates,
7399 Neg: options::OPT_fno_pch_instantiate_templates, Default: false))
7400 CmdArgs.push_back(Elt: "-fpch-instantiate-templates");
7401 if (Args.hasFlag(Pos: options::OPT_fpch_codegen, Neg: options::OPT_fno_pch_codegen,
7402 Default: false))
7403 CmdArgs.push_back(Elt: "-fmodules-codegen");
7404 if (Args.hasFlag(Pos: options::OPT_fpch_debuginfo, Neg: options::OPT_fno_pch_debuginfo,
7405 Default: false))
7406 CmdArgs.push_back(Elt: "-fmodules-debuginfo");
7407
7408 ObjCRuntime Runtime = AddObjCRuntimeArgs(args: Args, inputs: Inputs, cmdArgs&: CmdArgs, rewrite: rewriteKind);
7409 RenderObjCOptions(TC, D, T: RawTriple, Args, Runtime, InferCovariantReturns: rewriteKind != RK_None,
7410 Input, CmdArgs);
7411
7412 if (types::isObjC(Id: Input.getType()) &&
7413 Args.hasFlag(Pos: options::OPT_fobjc_encode_cxx_class_template_spec,
7414 Neg: options::OPT_fno_objc_encode_cxx_class_template_spec,
7415 Default: !Runtime.isNeXTFamily()))
7416 CmdArgs.push_back(Elt: "-fobjc-encode-cxx-class-template-spec");
7417
7418 if (Args.hasFlag(Pos: options::OPT_fapplication_extension,
7419 Neg: options::OPT_fno_application_extension, Default: false))
7420 CmdArgs.push_back(Elt: "-fapplication-extension");
7421
7422 // Handle GCC-style exception args.
7423 bool EH = false;
7424 if (!C.getDriver().IsCLMode())
7425 EH = addExceptionArgs(Args, InputType, TC, KernelOrKext, objcRuntime: Runtime, CmdArgs);
7426
7427 // Handle exception personalities
7428 Arg *A = Args.getLastArg(
7429 Ids: options::OPT_fsjlj_exceptions, Ids: options::OPT_fseh_exceptions,
7430 Ids: options::OPT_fdwarf_exceptions, Ids: options::OPT_fwasm_exceptions);
7431 if (A) {
7432 const Option &Opt = A->getOption();
7433 if (Opt.matches(ID: options::OPT_fsjlj_exceptions))
7434 CmdArgs.push_back(Elt: "-exception-model=sjlj");
7435 if (Opt.matches(ID: options::OPT_fseh_exceptions))
7436 CmdArgs.push_back(Elt: "-exception-model=seh");
7437 if (Opt.matches(ID: options::OPT_fdwarf_exceptions))
7438 CmdArgs.push_back(Elt: "-exception-model=dwarf");
7439 if (Opt.matches(ID: options::OPT_fwasm_exceptions))
7440 CmdArgs.push_back(Elt: "-exception-model=wasm");
7441 } else {
7442 switch (TC.GetExceptionModel(Args)) {
7443 default:
7444 break;
7445 case llvm::ExceptionHandling::DwarfCFI:
7446 CmdArgs.push_back(Elt: "-exception-model=dwarf");
7447 break;
7448 case llvm::ExceptionHandling::SjLj:
7449 CmdArgs.push_back(Elt: "-exception-model=sjlj");
7450 break;
7451 case llvm::ExceptionHandling::WinEH:
7452 CmdArgs.push_back(Elt: "-exception-model=seh");
7453 break;
7454 }
7455 }
7456
7457 // Unwind v2 (epilog) information for x64 Windows.
7458 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_winx64_eh_unwindv2);
7459
7460 // C++ "sane" operator new.
7461 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_sane_operator_new,
7462 Neg: options::OPT_fno_assume_sane_operator_new);
7463
7464 // -fassume-unique-vtables is on by default.
7465 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fassume_unique_vtables,
7466 Neg: options::OPT_fno_assume_unique_vtables);
7467
7468 // -fsized-deallocation is on by default in C++14 onwards and otherwise off
7469 // by default.
7470 Args.addLastArg(Output&: CmdArgs, Ids: options::OPT_fsized_deallocation,
7471 Ids: options::OPT_fno_sized_deallocation);
7472
7473 // -faligned-allocation is on by default in C++17 onwards and otherwise off
7474 // by default.
7475 if (Arg *A = Args.getLastArg(Ids: options::OPT_faligned_allocation,
7476 Ids: options::OPT_fno_aligned_allocation,
7477 Ids: options::OPT_faligned_new_EQ)) {
7478 if (A->getOption().matches(ID: options::OPT_fno_aligned_allocation))
7479 CmdArgs.push_back(Elt: "-fno-aligned-allocation");
7480 else
7481 CmdArgs.push_back(Elt: "-faligned-allocation");
7482 }
7483
7484 // The default new alignment can be specified using a dedicated option or via
7485 // a GCC-compatible option that also turns on aligned allocation.
7486 if (Arg *A = Args.getLastArg(Ids: options::OPT_fnew_alignment_EQ,
7487 Ids: options::OPT_faligned_new_EQ))
7488 CmdArgs.push_back(
7489 Elt: Args.MakeArgString(Str: Twine("-fnew-alignment=") + A->getValue()));
7490
7491 // -fconstant-cfstrings is default, and may be subject to argument translation
7492 // on Darwin.
7493 if (!Args.hasFlag(Pos: options::OPT_fconstant_cfstrings,
7494 Neg: options::OPT_fno_constant_cfstrings, Default: true) ||
7495 !Args.hasFlag(Pos: options::OPT_mconstant_cfstrings,
7496 Neg: options::OPT_mno_constant_cfstrings, Default: true))
7497 CmdArgs.push_back(Elt: "-fno-constant-cfstrings");
7498
7499 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fpascal_strings,
7500 Neg: options::OPT_fno_pascal_strings);
7501
7502 // Honor -fpack-struct= and -fpack-struct, if given. Note that
7503 // -fno-pack-struct doesn't apply to -fpack-struct=.
7504 if (Arg *A = Args.getLastArg(Ids: options::OPT_fpack_struct_EQ)) {
7505 std::string PackStructStr = "-fpack-struct=";
7506 PackStructStr += A->getValue();
7507 CmdArgs.push_back(Elt: Args.MakeArgString(Str: PackStructStr));
7508 } else if (Args.hasFlag(Pos: options::OPT_fpack_struct,
7509 Neg: options::OPT_fno_pack_struct, Default: false)) {
7510 CmdArgs.push_back(Elt: "-fpack-struct=1");
7511 }
7512
7513 // Handle -fmax-type-align=N and -fno-type-align
7514 bool SkipMaxTypeAlign = Args.hasArg(Ids: options::OPT_fno_max_type_align);
7515 if (Arg *A = Args.getLastArg(Ids: options::OPT_fmax_type_align_EQ)) {
7516 if (!SkipMaxTypeAlign) {
7517 std::string MaxTypeAlignStr = "-fmax-type-align=";
7518 MaxTypeAlignStr += A->getValue();
7519 CmdArgs.push_back(Elt: Args.MakeArgString(Str: MaxTypeAlignStr));
7520 }
7521 } else if (RawTriple.isOSDarwin()) {
7522 if (!SkipMaxTypeAlign) {
7523 std::string MaxTypeAlignStr = "-fmax-type-align=16";
7524 CmdArgs.push_back(Elt: Args.MakeArgString(Str: MaxTypeAlignStr));
7525 }
7526 }
7527
7528 if (!Args.hasFlag(Pos: options::OPT_Qy, Neg: options::OPT_Qn, Default: true))
7529 CmdArgs.push_back(Elt: "-Qn");
7530
7531 // -fno-common is the default, set -fcommon only when that flag is set.
7532 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcommon, Neg: options::OPT_fno_common);
7533
7534 // -fsigned-bitfields is default, and clang doesn't yet support
7535 // -funsigned-bitfields.
7536 if (!Args.hasFlag(Pos: options::OPT_fsigned_bitfields,
7537 Neg: options::OPT_funsigned_bitfields, Default: true))
7538 D.Diag(DiagID: diag::warn_drv_clang_unsupported)
7539 << Args.getLastArg(Ids: options::OPT_funsigned_bitfields)->getAsString(Args);
7540
7541 // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
7542 if (!Args.hasFlag(Pos: options::OPT_ffor_scope, Neg: options::OPT_fno_for_scope, Default: true))
7543 D.Diag(DiagID: diag::err_drv_clang_unsupported)
7544 << Args.getLastArg(Ids: options::OPT_fno_for_scope)->getAsString(Args);
7545
7546 // -finput_charset=UTF-8 is default. Reject others
7547 if (Arg *inputCharset = Args.getLastArg(Ids: options::OPT_finput_charset_EQ)) {
7548 StringRef value = inputCharset->getValue();
7549 if (!value.equals_insensitive(RHS: "utf-8"))
7550 D.Diag(DiagID: diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
7551 << value;
7552 }
7553
7554 // -fexec_charset=UTF-8 is default. Reject others
7555 if (Arg *execCharset = Args.getLastArg(Ids: options::OPT_fexec_charset_EQ)) {
7556 StringRef value = execCharset->getValue();
7557 if (!value.equals_insensitive(RHS: "utf-8"))
7558 D.Diag(DiagID: diag::err_drv_invalid_value) << execCharset->getAsString(Args)
7559 << value;
7560 }
7561
7562 RenderDiagnosticsOptions(D, Args, CmdArgs);
7563
7564 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fasm_blocks,
7565 Neg: options::OPT_fno_asm_blocks);
7566
7567 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_fgnu_inline_asm,
7568 Neg: options::OPT_fno_gnu_inline_asm);
7569
7570 handleVectorizeLoopsArgs(Args, CmdArgs);
7571 handleVectorizeSLPArgs(Args, CmdArgs);
7572
7573 StringRef VecWidth = parseMPreferVectorWidthOption(Diags&: D.getDiags(), Args);
7574 if (!VecWidth.empty())
7575 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-mprefer-vector-width=" + VecWidth));
7576
7577 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fshow_overloads_EQ);
7578 Args.AddLastArg(Output&: CmdArgs,
7579 Ids: options::OPT_fsanitize_undefined_strip_path_components_EQ);
7580
7581 // -fdollars-in-identifiers default varies depending on platform and
7582 // language; only pass if specified.
7583 if (Arg *A = Args.getLastArg(Ids: options::OPT_fdollars_in_identifiers,
7584 Ids: options::OPT_fno_dollars_in_identifiers)) {
7585 if (A->getOption().matches(ID: options::OPT_fdollars_in_identifiers))
7586 CmdArgs.push_back(Elt: "-fdollars-in-identifiers");
7587 else
7588 CmdArgs.push_back(Elt: "-fno-dollars-in-identifiers");
7589 }
7590
7591 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fapple_pragma_pack,
7592 Neg: options::OPT_fno_apple_pragma_pack);
7593
7594 // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
7595 if (willEmitRemarks(Args) && checkRemarksOptions(D, Args, Triple))
7596 renderRemarksOptions(Args, CmdArgs, Triple, Input, Output, JA);
7597
7598 bool RewriteImports = Args.hasFlag(Pos: options::OPT_frewrite_imports,
7599 Neg: options::OPT_fno_rewrite_imports, Default: false);
7600 if (RewriteImports)
7601 CmdArgs.push_back(Elt: "-frewrite-imports");
7602
7603 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fdirectives_only,
7604 Neg: options::OPT_fno_directives_only);
7605
7606 // Enable rewrite includes if the user's asked for it or if we're generating
7607 // diagnostics.
7608 // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
7609 // nice to enable this when doing a crashdump for modules as well.
7610 if (Args.hasFlag(Pos: options::OPT_frewrite_includes,
7611 Neg: options::OPT_fno_rewrite_includes, Default: false) ||
7612 (C.isForDiagnostics() && !HaveModules))
7613 CmdArgs.push_back(Elt: "-frewrite-includes");
7614
7615 if (Args.hasFlag(Pos: options::OPT_fzos_extensions,
7616 Neg: options::OPT_fno_zos_extensions, Default: false))
7617 CmdArgs.push_back(Elt: "-fzos-extensions");
7618 else if (Args.hasArg(Ids: options::OPT_fno_zos_extensions))
7619 CmdArgs.push_back(Elt: "-fno-zos-extensions");
7620
7621 // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
7622 if (Arg *A = Args.getLastArg(Ids: options::OPT_traditional,
7623 Ids: options::OPT_traditional_cpp)) {
7624 if (isa<PreprocessJobAction>(Val: JA))
7625 CmdArgs.push_back(Elt: "-traditional-cpp");
7626 else
7627 D.Diag(DiagID: diag::err_drv_clang_unsupported) << A->getAsString(Args);
7628 }
7629
7630 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dM);
7631 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dD);
7632 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_dI);
7633
7634 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fmax_tokens_EQ);
7635
7636 // Handle serialized diagnostics.
7637 if (Arg *A = Args.getLastArg(Ids: options::OPT__serialize_diags)) {
7638 CmdArgs.push_back(Elt: "-serialize-diagnostic-file");
7639 CmdArgs.push_back(Elt: Args.MakeArgString(Str: A->getValue()));
7640 }
7641
7642 if (Args.hasArg(Ids: options::OPT_fretain_comments_from_system_headers))
7643 CmdArgs.push_back(Elt: "-fretain-comments-from-system-headers");
7644
7645 if (Arg *A = Args.getLastArg(Ids: options::OPT_fextend_variable_liveness_EQ)) {
7646 A->render(Args, Output&: CmdArgs);
7647 } else if (Arg *A = Args.getLastArg(Ids: options::OPT_O_Group);
7648 A && A->containsValue(Value: "g")) {
7649 // Set -fextend-variable-liveness=all by default at -Og.
7650 CmdArgs.push_back(Elt: "-fextend-variable-liveness=all");
7651 }
7652
7653 // Forward -fcomment-block-commands to -cc1.
7654 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fcomment_block_commands);
7655 // Forward -fparse-all-comments to -cc1.
7656 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_fparse_all_comments);
7657
7658 // Turn -fplugin=name.so into -load name.so
7659 for (const Arg *A : Args.filtered(Ids: options::OPT_fplugin_EQ)) {
7660 CmdArgs.push_back(Elt: "-load");
7661 CmdArgs.push_back(Elt: A->getValue());
7662 A->claim();
7663 }
7664
7665 // Turn -fplugin-arg-pluginname-key=value into
7666 // -plugin-arg-pluginname key=value
7667 // GCC has an actual plugin_argument struct with key/value pairs that it
7668 // passes to its plugins, but we don't, so just pass it on as-is.
7669 //
7670 // The syntax for -fplugin-arg- is ambiguous if both plugin name and
7671 // argument key are allowed to contain dashes. GCC therefore only
7672 // allows dashes in the key. We do the same.
7673 for (const Arg *A : Args.filtered(Ids: options::OPT_fplugin_arg)) {
7674 auto ArgValue = StringRef(A->getValue());
7675 auto FirstDashIndex = ArgValue.find(C: '-');
7676 StringRef PluginName = ArgValue.substr(Start: 0, N: FirstDashIndex);
7677 StringRef Arg = ArgValue.substr(Start: FirstDashIndex + 1);
7678
7679 A->claim();
7680 if (FirstDashIndex == StringRef::npos || Arg.empty()) {
7681 if (PluginName.empty()) {
7682 D.Diag(DiagID: diag::warn_drv_missing_plugin_name) << A->getAsString(Args);
7683 } else {
7684 D.Diag(DiagID: diag::warn_drv_missing_plugin_arg)
7685 << PluginName << A->getAsString(Args);
7686 }
7687 continue;
7688 }
7689
7690 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-plugin-arg-") + PluginName));
7691 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Arg));
7692 }
7693
7694 // Forward -fpass-plugin=name.so to -cc1.
7695 for (const Arg *A : Args.filtered(Ids: options::OPT_fpass_plugin_EQ)) {
7696 CmdArgs.push_back(
7697 Elt: Args.MakeArgString(Str: Twine("-fpass-plugin=") + A->getValue()));
7698 A->claim();
7699 }
7700
7701 // Forward --vfsoverlay to -cc1.
7702 for (const Arg *A : Args.filtered(Ids: options::OPT_vfsoverlay)) {
7703 CmdArgs.push_back(Elt: "--vfsoverlay");
7704 CmdArgs.push_back(Elt: A->getValue());
7705 A->claim();
7706 }
7707
7708 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fsafe_buffer_usage_suggestions,
7709 Neg: options::OPT_fno_safe_buffer_usage_suggestions);
7710
7711 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fexperimental_late_parse_attributes,
7712 Neg: options::OPT_fno_experimental_late_parse_attributes);
7713
7714 if (Args.hasFlag(Pos: options::OPT_funique_source_file_names,
7715 Neg: options::OPT_fno_unique_source_file_names, Default: false)) {
7716 if (Arg *A = Args.getLastArg(Ids: options::OPT_unique_source_file_identifier_EQ))
7717 A->render(Args, Output&: CmdArgs);
7718 else
7719 CmdArgs.push_back(Elt: Args.MakeArgString(
7720 Str: Twine("-funique-source-file-identifier=") + Input.getBaseInput()));
7721 }
7722
7723 // Setup statistics file output.
7724 SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
7725 if (!StatsFile.empty()) {
7726 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-stats-file=") + StatsFile));
7727 if (D.CCPrintInternalStats)
7728 CmdArgs.push_back(Elt: "-stats-file-append");
7729 }
7730
7731 // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
7732 // parser.
7733 for (auto Arg : Args.filtered(Ids: options::OPT_Xclang)) {
7734 Arg->claim();
7735 // -finclude-default-header flag is for preprocessor,
7736 // do not pass it to other cc1 commands when save-temps is enabled
7737 if (C.getDriver().isSaveTempsEnabled() &&
7738 !isa<PreprocessJobAction>(Val: JA)) {
7739 if (StringRef(Arg->getValue()) == "-finclude-default-header")
7740 continue;
7741 }
7742 CmdArgs.push_back(Elt: Arg->getValue());
7743 }
7744 for (const Arg *A : Args.filtered(Ids: options::OPT_mllvm)) {
7745 A->claim();
7746
7747 // We translate this by hand to the -cc1 argument, since nightly test uses
7748 // it and developers have been trained to spell it with -mllvm. Both
7749 // spellings are now deprecated and should be removed.
7750 if (StringRef(A->getValue(N: 0)) == "-disable-llvm-optzns") {
7751 CmdArgs.push_back(Elt: "-disable-llvm-optzns");
7752 } else {
7753 A->render(Args, Output&: CmdArgs);
7754 }
7755 }
7756
7757 // This needs to run after -Xclang argument forwarding to pick up the target
7758 // features enabled through -Xclang -target-feature flags.
7759 SanitizeArgs.addArgs(TC, Args, CmdArgs, InputType);
7760
7761 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_falloc_token_max_EQ);
7762
7763#if CLANG_ENABLE_CIR
7764 // Forward -mmlir arguments to to the MLIR option parser.
7765 for (const Arg *A : Args.filtered(options::OPT_mmlir)) {
7766 A->claim();
7767 A->render(Args, CmdArgs);
7768 }
7769#endif // CLANG_ENABLE_CIR
7770
7771 // With -save-temps, we want to save the unoptimized bitcode output from the
7772 // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
7773 // by the frontend.
7774 // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
7775 // has slightly different breakdown between stages.
7776 // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
7777 // pristine IR generated by the frontend. Ideally, a new compile action should
7778 // be added so both IR can be captured.
7779 if ((C.getDriver().isSaveTempsEnabled() ||
7780 JA.isHostOffloading(OKind: Action::OFK_OpenMP)) &&
7781 !(C.getDriver().embedBitcodeInObject() && !IsUsingLTO) &&
7782 isa<CompileJobAction>(Val: JA))
7783 CmdArgs.push_back(Elt: "-disable-llvm-passes");
7784
7785 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_undef);
7786
7787 const char *Exec = D.getClangProgramPath();
7788
7789 // Optionally embed the -cc1 level arguments into the debug info or a
7790 // section, for build analysis.
7791 // Also record command line arguments into the debug info if
7792 // -grecord-gcc-switches options is set on.
7793 // By default, -gno-record-gcc-switches is set on and no recording.
7794 auto GRecordSwitches = false;
7795 auto FRecordSwitches = false;
7796 if (shouldRecordCommandLine(TC, Args, FRecordCommandLine&: FRecordSwitches, GRecordCommandLine&: GRecordSwitches)) {
7797 auto FlagsArgString = renderEscapedCommandLine(TC, Args);
7798 if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
7799 CmdArgs.push_back(Elt: "-dwarf-debug-flags");
7800 CmdArgs.push_back(Elt: FlagsArgString);
7801 }
7802 if (FRecordSwitches) {
7803 CmdArgs.push_back(Elt: "-record-command-line");
7804 CmdArgs.push_back(Elt: FlagsArgString);
7805 }
7806 }
7807
7808 // Host-side offloading compilation receives all device-side outputs. Include
7809 // them in the host compilation depending on the target. If the host inputs
7810 // are not empty we use the new-driver scheme, otherwise use the old scheme.
7811 if ((IsCuda || IsHIP) && CudaDeviceInput) {
7812 CmdArgs.push_back(Elt: "-fcuda-include-gpubinary");
7813 CmdArgs.push_back(Elt: CudaDeviceInput->getFilename());
7814 } else if (!HostOffloadingInputs.empty()) {
7815 if ((IsCuda || IsHIP) && !IsRDCMode) {
7816 assert(HostOffloadingInputs.size() == 1 && "Only one input expected");
7817 CmdArgs.push_back(Elt: "-fcuda-include-gpubinary");
7818 CmdArgs.push_back(Elt: HostOffloadingInputs.front().getFilename());
7819 } else {
7820 for (const InputInfo Input : HostOffloadingInputs)
7821 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-fembed-offload-object=" +
7822 TC.getInputFilename(Input)));
7823 }
7824 }
7825
7826 if (IsCuda) {
7827 if (Args.hasFlag(Pos: options::OPT_fcuda_short_ptr,
7828 Neg: options::OPT_fno_cuda_short_ptr, Default: false))
7829 CmdArgs.push_back(Elt: "-fcuda-short-ptr");
7830 }
7831
7832 if (IsCuda || IsHIP) {
7833 // Determine the original source input.
7834 const Action *SourceAction = &JA;
7835 while (SourceAction->getKind() != Action::InputClass) {
7836 assert(!SourceAction->getInputs().empty() && "unexpected root action!");
7837 SourceAction = SourceAction->getInputs()[0];
7838 }
7839 auto CUID = cast<InputAction>(Val: SourceAction)->getId();
7840 if (!CUID.empty())
7841 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("-cuid=") + Twine(CUID)));
7842
7843 // -ffast-math turns on -fgpu-approx-transcendentals implicitly, but will
7844 // be overriden by -fno-gpu-approx-transcendentals.
7845 bool UseApproxTranscendentals = Args.hasFlag(
7846 Pos: options::OPT_ffast_math, Neg: options::OPT_fno_fast_math, Default: false);
7847 if (Args.hasFlag(Pos: options::OPT_fgpu_approx_transcendentals,
7848 Neg: options::OPT_fno_gpu_approx_transcendentals,
7849 Default: UseApproxTranscendentals))
7850 CmdArgs.push_back(Elt: "-fgpu-approx-transcendentals");
7851 } else {
7852 Args.claimAllArgs(Ids: options::OPT_fgpu_approx_transcendentals,
7853 Ids: options::OPT_fno_gpu_approx_transcendentals);
7854 }
7855
7856 if (IsHIP) {
7857 CmdArgs.push_back(Elt: "-fcuda-allow-variadic-functions");
7858 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_fgpu_default_stream_EQ);
7859 }
7860
7861 Args.AddAllArgs(Output&: CmdArgs,
7862 Id0: options::OPT_fsanitize_undefined_ignore_overflow_pattern_EQ);
7863
7864 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foffload_uniform_block,
7865 Ids: options::OPT_fno_offload_uniform_block);
7866
7867 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_foffload_implicit_host_device_templates,
7868 Ids: options::OPT_fno_offload_implicit_host_device_templates);
7869
7870 if (IsCudaDevice || IsHIPDevice) {
7871 StringRef InlineThresh =
7872 Args.getLastArgValue(Id: options::OPT_fgpu_inline_threshold_EQ);
7873 if (!InlineThresh.empty()) {
7874 std::string ArgStr =
7875 std::string("-inline-threshold=") + InlineThresh.str();
7876 CmdArgs.append(IL: {"-mllvm", Args.MakeArgStringRef(Str: ArgStr)});
7877 }
7878 }
7879
7880 if (IsHIPDevice)
7881 Args.addOptOutFlag(Output&: CmdArgs,
7882 Pos: options::OPT_fhip_fp32_correctly_rounded_divide_sqrt,
7883 Neg: options::OPT_fno_hip_fp32_correctly_rounded_divide_sqrt);
7884
7885 // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
7886 // to specify the result of the compile phase on the host, so the meaningful
7887 // device declarations can be identified. Also, -fopenmp-is-target-device is
7888 // passed along to tell the frontend that it is generating code for a device,
7889 // so that only the relevant declarations are emitted.
7890 if (IsOpenMPDevice) {
7891 CmdArgs.push_back(Elt: "-fopenmp-is-target-device");
7892 // If we are offloading cuda/hip via llvm, it's also "cuda device code".
7893 if (Args.hasArg(Ids: options::OPT_foffload_via_llvm))
7894 CmdArgs.push_back(Elt: "-fcuda-is-device");
7895
7896 if (OpenMPDeviceInput) {
7897 CmdArgs.push_back(Elt: "-fopenmp-host-ir-file-path");
7898 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OpenMPDeviceInput->getFilename()));
7899 }
7900 }
7901
7902 if (Triple.isAMDGPU()) {
7903 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs);
7904
7905 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_munsafe_fp_atomics,
7906 Neg: options::OPT_mno_unsafe_fp_atomics);
7907 Args.addOptOutFlag(Output&: CmdArgs, Pos: options::OPT_mamdgpu_ieee,
7908 Neg: options::OPT_mno_amdgpu_ieee);
7909 }
7910
7911 addOpenMPHostOffloadingArgs(C, JA, Args, CmdArgs);
7912
7913 if (Args.hasFlag(Pos: options::OPT_fdevirtualize_speculatively,
7914 Neg: options::OPT_fno_devirtualize_speculatively,
7915 /*Default value*/ Default: false))
7916 CmdArgs.push_back(Elt: "-fdevirtualize-speculatively");
7917
7918 bool VirtualFunctionElimination =
7919 Args.hasFlag(Pos: options::OPT_fvirtual_function_elimination,
7920 Neg: options::OPT_fno_virtual_function_elimination, Default: false);
7921 if (VirtualFunctionElimination) {
7922 // VFE requires full LTO (currently, this might be relaxed to allow ThinLTO
7923 // in the future).
7924 if (LTOMode != LTOK_Full)
7925 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
7926 << "-fvirtual-function-elimination"
7927 << "-flto=full";
7928
7929 CmdArgs.push_back(Elt: "-fvirtual-function-elimination");
7930 }
7931
7932 // VFE requires whole-program-vtables, and enables it by default.
7933 bool WholeProgramVTables = Args.hasFlag(
7934 Pos: options::OPT_fwhole_program_vtables,
7935 Neg: options::OPT_fno_whole_program_vtables, Default: VirtualFunctionElimination);
7936 if (VirtualFunctionElimination && !WholeProgramVTables) {
7937 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
7938 << "-fno-whole-program-vtables"
7939 << "-fvirtual-function-elimination";
7940 }
7941
7942 if (WholeProgramVTables) {
7943 // PS4 uses the legacy LTO API, which does not support this feature in
7944 // ThinLTO mode.
7945 bool IsPS4 = getToolChain().getTriple().isPS4();
7946
7947 // Check if we passed LTO options but they were suppressed because this is a
7948 // device offloading action, or we passed device offload LTO options which
7949 // were suppressed because this is not the device offload action.
7950 // Check if we are using PS4 in regular LTO mode.
7951 // Otherwise, issue an error.
7952
7953 auto OtherLTOMode =
7954 IsDeviceOffloadAction ? D.getLTOMode() : D.getOffloadLTOMode();
7955 auto OtherIsUsingLTO = OtherLTOMode != LTOK_None;
7956
7957 if ((!IsUsingLTO && !OtherIsUsingLTO) ||
7958 (IsPS4 && !UnifiedLTO && (D.getLTOMode() != LTOK_Full)))
7959 D.Diag(DiagID: diag::err_drv_argument_only_allowed_with)
7960 << "-fwhole-program-vtables"
7961 << ((IsPS4 && !UnifiedLTO) ? "-flto=full" : "-flto");
7962
7963 // Propagate -fwhole-program-vtables if this is an LTO compile.
7964 if (IsUsingLTO)
7965 CmdArgs.push_back(Elt: "-fwhole-program-vtables");
7966 }
7967
7968 bool DefaultsSplitLTOUnit =
7969 ((WholeProgramVTables || SanitizeArgs.needsLTO()) &&
7970 (LTOMode == LTOK_Full || TC.canSplitThinLTOUnit())) ||
7971 (!Triple.isPS4() && UnifiedLTO);
7972 bool SplitLTOUnit =
7973 Args.hasFlag(Pos: options::OPT_fsplit_lto_unit,
7974 Neg: options::OPT_fno_split_lto_unit, Default: DefaultsSplitLTOUnit);
7975 if (SanitizeArgs.needsLTO() && !SplitLTOUnit)
7976 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "-fno-split-lto-unit"
7977 << "-fsanitize=cfi";
7978 if (SplitLTOUnit)
7979 CmdArgs.push_back(Elt: "-fsplit-lto-unit");
7980
7981 if (Arg *A = Args.getLastArg(Ids: options::OPT_ffat_lto_objects,
7982 Ids: options::OPT_fno_fat_lto_objects)) {
7983 if (IsUsingLTO && A->getOption().matches(ID: options::OPT_ffat_lto_objects)) {
7984 assert(LTOMode == LTOK_Full || LTOMode == LTOK_Thin);
7985 if (!Triple.isOSBinFormatELF() && !Triple.isOSBinFormatCOFF()) {
7986 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
7987 << A->getAsString(Args) << TC.getTripleString();
7988 }
7989 CmdArgs.push_back(Elt: Args.MakeArgString(
7990 Str: Twine("-flto=") + (LTOMode == LTOK_Thin ? "thin" : "full")));
7991 CmdArgs.push_back(Elt: "-flto-unit");
7992 CmdArgs.push_back(Elt: "-ffat-lto-objects");
7993 A->render(Args, Output&: CmdArgs);
7994 }
7995 }
7996
7997 renderGlobalISelOptions(D, Args, CmdArgs, Triple);
7998
7999 if (Arg *A = Args.getLastArg(Ids: options::OPT_fforce_enable_int128,
8000 Ids: options::OPT_fno_force_enable_int128)) {
8001 if (A->getOption().matches(ID: options::OPT_fforce_enable_int128))
8002 CmdArgs.push_back(Elt: "-fforce-enable-int128");
8003 }
8004
8005 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_static_consts,
8006 Neg: options::OPT_fno_keep_static_consts);
8007 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fkeep_persistent_storage_variables,
8008 Neg: options::OPT_fno_keep_persistent_storage_variables);
8009 Args.addOptInFlag(Output&: CmdArgs, Pos: options::OPT_fcomplete_member_pointers,
8010 Neg: options::OPT_fno_complete_member_pointers);
8011 if (Arg *A = Args.getLastArg(Ids: options::OPT_cxx_static_destructors_EQ))
8012 A->render(Args, Output&: CmdArgs);
8013
8014 addMachineOutlinerArgs(D, Args, CmdArgs, Triple, /*IsLTO=*/false);
8015
8016 addOutlineAtomicsArgs(D, TC: getToolChain(), Args, CmdArgs, Triple);
8017
8018 if (Triple.isAArch64() &&
8019 (Args.hasArg(Ids: options::OPT_mno_fmv) ||
8020 (Triple.isAndroid() && Triple.isAndroidVersionLT(Major: 23)) ||
8021 getToolChain().GetRuntimeLibType(Args) != ToolChain::RLT_CompilerRT)) {
8022 // Disable Function Multiversioning on AArch64 target.
8023 CmdArgs.push_back(Elt: "-target-feature");
8024 CmdArgs.push_back(Elt: "-fmv");
8025 }
8026
8027 if (Args.hasFlag(Pos: options::OPT_faddrsig, Neg: options::OPT_fno_addrsig,
8028 Default: (TC.getTriple().isOSBinFormatELF() ||
8029 TC.getTriple().isOSBinFormatCOFF()) &&
8030 !TC.getTriple().isPS4() && !TC.getTriple().isVE() &&
8031 !TC.getTriple().isOSNetBSD() &&
8032 !Distro(D.getVFS(), TC.getTriple()).IsGentoo() &&
8033 !TC.getTriple().isAndroid() && TC.useIntegratedAs()))
8034 CmdArgs.push_back(Elt: "-faddrsig");
8035
8036 const bool HasDefaultDwarf2CFIASM =
8037 (Triple.isOSBinFormatELF() || Triple.isOSBinFormatMachO()) &&
8038 (EH || UnwindTables || AsyncUnwindTables ||
8039 DebugInfoKind != llvm::codegenoptions::NoDebugInfo);
8040 if (Args.hasFlag(Pos: options::OPT_fdwarf2_cfi_asm,
8041 Neg: options::OPT_fno_dwarf2_cfi_asm, Default: HasDefaultDwarf2CFIASM))
8042 CmdArgs.push_back(Elt: "-fdwarf2-cfi-asm");
8043
8044 if (Arg *A = Args.getLastArg(Ids: options::OPT_fsymbol_partition_EQ)) {
8045 std::string Str = A->getAsString(Args);
8046 if (!TC.getTriple().isOSBinFormatELF())
8047 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
8048 << Str << TC.getTripleString();
8049 CmdArgs.push_back(Elt: Args.MakeArgString(Str));
8050 }
8051
8052 // Add the "-o out -x type src.c" flags last. This is done primarily to make
8053 // the -cc1 command easier to edit when reproducing compiler crashes.
8054 if (Output.getType() == types::TY_Dependencies) {
8055 // Handled with other dependency code.
8056 } else if (Output.isFilename()) {
8057 if (Output.getType() == clang::driver::types::TY_IFS_CPP ||
8058 Output.getType() == clang::driver::types::TY_IFS) {
8059 SmallString<128> OutputFilename(Output.getFilename());
8060 llvm::sys::path::replace_extension(path&: OutputFilename, extension: "ifs");
8061 CmdArgs.push_back(Elt: "-o");
8062 CmdArgs.push_back(Elt: Args.MakeArgString(Str: OutputFilename));
8063 } else {
8064 CmdArgs.push_back(Elt: "-o");
8065 CmdArgs.push_back(Elt: Output.getFilename());
8066 }
8067 } else {
8068 assert(Output.isNothing() && "Invalid output.");
8069 }
8070
8071 addDashXForInput(Args, Input, CmdArgs);
8072
8073 ArrayRef<InputInfo> FrontendInputs = Input;
8074 if (IsExtractAPI)
8075 FrontendInputs = ExtractAPIInputs;
8076 else if (Input.isNothing())
8077 FrontendInputs = {};
8078
8079 for (const InputInfo &Input : FrontendInputs) {
8080 if (Input.isFilename())
8081 CmdArgs.push_back(Elt: Input.getFilename());
8082 else
8083 Input.getInputArg().renderAsInput(Args, Output&: CmdArgs);
8084 }
8085
8086 if (D.CC1Main && !D.CCGenDiagnostics) {
8087 // Invoke the CC1 directly in this process
8088 C.addCommand(C: std::make_unique<CC1Command>(
8089 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8090 args: Output, args: D.getPrependArg()));
8091 } else {
8092 C.addCommand(C: std::make_unique<Command>(
8093 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8094 args: Output, args: D.getPrependArg()));
8095 }
8096
8097 // Make the compile command echo its inputs for /showFilenames.
8098 if (Output.getType() == types::TY_Object &&
8099 Args.hasFlag(Pos: options::OPT__SLASH_showFilenames,
8100 Neg: options::OPT__SLASH_showFilenames_, Default: false)) {
8101 C.getJobs().getJobs().back()->PrintInputFilenames = true;
8102 }
8103
8104 if (Arg *A = Args.getLastArg(Ids: options::OPT_pg))
8105 if (FPKeepKind == CodeGenOptions::FramePointerKind::None &&
8106 !Args.hasArg(Ids: options::OPT_mfentry))
8107 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
8108 << A->getAsString(Args);
8109
8110 // Claim some arguments which clang supports automatically.
8111
8112 // -fpch-preprocess is used with gcc to add a special marker in the output to
8113 // include the PCH file.
8114 Args.ClaimAllArgs(Id0: options::OPT_fpch_preprocess);
8115
8116 // Claim some arguments which clang doesn't support, but we don't
8117 // care to warn the user about.
8118 Args.ClaimAllArgs(Id0: options::OPT_clang_ignored_f_Group);
8119 Args.ClaimAllArgs(Id0: options::OPT_clang_ignored_m_Group);
8120
8121 // Disable warnings for clang -E -emit-llvm foo.c
8122 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
8123}
8124
8125Clang::Clang(const ToolChain &TC, bool HasIntegratedBackend)
8126 // CAUTION! The first constructor argument ("clang") is not arbitrary,
8127 // as it is for other tools. Some operations on a Tool actually test
8128 // whether that tool is Clang based on the Tool's Name as a string.
8129 : Tool("clang", "clang frontend", TC), HasBackend(HasIntegratedBackend) {}
8130
8131Clang::~Clang() {}
8132
8133/// Add options related to the Objective-C runtime/ABI.
8134///
8135/// Returns true if the runtime is non-fragile.
8136ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
8137 const InputInfoList &inputs,
8138 ArgStringList &cmdArgs,
8139 RewriteKind rewriteKind) const {
8140 // Look for the controlling runtime option.
8141 Arg *runtimeArg =
8142 args.getLastArg(Ids: options::OPT_fnext_runtime, Ids: options::OPT_fgnu_runtime,
8143 Ids: options::OPT_fobjc_runtime_EQ);
8144
8145 // Just forward -fobjc-runtime= to the frontend. This supercedes
8146 // options about fragility.
8147 if (runtimeArg &&
8148 runtimeArg->getOption().matches(ID: options::OPT_fobjc_runtime_EQ)) {
8149 ObjCRuntime runtime;
8150 StringRef value = runtimeArg->getValue();
8151 if (runtime.tryParse(input: value)) {
8152 getToolChain().getDriver().Diag(DiagID: diag::err_drv_unknown_objc_runtime)
8153 << value;
8154 }
8155 if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
8156 (runtime.getVersion() >= VersionTuple(2, 0)))
8157 if (!getToolChain().getTriple().isOSBinFormatELF() &&
8158 !getToolChain().getTriple().isOSBinFormatCOFF()) {
8159 getToolChain().getDriver().Diag(
8160 DiagID: diag::err_drv_gnustep_objc_runtime_incompatible_binary)
8161 << runtime.getVersion().getMajor();
8162 }
8163
8164 runtimeArg->render(Args: args, Output&: cmdArgs);
8165 return runtime;
8166 }
8167
8168 // Otherwise, we'll need the ABI "version". Version numbers are
8169 // slightly confusing for historical reasons:
8170 // 1 - Traditional "fragile" ABI
8171 // 2 - Non-fragile ABI, version 1
8172 // 3 - Non-fragile ABI, version 2
8173 unsigned objcABIVersion = 1;
8174 // If -fobjc-abi-version= is present, use that to set the version.
8175 if (Arg *abiArg = args.getLastArg(Ids: options::OPT_fobjc_abi_version_EQ)) {
8176 StringRef value = abiArg->getValue();
8177 if (value == "1")
8178 objcABIVersion = 1;
8179 else if (value == "2")
8180 objcABIVersion = 2;
8181 else if (value == "3")
8182 objcABIVersion = 3;
8183 else
8184 getToolChain().getDriver().Diag(DiagID: diag::err_drv_clang_unsupported) << value;
8185 } else {
8186 // Otherwise, determine if we are using the non-fragile ABI.
8187 bool nonFragileABIIsDefault =
8188 (rewriteKind == RK_NonFragile ||
8189 (rewriteKind == RK_None &&
8190 getToolChain().IsObjCNonFragileABIDefault()));
8191 if (args.hasFlag(Pos: options::OPT_fobjc_nonfragile_abi,
8192 Neg: options::OPT_fno_objc_nonfragile_abi,
8193 Default: nonFragileABIIsDefault)) {
8194// Determine the non-fragile ABI version to use.
8195#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
8196 unsigned nonFragileABIVersion = 1;
8197#else
8198 unsigned nonFragileABIVersion = 2;
8199#endif
8200
8201 if (Arg *abiArg =
8202 args.getLastArg(Ids: options::OPT_fobjc_nonfragile_abi_version_EQ)) {
8203 StringRef value = abiArg->getValue();
8204 if (value == "1")
8205 nonFragileABIVersion = 1;
8206 else if (value == "2")
8207 nonFragileABIVersion = 2;
8208 else
8209 getToolChain().getDriver().Diag(DiagID: diag::err_drv_clang_unsupported)
8210 << value;
8211 }
8212
8213 objcABIVersion = 1 + nonFragileABIVersion;
8214 } else {
8215 objcABIVersion = 1;
8216 }
8217 }
8218
8219 // We don't actually care about the ABI version other than whether
8220 // it's non-fragile.
8221 bool isNonFragile = objcABIVersion != 1;
8222
8223 // If we have no runtime argument, ask the toolchain for its default runtime.
8224 // However, the rewriter only really supports the Mac runtime, so assume that.
8225 ObjCRuntime runtime;
8226 if (!runtimeArg) {
8227 switch (rewriteKind) {
8228 case RK_None:
8229 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8230 break;
8231 case RK_Fragile:
8232 runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
8233 break;
8234 case RK_NonFragile:
8235 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8236 break;
8237 }
8238
8239 // -fnext-runtime
8240 } else if (runtimeArg->getOption().matches(ID: options::OPT_fnext_runtime)) {
8241 // On Darwin, make this use the default behavior for the toolchain.
8242 if (getToolChain().getTriple().isOSDarwin()) {
8243 runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
8244
8245 // Otherwise, build for a generic macosx port.
8246 } else {
8247 runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
8248 }
8249
8250 // -fgnu-runtime
8251 } else {
8252 assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
8253 // Legacy behaviour is to target the gnustep runtime if we are in
8254 // non-fragile mode or the GCC runtime in fragile mode.
8255 if (isNonFragile)
8256 runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(2, 0));
8257 else
8258 runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
8259 }
8260
8261 if (llvm::any_of(Range: inputs, P: [](const InputInfo &input) {
8262 return types::isObjC(Id: input.getType());
8263 }))
8264 cmdArgs.push_back(
8265 Elt: args.MakeArgString(Str: "-fobjc-runtime=" + runtime.getAsString()));
8266 return runtime;
8267}
8268
8269static bool maybeConsumeDash(const std::string &EH, size_t &I) {
8270 bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
8271 I += HaveDash;
8272 return !HaveDash;
8273}
8274
8275namespace {
8276struct EHFlags {
8277 bool Synch = false;
8278 bool Asynch = false;
8279 bool NoUnwindC = false;
8280};
8281} // end anonymous namespace
8282
8283/// /EH controls whether to run destructor cleanups when exceptions are
8284/// thrown. There are three modifiers:
8285/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
8286/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
8287/// The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
8288/// - c: Assume that extern "C" functions are implicitly nounwind.
8289/// The default is /EHs-c-, meaning cleanups are disabled.
8290static EHFlags parseClangCLEHFlags(const Driver &D, const ArgList &Args,
8291 bool isWindowsMSVC) {
8292 EHFlags EH;
8293
8294 std::vector<std::string> EHArgs =
8295 Args.getAllArgValues(Id: options::OPT__SLASH_EH);
8296 for (const auto &EHVal : EHArgs) {
8297 for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
8298 switch (EHVal[I]) {
8299 case 'a':
8300 EH.Asynch = maybeConsumeDash(EH: EHVal, I);
8301 if (EH.Asynch) {
8302 // Async exceptions are Windows MSVC only.
8303 if (!isWindowsMSVC) {
8304 EH.Asynch = false;
8305 D.Diag(DiagID: clang::diag::warn_drv_unused_argument) << "/EHa" << EHVal;
8306 continue;
8307 }
8308 EH.Synch = false;
8309 }
8310 continue;
8311 case 'c':
8312 EH.NoUnwindC = maybeConsumeDash(EH: EHVal, I);
8313 continue;
8314 case 's':
8315 EH.Synch = maybeConsumeDash(EH: EHVal, I);
8316 if (EH.Synch)
8317 EH.Asynch = false;
8318 continue;
8319 default:
8320 break;
8321 }
8322 D.Diag(DiagID: clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
8323 break;
8324 }
8325 }
8326 // The /GX, /GX- flags are only processed if there are not /EH flags.
8327 // The default is that /GX is not specified.
8328 if (EHArgs.empty() &&
8329 Args.hasFlag(Pos: options::OPT__SLASH_GX, Neg: options::OPT__SLASH_GX_,
8330 /*Default=*/false)) {
8331 EH.Synch = true;
8332 EH.NoUnwindC = true;
8333 }
8334
8335 if (Args.hasArg(Ids: options::OPT__SLASH_kernel)) {
8336 EH.Synch = false;
8337 EH.NoUnwindC = false;
8338 EH.Asynch = false;
8339 }
8340
8341 return EH;
8342}
8343
8344void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
8345 ArgStringList &CmdArgs) const {
8346 bool isNVPTX = getToolChain().getTriple().isNVPTX();
8347
8348 ProcessVSRuntimeLibrary(TC: getToolChain(), Args, CmdArgs);
8349
8350 if (Arg *ShowIncludes =
8351 Args.getLastArg(Ids: options::OPT__SLASH_showIncludes,
8352 Ids: options::OPT__SLASH_showIncludes_user)) {
8353 CmdArgs.push_back(Elt: "--show-includes");
8354 if (ShowIncludes->getOption().matches(ID: options::OPT__SLASH_showIncludes))
8355 CmdArgs.push_back(Elt: "-sys-header-deps");
8356 }
8357
8358 // This controls whether or not we emit RTTI data for polymorphic types.
8359 if (Args.hasFlag(Pos: options::OPT__SLASH_GR_, Neg: options::OPT__SLASH_GR,
8360 /*Default=*/false))
8361 CmdArgs.push_back(Elt: "-fno-rtti-data");
8362
8363 // This controls whether or not we emit stack-protector instrumentation.
8364 // In MSVC, Buffer Security Check (/GS) is on by default.
8365 if (!isNVPTX && Args.hasFlag(Pos: options::OPT__SLASH_GS, Neg: options::OPT__SLASH_GS_,
8366 /*Default=*/true)) {
8367 CmdArgs.push_back(Elt: "-stack-protector");
8368 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine(LangOptions::SSPStrong)));
8369 }
8370
8371 const Driver &D = getToolChain().getDriver();
8372
8373 bool IsWindowsMSVC = getToolChain().getTriple().isWindowsMSVCEnvironment();
8374 EHFlags EH = parseClangCLEHFlags(D, Args, isWindowsMSVC: IsWindowsMSVC);
8375 if (!isNVPTX && (EH.Synch || EH.Asynch)) {
8376 if (types::isCXX(Id: InputType))
8377 CmdArgs.push_back(Elt: "-fcxx-exceptions");
8378 CmdArgs.push_back(Elt: "-fexceptions");
8379 if (EH.Asynch)
8380 CmdArgs.push_back(Elt: "-fasync-exceptions");
8381 }
8382 if (types::isCXX(Id: InputType) && EH.Synch && EH.NoUnwindC)
8383 CmdArgs.push_back(Elt: "-fexternc-nounwind");
8384
8385 // /EP should expand to -E -P.
8386 if (Args.hasArg(Ids: options::OPT__SLASH_EP)) {
8387 CmdArgs.push_back(Elt: "-E");
8388 CmdArgs.push_back(Elt: "-P");
8389 }
8390
8391 if (Args.hasFlag(Pos: options::OPT__SLASH_Zc_dllexportInlines_,
8392 Neg: options::OPT__SLASH_Zc_dllexportInlines,
8393 Default: false)) {
8394 CmdArgs.push_back(Elt: "-fno-dllexport-inlines");
8395 }
8396
8397 if (Args.hasFlag(Pos: options::OPT__SLASH_Zc_wchar_t_,
8398 Neg: options::OPT__SLASH_Zc_wchar_t, Default: false)) {
8399 CmdArgs.push_back(Elt: "-fno-wchar");
8400 }
8401
8402 if (Args.hasArg(Ids: options::OPT__SLASH_kernel)) {
8403 llvm::Triple::ArchType Arch = getToolChain().getArch();
8404 std::vector<std::string> Values =
8405 Args.getAllArgValues(Id: options::OPT__SLASH_arch);
8406 if (!Values.empty()) {
8407 llvm::SmallSet<std::string, 4> SupportedArches;
8408 if (Arch == llvm::Triple::x86)
8409 SupportedArches.insert(V: "IA32");
8410
8411 for (auto &V : Values)
8412 if (!SupportedArches.contains(V))
8413 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
8414 << std::string("/arch:").append(str: V) << "/kernel";
8415 }
8416
8417 CmdArgs.push_back(Elt: "-fno-rtti");
8418 if (Args.hasFlag(Pos: options::OPT__SLASH_GR, Neg: options::OPT__SLASH_GR_, Default: false))
8419 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with) << "/GR"
8420 << "/kernel";
8421 }
8422
8423 if (const Arg *A = Args.getLastArg(Ids: options::OPT__SLASH_vlen,
8424 Ids: options::OPT__SLASH_vlen_EQ_256,
8425 Ids: options::OPT__SLASH_vlen_EQ_512)) {
8426 llvm::Triple::ArchType AT = getToolChain().getArch();
8427 StringRef Default = AT == llvm::Triple::x86 ? "IA32" : "SSE2";
8428 StringRef Arch = Args.getLastArgValue(Id: options::OPT__SLASH_arch, Default);
8429 llvm::SmallSet<StringRef, 4> Arch512 = {"AVX512F", "AVX512", "AVX10.1",
8430 "AVX10.2"};
8431
8432 if (A->getOption().matches(ID: options::OPT__SLASH_vlen_EQ_512)) {
8433 if (Arch512.contains(V: Arch))
8434 CmdArgs.push_back(Elt: "-mprefer-vector-width=512");
8435 else
8436 D.Diag(DiagID: diag::warn_drv_argument_not_allowed_with)
8437 << "/vlen=512" << std::string("/arch:").append(svt: Arch);
8438 } else if (A->getOption().matches(ID: options::OPT__SLASH_vlen_EQ_256)) {
8439 if (Arch512.contains(V: Arch))
8440 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
8441 else if (Arch != "AVX" && Arch != "AVX2")
8442 D.Diag(DiagID: diag::warn_drv_argument_not_allowed_with)
8443 << "/vlen=256" << std::string("/arch:").append(svt: Arch);
8444 } else {
8445 if (Arch == "AVX10.1" || Arch == "AVX10.2")
8446 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
8447 }
8448 } else {
8449 StringRef Arch = Args.getLastArgValue(Id: options::OPT__SLASH_arch);
8450 if (Arch == "AVX10.1" || Arch == "AVX10.2")
8451 CmdArgs.push_back(Elt: "-mprefer-vector-width=256");
8452 }
8453
8454 Arg *MostGeneralArg = Args.getLastArg(Ids: options::OPT__SLASH_vmg);
8455 Arg *BestCaseArg = Args.getLastArg(Ids: options::OPT__SLASH_vmb);
8456 if (MostGeneralArg && BestCaseArg)
8457 D.Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with)
8458 << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
8459
8460 if (MostGeneralArg) {
8461 Arg *SingleArg = Args.getLastArg(Ids: options::OPT__SLASH_vms);
8462 Arg *MultipleArg = Args.getLastArg(Ids: options::OPT__SLASH_vmm);
8463 Arg *VirtualArg = Args.getLastArg(Ids: options::OPT__SLASH_vmv);
8464
8465 Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
8466 Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
8467 if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
8468 D.Diag(DiagID: clang::diag::err_drv_argument_not_allowed_with)
8469 << FirstConflict->getAsString(Args)
8470 << SecondConflict->getAsString(Args);
8471
8472 if (SingleArg)
8473 CmdArgs.push_back(Elt: "-fms-memptr-rep=single");
8474 else if (MultipleArg)
8475 CmdArgs.push_back(Elt: "-fms-memptr-rep=multiple");
8476 else
8477 CmdArgs.push_back(Elt: "-fms-memptr-rep=virtual");
8478 }
8479
8480 if (Args.hasArg(Ids: options::OPT_regcall4))
8481 CmdArgs.push_back(Elt: "-regcall4");
8482
8483 // Parse the default calling convention options.
8484 if (Arg *CCArg =
8485 Args.getLastArg(Ids: options::OPT__SLASH_Gd, Ids: options::OPT__SLASH_Gr,
8486 Ids: options::OPT__SLASH_Gz, Ids: options::OPT__SLASH_Gv,
8487 Ids: options::OPT__SLASH_Gregcall)) {
8488 unsigned DCCOptId = CCArg->getOption().getID();
8489 const char *DCCFlag = nullptr;
8490 bool ArchSupported = !isNVPTX;
8491 llvm::Triple::ArchType Arch = getToolChain().getArch();
8492 switch (DCCOptId) {
8493 case options::OPT__SLASH_Gd:
8494 DCCFlag = "-fdefault-calling-conv=cdecl";
8495 break;
8496 case options::OPT__SLASH_Gr:
8497 ArchSupported = Arch == llvm::Triple::x86;
8498 DCCFlag = "-fdefault-calling-conv=fastcall";
8499 break;
8500 case options::OPT__SLASH_Gz:
8501 ArchSupported = Arch == llvm::Triple::x86;
8502 DCCFlag = "-fdefault-calling-conv=stdcall";
8503 break;
8504 case options::OPT__SLASH_Gv:
8505 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8506 DCCFlag = "-fdefault-calling-conv=vectorcall";
8507 break;
8508 case options::OPT__SLASH_Gregcall:
8509 ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
8510 DCCFlag = "-fdefault-calling-conv=regcall";
8511 break;
8512 }
8513
8514 // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
8515 if (ArchSupported && DCCFlag)
8516 CmdArgs.push_back(Elt: DCCFlag);
8517 }
8518
8519 if (Args.hasArg(Ids: options::OPT__SLASH_Gregcall4))
8520 CmdArgs.push_back(Elt: "-regcall4");
8521
8522 Args.AddLastArg(Output&: CmdArgs, Ids: options::OPT_vtordisp_mode_EQ);
8523
8524 if (!Args.hasArg(Ids: options::OPT_fdiagnostics_format_EQ)) {
8525 CmdArgs.push_back(Elt: "-fdiagnostics-format");
8526 CmdArgs.push_back(Elt: "msvc");
8527 }
8528
8529 if (Args.hasArg(Ids: options::OPT__SLASH_kernel))
8530 CmdArgs.push_back(Elt: "-fms-kernel");
8531
8532 // Unwind v2 (epilog) information for x64 Windows.
8533 if (Args.hasArg(Ids: options::OPT__SLASH_d2epilogunwindrequirev2))
8534 CmdArgs.push_back(Elt: "-fwinx64-eh-unwindv2=required");
8535 else if (Args.hasArg(Ids: options::OPT__SLASH_d2epilogunwind))
8536 CmdArgs.push_back(Elt: "-fwinx64-eh-unwindv2=best-effort");
8537
8538 for (const Arg *A : Args.filtered(Ids: options::OPT__SLASH_guard)) {
8539 StringRef GuardArgs = A->getValue();
8540 // The only valid options are "cf", "cf,nochecks", "cf-", "ehcont" and
8541 // "ehcont-".
8542 if (GuardArgs.equals_insensitive(RHS: "cf")) {
8543 // Emit CFG instrumentation and the table of address-taken functions.
8544 CmdArgs.push_back(Elt: "-cfguard");
8545 } else if (GuardArgs.equals_insensitive(RHS: "cf,nochecks")) {
8546 // Emit only the table of address-taken functions.
8547 CmdArgs.push_back(Elt: "-cfguard-no-checks");
8548 } else if (GuardArgs.equals_insensitive(RHS: "ehcont")) {
8549 // Emit EH continuation table.
8550 CmdArgs.push_back(Elt: "-ehcontguard");
8551 } else if (GuardArgs.equals_insensitive(RHS: "cf-") ||
8552 GuardArgs.equals_insensitive(RHS: "ehcont-")) {
8553 // Do nothing, but we might want to emit a security warning in future.
8554 } else {
8555 D.Diag(DiagID: diag::err_drv_invalid_value) << A->getSpelling() << GuardArgs;
8556 }
8557 A->claim();
8558 }
8559
8560 for (const auto &FuncOverride :
8561 Args.getAllArgValues(Id: options::OPT__SLASH_funcoverride)) {
8562 CmdArgs.push_back(Elt: Args.MakeArgString(
8563 Str: Twine("-loader-replaceable-function=") + FuncOverride));
8564 }
8565}
8566
8567const char *Clang::getBaseInputName(const ArgList &Args,
8568 const InputInfo &Input) {
8569 return Args.MakeArgString(Str: llvm::sys::path::filename(path: Input.getBaseInput()));
8570}
8571
8572const char *Clang::getBaseInputStem(const ArgList &Args,
8573 const InputInfoList &Inputs) {
8574 const char *Str = getBaseInputName(Args, Input: Inputs[0]);
8575
8576 if (const char *End = strrchr(s: Str, c: '.'))
8577 return Args.MakeArgString(Str: std::string(Str, End));
8578
8579 return Str;
8580}
8581
8582const char *Clang::getDependencyFileName(const ArgList &Args,
8583 const InputInfoList &Inputs) {
8584 // FIXME: Think about this more.
8585
8586 if (Arg *OutputOpt = Args.getLastArg(Ids: options::OPT_o)) {
8587 SmallString<128> OutputFilename(OutputOpt->getValue());
8588 llvm::sys::path::replace_extension(path&: OutputFilename, extension: llvm::Twine('d'));
8589 return Args.MakeArgString(Str: OutputFilename);
8590 }
8591
8592 return Args.MakeArgString(Str: Twine(getBaseInputStem(Args, Inputs)) + ".d");
8593}
8594
8595// Begin ClangAs
8596
8597void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
8598 ArgStringList &CmdArgs) const {
8599 StringRef CPUName;
8600 StringRef ABIName;
8601 const llvm::Triple &Triple = getToolChain().getTriple();
8602 mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
8603
8604 CmdArgs.push_back(Elt: "-target-abi");
8605 CmdArgs.push_back(Elt: ABIName.data());
8606}
8607
8608void ClangAs::AddX86TargetArgs(const ArgList &Args,
8609 ArgStringList &CmdArgs) const {
8610 addX86AlignBranchArgs(D: getToolChain().getDriver(), Args, CmdArgs,
8611 /*IsLTO=*/false);
8612
8613 if (Arg *A = Args.getLastArg(Ids: options::OPT_masm_EQ)) {
8614 StringRef Value = A->getValue();
8615 if (Value == "intel" || Value == "att") {
8616 CmdArgs.push_back(Elt: "-mllvm");
8617 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "-x86-asm-syntax=" + Value));
8618 } else {
8619 getToolChain().getDriver().Diag(DiagID: diag::err_drv_unsupported_option_argument)
8620 << A->getSpelling() << Value;
8621 }
8622 }
8623}
8624
8625void ClangAs::AddLoongArchTargetArgs(const ArgList &Args,
8626 ArgStringList &CmdArgs) const {
8627 CmdArgs.push_back(Elt: "-target-abi");
8628 CmdArgs.push_back(Elt: loongarch::getLoongArchABI(D: getToolChain().getDriver(), Args,
8629 Triple: getToolChain().getTriple())
8630 .data());
8631}
8632
8633void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
8634 ArgStringList &CmdArgs) const {
8635 const llvm::Triple &Triple = getToolChain().getTriple();
8636 StringRef ABIName = riscv::getRISCVABI(Args, Triple);
8637
8638 CmdArgs.push_back(Elt: "-target-abi");
8639 CmdArgs.push_back(Elt: ABIName.data());
8640
8641 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
8642 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
8643 CmdArgs.push_back(Elt: "-mllvm");
8644 CmdArgs.push_back(Elt: "-riscv-add-build-attributes");
8645 }
8646}
8647
8648void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
8649 const InputInfo &Output, const InputInfoList &Inputs,
8650 const ArgList &Args,
8651 const char *LinkingOutput) const {
8652 ArgStringList CmdArgs;
8653
8654 assert(Inputs.size() == 1 && "Unexpected number of inputs.");
8655 const InputInfo &Input = Inputs[0];
8656
8657 const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
8658 const std::string &TripleStr = Triple.getTriple();
8659 const auto &D = getToolChain().getDriver();
8660
8661 // Don't warn about "clang -w -c foo.s"
8662 Args.ClaimAllArgs(Id0: options::OPT_w);
8663 // and "clang -emit-llvm -c foo.s"
8664 Args.ClaimAllArgs(Id0: options::OPT_emit_llvm);
8665
8666 claimNoWarnArgs(Args);
8667
8668 // Invoke ourselves in -cc1as mode.
8669 //
8670 // FIXME: Implement custom jobs for internal actions.
8671 CmdArgs.push_back(Elt: "-cc1as");
8672
8673 // Add the "effective" target triple.
8674 CmdArgs.push_back(Elt: "-triple");
8675 CmdArgs.push_back(Elt: Args.MakeArgString(Str: TripleStr));
8676
8677 getToolChain().addClangCC1ASTargetOptions(Args, CC1ASArgs&: CmdArgs);
8678
8679 // Set the output mode, we currently only expect to be used as a real
8680 // assembler.
8681 CmdArgs.push_back(Elt: "-filetype");
8682 CmdArgs.push_back(Elt: "obj");
8683
8684 // Set the main file name, so that debug info works even with
8685 // -save-temps or preprocessed assembly.
8686 CmdArgs.push_back(Elt: "-main-file-name");
8687 CmdArgs.push_back(Elt: Clang::getBaseInputName(Args, Input));
8688
8689 // Add the target cpu
8690 std::string CPU = getCPUName(D, Args, T: Triple, /*FromAs*/ true);
8691 if (!CPU.empty()) {
8692 CmdArgs.push_back(Elt: "-target-cpu");
8693 CmdArgs.push_back(Elt: Args.MakeArgString(Str: CPU));
8694 }
8695
8696 // Add the target features
8697 getTargetFeatures(D, Triple, Args, CmdArgs, ForAS: true);
8698
8699 // Ignore explicit -force_cpusubtype_ALL option.
8700 (void)Args.hasArg(Ids: options::OPT_force__cpusubtype__ALL);
8701
8702 // Pass along any -I options so we get proper .include search paths.
8703 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_I_Group);
8704
8705 // Pass along any --embed-dir or similar options so we get proper embed paths.
8706 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_embed_dir_EQ);
8707
8708 // Determine the original source input.
8709 auto FindSource = [](const Action *S) -> const Action * {
8710 while (S->getKind() != Action::InputClass) {
8711 assert(!S->getInputs().empty() && "unexpected root action!");
8712 S = S->getInputs()[0];
8713 }
8714 return S;
8715 };
8716 const Action *SourceAction = FindSource(&JA);
8717
8718 // Forward -g and handle debug info related flags, assuming we are dealing
8719 // with an actual assembly file.
8720 bool WantDebug = false;
8721 Args.ClaimAllArgs(Id0: options::OPT_g_Group);
8722 if (Arg *A = Args.getLastArg(Ids: options::OPT_g_Group))
8723 WantDebug = !A->getOption().matches(ID: options::OPT_g0) &&
8724 !A->getOption().matches(ID: options::OPT_ggdb0);
8725
8726 // If a -gdwarf argument appeared, remember it.
8727 bool EmitDwarf = false;
8728 if (const Arg *A = getDwarfNArg(Args))
8729 EmitDwarf = checkDebugInfoOption(A, Args, D, TC: getToolChain());
8730
8731 bool EmitCodeView = false;
8732 if (const Arg *A = Args.getLastArg(Ids: options::OPT_gcodeview))
8733 EmitCodeView = checkDebugInfoOption(A, Args, D, TC: getToolChain());
8734
8735 // If the user asked for debug info but did not explicitly specify -gcodeview
8736 // or -gdwarf, ask the toolchain for the default format.
8737 if (!EmitCodeView && !EmitDwarf && WantDebug) {
8738 switch (getToolChain().getDefaultDebugFormat()) {
8739 case llvm::codegenoptions::DIF_CodeView:
8740 EmitCodeView = true;
8741 break;
8742 case llvm::codegenoptions::DIF_DWARF:
8743 EmitDwarf = true;
8744 break;
8745 }
8746 }
8747
8748 // If the arguments don't imply DWARF, don't emit any debug info here.
8749 if (!EmitDwarf)
8750 WantDebug = false;
8751
8752 llvm::codegenoptions::DebugInfoKind DebugInfoKind =
8753 llvm::codegenoptions::NoDebugInfo;
8754
8755 // Add the -fdebug-compilation-dir flag if needed.
8756 const char *DebugCompilationDir =
8757 addDebugCompDirArg(Args, CmdArgs, VFS: C.getDriver().getVFS());
8758
8759 if (SourceAction->getType() == types::TY_Asm ||
8760 SourceAction->getType() == types::TY_PP_Asm) {
8761 // You might think that it would be ok to set DebugInfoKind outside of
8762 // the guard for source type, however there is a test which asserts
8763 // that some assembler invocation receives no -debug-info-kind,
8764 // and it's not clear whether that test is just overly restrictive.
8765 DebugInfoKind = (WantDebug ? llvm::codegenoptions::DebugInfoConstructor
8766 : llvm::codegenoptions::NoDebugInfo);
8767
8768 addDebugPrefixMapArg(D: getToolChain().getDriver(), TC: getToolChain(), Args,
8769 CmdArgs);
8770
8771 // Set the AT_producer to the clang version when using the integrated
8772 // assembler on assembly source files.
8773 CmdArgs.push_back(Elt: "-dwarf-debug-producer");
8774 CmdArgs.push_back(Elt: Args.MakeArgString(Str: getClangFullVersion()));
8775
8776 // And pass along -I options
8777 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_I);
8778 }
8779 const unsigned DwarfVersion = getDwarfVersion(TC: getToolChain(), Args);
8780 RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
8781 DebuggerTuning: llvm::DebuggerKind::Default);
8782 renderDwarfFormat(D, T: Triple, Args, CmdArgs, DwarfVersion);
8783 RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC: getToolChain());
8784
8785 // Handle -fPIC et al -- the relocation-model affects the assembler
8786 // for some targets.
8787 llvm::Reloc::Model RelocationModel;
8788 unsigned PICLevel;
8789 bool IsPIE;
8790 std::tie(args&: RelocationModel, args&: PICLevel, args&: IsPIE) =
8791 ParsePICArgs(ToolChain: getToolChain(), Args);
8792
8793 const char *RMName = RelocationModelName(Model: RelocationModel);
8794 if (RMName) {
8795 CmdArgs.push_back(Elt: "-mrelocation-model");
8796 CmdArgs.push_back(Elt: RMName);
8797 }
8798
8799 // Optionally embed the -cc1as level arguments into the debug info, for build
8800 // analysis.
8801 if (getToolChain().UseDwarfDebugFlags()) {
8802 ArgStringList OriginalArgs;
8803 for (const auto &Arg : Args)
8804 Arg->render(Args, Output&: OriginalArgs);
8805
8806 SmallString<256> Flags;
8807 const char *Exec = getToolChain().getDriver().getClangProgramPath();
8808 escapeSpacesAndBackslashes(Arg: Exec, Res&: Flags);
8809 for (const char *OriginalArg : OriginalArgs) {
8810 SmallString<128> EscapedArg;
8811 escapeSpacesAndBackslashes(Arg: OriginalArg, Res&: EscapedArg);
8812 Flags += " ";
8813 Flags += EscapedArg;
8814 }
8815 CmdArgs.push_back(Elt: "-dwarf-debug-flags");
8816 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Flags));
8817 }
8818
8819 // FIXME: Add -static support, once we have it.
8820
8821 // Add target specific flags.
8822 switch (getToolChain().getArch()) {
8823 default:
8824 break;
8825
8826 case llvm::Triple::mips:
8827 case llvm::Triple::mipsel:
8828 case llvm::Triple::mips64:
8829 case llvm::Triple::mips64el:
8830 AddMIPSTargetArgs(Args, CmdArgs);
8831 break;
8832
8833 case llvm::Triple::x86:
8834 case llvm::Triple::x86_64:
8835 AddX86TargetArgs(Args, CmdArgs);
8836 break;
8837
8838 case llvm::Triple::arm:
8839 case llvm::Triple::armeb:
8840 case llvm::Triple::thumb:
8841 case llvm::Triple::thumbeb:
8842 // This isn't in AddARMTargetArgs because we want to do this for assembly
8843 // only, not C/C++.
8844 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
8845 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
8846 CmdArgs.push_back(Elt: "-mllvm");
8847 CmdArgs.push_back(Elt: "-arm-add-build-attributes");
8848 }
8849 break;
8850
8851 case llvm::Triple::aarch64:
8852 case llvm::Triple::aarch64_32:
8853 case llvm::Triple::aarch64_be:
8854 if (Args.hasArg(Ids: options::OPT_mmark_bti_property)) {
8855 CmdArgs.push_back(Elt: "-mllvm");
8856 CmdArgs.push_back(Elt: "-aarch64-mark-bti-property");
8857 }
8858 break;
8859
8860 case llvm::Triple::loongarch32:
8861 case llvm::Triple::loongarch64:
8862 AddLoongArchTargetArgs(Args, CmdArgs);
8863 break;
8864
8865 case llvm::Triple::riscv32:
8866 case llvm::Triple::riscv64:
8867 AddRISCVTargetArgs(Args, CmdArgs);
8868 break;
8869
8870 case llvm::Triple::hexagon:
8871 if (Args.hasFlag(Pos: options::OPT_mdefault_build_attributes,
8872 Neg: options::OPT_mno_default_build_attributes, Default: true)) {
8873 CmdArgs.push_back(Elt: "-mllvm");
8874 CmdArgs.push_back(Elt: "-hexagon-add-build-attributes");
8875 }
8876 break;
8877 }
8878
8879 // Consume all the warning flags. Usually this would be handled more
8880 // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
8881 // doesn't handle that so rather than warning about unused flags that are
8882 // actually used, we'll lie by omission instead.
8883 // FIXME: Stop lying and consume only the appropriate driver flags
8884 Args.ClaimAllArgs(Id0: options::OPT_W_Group);
8885
8886 CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
8887 D: getToolChain().getDriver());
8888
8889 // Forward -Xclangas arguments to -cc1as
8890 for (auto Arg : Args.filtered(Ids: options::OPT_Xclangas)) {
8891 Arg->claim();
8892 CmdArgs.push_back(Elt: Arg->getValue());
8893 }
8894
8895 Args.AddAllArgs(Output&: CmdArgs, Id0: options::OPT_mllvm);
8896
8897 if (DebugInfoKind > llvm::codegenoptions::NoDebugInfo && Output.isFilename())
8898 addDebugObjectName(Args, CmdArgs, DebugCompilationDir,
8899 OutputFileName: Output.getFilename());
8900
8901 // Fixup any previous commands that use -object-file-name because when we
8902 // generated them, the final .obj name wasn't yet known.
8903 for (Command &J : C.getJobs()) {
8904 if (SourceAction != FindSource(&J.getSource()))
8905 continue;
8906 auto &JArgs = J.getArguments();
8907 for (unsigned I = 0; I < JArgs.size(); ++I) {
8908 if (StringRef(JArgs[I]).starts_with(Prefix: "-object-file-name=") &&
8909 Output.isFilename()) {
8910 ArgStringList NewArgs(JArgs.begin(), JArgs.begin() + I);
8911 addDebugObjectName(Args, CmdArgs&: NewArgs, DebugCompilationDir,
8912 OutputFileName: Output.getFilename());
8913 NewArgs.append(in_start: JArgs.begin() + I + 1, in_end: JArgs.end());
8914 J.replaceArguments(List: NewArgs);
8915 break;
8916 }
8917 }
8918 }
8919
8920 assert(Output.isFilename() && "Unexpected lipo output.");
8921 CmdArgs.push_back(Elt: "-o");
8922 CmdArgs.push_back(Elt: Output.getFilename());
8923
8924 const llvm::Triple &T = getToolChain().getTriple();
8925 Arg *A;
8926 if (getDebugFissionKind(D, Args, Arg&: A) == DwarfFissionKind::Split &&
8927 T.isOSBinFormatELF()) {
8928 CmdArgs.push_back(Elt: "-split-dwarf-output");
8929 CmdArgs.push_back(Elt: SplitDebugName(JA, Args, Input, Output));
8930 }
8931
8932 if (Triple.isAMDGPU())
8933 handleAMDGPUCodeObjectVersionOptions(D, Args, CmdArgs, /*IsCC1As=*/true);
8934
8935 assert(Input.isFilename() && "Invalid input.");
8936 CmdArgs.push_back(Elt: Input.getFilename());
8937
8938 const char *Exec = getToolChain().getDriver().getClangProgramPath();
8939 if (D.CC1Main && !D.CCGenDiagnostics) {
8940 // Invoke cc1as directly in this process.
8941 C.addCommand(C: std::make_unique<CC1Command>(
8942 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8943 args: Output, args: D.getPrependArg()));
8944 } else {
8945 C.addCommand(C: std::make_unique<Command>(
8946 args: JA, args: *this, args: ResponseFileSupport::AtFileUTF8(), args&: Exec, args&: CmdArgs, args: Inputs,
8947 args: Output, args: D.getPrependArg()));
8948 }
8949}
8950
8951// Begin OffloadBundler
8952void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
8953 const InputInfo &Output,
8954 const InputInfoList &Inputs,
8955 const llvm::opt::ArgList &TCArgs,
8956 const char *LinkingOutput) const {
8957 // The version with only one output is expected to refer to a bundling job.
8958 assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
8959
8960 // The bundling command looks like this:
8961 // clang-offload-bundler -type=bc
8962 // -targets=host-triple,openmp-triple1,openmp-triple2
8963 // -output=output_file
8964 // -input=unbundle_file_host
8965 // -input=unbundle_file_tgt1
8966 // -input=unbundle_file_tgt2
8967
8968 ArgStringList CmdArgs;
8969
8970 // Get the type.
8971 CmdArgs.push_back(Elt: TCArgs.MakeArgString(
8972 Str: Twine("-type=") + types::getTypeTempSuffix(Id: Output.getType())));
8973
8974 assert(JA.getInputs().size() == Inputs.size() &&
8975 "Not have inputs for all dependence actions??");
8976
8977 // Get the targets.
8978 SmallString<128> Triples;
8979 Triples += "-targets=";
8980 for (unsigned I = 0; I < Inputs.size(); ++I) {
8981 if (I)
8982 Triples += ',';
8983
8984 // Find ToolChain for this input.
8985 Action::OffloadKind CurKind = Action::OFK_Host;
8986 const ToolChain *CurTC = &getToolChain();
8987 const Action *CurDep = JA.getInputs()[I];
8988
8989 if (const auto *OA = dyn_cast<OffloadAction>(Val: CurDep)) {
8990 CurTC = nullptr;
8991 OA->doOnEachDependence(Work: [&](Action *A, const ToolChain *TC, const char *) {
8992 assert(CurTC == nullptr && "Expected one dependence!");
8993 CurKind = A->getOffloadingDeviceKind();
8994 CurTC = TC;
8995 });
8996 }
8997 Triples += Action::GetOffloadKindName(Kind: CurKind);
8998 Triples += '-';
8999 Triples +=
9000 CurTC->getTriple().normalize(Form: llvm::Triple::CanonicalForm::FOUR_IDENT);
9001 if ((CurKind == Action::OFK_HIP || CurKind == Action::OFK_Cuda) &&
9002 !StringRef(CurDep->getOffloadingArch()).empty()) {
9003 Triples += '-';
9004 Triples += CurDep->getOffloadingArch();
9005 }
9006
9007 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
9008 // with each toolchain.
9009 StringRef GPUArchName;
9010 if (CurKind == Action::OFK_OpenMP) {
9011 // Extract GPUArch from -march argument in TC argument list.
9012 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
9013 auto ArchStr = StringRef(TCArgs.getArgString(Index: ArgIndex));
9014 auto Arch = ArchStr.starts_with_insensitive(Prefix: "-march=");
9015 if (Arch) {
9016 GPUArchName = ArchStr.substr(Start: 7);
9017 Triples += "-";
9018 break;
9019 }
9020 }
9021 Triples += GPUArchName.str();
9022 }
9023 }
9024 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: Triples));
9025
9026 // Get bundled file command.
9027 CmdArgs.push_back(
9028 Elt: TCArgs.MakeArgString(Str: Twine("-output=") + Output.getFilename()));
9029
9030 // Get unbundled files command.
9031 for (unsigned I = 0; I < Inputs.size(); ++I) {
9032 SmallString<128> UB;
9033 UB += "-input=";
9034
9035 // Find ToolChain for this input.
9036 const ToolChain *CurTC = &getToolChain();
9037 if (const auto *OA = dyn_cast<OffloadAction>(Val: JA.getInputs()[I])) {
9038 CurTC = nullptr;
9039 OA->doOnEachDependence(Work: [&](Action *, const ToolChain *TC, const char *) {
9040 assert(CurTC == nullptr && "Expected one dependence!");
9041 CurTC = TC;
9042 });
9043 UB += C.addTempFile(
9044 Name: C.getArgs().MakeArgString(Str: CurTC->getInputFilename(Input: Inputs[I])));
9045 } else {
9046 UB += CurTC->getInputFilename(Input: Inputs[I]);
9047 }
9048 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: UB));
9049 }
9050 addOffloadCompressArgs(TCArgs, CmdArgs);
9051 // All the inputs are encoded as commands.
9052 C.addCommand(C: std::make_unique<Command>(
9053 args: JA, args: *this, args: ResponseFileSupport::None(),
9054 args: TCArgs.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9055 args&: CmdArgs, args: ArrayRef<InputInfo>(), args: Output));
9056}
9057
9058void OffloadBundler::ConstructJobMultipleOutputs(
9059 Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
9060 const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
9061 const char *LinkingOutput) const {
9062 // The version with multiple outputs is expected to refer to a unbundling job.
9063 auto &UA = cast<OffloadUnbundlingJobAction>(Val: JA);
9064
9065 // The unbundling command looks like this:
9066 // clang-offload-bundler -type=bc
9067 // -targets=host-triple,openmp-triple1,openmp-triple2
9068 // -input=input_file
9069 // -output=unbundle_file_host
9070 // -output=unbundle_file_tgt1
9071 // -output=unbundle_file_tgt2
9072 // -unbundle
9073
9074 ArgStringList CmdArgs;
9075
9076 assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
9077 InputInfo Input = Inputs.front();
9078
9079 // Get the type.
9080 CmdArgs.push_back(Elt: TCArgs.MakeArgString(
9081 Str: Twine("-type=") + types::getTypeTempSuffix(Id: Input.getType())));
9082
9083 // Get the targets.
9084 SmallString<128> Triples;
9085 Triples += "-targets=";
9086 auto DepInfo = UA.getDependentActionsInfo();
9087 for (unsigned I = 0; I < DepInfo.size(); ++I) {
9088 if (I)
9089 Triples += ',';
9090
9091 auto &Dep = DepInfo[I];
9092 Triples += Action::GetOffloadKindName(Kind: Dep.DependentOffloadKind);
9093 Triples += '-';
9094 Triples += Dep.DependentToolChain->getTriple().normalize(
9095 Form: llvm::Triple::CanonicalForm::FOUR_IDENT);
9096 if ((Dep.DependentOffloadKind == Action::OFK_HIP ||
9097 Dep.DependentOffloadKind == Action::OFK_Cuda) &&
9098 !Dep.DependentBoundArch.empty()) {
9099 Triples += '-';
9100 Triples += Dep.DependentBoundArch;
9101 }
9102 // TODO: Replace parsing of -march flag. Can be done by storing GPUArch
9103 // with each toolchain.
9104 StringRef GPUArchName;
9105 if (Dep.DependentOffloadKind == Action::OFK_OpenMP) {
9106 // Extract GPUArch from -march argument in TC argument list.
9107 for (unsigned ArgIndex = 0; ArgIndex < TCArgs.size(); ArgIndex++) {
9108 StringRef ArchStr = StringRef(TCArgs.getArgString(Index: ArgIndex));
9109 auto Arch = ArchStr.starts_with_insensitive(Prefix: "-march=");
9110 if (Arch) {
9111 GPUArchName = ArchStr.substr(Start: 7);
9112 Triples += "-";
9113 break;
9114 }
9115 }
9116 Triples += GPUArchName.str();
9117 }
9118 }
9119
9120 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: Triples));
9121
9122 // Get bundled file command.
9123 CmdArgs.push_back(
9124 Elt: TCArgs.MakeArgString(Str: Twine("-input=") + Input.getFilename()));
9125
9126 // Get unbundled files command.
9127 for (unsigned I = 0; I < Outputs.size(); ++I) {
9128 SmallString<128> UB;
9129 UB += "-output=";
9130 UB += DepInfo[I].DependentToolChain->getInputFilename(Input: Outputs[I]);
9131 CmdArgs.push_back(Elt: TCArgs.MakeArgString(Str: UB));
9132 }
9133 CmdArgs.push_back(Elt: "-unbundle");
9134 CmdArgs.push_back(Elt: "-allow-missing-bundles");
9135 if (TCArgs.hasArg(Ids: options::OPT_v))
9136 CmdArgs.push_back(Elt: "-verbose");
9137
9138 // All the inputs are encoded as commands.
9139 C.addCommand(C: std::make_unique<Command>(
9140 args: JA, args: *this, args: ResponseFileSupport::None(),
9141 args: TCArgs.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9142 args&: CmdArgs, args: ArrayRef<InputInfo>(), args: Outputs));
9143}
9144
9145void OffloadPackager::ConstructJob(Compilation &C, const JobAction &JA,
9146 const InputInfo &Output,
9147 const InputInfoList &Inputs,
9148 const llvm::opt::ArgList &Args,
9149 const char *LinkingOutput) const {
9150 ArgStringList CmdArgs;
9151
9152 // Add the output file name.
9153 assert(Output.isFilename() && "Invalid output.");
9154 CmdArgs.push_back(Elt: "-o");
9155 CmdArgs.push_back(Elt: Output.getFilename());
9156
9157 // Create the inputs to bundle the needed metadata.
9158 for (const InputInfo &Input : Inputs) {
9159 const Action *OffloadAction = Input.getAction();
9160 const ToolChain *TC = OffloadAction->getOffloadingToolChain();
9161 const ArgList &TCArgs =
9162 C.getArgsForToolChain(TC, BoundArch: OffloadAction->getOffloadingArch(),
9163 DeviceOffloadKind: OffloadAction->getOffloadingDeviceKind());
9164 StringRef File = C.getArgs().MakeArgString(Str: TC->getInputFilename(Input));
9165 StringRef Arch = OffloadAction->getOffloadingArch()
9166 ? OffloadAction->getOffloadingArch()
9167 : TCArgs.getLastArgValue(Id: options::OPT_march_EQ);
9168 StringRef Kind =
9169 Action::GetOffloadKindName(Kind: OffloadAction->getOffloadingDeviceKind());
9170
9171 ArgStringList Features;
9172 SmallVector<StringRef> FeatureArgs;
9173 getTargetFeatures(D: TC->getDriver(), Triple: TC->getTriple(), Args: TCArgs, CmdArgs&: Features,
9174 ForAS: false);
9175 llvm::copy_if(Range&: Features, Out: std::back_inserter(x&: FeatureArgs),
9176 P: [](StringRef Arg) { return !Arg.starts_with(Prefix: "-target"); });
9177
9178 // TODO: We need to pass in the full target-id and handle it properly in the
9179 // linker wrapper.
9180 SmallVector<std::string> Parts{
9181 "file=" + File.str(),
9182 "triple=" + TC->getTripleString(),
9183 "arch=" + (Arch.empty() ? "generic" : Arch.str()),
9184 "kind=" + Kind.str(),
9185 };
9186
9187 if (TC->getDriver().isUsingOffloadLTO())
9188 for (StringRef Feature : FeatureArgs)
9189 Parts.emplace_back(Args: "feature=" + Feature.str());
9190
9191 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--image=" + llvm::join(R&: Parts, Separator: ",")));
9192 }
9193
9194 C.addCommand(C: std::make_unique<Command>(
9195 args: JA, args: *this, args: ResponseFileSupport::None(),
9196 args: Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: getShortName())),
9197 args&: CmdArgs, args: Inputs, args: Output));
9198}
9199
9200void LinkerWrapper::ConstructJob(Compilation &C, const JobAction &JA,
9201 const InputInfo &Output,
9202 const InputInfoList &Inputs,
9203 const ArgList &Args,
9204 const char *LinkingOutput) const {
9205 using namespace options;
9206
9207 // A list of permitted options that will be forwarded to the embedded device
9208 // compilation job.
9209 const llvm::DenseSet<unsigned> CompilerOptions{
9210 OPT_v,
9211 OPT_cuda_path_EQ,
9212 OPT_rocm_path_EQ,
9213 OPT_O_Group,
9214 OPT_g_Group,
9215 OPT_g_flags_Group,
9216 OPT_R_value_Group,
9217 OPT_R_Group,
9218 OPT_Xcuda_ptxas,
9219 OPT_ftime_report,
9220 OPT_ftime_trace,
9221 OPT_ftime_trace_EQ,
9222 OPT_ftime_trace_granularity_EQ,
9223 OPT_ftime_trace_verbose,
9224 OPT_opt_record_file,
9225 OPT_opt_record_format,
9226 OPT_opt_record_passes,
9227 OPT_fsave_optimization_record,
9228 OPT_fsave_optimization_record_EQ,
9229 OPT_fno_save_optimization_record,
9230 OPT_foptimization_record_file_EQ,
9231 OPT_foptimization_record_passes_EQ,
9232 OPT_save_temps,
9233 OPT_save_temps_EQ,
9234 OPT_mcode_object_version_EQ,
9235 OPT_load,
9236 OPT_fno_lto,
9237 OPT_flto,
9238 OPT_flto_partitions_EQ,
9239 OPT_flto_EQ,
9240 OPT_use_spirv_backend};
9241
9242 const llvm::DenseSet<unsigned> LinkerOptions{OPT_mllvm, OPT_Zlinker_input};
9243 auto ShouldForwardForToolChain = [&](Arg *A, const ToolChain &TC) {
9244 // Don't forward -mllvm to toolchains that don't support LLVM.
9245 return TC.HasNativeLLVMSupport() || A->getOption().getID() != OPT_mllvm;
9246 };
9247 auto ShouldForward = [&](const llvm::DenseSet<unsigned> &Set, Arg *A,
9248 const ToolChain &TC) {
9249 // CMake hack to avoid printing verbose informatoin for HIP non-RDC mode.
9250 if (A->getOption().matches(ID: OPT_v) && JA.getType() == types::TY_HIP_FATBIN)
9251 return false;
9252 return (Set.contains(V: A->getOption().getID()) ||
9253 (A->getOption().getGroup().isValid() &&
9254 Set.contains(V: A->getOption().getGroup().getID()))) &&
9255 ShouldForwardForToolChain(A, TC);
9256 };
9257
9258 ArgStringList CmdArgs;
9259 for (Action::OffloadKind Kind : {Action::OFK_Cuda, Action::OFK_OpenMP,
9260 Action::OFK_HIP, Action::OFK_SYCL}) {
9261 auto TCRange = C.getOffloadToolChains(Kind);
9262 for (auto &I : llvm::make_range(p: TCRange)) {
9263 const ToolChain *TC = I.second;
9264
9265 // We do not use a bound architecture here so options passed only to a
9266 // specific architecture via -Xarch_<cpu> will not be forwarded.
9267 ArgStringList CompilerArgs;
9268 ArgStringList LinkerArgs;
9269 const DerivedArgList &ToolChainArgs =
9270 C.getArgsForToolChain(TC, /*BoundArch=*/"", DeviceOffloadKind: Kind);
9271 for (Arg *A : ToolChainArgs) {
9272 if (A->getOption().matches(ID: OPT_Zlinker_input))
9273 LinkerArgs.emplace_back(Args: A->getValue());
9274 else if (ShouldForward(CompilerOptions, A, *TC))
9275 A->render(Args, Output&: CompilerArgs);
9276 else if (ShouldForward(LinkerOptions, A, *TC))
9277 A->render(Args, Output&: LinkerArgs);
9278 }
9279
9280 // If the user explicitly requested it via `--offload-arch` we should
9281 // extract it from any static libraries if present.
9282 for (StringRef Arg : ToolChainArgs.getAllArgValues(Id: OPT_offload_arch_EQ))
9283 CmdArgs.emplace_back(Args: Args.MakeArgString(Str: "--should-extract=" + Arg));
9284
9285 // If this is OpenMP the device linker will need `-lompdevice`.
9286 if (Kind == Action::OFK_OpenMP && !Args.hasArg(Ids: OPT_no_offloadlib) &&
9287 (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
9288 LinkerArgs.emplace_back(Args: "-lompdevice");
9289
9290 // Forward all of these to the appropriate toolchain.
9291 for (StringRef Arg : CompilerArgs)
9292 CmdArgs.push_back(Elt: Args.MakeArgString(
9293 Str: "--device-compiler=" + TC->getTripleString() + "=" + Arg));
9294 for (StringRef Arg : LinkerArgs)
9295 CmdArgs.push_back(Elt: Args.MakeArgString(
9296 Str: "--device-linker=" + TC->getTripleString() + "=" + Arg));
9297
9298 // Forward the LTO mode relying on the Driver's parsing.
9299 if (C.getDriver().getOffloadLTOMode() == LTOK_Full)
9300 CmdArgs.push_back(Elt: Args.MakeArgString(
9301 Str: "--device-compiler=" + TC->getTripleString() + "=-flto=full"));
9302 else if (C.getDriver().getOffloadLTOMode() == LTOK_Thin) {
9303 CmdArgs.push_back(Elt: Args.MakeArgString(
9304 Str: "--device-compiler=" + TC->getTripleString() + "=-flto=thin"));
9305 if (TC->getTriple().isAMDGPU()) {
9306 CmdArgs.push_back(
9307 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9308 "=-plugin-opt=-force-import-all"));
9309 CmdArgs.push_back(
9310 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9311 "=-plugin-opt=-avail-extern-to-local"));
9312 CmdArgs.push_back(Elt: Args.MakeArgString(
9313 Str: "--device-linker=" + TC->getTripleString() +
9314 "=-plugin-opt=-avail-extern-gv-in-addrspace-to-local=3"));
9315 if (Kind == Action::OFK_OpenMP) {
9316 CmdArgs.push_back(
9317 Elt: Args.MakeArgString(Str: "--device-linker=" + TC->getTripleString() +
9318 "=-plugin-opt=-amdgpu-internalize-symbols"));
9319 }
9320 }
9321 }
9322 }
9323 }
9324
9325 CmdArgs.push_back(
9326 Elt: Args.MakeArgString(Str: "--host-triple=" + getToolChain().getTripleString()));
9327
9328 // CMake hack, suppress passing verbose arguments for the special-case HIP
9329 // non-RDC mode compilation. This confuses default CMake implicit linker
9330 // argument parsing when the language is set to HIP and the system linker is
9331 // also `ld.lld`.
9332 if (Args.hasArg(Ids: options::OPT_v) && JA.getType() != types::TY_HIP_FATBIN)
9333 CmdArgs.push_back(Elt: "--wrapper-verbose");
9334 if (Arg *A = Args.getLastArg(Ids: options::OPT_cuda_path_EQ))
9335 CmdArgs.push_back(
9336 Elt: Args.MakeArgString(Str: Twine("--cuda-path=") + A->getValue()));
9337
9338 // Construct the link job so we can wrap around it.
9339 Linker->ConstructJob(C, JA, Output, Inputs, TCArgs: Args, LinkingOutput);
9340 const auto &LinkCommand = C.getJobs().getJobs().back();
9341
9342 // Forward -Xoffload-{compiler,linker}<-triple> arguments to the linker
9343 // wrapper.
9344 for (Arg *A :
9345 Args.filtered(Ids: options::OPT_Xoffload_compiler, Ids: OPT_Xoffload_linker)) {
9346 StringRef Val = A->getValue(N: 0);
9347 bool IsLinkJob = A->getOption().getID() == OPT_Xoffload_linker;
9348 auto WrapperOption =
9349 IsLinkJob ? Twine("--device-linker=") : Twine("--device-compiler=");
9350 if (Val.empty())
9351 CmdArgs.push_back(Elt: Args.MakeArgString(Str: WrapperOption + A->getValue(N: 1)));
9352 else
9353 CmdArgs.push_back(Elt: Args.MakeArgString(
9354 Str: WrapperOption +
9355 ToolChain::getOpenMPTriple(TripleStr: Val.drop_front()).getTriple() + "=" +
9356 A->getValue(N: 1)));
9357 }
9358 Args.ClaimAllArgs(Id0: options::OPT_Xoffload_compiler);
9359 Args.ClaimAllArgs(Id0: options::OPT_Xoffload_linker);
9360
9361 // Embed bitcode instead of an object in JIT mode.
9362 if (Args.hasFlag(Pos: options::OPT_fopenmp_target_jit,
9363 Neg: options::OPT_fno_openmp_target_jit, Default: false))
9364 CmdArgs.push_back(Elt: "--embed-bitcode");
9365
9366 // Save temporary files created by the linker wrapper.
9367 if (Args.hasArg(Ids: options::OPT_save_temps_EQ) ||
9368 Args.hasArg(Ids: options::OPT_save_temps))
9369 CmdArgs.push_back(Elt: "--save-temps");
9370
9371 // Pass in the C library for GPUs if present and not disabled.
9372 if (Args.hasFlag(Pos: options::OPT_offloadlib, Neg: OPT_no_offloadlib, Default: true) &&
9373 !Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_r,
9374 Ids: options::OPT_nodefaultlibs, Ids: options::OPT_nolibc,
9375 Ids: options::OPT_nogpulibc)) {
9376 forAllAssociatedToolChains(C, JA, RegularToolChain: getToolChain(), Work: [&](const ToolChain &TC) {
9377 // The device C library is only available for NVPTX and AMDGPU targets
9378 // and we only link it by default for OpenMP currently.
9379 if ((!TC.getTriple().isNVPTX() && !TC.getTriple().isAMDGPU()) ||
9380 !JA.isHostOffloading(OKind: Action::OFK_OpenMP))
9381 return;
9382 bool HasLibC = TC.getStdlibIncludePath().has_value();
9383 if (HasLibC) {
9384 CmdArgs.push_back(Elt: Args.MakeArgString(
9385 Str: "--device-linker=" + TC.getTripleString() + "=" + "-lc"));
9386 CmdArgs.push_back(Elt: Args.MakeArgString(
9387 Str: "--device-linker=" + TC.getTripleString() + "=" + "-lm"));
9388 }
9389 auto HasCompilerRT = getToolChain().getVFS().exists(
9390 Path: TC.getCompilerRT(Args, Component: "builtins", Type: ToolChain::FT_Static));
9391 if (HasCompilerRT)
9392 CmdArgs.push_back(
9393 Elt: Args.MakeArgString(Str: "--device-linker=" + TC.getTripleString() + "=" +
9394 "-lclang_rt.builtins"));
9395 bool HasFlangRT = HasCompilerRT && C.getDriver().IsFlangMode();
9396 if (HasFlangRT)
9397 CmdArgs.push_back(
9398 Elt: Args.MakeArgString(Str: "--device-linker=" + TC.getTripleString() + "=" +
9399 "-lflang_rt.runtime"));
9400 });
9401 }
9402
9403 // Add the linker arguments to be forwarded by the wrapper.
9404 CmdArgs.push_back(Elt: Args.MakeArgString(Str: Twine("--linker-path=") +
9405 LinkCommand->getExecutable()));
9406
9407 // We use action type to differentiate two use cases of the linker wrapper.
9408 // TY_Image for normal linker wrapper work.
9409 // TY_HIP_FATBIN for HIP fno-gpu-rdc emitting a fat binary without wrapping.
9410 assert(JA.getType() == types::TY_HIP_FATBIN ||
9411 JA.getType() == types::TY_Image);
9412 if (JA.getType() == types::TY_HIP_FATBIN) {
9413 CmdArgs.push_back(Elt: "--emit-fatbin-only");
9414 CmdArgs.append(IL: {"-o", Output.getFilename()});
9415 for (auto Input : Inputs)
9416 CmdArgs.push_back(Elt: Input.getFilename());
9417 } else
9418 for (const char *LinkArg : LinkCommand->getArguments())
9419 CmdArgs.push_back(Elt: LinkArg);
9420
9421 addOffloadCompressArgs(TCArgs: Args, CmdArgs);
9422
9423 if (Arg *A = Args.getLastArg(Ids: options::OPT_offload_jobs_EQ)) {
9424 StringRef Val = A->getValue();
9425
9426 if (Val.equals_insensitive(RHS: "jobserver"))
9427 CmdArgs.push_back(Elt: Args.MakeArgString(Str: "--wrapper-jobs=jobserver"));
9428 else {
9429 int NumThreads;
9430 if (Val.getAsInteger(Radix: 10, Result&: NumThreads) || NumThreads <= 0) {
9431 C.getDriver().Diag(DiagID: diag::err_drv_invalid_int_value)
9432 << A->getAsString(Args) << Val;
9433 } else {
9434 CmdArgs.push_back(
9435 Elt: Args.MakeArgString(Str: "--wrapper-jobs=" + Twine(NumThreads)));
9436 }
9437 }
9438 }
9439
9440 const char *Exec =
9441 Args.MakeArgString(Str: getToolChain().GetProgramPath(Name: "clang-linker-wrapper"));
9442
9443 // Replace the executable and arguments of the link job with the
9444 // wrapper.
9445 LinkCommand->replaceExecutable(Exe: Exec);
9446 LinkCommand->replaceArguments(List: CmdArgs);
9447}
9448